Xinqi Bao's Git

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