Xinqi Bao's Git

Removing the xclearborders() hack. St now cleans up the parts of the border,
[st.git] / st.c
1 /* See LICENSE for licence details. */
2 #define _XOPEN_SOURCE 600
3 #include <ctype.h>
4 #include <errno.h>
5 #include <fcntl.h>
6 #include <limits.h>
7 #include <locale.h>
8 #include <stdarg.h>
9 #include <stdbool.h>
10 #include <stdio.h>
11 #include <stdlib.h>
12 #include <string.h>
13 #include <signal.h>
14 #include <sys/ioctl.h>
15 #include <sys/select.h>
16 #include <sys/stat.h>
17 #include <sys/time.h>
18 #include <sys/types.h>
19 #include <sys/wait.h>
20 #include <time.h>
21 #include <unistd.h>
22 #include <X11/Xatom.h>
23 #include <X11/Xlib.h>
24 #include <X11/Xutil.h>
25 #include <X11/cursorfont.h>
26 #include <X11/keysym.h>
27 #include <X11/extensions/Xdbe.h>
28 #include <X11/Xft/Xft.h>
29 #include <fontconfig/fontconfig.h>
30 #define Glyph Glyph_
31 #define Font Font_
32
33 #if defined(__linux)
34 #include <pty.h>
35 #elif defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
36 #include <util.h>
37 #elif defined(__FreeBSD__) || defined(__DragonFly__)
38 #include <libutil.h>
39 #endif
40
41 #define USAGE \
42 "st " VERSION " (c) 2010-2012 st engineers\n" \
43 "usage: st [-v] [-c class] [-f font] [-g geometry] [-o file]" \
44 " [-t title] [-w windowid] [-e command ...]\n"
45
46 /* XEMBED messages */
47 #define XEMBED_FOCUS_IN 4
48 #define XEMBED_FOCUS_OUT 5
49
50 /* Arbitrary sizes */
51 #define ESC_BUF_SIZ 256
52 #define ESC_ARG_SIZ 16
53 #define STR_BUF_SIZ 256
54 #define STR_ARG_SIZ 16
55 #define DRAW_BUF_SIZ 20*1024
56 #define UTF_SIZ 4
57 #define XK_NO_MOD UINT_MAX
58 #define XK_ANY_MOD 0
59
60 #define REDRAW_TIMEOUT (80*1000) /* 80 ms */
61
62 #define SERRNO strerror(errno)
63 #define MIN(a, b) ((a) < (b) ? (a) : (b))
64 #define MAX(a, b) ((a) < (b) ? (b) : (a))
65 #define LEN(a) (sizeof(a) / sizeof(a[0]))
66 #define DEFAULT(a, b) (a) = (a) ? (a) : (b)
67 #define BETWEEN(x, a, b) ((a) <= (x) && (x) <= (b))
68 #define LIMIT(x, a, b) (x) = (x) < (a) ? (a) : (x) > (b) ? (b) : (x)
69 #define ATTRCMP(a, b) ((a).mode != (b).mode || (a).fg != (b).fg || (a).bg != (b).bg)
70 #define IS_SET(flag) (term.mode & (flag))
71 #define TIMEDIFF(t1, t2) ((t1.tv_sec-t2.tv_sec)*1000 + (t1.tv_usec-t2.tv_usec)/1000)
72 #define X2COL(x) (((x) - BORDER)/xw.cw)
73 #define Y2ROW(y) (((y) - BORDER)/xw.ch)
74
75 enum glyph_attribute {
76 ATTR_NULL = 0,
77 ATTR_REVERSE = 1,
78 ATTR_UNDERLINE = 2,
79 ATTR_BOLD = 4,
80 ATTR_GFX = 8,
81 ATTR_ITALIC = 16,
82 ATTR_BLINK = 32,
83 };
84
85 enum cursor_movement {
86 CURSOR_UP,
87 CURSOR_DOWN,
88 CURSOR_LEFT,
89 CURSOR_RIGHT,
90 CURSOR_SAVE,
91 CURSOR_LOAD
92 };
93
94 enum cursor_state {
95 CURSOR_DEFAULT = 0,
96 CURSOR_HIDE = 1,
97 CURSOR_WRAPNEXT = 2
98 };
99
100 enum glyph_state {
101 GLYPH_SET = 1,
102 GLYPH_DIRTY = 2
103 };
104
105 enum term_mode {
106 MODE_WRAP = 1,
107 MODE_INSERT = 2,
108 MODE_APPKEYPAD = 4,
109 MODE_ALTSCREEN = 8,
110 MODE_CRLF = 16,
111 MODE_MOUSEBTN = 32,
112 MODE_MOUSEMOTION = 64,
113 MODE_MOUSE = 32|64,
114 MODE_REVERSE = 128,
115 MODE_KBDLOCK = 256
116 };
117
118 enum escape_state {
119 ESC_START = 1,
120 ESC_CSI = 2,
121 ESC_STR = 4, /* DSC, OSC, PM, APC */
122 ESC_ALTCHARSET = 8,
123 ESC_STR_END = 16, /* a final string was encountered */
124 };
125
126 enum window_state {
127 WIN_VISIBLE = 1,
128 WIN_REDRAW = 2,
129 WIN_FOCUSED = 4
130 };
131
132 /* bit macro */
133 #undef B0
134 enum { B0=1, B1=2, B2=4, B3=8, B4=16, B5=32, B6=64, B7=128 };
135
136 typedef unsigned char uchar;
137 typedef unsigned int uint;
138 typedef unsigned long ulong;
139 typedef unsigned short ushort;
140
141 typedef struct {
142 char c[UTF_SIZ]; /* character code */
143 uchar mode; /* attribute flags */
144 ushort fg; /* foreground */
145 ushort bg; /* background */
146 uchar state; /* state flags */
147 } Glyph;
148
149 typedef Glyph* Line;
150
151 typedef struct {
152 Glyph attr; /* current char attributes */
153 int x;
154 int y;
155 char state;
156 } TCursor;
157
158 /* CSI Escape sequence structs */
159 /* ESC '[' [[ [<priv>] <arg> [;]] <mode>] */
160 typedef struct {
161 char buf[ESC_BUF_SIZ]; /* raw string */
162 int len; /* raw string length */
163 char priv;
164 int arg[ESC_ARG_SIZ];
165 int narg; /* nb of args */
166 char mode;
167 } CSIEscape;
168
169 /* STR Escape sequence structs */
170 /* ESC type [[ [<priv>] <arg> [;]] <mode>] ESC '\' */
171 typedef struct {
172 char type; /* ESC type ... */
173 char buf[STR_BUF_SIZ]; /* raw string */
174 int len; /* raw string length */
175 char *args[STR_ARG_SIZ];
176 int narg; /* nb of args */
177 } STREscape;
178
179 /* Internal representation of the screen */
180 typedef struct {
181 int row; /* nb row */
182 int col; /* nb col */
183 Line *line; /* screen */
184 Line *alt; /* alternate screen */
185 bool *dirty; /* dirtyness of lines */
186 TCursor c; /* cursor */
187 int top; /* top scroll limit */
188 int bot; /* bottom scroll limit */
189 int mode; /* terminal mode flags */
190 int esc; /* escape state flags */
191 bool *tabs;
192 } Term;
193
194 /* Purely graphic info */
195 typedef struct {
196 Display* dpy;
197 Colormap cmap;
198 Window win;
199 XdbeBackBuffer buf;
200 Atom xembed, wmdeletewin;
201 XIM xim;
202 XIC xic;
203 XftDraw *xft_draw;
204 Visual *vis;
205 int scr;
206 bool isfixed; /* is fixed geometry? */
207 int fx, fy, fw, fh; /* fixed geometry */
208 int tw, th; /* tty width and height */
209 int w; /* window width */
210 int h; /* window height */
211 int ch; /* char height */
212 int cw; /* char width */
213 char state; /* focus, redraw, visible */
214 } XWindow;
215
216 typedef struct {
217 KeySym k;
218 uint mask;
219 char s[ESC_BUF_SIZ];
220 } Key;
221
222 /* TODO: use better name for vars... */
223 typedef struct {
224 int mode;
225 int bx, by;
226 int ex, ey;
227 struct {
228 int x, y;
229 } b, e;
230 char *clip;
231 Atom xtarget;
232 bool alt;
233 struct timeval tclick1;
234 struct timeval tclick2;
235 } Selection;
236
237 #include "config.h"
238
239 /* Font structure */
240 typedef struct {
241 int height;
242 int width;
243 int ascent;
244 int descent;
245 short lbearing;
246 short rbearing;
247 XftFont *xft_set;
248 } Font;
249
250 /* Drawing Context */
251 typedef struct {
252 XftColor xft_col[LEN(colorname) < 256 ? 256 : LEN(colorname)];
253 GC gc;
254 Font font, bfont, ifont, ibfont;
255 } DC;
256
257 static void die(const char *, ...);
258 static void draw(void);
259 static void redraw(void);
260 static void drawregion(int, int, int, int);
261 static void execsh(void);
262 static void sigchld(int);
263 static void run(void);
264
265 static void csidump(void);
266 static void csihandle(void);
267 static void csiparse(void);
268 static void csireset(void);
269 static void strdump(void);
270 static void strhandle(void);
271 static void strparse(void);
272 static void strreset(void);
273
274 static void tclearregion(int, int, int, int);
275 static void tcursor(int);
276 static void tdeletechar(int);
277 static void tdeleteline(int);
278 static void tinsertblank(int);
279 static void tinsertblankline(int);
280 static void tmoveto(int, int);
281 static void tnew(int, int);
282 static void tnewline(int);
283 static void tputtab(bool);
284 static void tputc(char *, int);
285 static void treset(void);
286 static int tresize(int, int);
287 static void tscrollup(int, int);
288 static void tscrolldown(int, int);
289 static void tsetattr(int*, int);
290 static void tsetchar(char*);
291 static void tsetscroll(int, int);
292 static void tswapscreen(void);
293 static void tsetdirt(int, int);
294 static void tsetmode(bool, bool, int *, int);
295 static void tfulldirt(void);
296
297 static void ttynew(void);
298 static void ttyread(void);
299 static void ttyresize(void);
300 static void ttywrite(const char *, size_t);
301
302 static void xdraws(char *, Glyph, int, int, int, int);
303 static void xhints(void);
304 static void xclear(int, int, int, int);
305 static void xclearborders(void);
306 static void xdrawcursor(void);
307 static void xinit(void);
308 static void xloadcols(void);
309 static void xresettitle(void);
310 static void xseturgency(int);
311 static void xsetsel(char*);
312 static void xtermclear(int, int, int, int);
313 static void xresize(int, int);
314
315 static void expose(XEvent *);
316 static void visibility(XEvent *);
317 static void unmap(XEvent *);
318 static char *kmap(KeySym, uint);
319 static void kpress(XEvent *);
320 static void cmessage(XEvent *);
321 static void resize(XEvent *);
322 static void focus(XEvent *);
323 static void brelease(XEvent *);
324 static void bpress(XEvent *);
325 static void bmotion(XEvent *);
326 static void selnotify(XEvent *);
327 static void selclear(XEvent *);
328 static void selrequest(XEvent *);
329
330 static void selinit(void);
331 static inline bool selected(int, int);
332 static void selcopy(void);
333 static void selpaste(void);
334 static void selscroll(int, int);
335
336 static int utf8decode(char *, long *);
337 static int utf8encode(long *, char *);
338 static int utf8size(char *);
339 static int isfullutf8(char *, int);
340
341 static void *xmalloc(size_t);
342 static void *xrealloc(void *, size_t);
343 static void *xcalloc(size_t nmemb, size_t size);
344 static char *smstrcat(char *, ...);
345
346 static void (*handler[LASTEvent])(XEvent *) = {
347 [KeyPress] = kpress,
348 [ClientMessage] = cmessage,
349 [ConfigureNotify] = resize,
350 [VisibilityNotify] = visibility,
351 [UnmapNotify] = unmap,
352 [Expose] = expose,
353 [FocusIn] = focus,
354 [FocusOut] = focus,
355 [MotionNotify] = bmotion,
356 [ButtonPress] = bpress,
357 [ButtonRelease] = brelease,
358 [SelectionClear] = selclear,
359 [SelectionNotify] = selnotify,
360 [SelectionRequest] = selrequest,
361 };
362
363 /* Globals */
364 static DC dc;
365 static XWindow xw;
366 static Term term;
367 static CSIEscape csiescseq;
368 static STREscape strescseq;
369 static int cmdfd;
370 static pid_t pid;
371 static Selection sel;
372 static int iofd = -1;
373 static char **opt_cmd = NULL;
374 static char *opt_io = NULL;
375 static char *opt_title = NULL;
376 static char *opt_embed = NULL;
377 static char *opt_class = NULL;
378 static char *opt_font = NULL;
379
380 void *
381 xmalloc(size_t len) {
382 void *p = malloc(len);
383
384 if(!p)
385 die("Out of memory\n");
386
387 return p;
388 }
389
390 void *
391 xrealloc(void *p, size_t len) {
392 if((p = realloc(p, len)) == NULL)
393 die("Out of memory\n");
394
395 return p;
396 }
397
398 void *
399 xcalloc(size_t nmemb, size_t size) {
400 void *p = calloc(nmemb, size);
401
402 if(!p)
403 die("Out of memory\n");
404
405 return p;
406 }
407
408 char *
409 smstrcat(char *src, ...)
410 {
411 va_list fmtargs;
412 char *ret, *p, *v;
413 int len, slen, flen;
414
415 len = slen = strlen(src);
416
417 va_start(fmtargs, src);
418 for(;;) {
419 v = va_arg(fmtargs, char *);
420 if(v == NULL)
421 break;
422 len += strlen(v);
423 }
424 va_end(fmtargs);
425
426 p = ret = xmalloc(len+1);
427 memmove(p, src, slen);
428 p += slen;
429
430 va_start(fmtargs, src);
431 for(;;) {
432 v = va_arg(fmtargs, char *);
433 if(v == NULL)
434 break;
435 flen = strlen(v);
436 memmove(p, v, flen);
437 p += flen;
438 }
439 va_end(fmtargs);
440
441 ret[len] = '\0';
442
443 return ret;
444 }
445
446 int
447 utf8decode(char *s, long *u) {
448 uchar c;
449 int i, n, rtn;
450
451 rtn = 1;
452 c = *s;
453 if(~c & B7) { /* 0xxxxxxx */
454 *u = c;
455 return rtn;
456 } else if((c & (B7|B6|B5)) == (B7|B6)) { /* 110xxxxx */
457 *u = c&(B4|B3|B2|B1|B0);
458 n = 1;
459 } else if((c & (B7|B6|B5|B4)) == (B7|B6|B5)) { /* 1110xxxx */
460 *u = c&(B3|B2|B1|B0);
461 n = 2;
462 } else if((c & (B7|B6|B5|B4|B3)) == (B7|B6|B5|B4)) { /* 11110xxx */
463 *u = c & (B2|B1|B0);
464 n = 3;
465 } else {
466 goto invalid;
467 }
468
469 for(i = n, ++s; i > 0; --i, ++rtn, ++s) {
470 c = *s;
471 if((c & (B7|B6)) != B7) /* 10xxxxxx */
472 goto invalid;
473 *u <<= 6;
474 *u |= c & (B5|B4|B3|B2|B1|B0);
475 }
476
477 if((n == 1 && *u < 0x80) ||
478 (n == 2 && *u < 0x800) ||
479 (n == 3 && *u < 0x10000) ||
480 (*u >= 0xD800 && *u <= 0xDFFF)) {
481 goto invalid;
482 }
483
484 return rtn;
485 invalid:
486 *u = 0xFFFD;
487
488 return rtn;
489 }
490
491 int
492 utf8encode(long *u, char *s) {
493 uchar *sp;
494 ulong uc;
495 int i, n;
496
497 sp = (uchar *)s;
498 uc = *u;
499 if(uc < 0x80) {
500 *sp = uc; /* 0xxxxxxx */
501 return 1;
502 } else if(*u < 0x800) {
503 *sp = (uc >> 6) | (B7|B6); /* 110xxxxx */
504 n = 1;
505 } else if(uc < 0x10000) {
506 *sp = (uc >> 12) | (B7|B6|B5); /* 1110xxxx */
507 n = 2;
508 } else if(uc <= 0x10FFFF) {
509 *sp = (uc >> 18) | (B7|B6|B5|B4); /* 11110xxx */
510 n = 3;
511 } else {
512 goto invalid;
513 }
514
515 for(i=n,++sp; i>0; --i,++sp)
516 *sp = ((uc >> 6*(i-1)) & (B5|B4|B3|B2|B1|B0)) | B7; /* 10xxxxxx */
517
518 return n+1;
519 invalid:
520 /* U+FFFD */
521 *s++ = '\xEF';
522 *s++ = '\xBF';
523 *s = '\xBD';
524
525 return 3;
526 }
527
528 /* use this if your buffer is less than UTF_SIZ, it returns 1 if you can decode
529 UTF-8 otherwise return 0 */
530 int
531 isfullutf8(char *s, int b) {
532 uchar *c1, *c2, *c3;
533
534 c1 = (uchar *)s;
535 c2 = (uchar *)++s;
536 c3 = (uchar *)++s;
537 if(b < 1) {
538 return 0;
539 } else if((*c1&(B7|B6|B5)) == (B7|B6) && b == 1) {
540 return 0;
541 } else if((*c1&(B7|B6|B5|B4)) == (B7|B6|B5) &&
542 ((b == 1) ||
543 ((b == 2) && (*c2&(B7|B6)) == B7))) {
544 return 0;
545 } else if((*c1&(B7|B6|B5|B4|B3)) == (B7|B6|B5|B4) &&
546 ((b == 1) ||
547 ((b == 2) && (*c2&(B7|B6)) == B7) ||
548 ((b == 3) && (*c2&(B7|B6)) == B7 && (*c3&(B7|B6)) == B7))) {
549 return 0;
550 } else {
551 return 1;
552 }
553 }
554
555 int
556 utf8size(char *s) {
557 uchar c = *s;
558
559 if(~c&B7) {
560 return 1;
561 } else if((c&(B7|B6|B5)) == (B7|B6)) {
562 return 2;
563 } else if((c&(B7|B6|B5|B4)) == (B7|B6|B5)) {
564 return 3;
565 } else {
566 return 4;
567 }
568 }
569
570 void
571 selinit(void) {
572 memset(&sel.tclick1, 0, sizeof(sel.tclick1));
573 memset(&sel.tclick2, 0, sizeof(sel.tclick2));
574 sel.mode = 0;
575 sel.bx = -1;
576 sel.clip = NULL;
577 sel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
578 if(sel.xtarget == None)
579 sel.xtarget = XA_STRING;
580 }
581
582 static inline bool
583 selected(int x, int y) {
584 int bx, ex;
585
586 if(sel.ey == y && sel.by == y) {
587 bx = MIN(sel.bx, sel.ex);
588 ex = MAX(sel.bx, sel.ex);
589 return BETWEEN(x, bx, ex);
590 }
591
592 return ((sel.b.y < y && y < sel.e.y)
593 || (y == sel.e.y && x <= sel.e.x))
594 || (y == sel.b.y && x >= sel.b.x
595 && (x <= sel.e.x || sel.b.y != sel.e.y));
596 }
597
598 void
599 getbuttoninfo(XEvent *e, int *b, int *x, int *y) {
600 if(b)
601 *b = e->xbutton.button;
602
603 *x = X2COL(e->xbutton.x);
604 *y = Y2ROW(e->xbutton.y);
605 sel.b.x = sel.by < sel.ey ? sel.bx : sel.ex;
606 sel.b.y = MIN(sel.by, sel.ey);
607 sel.e.x = sel.by < sel.ey ? sel.ex : sel.bx;
608 sel.e.y = MAX(sel.by, sel.ey);
609 }
610
611 void
612 mousereport(XEvent *e) {
613 int x = X2COL(e->xbutton.x);
614 int y = Y2ROW(e->xbutton.y);
615 int button = e->xbutton.button;
616 int state = e->xbutton.state;
617 char buf[] = { '\033', '[', 'M', 0, 32+x+1, 32+y+1 };
618 static int ob, ox, oy;
619
620 /* from urxvt */
621 if(e->xbutton.type == MotionNotify) {
622 if(!IS_SET(MODE_MOUSEMOTION) || (x == ox && y == oy))
623 return;
624 button = ob + 32;
625 ox = x, oy = y;
626 } else if(e->xbutton.type == ButtonRelease || button == AnyButton) {
627 button = 3;
628 } else {
629 button -= Button1;
630 if(button >= 3)
631 button += 64 - 3;
632 if(e->xbutton.type == ButtonPress) {
633 ob = button;
634 ox = x, oy = y;
635 }
636 }
637
638 buf[3] = 32 + button + (state & ShiftMask ? 4 : 0)
639 + (state & Mod4Mask ? 8 : 0)
640 + (state & ControlMask ? 16 : 0);
641
642 ttywrite(buf, sizeof(buf));
643 }
644
645 void
646 bpress(XEvent *e) {
647 if(IS_SET(MODE_MOUSE)) {
648 mousereport(e);
649 } else if(e->xbutton.button == Button1) {
650 if(sel.bx != -1) {
651 sel.bx = -1;
652 tsetdirt(sel.b.y, sel.e.y);
653 draw();
654 }
655 sel.mode = 1;
656 sel.ex = sel.bx = X2COL(e->xbutton.x);
657 sel.ey = sel.by = Y2ROW(e->xbutton.y);
658 }
659 }
660
661 void
662 selcopy(void) {
663 char *str, *ptr, *p;
664 int x, y, bufsize, is_selected = 0, size;
665 Glyph *gp;
666
667 if(sel.bx == -1) {
668 str = NULL;
669 } else {
670 bufsize = (term.col+1) * (sel.e.y-sel.b.y+1) * UTF_SIZ;
671 ptr = str = xmalloc(bufsize);
672
673 /* append every set & selected glyph to the selection */
674 for(y = 0; y < term.row; y++) {
675 for(x = 0; x < term.col; x++) {
676 gp = &term.line[y][x];
677
678 if(!(is_selected = selected(x, y)))
679 continue;
680 p = (gp->state & GLYPH_SET) ? gp->c : " ";
681 size = utf8size(p);
682 memcpy(ptr, p, size);
683 ptr += size;
684 }
685 /* \n at the end of every selected line except for the last one */
686 if(is_selected && y < sel.e.y)
687 *ptr++ = '\n';
688 }
689 *ptr = 0;
690 }
691 sel.alt = IS_SET(MODE_ALTSCREEN);
692 xsetsel(str);
693 }
694
695 void
696 selnotify(XEvent *e) {
697 ulong nitems, ofs, rem;
698 int format;
699 uchar *data;
700 Atom type;
701
702 ofs = 0;
703 do {
704 if(XGetWindowProperty(xw.dpy, xw.win, XA_PRIMARY, ofs, BUFSIZ/4,
705 False, AnyPropertyType, &type, &format,
706 &nitems, &rem, &data)) {
707 fprintf(stderr, "Clipboard allocation failed\n");
708 return;
709 }
710 ttywrite((const char *) data, nitems * format / 8);
711 XFree(data);
712 /* number of 32-bit chunks returned */
713 ofs += nitems * format / 32;
714 } while(rem > 0);
715 }
716
717 void
718 selpaste(void) {
719 XConvertSelection(xw.dpy, XA_PRIMARY, sel.xtarget, XA_PRIMARY,
720 xw.win, CurrentTime);
721 }
722
723 void selclear(XEvent *e) {
724 if(sel.bx == -1)
725 return;
726 sel.bx = -1;
727 tsetdirt(sel.b.y, sel.e.y);
728 }
729
730 void
731 selrequest(XEvent *e) {
732 XSelectionRequestEvent *xsre;
733 XSelectionEvent xev;
734 Atom xa_targets, string;
735
736 xsre = (XSelectionRequestEvent *) e;
737 xev.type = SelectionNotify;
738 xev.requestor = xsre->requestor;
739 xev.selection = xsre->selection;
740 xev.target = xsre->target;
741 xev.time = xsre->time;
742 /* reject */
743 xev.property = None;
744
745 xa_targets = XInternAtom(xw.dpy, "TARGETS", 0);
746 if(xsre->target == xa_targets) {
747 /* respond with the supported type */
748 string = sel.xtarget;
749 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
750 XA_ATOM, 32, PropModeReplace,
751 (uchar *) &string, 1);
752 xev.property = xsre->property;
753 } else if(xsre->target == sel.xtarget && sel.clip != NULL) {
754 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
755 xsre->target, 8, PropModeReplace,
756 (uchar *) sel.clip, strlen(sel.clip));
757 xev.property = xsre->property;
758 }
759
760 /* all done, send a notification to the listener */
761 if(!XSendEvent(xsre->display, xsre->requestor, True, 0, (XEvent *) &xev))
762 fprintf(stderr, "Error sending SelectionNotify event\n");
763 }
764
765 void
766 xsetsel(char *str) {
767 /* register the selection for both the clipboard and the primary */
768 Atom clipboard;
769
770 free(sel.clip);
771 sel.clip = str;
772
773 XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, CurrentTime);
774
775 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
776 XSetSelectionOwner(xw.dpy, clipboard, xw.win, CurrentTime);
777 }
778
779 void
780 brelease(XEvent *e) {
781 struct timeval now;
782
783 if(IS_SET(MODE_MOUSE)) {
784 mousereport(e);
785 return;
786 }
787
788 if(e->xbutton.button == Button2) {
789 selpaste();
790 } else if(e->xbutton.button == Button1) {
791 sel.mode = 0;
792 getbuttoninfo(e, NULL, &sel.ex, &sel.ey);
793 term.dirty[sel.ey] = 1;
794 if(sel.bx == sel.ex && sel.by == sel.ey) {
795 sel.bx = -1;
796 gettimeofday(&now, NULL);
797
798 if(TIMEDIFF(now, sel.tclick2) <= TRIPLECLICK_TIMEOUT) {
799 /* triple click on the line */
800 sel.b.x = sel.bx = 0;
801 sel.e.x = sel.ex = term.col;
802 sel.b.y = sel.e.y = sel.ey;
803 selcopy();
804 } else if(TIMEDIFF(now, sel.tclick1) <= DOUBLECLICK_TIMEOUT) {
805 /* double click to select word */
806 sel.bx = sel.ex;
807 while(sel.bx > 0 && term.line[sel.ey][sel.bx-1].state & GLYPH_SET &&
808 term.line[sel.ey][sel.bx-1].c[0] != ' ') {
809 sel.bx--;
810 }
811 sel.b.x = sel.bx;
812 while(sel.ex < term.col-1 && term.line[sel.ey][sel.ex+1].state & GLYPH_SET &&
813 term.line[sel.ey][sel.ex+1].c[0] != ' ') {
814 sel.ex++;
815 }
816 sel.e.x = sel.ex;
817 sel.b.y = sel.e.y = sel.ey;
818 selcopy();
819 }
820 } else {
821 selcopy();
822 }
823 }
824
825 memcpy(&sel.tclick2, &sel.tclick1, sizeof(struct timeval));
826 gettimeofday(&sel.tclick1, NULL);
827 }
828
829 void
830 bmotion(XEvent *e) {
831 int starty, endy, oldey, oldex;
832
833 if(IS_SET(MODE_MOUSE)) {
834 mousereport(e);
835 return;
836 }
837
838 if(sel.mode) {
839 oldey = sel.ey;
840 oldex = sel.ex;
841 getbuttoninfo(e, NULL, &sel.ex, &sel.ey);
842
843 if(oldey != sel.ey || oldex != sel.ex) {
844 starty = MIN(oldey, sel.ey);
845 endy = MAX(oldey, sel.ey);
846 tsetdirt(starty, endy);
847 }
848 }
849 }
850
851 void
852 die(const char *errstr, ...) {
853 va_list ap;
854
855 va_start(ap, errstr);
856 vfprintf(stderr, errstr, ap);
857 va_end(ap);
858 exit(EXIT_FAILURE);
859 }
860
861 void
862 execsh(void) {
863 char **args;
864 char *envshell = getenv("SHELL");
865
866 unsetenv("COLUMNS");
867 unsetenv("LINES");
868 unsetenv("TERMCAP");
869
870 signal(SIGCHLD, SIG_DFL);
871 signal(SIGHUP, SIG_DFL);
872 signal(SIGINT, SIG_DFL);
873 signal(SIGQUIT, SIG_DFL);
874 signal(SIGTERM, SIG_DFL);
875 signal(SIGALRM, SIG_DFL);
876
877 DEFAULT(envshell, SHELL);
878 putenv("TERM="TNAME);
879 args = opt_cmd ? opt_cmd : (char*[]){envshell, "-i", NULL};
880 execvp(args[0], args);
881 exit(EXIT_FAILURE);
882 }
883
884 void
885 sigchld(int a) {
886 int stat = 0;
887
888 if(waitpid(pid, &stat, 0) < 0)
889 die("Waiting for pid %hd failed: %s\n", pid, SERRNO);
890
891 if(WIFEXITED(stat)) {
892 exit(WEXITSTATUS(stat));
893 } else {
894 exit(EXIT_FAILURE);
895 }
896 }
897
898 void
899 ttynew(void) {
900 int m, s;
901 struct winsize w = {term.row, term.col, 0, 0};
902
903 /* seems to work fine on linux, openbsd and freebsd */
904 if(openpty(&m, &s, NULL, NULL, &w) < 0)
905 die("openpty failed: %s\n", SERRNO);
906
907 switch(pid = fork()) {
908 case -1:
909 die("fork failed\n");
910 break;
911 case 0:
912 setsid(); /* create a new process group */
913 dup2(s, STDIN_FILENO);
914 dup2(s, STDOUT_FILENO);
915 dup2(s, STDERR_FILENO);
916 if(ioctl(s, TIOCSCTTY, NULL) < 0)
917 die("ioctl TIOCSCTTY failed: %s\n", SERRNO);
918 close(s);
919 close(m);
920 execsh();
921 break;
922 default:
923 close(s);
924 cmdfd = m;
925 signal(SIGCHLD, sigchld);
926 if(opt_io) {
927 if(!strcmp(opt_io, "-")) {
928 iofd = STDOUT_FILENO;
929 } else {
930 if((iofd = open(opt_io, O_WRONLY | O_CREAT, 0666)) < 0) {
931 fprintf(stderr, "Error opening %s:%s\n",
932 opt_io, strerror(errno));
933 }
934 }
935 }
936 }
937 }
938
939 void
940 dump(char c) {
941 static int col;
942
943 fprintf(stderr, " %02x '%c' ", c, isprint(c)?c:'.');
944 if(++col % 10 == 0)
945 fprintf(stderr, "\n");
946 }
947
948 void
949 ttyread(void) {
950 static char buf[BUFSIZ];
951 static int buflen = 0;
952 char *ptr;
953 char s[UTF_SIZ];
954 int charsize; /* size of utf8 char in bytes */
955 long utf8c;
956 int ret;
957
958 /* append read bytes to unprocessed bytes */
959 if((ret = read(cmdfd, buf+buflen, LEN(buf)-buflen)) < 0)
960 die("Couldn't read from shell: %s\n", SERRNO);
961
962 /* process every complete utf8 char */
963 buflen += ret;
964 ptr = buf;
965 while(buflen >= UTF_SIZ || isfullutf8(ptr,buflen)) {
966 charsize = utf8decode(ptr, &utf8c);
967 utf8encode(&utf8c, s);
968 tputc(s, charsize);
969 ptr += charsize;
970 buflen -= charsize;
971 }
972
973 /* keep any uncomplete utf8 char for the next call */
974 memmove(buf, ptr, buflen);
975 }
976
977 void
978 ttywrite(const char *s, size_t n) {
979 if(write(cmdfd, s, n) == -1)
980 die("write error on tty: %s\n", SERRNO);
981 }
982
983 void
984 ttyresize(void) {
985 struct winsize w;
986
987 w.ws_row = term.row;
988 w.ws_col = term.col;
989 w.ws_xpixel = xw.tw;
990 w.ws_ypixel = xw.th;
991 if(ioctl(cmdfd, TIOCSWINSZ, &w) < 0)
992 fprintf(stderr, "Couldn't set window size: %s\n", SERRNO);
993 }
994
995 void
996 tsetdirt(int top, int bot) {
997 int i;
998
999 LIMIT(top, 0, term.row-1);
1000 LIMIT(bot, 0, term.row-1);
1001
1002 for(i = top; i <= bot; i++)
1003 term.dirty[i] = 1;
1004 }
1005
1006 void
1007 tfulldirt(void) {
1008 tsetdirt(0, term.row-1);
1009 }
1010
1011 void
1012 tcursor(int mode) {
1013 static TCursor c;
1014
1015 if(mode == CURSOR_SAVE) {
1016 c = term.c;
1017 } else if(mode == CURSOR_LOAD) {
1018 term.c = c;
1019 tmoveto(c.x, c.y);
1020 }
1021 }
1022
1023 void
1024 treset(void) {
1025 uint i;
1026
1027 term.c = (TCursor){{
1028 .mode = ATTR_NULL,
1029 .fg = DefaultFG,
1030 .bg = DefaultBG
1031 }, .x = 0, .y = 0, .state = CURSOR_DEFAULT};
1032
1033 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1034 for(i = TAB; i < term.col; i += TAB)
1035 term.tabs[i] = 1;
1036 term.top = 0;
1037 term.bot = term.row - 1;
1038 term.mode = MODE_WRAP;
1039
1040 tclearregion(0, 0, term.col-1, term.row-1);
1041 }
1042
1043 void
1044 tnew(int col, int row) {
1045 /* set screen size */
1046 term.row = row;
1047 term.col = col;
1048 term.line = xmalloc(term.row * sizeof(Line));
1049 term.alt = xmalloc(term.row * sizeof(Line));
1050 term.dirty = xmalloc(term.row * sizeof(*term.dirty));
1051 term.tabs = xmalloc(term.col * sizeof(*term.tabs));
1052
1053 for(row = 0; row < term.row; row++) {
1054 term.line[row] = xmalloc(term.col * sizeof(Glyph));
1055 term.alt [row] = xmalloc(term.col * sizeof(Glyph));
1056 term.dirty[row] = 0;
1057 }
1058 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1059 /* setup screen */
1060 treset();
1061 }
1062
1063 void
1064 tswapscreen(void) {
1065 Line *tmp = term.line;
1066
1067 term.line = term.alt;
1068 term.alt = tmp;
1069 term.mode ^= MODE_ALTSCREEN;
1070 tfulldirt();
1071 }
1072
1073 void
1074 tscrolldown(int orig, int n) {
1075 int i;
1076 Line temp;
1077
1078 LIMIT(n, 0, term.bot-orig+1);
1079
1080 tclearregion(0, term.bot-n+1, term.col-1, term.bot);
1081
1082 for(i = term.bot; i >= orig+n; i--) {
1083 temp = term.line[i];
1084 term.line[i] = term.line[i-n];
1085 term.line[i-n] = temp;
1086
1087 term.dirty[i] = 1;
1088 term.dirty[i-n] = 1;
1089 }
1090
1091 selscroll(orig, n);
1092 }
1093
1094 void
1095 tscrollup(int orig, int n) {
1096 int i;
1097 Line temp;
1098 LIMIT(n, 0, term.bot-orig+1);
1099
1100 tclearregion(0, orig, term.col-1, orig+n-1);
1101
1102 for(i = orig; i <= term.bot-n; i++) {
1103 temp = term.line[i];
1104 term.line[i] = term.line[i+n];
1105 term.line[i+n] = temp;
1106
1107 term.dirty[i] = 1;
1108 term.dirty[i+n] = 1;
1109 }
1110
1111 selscroll(orig, -n);
1112 }
1113
1114 void
1115 selscroll(int orig, int n) {
1116 if(sel.bx == -1)
1117 return;
1118
1119 if(BETWEEN(sel.by, orig, term.bot) || BETWEEN(sel.ey, orig, term.bot)) {
1120 if((sel.by += n) > term.bot || (sel.ey += n) < term.top) {
1121 sel.bx = -1;
1122 return;
1123 }
1124 if(sel.by < term.top) {
1125 sel.by = term.top;
1126 sel.bx = 0;
1127 }
1128 if(sel.ey > term.bot) {
1129 sel.ey = term.bot;
1130 sel.ex = term.col;
1131 }
1132 sel.b.y = sel.by, sel.b.x = sel.bx;
1133 sel.e.y = sel.ey, sel.e.x = sel.ex;
1134 }
1135 }
1136
1137 void
1138 tnewline(int first_col) {
1139 int y = term.c.y;
1140
1141 if(y == term.bot) {
1142 tscrollup(term.top, 1);
1143 } else {
1144 y++;
1145 }
1146 tmoveto(first_col ? 0 : term.c.x, y);
1147 }
1148
1149 void
1150 csiparse(void) {
1151 /* int noarg = 1; */
1152 char *p = csiescseq.buf;
1153
1154 csiescseq.narg = 0;
1155 if(*p == '?')
1156 csiescseq.priv = 1, p++;
1157
1158 while(p < csiescseq.buf+csiescseq.len) {
1159 while(isdigit(*p)) {
1160 csiescseq.arg[csiescseq.narg] *= 10;
1161 csiescseq.arg[csiescseq.narg] += *p++ - '0'/*, noarg = 0 */;
1162 }
1163 if(*p == ';' && csiescseq.narg+1 < ESC_ARG_SIZ) {
1164 csiescseq.narg++, p++;
1165 } else {
1166 csiescseq.mode = *p;
1167 csiescseq.narg++;
1168
1169 return;
1170 }
1171 }
1172 }
1173
1174 void
1175 tmoveto(int x, int y) {
1176 LIMIT(x, 0, term.col-1);
1177 LIMIT(y, 0, term.row-1);
1178 term.c.state &= ~CURSOR_WRAPNEXT;
1179 term.c.x = x;
1180 term.c.y = y;
1181 }
1182
1183 void
1184 tsetchar(char *c) {
1185 char *vt100_0[62] = { /* 0x41 - 0x7e */
1186 "↑", "↓", "→", "←", "█", "▚", "☃", /* A - G */
1187 0, 0, 0, 0, 0, 0, 0, 0, /* H - O */
1188 0, 0, 0, 0, 0, 0, 0, 0, /* P - W */
1189 0, 0, 0, 0, 0, 0, 0, " ", /* X - _ */
1190 "◆", "▒", "␉", "␌", "␍", "␊", "°", "±", /* ` - g */
1191 "␤", "␋", "┘", "┐", "┌", "└", "┼", "⎺", /* h - o */
1192 "⎻", "─", "⎼", "⎽", "├", "┤", "┴", "┬", /* p - w */
1193 "│", "≤", "≥", "π", "≠", "£", "·", /* x - ~ */
1194 };
1195
1196 /*
1197 * The table is proudly stolen from rxvt.
1198 */
1199 if(term.c.attr.mode & ATTR_GFX) {
1200 if(c[0] >= 0x41 && c[0] <= 0x7e
1201 && vt100_0[c[0] - 0x41]) {
1202 c = vt100_0[c[0] - 0x41];
1203 }
1204 }
1205
1206 term.dirty[term.c.y] = 1;
1207 term.line[term.c.y][term.c.x] = term.c.attr;
1208 memcpy(term.line[term.c.y][term.c.x].c, c, UTF_SIZ);
1209 term.line[term.c.y][term.c.x].state |= GLYPH_SET;
1210 }
1211
1212 void
1213 tclearregion(int x1, int y1, int x2, int y2) {
1214 int x, y, temp;
1215
1216 if(x1 > x2)
1217 temp = x1, x1 = x2, x2 = temp;
1218 if(y1 > y2)
1219 temp = y1, y1 = y2, y2 = temp;
1220
1221 LIMIT(x1, 0, term.col-1);
1222 LIMIT(x2, 0, term.col-1);
1223 LIMIT(y1, 0, term.row-1);
1224 LIMIT(y2, 0, term.row-1);
1225
1226 for(y = y1; y <= y2; y++) {
1227 term.dirty[y] = 1;
1228 for(x = x1; x <= x2; x++)
1229 term.line[y][x].state = 0;
1230 }
1231 }
1232
1233 void
1234 tdeletechar(int n) {
1235 int src = term.c.x + n;
1236 int dst = term.c.x;
1237 int size = term.col - src;
1238
1239 term.dirty[term.c.y] = 1;
1240
1241 if(src >= term.col) {
1242 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1243 return;
1244 }
1245
1246 memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src],
1247 size * sizeof(Glyph));
1248 tclearregion(term.col-n, term.c.y, term.col-1, term.c.y);
1249 }
1250
1251 void
1252 tinsertblank(int n) {
1253 int src = term.c.x;
1254 int dst = src + n;
1255 int size = term.col - dst;
1256
1257 term.dirty[term.c.y] = 1;
1258
1259 if(dst >= term.col) {
1260 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1261 return;
1262 }
1263
1264 memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src],
1265 size * sizeof(Glyph));
1266 tclearregion(src, term.c.y, dst - 1, term.c.y);
1267 }
1268
1269 void
1270 tinsertblankline(int n) {
1271 if(term.c.y < term.top || term.c.y > term.bot)
1272 return;
1273
1274 tscrolldown(term.c.y, n);
1275 }
1276
1277 void
1278 tdeleteline(int n) {
1279 if(term.c.y < term.top || term.c.y > term.bot)
1280 return;
1281
1282 tscrollup(term.c.y, n);
1283 }
1284
1285 void
1286 tsetattr(int *attr, int l) {
1287 int i;
1288
1289 for(i = 0; i < l; i++) {
1290 switch(attr[i]) {
1291 case 0:
1292 term.c.attr.mode &= ~(ATTR_REVERSE | ATTR_UNDERLINE | ATTR_BOLD \
1293 | ATTR_ITALIC | ATTR_BLINK);
1294 term.c.attr.fg = DefaultFG;
1295 term.c.attr.bg = DefaultBG;
1296 break;
1297 case 1:
1298 term.c.attr.mode |= ATTR_BOLD;
1299 break;
1300 case 3: /* enter standout (highlight) */
1301 term.c.attr.mode |= ATTR_ITALIC;
1302 break;
1303 case 4:
1304 term.c.attr.mode |= ATTR_UNDERLINE;
1305 break;
1306 case 5:
1307 term.c.attr.mode |= ATTR_BLINK;
1308 break;
1309 case 7:
1310 term.c.attr.mode |= ATTR_REVERSE;
1311 break;
1312 case 21:
1313 case 22:
1314 term.c.attr.mode &= ~ATTR_BOLD;
1315 break;
1316 case 23: /* leave standout (highlight) mode */
1317 term.c.attr.mode &= ~ATTR_ITALIC;
1318 break;
1319 case 24:
1320 term.c.attr.mode &= ~ATTR_UNDERLINE;
1321 break;
1322 case 25:
1323 term.c.attr.mode &= ~ATTR_BLINK;
1324 break;
1325 case 27:
1326 term.c.attr.mode &= ~ATTR_REVERSE;
1327 break;
1328 case 38:
1329 if(i + 2 < l && attr[i + 1] == 5) {
1330 i += 2;
1331 if(BETWEEN(attr[i], 0, 255)) {
1332 term.c.attr.fg = attr[i];
1333 } else {
1334 fprintf(stderr,
1335 "erresc: bad fgcolor %d\n",
1336 attr[i]);
1337 }
1338 } else {
1339 fprintf(stderr,
1340 "erresc(38): gfx attr %d unknown\n",
1341 attr[i]);
1342 }
1343 break;
1344 case 39:
1345 term.c.attr.fg = DefaultFG;
1346 break;
1347 case 48:
1348 if(i + 2 < l && attr[i + 1] == 5) {
1349 i += 2;
1350 if(BETWEEN(attr[i], 0, 255)) {
1351 term.c.attr.bg = attr[i];
1352 } else {
1353 fprintf(stderr,
1354 "erresc: bad bgcolor %d\n",
1355 attr[i]);
1356 }
1357 } else {
1358 fprintf(stderr,
1359 "erresc(48): gfx attr %d unknown\n",
1360 attr[i]);
1361 }
1362 break;
1363 case 49:
1364 term.c.attr.bg = DefaultBG;
1365 break;
1366 default:
1367 if(BETWEEN(attr[i], 30, 37)) {
1368 term.c.attr.fg = attr[i] - 30;
1369 } else if(BETWEEN(attr[i], 40, 47)) {
1370 term.c.attr.bg = attr[i] - 40;
1371 } else if(BETWEEN(attr[i], 90, 97)) {
1372 term.c.attr.fg = attr[i] - 90 + 8;
1373 } else if(BETWEEN(attr[i], 100, 107)) {
1374 term.c.attr.bg = attr[i] - 100 + 8;
1375 } else {
1376 fprintf(stderr,
1377 "erresc(default): gfx attr %d unknown\n",
1378 attr[i]), csidump();
1379 }
1380 break;
1381 }
1382 }
1383 }
1384
1385 void
1386 tsetscroll(int t, int b) {
1387 int temp;
1388
1389 LIMIT(t, 0, term.row-1);
1390 LIMIT(b, 0, term.row-1);
1391 if(t > b) {
1392 temp = t;
1393 t = b;
1394 b = temp;
1395 }
1396 term.top = t;
1397 term.bot = b;
1398 }
1399
1400 #define MODBIT(x, set, bit) ((set) ? ((x) |= (bit)) : ((x) &= ~(bit)))
1401
1402 void
1403 tsetmode(bool priv, bool set, int *args, int narg) {
1404 int *lim, mode;
1405
1406 for(lim = args + narg; args < lim; ++args) {
1407 if(priv) {
1408 switch(*args) {
1409 break;
1410 case 1: /* DECCKM -- Cursor key */
1411 MODBIT(term.mode, set, MODE_APPKEYPAD);
1412 break;
1413 case 5: /* DECSCNM -- Reverse video */
1414 mode = term.mode;
1415 MODBIT(term.mode, set, MODE_REVERSE);
1416 if(mode != term.mode)
1417 redraw();
1418 break;
1419 case 6: /* XXX: DECOM -- Origin */
1420 break;
1421 case 7: /* DECAWM -- Auto wrap */
1422 MODBIT(term.mode, set, MODE_WRAP);
1423 break;
1424 case 8: /* XXX: DECARM -- Auto repeat */
1425 break;
1426 case 0: /* Error (IGNORED) */
1427 case 12: /* att610 -- Start blinking cursor (IGNORED) */
1428 break;
1429 case 25:
1430 MODBIT(term.c.state, !set, CURSOR_HIDE);
1431 break;
1432 case 1000: /* 1000,1002: enable xterm mouse report */
1433 MODBIT(term.mode, set, MODE_MOUSEBTN);
1434 break;
1435 case 1002:
1436 MODBIT(term.mode, set, MODE_MOUSEMOTION);
1437 break;
1438 case 1049: /* = 1047 and 1048 */
1439 case 47:
1440 case 1047:
1441 if(IS_SET(MODE_ALTSCREEN))
1442 tclearregion(0, 0, term.col-1, term.row-1);
1443 if((set && !IS_SET(MODE_ALTSCREEN)) ||
1444 (!set && IS_SET(MODE_ALTSCREEN))) {
1445 tswapscreen();
1446 }
1447 if(*args != 1049)
1448 break;
1449 /* pass through */
1450 case 1048:
1451 tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
1452 break;
1453 default:
1454 /* case 2: DECANM -- ANSI/VT52 (NOT SUPPOURTED) */
1455 /* case 3: DECCOLM -- Column (NOT SUPPORTED) */
1456 /* case 4: DECSCLM -- Scroll (NOT SUPPORTED) */
1457 /* case 18: DECPFF -- Printer feed (NOT SUPPORTED) */
1458 /* case 19: DECPEX -- Printer extent (NOT SUPPORTED) */
1459 /* case 42: DECNRCM -- National characters (NOT SUPPORTED) */
1460 fprintf(stderr,
1461 "erresc: unknown private set/reset mode %d\n",
1462 *args);
1463 break;
1464 }
1465 } else {
1466 switch(*args) {
1467 case 0: /* Error (IGNORED) */
1468 break;
1469 case 2: /* KAM -- keyboard action */
1470 MODBIT(term.mode, set, MODE_KBDLOCK);
1471 break;
1472 case 4: /* IRM -- Insertion-replacement */
1473 MODBIT(term.mode, set, MODE_INSERT);
1474 break;
1475 case 12: /* XXX: SRM -- Send/Receive */
1476 break;
1477 case 20: /* LNM -- Linefeed/new line */
1478 MODBIT(term.mode, set, MODE_CRLF);
1479 break;
1480 default:
1481 fprintf(stderr,
1482 "erresc: unknown set/reset mode %d\n",
1483 *args);
1484 break;
1485 }
1486 }
1487 }
1488 }
1489 #undef MODBIT
1490
1491
1492 void
1493 csihandle(void) {
1494 switch(csiescseq.mode) {
1495 default:
1496 unknown:
1497 fprintf(stderr, "erresc: unknown csi ");
1498 csidump();
1499 /* die(""); */
1500 break;
1501 case '@': /* ICH -- Insert <n> blank char */
1502 DEFAULT(csiescseq.arg[0], 1);
1503 tinsertblank(csiescseq.arg[0]);
1504 break;
1505 case 'A': /* CUU -- Cursor <n> Up */
1506 case 'e':
1507 DEFAULT(csiescseq.arg[0], 1);
1508 tmoveto(term.c.x, term.c.y-csiescseq.arg[0]);
1509 break;
1510 case 'B': /* CUD -- Cursor <n> Down */
1511 DEFAULT(csiescseq.arg[0], 1);
1512 tmoveto(term.c.x, term.c.y+csiescseq.arg[0]);
1513 break;
1514 case 'C': /* CUF -- Cursor <n> Forward */
1515 case 'a':
1516 DEFAULT(csiescseq.arg[0], 1);
1517 tmoveto(term.c.x+csiescseq.arg[0], term.c.y);
1518 break;
1519 case 'D': /* CUB -- Cursor <n> Backward */
1520 DEFAULT(csiescseq.arg[0], 1);
1521 tmoveto(term.c.x-csiescseq.arg[0], term.c.y);
1522 break;
1523 case 'E': /* CNL -- Cursor <n> Down and first col */
1524 DEFAULT(csiescseq.arg[0], 1);
1525 tmoveto(0, term.c.y+csiescseq.arg[0]);
1526 break;
1527 case 'F': /* CPL -- Cursor <n> Up and first col */
1528 DEFAULT(csiescseq.arg[0], 1);
1529 tmoveto(0, term.c.y-csiescseq.arg[0]);
1530 break;
1531 case 'g': /* TBC -- Tabulation clear */
1532 switch (csiescseq.arg[0]) {
1533 case 0: /* clear current tab stop */
1534 term.tabs[term.c.x] = 0;
1535 break;
1536 case 3: /* clear all the tabs */
1537 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1538 break;
1539 default:
1540 goto unknown;
1541 }
1542 break;
1543 case 'G': /* CHA -- Move to <col> */
1544 case '`': /* HPA */
1545 DEFAULT(csiescseq.arg[0], 1);
1546 tmoveto(csiescseq.arg[0]-1, term.c.y);
1547 break;
1548 case 'H': /* CUP -- Move to <row> <col> */
1549 case 'f': /* HVP */
1550 DEFAULT(csiescseq.arg[0], 1);
1551 DEFAULT(csiescseq.arg[1], 1);
1552 tmoveto(csiescseq.arg[1]-1, csiescseq.arg[0]-1);
1553 break;
1554 case 'I': /* CHT -- Cursor Forward Tabulation <n> tab stops */
1555 DEFAULT(csiescseq.arg[0], 1);
1556 while(csiescseq.arg[0]--)
1557 tputtab(1);
1558 break;
1559 case 'J': /* ED -- Clear screen */
1560 sel.bx = -1;
1561 switch(csiescseq.arg[0]) {
1562 case 0: /* below */
1563 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1564 if(term.c.y < term.row-1)
1565 tclearregion(0, term.c.y+1, term.col-1, term.row-1);
1566 break;
1567 case 1: /* above */
1568 if(term.c.y > 1)
1569 tclearregion(0, 0, term.col-1, term.c.y-1);
1570 tclearregion(0, term.c.y, term.c.x, term.c.y);
1571 break;
1572 case 2: /* all */
1573 tclearregion(0, 0, term.col-1, term.row-1);
1574 break;
1575 default:
1576 goto unknown;
1577 }
1578 break;
1579 case 'K': /* EL -- Clear line */
1580 switch(csiescseq.arg[0]) {
1581 case 0: /* right */
1582 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1583 break;
1584 case 1: /* left */
1585 tclearregion(0, term.c.y, term.c.x, term.c.y);
1586 break;
1587 case 2: /* all */
1588 tclearregion(0, term.c.y, term.col-1, term.c.y);
1589 break;
1590 }
1591 break;
1592 case 'S': /* SU -- Scroll <n> line up */
1593 DEFAULT(csiescseq.arg[0], 1);
1594 tscrollup(term.top, csiescseq.arg[0]);
1595 break;
1596 case 'T': /* SD -- Scroll <n> line down */
1597 DEFAULT(csiescseq.arg[0], 1);
1598 tscrolldown(term.top, csiescseq.arg[0]);
1599 break;
1600 case 'L': /* IL -- Insert <n> blank lines */
1601 DEFAULT(csiescseq.arg[0], 1);
1602 tinsertblankline(csiescseq.arg[0]);
1603 break;
1604 case 'l': /* RM -- Reset Mode */
1605 tsetmode(csiescseq.priv, 0, csiescseq.arg, csiescseq.narg);
1606 break;
1607 case 'M': /* DL -- Delete <n> lines */
1608 DEFAULT(csiescseq.arg[0], 1);
1609 tdeleteline(csiescseq.arg[0]);
1610 break;
1611 case 'X': /* ECH -- Erase <n> char */
1612 DEFAULT(csiescseq.arg[0], 1);
1613 tclearregion(term.c.x, term.c.y, term.c.x + csiescseq.arg[0], term.c.y);
1614 break;
1615 case 'P': /* DCH -- Delete <n> char */
1616 DEFAULT(csiescseq.arg[0], 1);
1617 tdeletechar(csiescseq.arg[0]);
1618 break;
1619 case 'Z': /* CBT -- Cursor Backward Tabulation <n> tab stops */
1620 DEFAULT(csiescseq.arg[0], 1);
1621 while(csiescseq.arg[0]--)
1622 tputtab(0);
1623 break;
1624 case 'd': /* VPA -- Move to <row> */
1625 DEFAULT(csiescseq.arg[0], 1);
1626 tmoveto(term.c.x, csiescseq.arg[0]-1);
1627 break;
1628 case 'h': /* SM -- Set terminal mode */
1629 tsetmode(csiescseq.priv, 1, csiescseq.arg, csiescseq.narg);
1630 break;
1631 case 'm': /* SGR -- Terminal attribute (color) */
1632 tsetattr(csiescseq.arg, csiescseq.narg);
1633 break;
1634 case 'r': /* DECSTBM -- Set Scrolling Region */
1635 if(csiescseq.priv) {
1636 goto unknown;
1637 } else {
1638 DEFAULT(csiescseq.arg[0], 1);
1639 DEFAULT(csiescseq.arg[1], term.row);
1640 tsetscroll(csiescseq.arg[0]-1, csiescseq.arg[1]-1);
1641 tmoveto(0, 0);
1642 }
1643 break;
1644 case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
1645 tcursor(CURSOR_SAVE);
1646 break;
1647 case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
1648 tcursor(CURSOR_LOAD);
1649 break;
1650 }
1651 }
1652
1653 void
1654 csidump(void) {
1655 int i;
1656 uint c;
1657
1658 printf("ESC[");
1659 for(i = 0; i < csiescseq.len; i++) {
1660 c = csiescseq.buf[i] & 0xff;
1661 if(isprint(c)) {
1662 putchar(c);
1663 } else if(c == '\n') {
1664 printf("(\\n)");
1665 } else if(c == '\r') {
1666 printf("(\\r)");
1667 } else if(c == 0x1b) {
1668 printf("(\\e)");
1669 } else {
1670 printf("(%02x)", c);
1671 }
1672 }
1673 putchar('\n');
1674 }
1675
1676 void
1677 csireset(void) {
1678 memset(&csiescseq, 0, sizeof(csiescseq));
1679 }
1680
1681 void
1682 strhandle(void) {
1683 char *p;
1684
1685 /*
1686 * TODO: make this being useful in case of color palette change.
1687 */
1688 strparse();
1689
1690 p = strescseq.buf;
1691
1692 switch(strescseq.type) {
1693 case ']': /* OSC -- Operating System Command */
1694 switch(p[0]) {
1695 case '0':
1696 case '1':
1697 case '2':
1698 /*
1699 * TODO: Handle special chars in string, like umlauts.
1700 */
1701 if(p[1] == ';') {
1702 XStoreName(xw.dpy, xw.win, strescseq.buf+2);
1703 }
1704 break;
1705 case ';':
1706 XStoreName(xw.dpy, xw.win, strescseq.buf+1);
1707 break;
1708 case '4': /* TODO: Set color (arg0) to "rgb:%hexr/$hexg/$hexb" (arg1) */
1709 break;
1710 default:
1711 fprintf(stderr, "erresc: unknown str ");
1712 strdump();
1713 break;
1714 }
1715 break;
1716 case 'k': /* old title set compatibility */
1717 XStoreName(xw.dpy, xw.win, strescseq.buf);
1718 break;
1719 case 'P': /* DSC -- Device Control String */
1720 case '_': /* APC -- Application Program Command */
1721 case '^': /* PM -- Privacy Message */
1722 default:
1723 fprintf(stderr, "erresc: unknown str ");
1724 strdump();
1725 /* die(""); */
1726 break;
1727 }
1728 }
1729
1730 void
1731 strparse(void) {
1732 /*
1733 * TODO: Implement parsing like for CSI when required.
1734 * Format: ESC type cmd ';' arg0 [';' argn] ESC \
1735 */
1736 return;
1737 }
1738
1739 void
1740 strdump(void) {
1741 int i;
1742 uint c;
1743
1744 printf("ESC%c", strescseq.type);
1745 for(i = 0; i < strescseq.len; i++) {
1746 c = strescseq.buf[i] & 0xff;
1747 if(isprint(c)) {
1748 putchar(c);
1749 } else if(c == '\n') {
1750 printf("(\\n)");
1751 } else if(c == '\r') {
1752 printf("(\\r)");
1753 } else if(c == 0x1b) {
1754 printf("(\\e)");
1755 } else {
1756 printf("(%02x)", c);
1757 }
1758 }
1759 printf("ESC\\\n");
1760 }
1761
1762 void
1763 strreset(void) {
1764 memset(&strescseq, 0, sizeof(strescseq));
1765 }
1766
1767 void
1768 tputtab(bool forward) {
1769 uint x = term.c.x;
1770
1771 if(forward) {
1772 if(x == term.col)
1773 return;
1774 for(++x; x < term.col && !term.tabs[x]; ++x)
1775 /* nothing */ ;
1776 } else {
1777 if(x == 0)
1778 return;
1779 for(--x; x > 0 && !term.tabs[x]; --x)
1780 /* nothing */ ;
1781 }
1782 tmoveto(x, term.c.y);
1783 }
1784
1785 void
1786 tputc(char *c, int len) {
1787 uchar ascii = *c;
1788
1789 if(iofd != -1)
1790 write(iofd, c, len);
1791
1792 switch(ascii) {
1793 case '\t':
1794 tputtab(1);
1795 return;
1796 case '\b':
1797 tmoveto(term.c.x-1, term.c.y);
1798 return;
1799 case '\r':
1800 tmoveto(0, term.c.y);
1801 return;
1802 case '\f':
1803 case '\v':
1804 case '\n':
1805 /* go to first col if the mode is set */
1806 tnewline(IS_SET(MODE_CRLF));
1807 return;
1808 case '\a':
1809 if(term.esc & ESC_STR)
1810 break;
1811
1812 if(!(xw.state & WIN_FOCUSED))
1813 xseturgency(1);
1814 return;
1815 case '\033':
1816 csireset();
1817 term.esc = ESC_START;
1818 return;
1819 }
1820
1821 if(term.esc & ESC_START) {
1822 if(term.esc & ESC_CSI) {
1823 csiescseq.buf[csiescseq.len++] = ascii;
1824 if(BETWEEN(ascii, 0x40, 0x7E)
1825 || csiescseq.len >= ESC_BUF_SIZ) {
1826 term.esc = 0;
1827 csiparse(), csihandle();
1828 }
1829 } else if(term.esc & ESC_STR) {
1830 switch(ascii) {
1831 case '\033':
1832 term.esc = ESC_START | ESC_STR_END;
1833 break;
1834 case '\a': /* backwards compatibility to xterm */
1835 term.esc = 0;
1836 strhandle();
1837 break;
1838 default:
1839 strescseq.buf[strescseq.len++] = ascii;
1840 if(strescseq.len+1 >= STR_BUF_SIZ) {
1841 term.esc = 0;
1842 strhandle();
1843 }
1844 }
1845 } else if(term.esc & ESC_STR_END) {
1846 term.esc = 0;
1847 if(ascii == '\\')
1848 strhandle();
1849 } else if(term.esc & ESC_ALTCHARSET) {
1850 switch(ascii) {
1851 case '0': /* Line drawing set */
1852 term.c.attr.mode |= ATTR_GFX;
1853 break;
1854 case 'B': /* USASCII */
1855 term.c.attr.mode &= ~ATTR_GFX;
1856 break;
1857 case 'A': /* UK (IGNORED) */
1858 case '<': /* multinational charset (IGNORED) */
1859 case '5': /* Finnish (IGNORED) */
1860 case 'C': /* Finnish (IGNORED) */
1861 case 'K': /* German (IGNORED) */
1862 break;
1863 default:
1864 fprintf(stderr, "esc unhandled charset: ESC ( %c\n", ascii);
1865 }
1866 term.esc = 0;
1867 } else {
1868 switch(ascii) {
1869 case '[':
1870 term.esc |= ESC_CSI;
1871 break;
1872 case 'P': /* DCS -- Device Control String */
1873 case '_': /* APC -- Application Program Command */
1874 case '^': /* PM -- Privacy Message */
1875 case ']': /* OSC -- Operating System Command */
1876 case 'k': /* old title set compatibility */
1877 strreset();
1878 strescseq.type = ascii;
1879 term.esc |= ESC_STR;
1880 break;
1881 case '(': /* set primary charset G0 */
1882 term.esc |= ESC_ALTCHARSET;
1883 break;
1884 case ')': /* set secondary charset G1 (IGNORED) */
1885 case '*': /* set tertiary charset G2 (IGNORED) */
1886 case '+': /* set quaternary charset G3 (IGNORED) */
1887 term.esc = 0;
1888 break;
1889 case 'D': /* IND -- Linefeed */
1890 if(term.c.y == term.bot) {
1891 tscrollup(term.top, 1);
1892 } else {
1893 tmoveto(term.c.x, term.c.y+1);
1894 }
1895 term.esc = 0;
1896 break;
1897 case 'E': /* NEL -- Next line */
1898 tnewline(1); /* always go to first col */
1899 term.esc = 0;
1900 break;
1901 case 'H': /* HTS -- Horizontal tab stop */
1902 term.tabs[term.c.x] = 1;
1903 term.esc = 0;
1904 break;
1905 case 'M': /* RI -- Reverse index */
1906 if(term.c.y == term.top) {
1907 tscrolldown(term.top, 1);
1908 } else {
1909 tmoveto(term.c.x, term.c.y-1);
1910 }
1911 term.esc = 0;
1912 break;
1913 case 'c': /* RIS -- Reset to inital state */
1914 treset();
1915 term.esc = 0;
1916 xresettitle();
1917 break;
1918 case '=': /* DECPAM -- Application keypad */
1919 term.mode |= MODE_APPKEYPAD;
1920 term.esc = 0;
1921 break;
1922 case '>': /* DECPNM -- Normal keypad */
1923 term.mode &= ~MODE_APPKEYPAD;
1924 term.esc = 0;
1925 break;
1926 case '7': /* DECSC -- Save Cursor */
1927 tcursor(CURSOR_SAVE);
1928 term.esc = 0;
1929 break;
1930 case '8': /* DECRC -- Restore Cursor */
1931 tcursor(CURSOR_LOAD);
1932 term.esc = 0;
1933 break;
1934 case '\\': /* ST -- Stop */
1935 term.esc = 0;
1936 break;
1937 default:
1938 fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n",
1939 (uchar) ascii, isprint(ascii)? ascii:'.');
1940 term.esc = 0;
1941 }
1942 }
1943 } else {
1944 if(sel.bx != -1 && BETWEEN(term.c.y, sel.by, sel.ey))
1945 sel.bx = -1;
1946 if(ascii >= '\020' || term.c.attr.mode & ATTR_GFX) {
1947 if(IS_SET(MODE_WRAP) && term.c.state & CURSOR_WRAPNEXT)
1948 tnewline(1); /* always go to first col */
1949 tsetchar(c);
1950 if(term.c.x+1 < term.col) {
1951 tmoveto(term.c.x+1, term.c.y);
1952 } else {
1953 term.c.state |= CURSOR_WRAPNEXT;
1954 }
1955 }
1956 }
1957 }
1958
1959 int
1960 tresize(int col, int row) {
1961 int i, x;
1962 int minrow = MIN(row, term.row);
1963 int mincol = MIN(col, term.col);
1964 int slide = term.c.y - row + 1;
1965 bool *bp;
1966
1967 if(col < 1 || row < 1)
1968 return 0;
1969
1970 /* free unneeded rows */
1971 i = 0;
1972 if(slide > 0) {
1973 /* slide screen to keep cursor where we expect it -
1974 * tscrollup would work here, but we can optimize to
1975 * memmove because we're freeing the earlier lines */
1976 for(/* i = 0 */; i < slide; i++) {
1977 free(term.line[i]);
1978 free(term.alt[i]);
1979 }
1980 memmove(term.line, term.line + slide, row * sizeof(Line));
1981 memmove(term.alt, term.alt + slide, row * sizeof(Line));
1982 }
1983 for(i += row; i < term.row; i++) {
1984 free(term.line[i]);
1985 free(term.alt[i]);
1986 }
1987
1988 /* resize to new height */
1989 term.line = xrealloc(term.line, row * sizeof(Line));
1990 term.alt = xrealloc(term.alt, row * sizeof(Line));
1991 term.dirty = xrealloc(term.dirty, row * sizeof(*term.dirty));
1992 term.tabs = xrealloc(term.tabs, col * sizeof(*term.tabs));
1993
1994 /* resize each row to new width, zero-pad if needed */
1995 for(i = 0; i < minrow; i++) {
1996 term.dirty[i] = 1;
1997 term.line[i] = xrealloc(term.line[i], col * sizeof(Glyph));
1998 term.alt[i] = xrealloc(term.alt[i], col * sizeof(Glyph));
1999 for(x = mincol; x < col; x++) {
2000 term.line[i][x].state = 0;
2001 term.alt[i][x].state = 0;
2002 }
2003 }
2004
2005 /* allocate any new rows */
2006 for(/* i == minrow */; i < row; i++) {
2007 term.dirty[i] = 1;
2008 term.line[i] = xcalloc(col, sizeof(Glyph));
2009 term.alt [i] = xcalloc(col, sizeof(Glyph));
2010 }
2011 if(col > term.col) {
2012 bp = term.tabs + term.col;
2013
2014 memset(bp, 0, sizeof(*term.tabs) * (col - term.col));
2015 while(--bp > term.tabs && !*bp)
2016 /* nothing */ ;
2017 for(bp += TAB; bp < term.tabs + col; bp += TAB)
2018 *bp = 1;
2019 }
2020 /* update terminal size */
2021 term.col = col, term.row = row;
2022 /* make use of the LIMIT in tmoveto */
2023 tmoveto(term.c.x, term.c.y);
2024 /* reset scrolling region */
2025 tsetscroll(0, row-1);
2026
2027 return (slide > 0);
2028 }
2029
2030 void
2031 xresize(int col, int row) {
2032 xw.tw = MAX(1, 2*BORDER + col * xw.cw);
2033 xw.th = MAX(1, 2*BORDER + row * xw.ch);
2034
2035 XftDrawChange(xw.xft_draw, xw.buf);
2036 }
2037
2038 void
2039 xloadcols(void) {
2040 int i, r, g, b;
2041 XRenderColor xft_color = { .alpha = 0 };
2042
2043 /* load colors [0-15] colors and [256-LEN(colorname)[ (config.h) */
2044 for(i = 0; i < LEN(colorname); i++) {
2045 if(!colorname[i])
2046 continue;
2047 if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, colorname[i], &dc.xft_col[i])) {
2048 die("Could not allocate color '%s'\n", colorname[i]);
2049 }
2050 }
2051
2052 /* load colors [16-255] ; same colors as xterm */
2053 for(i = 16, r = 0; r < 6; r++) {
2054 for(g = 0; g < 6; g++) {
2055 for(b = 0; b < 6; b++) {
2056 xft_color.red = r == 0 ? 0 : 0x3737 + 0x2828 * r;
2057 xft_color.green = g == 0 ? 0 : 0x3737 + 0x2828 * g;
2058 xft_color.blue = b == 0 ? 0 : 0x3737 + 0x2828 * b;
2059 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &xft_color, &dc.xft_col[i])) {
2060 die("Could not allocate color %d\n", i);
2061 }
2062 i++;
2063 }
2064 }
2065 }
2066
2067 for(r = 0; r < 24; r++, i++) {
2068 xft_color.red = xft_color.green = xft_color.blue = 0x0808 + 0x0a0a * r;
2069 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &xft_color,
2070 &dc.xft_col[i])) {
2071 die("Could not allocate color %d\n", i);
2072 }
2073 }
2074 }
2075
2076 void
2077 xtermclear(int col1, int row1, int col2, int row2) {
2078 XftDrawRect(xw.xft_draw,
2079 &dc.xft_col[IS_SET(MODE_REVERSE) ? DefaultFG : DefaultBG],
2080 BORDER + col1 * xw.cw,
2081 BORDER + row1 * xw.ch,
2082 (col2-col1+1) * xw.cw,
2083 (row2-row1+1) * xw.ch);
2084 }
2085
2086 /*
2087 * Absolute coordinates.
2088 */
2089 void
2090 xclear(int x1, int y1, int x2, int y2) {
2091 XftDrawRect(xw.xft_draw,
2092 &dc.xft_col[IS_SET(MODE_REVERSE) ? DefaultFG : DefaultBG],
2093 x1, y1, x2-x1, y2-y1);
2094 }
2095
2096 void
2097 xhints(void) {
2098 XClassHint class = {opt_class ? opt_class : TNAME, TNAME};
2099 XWMHints wm = {.flags = InputHint, .input = 1};
2100 XSizeHints *sizeh = NULL;
2101
2102 sizeh = XAllocSizeHints();
2103 if(xw.isfixed == False) {
2104 sizeh->flags = PSize | PResizeInc | PBaseSize;
2105 sizeh->height = xw.h;
2106 sizeh->width = xw.w;
2107 sizeh->height_inc = xw.ch;
2108 sizeh->width_inc = xw.cw;
2109 sizeh->base_height = 2*BORDER;
2110 sizeh->base_width = 2*BORDER;
2111 } else {
2112 sizeh->flags = PMaxSize | PMinSize;
2113 sizeh->min_width = sizeh->max_width = xw.fw;
2114 sizeh->min_height = sizeh->max_height = xw.fh;
2115 }
2116
2117 XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm, &class);
2118 XFree(sizeh);
2119 }
2120
2121 void
2122 xinitfont(Font *f, char *fontstr) {
2123 FcPattern *pattern, *match;
2124 FcResult result;
2125
2126 pattern = FcNameParse((FcChar8 *)fontstr);
2127 if(!pattern)
2128 die("st: can't open font %s\n", fontstr);
2129
2130 match = XftFontMatch(xw.dpy, xw.scr, pattern, &result);
2131 FcPatternDestroy(pattern);
2132 if(!match)
2133 die("st: can't open font %s\n", fontstr);
2134 if(!(f->xft_set = XftFontOpenPattern(xw.dpy, match))) {
2135 FcPatternDestroy(match);
2136 die("st: can't open font %s.\n", fontstr);
2137 }
2138
2139 f->ascent = f->xft_set->ascent;
2140 f->descent = f->xft_set->descent;
2141 f->lbearing = 0;
2142 f->rbearing = f->xft_set->max_advance_width;
2143
2144 f->height = f->xft_set->height;
2145 f->width = f->lbearing + f->rbearing;
2146 }
2147
2148 void
2149 initfonts(char *fontstr) {
2150 char *fstr;
2151
2152 xinitfont(&dc.font, fontstr);
2153 xw.cw = dc.font.width;
2154 xw.ch = dc.font.height;
2155
2156 fstr = smstrcat(fontstr, ":weight=bold", NULL);
2157 xinitfont(&dc.bfont, fstr);
2158 free(fstr);
2159
2160 fstr = smstrcat(fontstr, ":slant=italic,oblique", NULL);
2161 xinitfont(&dc.ifont, fstr);
2162 free(fstr);
2163
2164 fstr = smstrcat(fontstr, ":weight=bold:slant=italic,oblique", NULL);
2165 xinitfont(&dc.ibfont, fstr);
2166 free(fstr);
2167 }
2168
2169 void
2170 xinit(void) {
2171 XSetWindowAttributes attrs;
2172 Cursor cursor;
2173 Window parent;
2174 int sw, sh, major, minor;
2175
2176 if(!(xw.dpy = XOpenDisplay(NULL)))
2177 die("Can't open display\n");
2178 xw.scr = XDefaultScreen(xw.dpy);
2179 xw.vis = XDefaultVisual(xw.dpy, xw.scr);
2180
2181 /* font */
2182 initfonts((opt_font != NULL)? opt_font : FONT);
2183
2184 /* colors */
2185 xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
2186 xloadcols();
2187
2188 /* adjust fixed window geometry */
2189 if(xw.isfixed) {
2190 sw = DisplayWidth(xw.dpy, xw.scr);
2191 sh = DisplayHeight(xw.dpy, xw.scr);
2192 if(xw.fx < 0)
2193 xw.fx = sw + xw.fx - xw.fw - 1;
2194 if(xw.fy < 0)
2195 xw.fy = sh + xw.fy - xw.fh - 1;
2196
2197 xw.h = xw.fh;
2198 xw.w = xw.fw;
2199 } else {
2200 /* window - default size */
2201 xw.h = 2*BORDER + term.row * xw.ch;
2202 xw.w = 2*BORDER + term.col * xw.cw;
2203 xw.fx = 0;
2204 xw.fy = 0;
2205 }
2206
2207 attrs.background_pixel = dc.xft_col[DefaultBG].pixel;
2208 attrs.border_pixel = dc.xft_col[DefaultBG].pixel;
2209 attrs.bit_gravity = NorthWestGravity;
2210 attrs.event_mask = FocusChangeMask | KeyPressMask
2211 | ExposureMask | VisibilityChangeMask | StructureNotifyMask
2212 | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
2213 attrs.colormap = xw.cmap;
2214
2215 parent = opt_embed ? strtol(opt_embed, NULL, 0) : XRootWindow(xw.dpy, xw.scr);
2216 xw.win = XCreateWindow(xw.dpy, parent, xw.fx, xw.fy,
2217 xw.w, xw.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
2218 xw.vis,
2219 CWBackPixel | CWBorderPixel | CWBitGravity | CWEventMask
2220 | CWColormap,
2221 &attrs);
2222
2223 /* double buffering */
2224 if(!XdbeQueryExtension(xw.dpy, &major, &minor))
2225 die("Xdbe extension is not present\n");
2226 xw.buf = XdbeAllocateBackBufferName(xw.dpy, xw.win, XdbeCopied);
2227
2228 /* Xft rendering context */
2229 xw.xft_draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
2230
2231 /* input methods */
2232 xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL);
2233 xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
2234 | XIMStatusNothing, XNClientWindow, xw.win,
2235 XNFocusWindow, xw.win, NULL);
2236 /* gc */
2237 dc.gc = XCreateGC(xw.dpy, xw.win, 0, NULL);
2238
2239 /* white cursor, black outline */
2240 cursor = XCreateFontCursor(xw.dpy, XC_xterm);
2241 XDefineCursor(xw.dpy, xw.win, cursor);
2242 XRecolorCursor(xw.dpy, cursor,
2243 &(XColor){.red = 0xffff, .green = 0xffff, .blue = 0xffff},
2244 &(XColor){.red = 0x0000, .green = 0x0000, .blue = 0x0000});
2245
2246 xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
2247 xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
2248 XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
2249
2250 xresettitle();
2251 XMapWindow(xw.dpy, xw.win);
2252 xhints();
2253 XSync(xw.dpy, 0);
2254 }
2255
2256 void
2257 xdraws(char *s, Glyph base, int x, int y, int charlen, int bytelen) {
2258 int winx = BORDER + x * xw.cw, winy = BORDER + y * xw.ch,
2259 width = charlen * xw.cw;
2260 Font *font = &dc.font;
2261 XGlyphInfo extents;
2262 XftColor *fg = &dc.xft_col[base.fg], *bg = &dc.xft_col[base.bg],
2263 *temp, revfg, revbg;
2264 XRenderColor colfg, colbg;
2265
2266 if(base.mode & ATTR_REVERSE)
2267 temp = fg, fg = bg, bg = temp;
2268
2269 if(base.mode & ATTR_BOLD) {
2270 if(BETWEEN(base.fg, 0, 7)) {
2271 /* basic system colors */
2272 fg = &dc.xft_col[base.fg + 8];
2273 } else if(BETWEEN(base.fg, 16, 195)) {
2274 /* 256 colors */
2275 fg = &dc.xft_col[base.fg + 36];
2276 } else if(BETWEEN(base.fg, 232, 251)) {
2277 /* greyscale */
2278 fg = &dc.xft_col[base.fg + 4];
2279 }
2280 /*
2281 * Those ranges will not be brightened:
2282 * 8 - 15 – bright system colors
2283 * 196 - 231 – highest 256 color cube
2284 * 252 - 255 – brightest colors in grescale
2285 */
2286 font = &dc.bfont;
2287 }
2288
2289 if(base.mode & ATTR_ITALIC)
2290 font = &dc.ifont;
2291 if(base.mode & (ATTR_ITALIC|ATTR_ITALIC))
2292 font = &dc.ibfont;
2293
2294 if(IS_SET(MODE_REVERSE)) {
2295 if(fg == &dc.xft_col[DefaultFG]) {
2296 fg = &dc.xft_col[DefaultBG];
2297 } else {
2298 colfg.red = ~fg->color.red;
2299 colfg.green = ~fg->color.green;
2300 colfg.blue = ~fg->color.blue;
2301 colfg.alpha = fg->color.alpha;
2302 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
2303 fg = &revfg;
2304 }
2305
2306 if(bg == &dc.xft_col[DefaultBG]) {
2307 bg = &dc.xft_col[DefaultFG];
2308 } else {
2309 colbg.red = ~bg->color.red;
2310 colbg.green = ~bg->color.green;
2311 colbg.blue = ~bg->color.blue;
2312 colbg.alpha = bg->color.alpha;
2313 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &revbg);
2314 bg = &revbg;
2315 }
2316 }
2317
2318 XftTextExtentsUtf8(xw.dpy, font->xft_set, (FcChar8 *)s, bytelen,
2319 &extents);
2320 width = extents.xOff;
2321
2322 /* Intelligent cleaning up of the borders. */
2323 if(x == 0) {
2324 xclear(0, (y == 0)? 0 : winy, BORDER,
2325 winy + xw.ch + (y == term.row-1)? xw.h : 0);
2326 }
2327 if(x + charlen >= term.col-1) {
2328 xclear(winx + width, (y == 0)? 0 : winy, xw.w,
2329 winy + xw.ch + (y == term.row-1)? xw.h : 0);
2330 }
2331 if(y == 0)
2332 xclear(winx, 0, winx + width, BORDER);
2333 if(y == term.row-1)
2334 xclear(winx, winy + xw.ch, winx + width, xw.h);
2335
2336 XftDrawRect(xw.xft_draw, bg, winx, winy, width, xw.ch);
2337 XftDrawStringUtf8(xw.xft_draw, fg, font->xft_set, winx,
2338 winy + font->ascent, (FcChar8 *)s, bytelen);
2339
2340 if(base.mode & ATTR_UNDERLINE) {
2341 XftDrawRect(xw.xft_draw, fg, winx, winy + font->ascent + 1,
2342 width, 1);
2343 }
2344 }
2345
2346 void
2347 xdrawcursor(void) {
2348 static int oldx = 0, oldy = 0;
2349 int sl;
2350 Glyph g = {{' '}, ATTR_NULL, DefaultBG, DefaultCS, 0};
2351
2352 LIMIT(oldx, 0, term.col-1);
2353 LIMIT(oldy, 0, term.row-1);
2354
2355 if(term.line[term.c.y][term.c.x].state & GLYPH_SET)
2356 memcpy(g.c, term.line[term.c.y][term.c.x].c, UTF_SIZ);
2357
2358 /* remove the old cursor */
2359 if(term.line[oldy][oldx].state & GLYPH_SET) {
2360 sl = utf8size(term.line[oldy][oldx].c);
2361 xdraws(term.line[oldy][oldx].c, term.line[oldy][oldx], oldx,
2362 oldy, 1, sl);
2363 } else {
2364 xtermclear(oldx, oldy, oldx, oldy);
2365 }
2366
2367 /* draw the new one */
2368 if(!(term.c.state & CURSOR_HIDE)) {
2369 if(!(xw.state & WIN_FOCUSED))
2370 g.bg = DefaultUCS;
2371
2372 if(IS_SET(MODE_REVERSE))
2373 g.mode |= ATTR_REVERSE, g.fg = DefaultCS, g.bg = DefaultFG;
2374
2375 sl = utf8size(g.c);
2376 xdraws(g.c, g, term.c.x, term.c.y, 1, sl);
2377 oldx = term.c.x, oldy = term.c.y;
2378 }
2379 }
2380
2381 void
2382 xresettitle(void) {
2383 XStoreName(xw.dpy, xw.win, opt_title ? opt_title : "st");
2384 }
2385
2386 void
2387 redraw(void) {
2388 struct timespec tv = {0, REDRAW_TIMEOUT * 1000};
2389
2390 tfulldirt();
2391 draw();
2392 XSync(xw.dpy, False); /* necessary for a good tput flash */
2393 nanosleep(&tv, NULL);
2394 }
2395
2396 void
2397 draw(void) {
2398 XdbeSwapInfo swpinfo[1] = {{xw.win, XdbeCopied}};
2399
2400 drawregion(0, 0, term.col, term.row);
2401 XdbeSwapBuffers(xw.dpy, swpinfo, 1);
2402 }
2403
2404 void
2405 drawregion(int x1, int y1, int x2, int y2) {
2406 int ic, ib, x, y, ox, sl;
2407 Glyph base, new;
2408 char buf[DRAW_BUF_SIZ];
2409 bool ena_sel = sel.bx != -1, alt = IS_SET(MODE_ALTSCREEN);
2410
2411 if((sel.alt && !alt) || (!sel.alt && alt))
2412 ena_sel = 0;
2413 if(!(xw.state & WIN_VISIBLE))
2414 return;
2415
2416 for(y = y1; y < y2; y++) {
2417 if(!term.dirty[y])
2418 continue;
2419
2420 xtermclear(0, y, term.col, y);
2421 term.dirty[y] = 0;
2422 base = term.line[y][0];
2423 ic = ib = ox = 0;
2424 for(x = x1; x < x2; x++) {
2425 new = term.line[y][x];
2426 if(ena_sel && *(new.c) && selected(x, y))
2427 new.mode ^= ATTR_REVERSE;
2428 if(ib > 0 && (!(new.state & GLYPH_SET)
2429 || ATTRCMP(base, new)
2430 || ib >= DRAW_BUF_SIZ-UTF_SIZ)) {
2431 xdraws(buf, base, ox, y, ic, ib);
2432 ic = ib = 0;
2433 }
2434 if(new.state & GLYPH_SET) {
2435 if(ib == 0) {
2436 ox = x;
2437 base = new;
2438 }
2439 sl = utf8size(new.c);
2440 memcpy(buf+ib, new.c, sl);
2441 ib += sl;
2442 ++ic;
2443 }
2444 }
2445 if(ib > 0)
2446 xdraws(buf, base, ox, y, ic, ib);
2447 }
2448 xdrawcursor();
2449 }
2450
2451 void
2452 expose(XEvent *ev) {
2453 XExposeEvent *e = &ev->xexpose;
2454
2455 if(xw.state & WIN_REDRAW) {
2456 if(!e->count)
2457 xw.state &= ~WIN_REDRAW;
2458 }
2459 }
2460
2461 void
2462 visibility(XEvent *ev) {
2463 XVisibilityEvent *e = &ev->xvisibility;
2464
2465 if(e->state == VisibilityFullyObscured) {
2466 xw.state &= ~WIN_VISIBLE;
2467 } else if(!(xw.state & WIN_VISIBLE)) {
2468 /* need a full redraw for next Expose, not just a buf copy */
2469 xw.state |= WIN_VISIBLE | WIN_REDRAW;
2470 }
2471 }
2472
2473 void
2474 unmap(XEvent *ev) {
2475 xw.state &= ~WIN_VISIBLE;
2476 }
2477
2478 void
2479 xseturgency(int add) {
2480 XWMHints *h = XGetWMHints(xw.dpy, xw.win);
2481
2482 h->flags = add ? (h->flags | XUrgencyHint) : (h->flags & ~XUrgencyHint);
2483 XSetWMHints(xw.dpy, xw.win, h);
2484 XFree(h);
2485 }
2486
2487 void
2488 focus(XEvent *ev) {
2489 if(ev->type == FocusIn) {
2490 xw.state |= WIN_FOCUSED;
2491 xseturgency(0);
2492 } else {
2493 xw.state &= ~WIN_FOCUSED;
2494 }
2495 }
2496
2497 char*
2498 kmap(KeySym k, uint state) {
2499 int i;
2500 uint mask;
2501
2502 state &= ~Mod2Mask;
2503 for(i = 0; i < LEN(key); i++) {
2504 mask = key[i].mask;
2505
2506 if(key[i].k == k && ((state & mask) == mask
2507 || (mask == XK_NO_MOD && !state))) {
2508 return (char*)key[i].s;
2509 }
2510 }
2511 return NULL;
2512 }
2513
2514 void
2515 kpress(XEvent *ev) {
2516 XKeyEvent *e = &ev->xkey;
2517 KeySym ksym;
2518 char buf[32];
2519 char *customkey;
2520 int len;
2521 int meta;
2522 int shift;
2523 Status status;
2524
2525 if (IS_SET(MODE_KBDLOCK))
2526 return;
2527
2528 meta = e->state & Mod1Mask;
2529 shift = e->state & ShiftMask;
2530 len = XmbLookupString(xw.xic, e, buf, sizeof(buf), &ksym, &status);
2531
2532 /* 1. custom keys from config.h */
2533 if((customkey = kmap(ksym, e->state))) {
2534 ttywrite(customkey, strlen(customkey));
2535 /* 2. hardcoded (overrides X lookup) */
2536 } else {
2537 switch(ksym) {
2538 case XK_Up:
2539 case XK_Down:
2540 case XK_Left:
2541 case XK_Right:
2542 /* XXX: shift up/down doesn't work */
2543 sprintf(buf, "\033%c%c",
2544 IS_SET(MODE_APPKEYPAD) ? 'O' : '[',
2545 (shift ? "dacb":"DACB")[ksym - XK_Left]);
2546 ttywrite(buf, 3);
2547 break;
2548 case XK_Insert:
2549 if(shift)
2550 selpaste();
2551 break;
2552 case XK_Return:
2553 if(IS_SET(MODE_CRLF)) {
2554 ttywrite("\r\n", 2);
2555 } else {
2556 ttywrite("\r", 1);
2557 }
2558 break;
2559 /* 3. X lookup */
2560 default:
2561 if(len > 0) {
2562 if(meta && len == 1)
2563 ttywrite("\033", 1);
2564 ttywrite(buf, len);
2565 }
2566 break;
2567 }
2568 }
2569 }
2570
2571 void
2572 cmessage(XEvent *e) {
2573 /* See xembed specs
2574 http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html */
2575 if(e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
2576 if(e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
2577 xw.state |= WIN_FOCUSED;
2578 xseturgency(0);
2579 } else if(e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
2580 xw.state &= ~WIN_FOCUSED;
2581 }
2582 } else if(e->xclient.data.l[0] == xw.wmdeletewin) {
2583 /* Send SIGHUP to shell */
2584 kill(pid, SIGHUP);
2585 exit(EXIT_SUCCESS);
2586 }
2587 }
2588
2589 void
2590 resize(XEvent *e) {
2591 int col, row;
2592
2593 if(e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
2594 return;
2595
2596 xw.w = e->xconfigure.width;
2597 xw.h = e->xconfigure.height;
2598 col = (xw.w - 2*BORDER) / xw.cw;
2599 row = (xw.h - 2*BORDER) / xw.ch;
2600 if(col == term.col && row == term.row)
2601 return;
2602
2603 tresize(col, row);
2604 xresize(col, row);
2605 ttyresize();
2606 }
2607
2608 void
2609 run(void) {
2610 XEvent ev;
2611 fd_set rfd;
2612 int xfd = XConnectionNumber(xw.dpy), i;
2613 struct timeval drawtimeout, *tv = NULL;
2614
2615 for(i = 0;; i++) {
2616 FD_ZERO(&rfd);
2617 FD_SET(cmdfd, &rfd);
2618 FD_SET(xfd, &rfd);
2619 if(select(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, tv) < 0) {
2620 if(errno == EINTR)
2621 continue;
2622 die("select failed: %s\n", SERRNO);
2623 }
2624
2625 /*
2626 * Stop after a certain number of reads so the user does not
2627 * feel like the system is stuttering.
2628 */
2629 if(i < 1000 && FD_ISSET(cmdfd, &rfd)) {
2630 ttyread();
2631
2632 /*
2633 * Just wait a bit so it isn't disturbing the
2634 * user and the system is able to write something.
2635 */
2636 drawtimeout.tv_sec = 0;
2637 drawtimeout.tv_usec = 5;
2638 tv = &drawtimeout;
2639 continue;
2640 }
2641 i = 0;
2642 tv = NULL;
2643
2644 while(XPending(xw.dpy)) {
2645 XNextEvent(xw.dpy, &ev);
2646 if(XFilterEvent(&ev, xw.win))
2647 continue;
2648 if(handler[ev.type])
2649 (handler[ev.type])(&ev);
2650 }
2651
2652 draw();
2653 XFlush(xw.dpy);
2654 }
2655 }
2656
2657 int
2658 main(int argc, char *argv[]) {
2659 int i, bitm, xr, yr;
2660 uint wr, hr;
2661
2662 xw.fw = xw.fh = xw.fx = xw.fy = 0;
2663 xw.isfixed = False;
2664
2665 for(i = 1; i < argc; i++) {
2666 switch(argv[i][0] != '-' || argv[i][2] ? -1 : argv[i][1]) {
2667 case 'c':
2668 if(++i < argc)
2669 opt_class = argv[i];
2670 break;
2671 case 'e':
2672 /* eat every remaining arguments */
2673 if(++i < argc)
2674 opt_cmd = &argv[i];
2675 goto run;
2676 case 'f':
2677 if(++i < argc)
2678 opt_font = argv[i];
2679 break;
2680 case 'g':
2681 if(++i >= argc)
2682 break;
2683
2684 bitm = XParseGeometry(argv[i], &xr, &yr, &wr, &hr);
2685 if(bitm & XValue)
2686 xw.fx = xr;
2687 if(bitm & YValue)
2688 xw.fy = yr;
2689 if(bitm & WidthValue)
2690 xw.fw = (int)wr;
2691 if(bitm & HeightValue)
2692 xw.fh = (int)hr;
2693 if(bitm & XNegative && xw.fx == 0)
2694 xw.fx = -1;
2695 if(bitm & XNegative && xw.fy == 0)
2696 xw.fy = -1;
2697
2698 if(xw.fh != 0 && xw.fw != 0)
2699 xw.isfixed = True;
2700 break;
2701 case 'o':
2702 if(++i < argc)
2703 opt_io = argv[i];
2704 break;
2705 case 't':
2706 if(++i < argc)
2707 opt_title = argv[i];
2708 break;
2709 case 'v':
2710 default:
2711 die(USAGE);
2712 case 'w':
2713 if(++i < argc)
2714 opt_embed = argv[i];
2715 break;
2716 }
2717 }
2718
2719 run:
2720 setlocale(LC_CTYPE, "");
2721 tnew(80, 24);
2722 ttynew();
2723 xinit();
2724 selinit();
2725 run();
2726 return 0;
2727 }
2728