Xinqi Bao's Git

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