Xinqi Bao's Git

Add SI and SO 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': /* SO */
1818 term.c.attr.mode |= ATTR_GFX;
1819 break;
1820 case '\017': /* SI */
1821 term.c.attr.mode &= ~ATTR_GFX;
1822 return;
1823 case '\032': /* SUB */
1824 case '\030': /* CAN */
1825 csireset();
1826 return;
1827 default:
1828 /* case '\005': ENQ (IGNORED) */
1829 /* case '\000': NUL (IGNORED) */
1830 /* case '\021': XON (IGNORED) */
1831 /* case '\023': XOFF (IGNORED) */
1832 /* case 0177: DEL (IGNORED) */
1833 break;
1834 }
1835
1836 if(term.esc & ESC_START) {
1837 if(term.esc & ESC_CSI) {
1838 csiescseq.buf[csiescseq.len++] = ascii;
1839 if(BETWEEN(ascii, 0x40, 0x7E)
1840 || csiescseq.len >= ESC_BUF_SIZ) {
1841 term.esc = 0;
1842 csiparse(), csihandle();
1843 }
1844 } else if(term.esc & ESC_STR) {
1845 switch(ascii) {
1846 case '\033':
1847 term.esc = ESC_START | ESC_STR_END;
1848 break;
1849 case '\a': /* backwards compatibility to xterm */
1850 term.esc = 0;
1851 strhandle();
1852 break;
1853 default:
1854 strescseq.buf[strescseq.len++] = ascii;
1855 if(strescseq.len+1 >= STR_BUF_SIZ) {
1856 term.esc = 0;
1857 strhandle();
1858 }
1859 }
1860 } else if(term.esc & ESC_STR_END) {
1861 term.esc = 0;
1862 if(ascii == '\\')
1863 strhandle();
1864 } else if(term.esc & ESC_ALTCHARSET) {
1865 switch(ascii) {
1866 case '0': /* Line drawing set */
1867 term.c.attr.mode |= ATTR_GFX;
1868 break;
1869 case 'B': /* USASCII */
1870 term.c.attr.mode &= ~ATTR_GFX;
1871 break;
1872 case 'A': /* UK (IGNORED) */
1873 case '<': /* multinational charset (IGNORED) */
1874 case '5': /* Finnish (IGNORED) */
1875 case 'C': /* Finnish (IGNORED) */
1876 case 'K': /* German (IGNORED) */
1877 break;
1878 default:
1879 fprintf(stderr, "esc unhandled charset: ESC ( %c\n", ascii);
1880 }
1881 term.esc = 0;
1882 } else {
1883 switch(ascii) {
1884 case '[':
1885 term.esc |= ESC_CSI;
1886 break;
1887 case 'P': /* DCS -- Device Control String */
1888 case '_': /* APC -- Application Program Command */
1889 case '^': /* PM -- Privacy Message */
1890 case ']': /* OSC -- Operating System Command */
1891 case 'k': /* old title set compatibility */
1892 strreset();
1893 strescseq.type = ascii;
1894 term.esc |= ESC_STR;
1895 break;
1896 case '(': /* set primary charset G0 */
1897 term.esc |= ESC_ALTCHARSET;
1898 break;
1899 case ')': /* set secondary charset G1 (IGNORED) */
1900 case '*': /* set tertiary charset G2 (IGNORED) */
1901 case '+': /* set quaternary charset G3 (IGNORED) */
1902 term.esc = 0;
1903 break;
1904 case 'D': /* IND -- Linefeed */
1905 if(term.c.y == term.bot) {
1906 tscrollup(term.top, 1);
1907 } else {
1908 tmoveto(term.c.x, term.c.y+1);
1909 }
1910 term.esc = 0;
1911 break;
1912 case 'E': /* NEL -- Next line */
1913 tnewline(1); /* always go to first col */
1914 term.esc = 0;
1915 break;
1916 case 'H': /* HTS -- Horizontal tab stop */
1917 term.tabs[term.c.x] = 1;
1918 term.esc = 0;
1919 break;
1920 case 'M': /* RI -- Reverse index */
1921 if(term.c.y == term.top) {
1922 tscrolldown(term.top, 1);
1923 } else {
1924 tmoveto(term.c.x, term.c.y-1);
1925 }
1926 term.esc = 0;
1927 break;
1928 case 'c': /* RIS -- Reset to inital state */
1929 treset();
1930 term.esc = 0;
1931 xresettitle();
1932 break;
1933 case '=': /* DECPAM -- Application keypad */
1934 term.mode |= MODE_APPKEYPAD;
1935 term.esc = 0;
1936 break;
1937 case '>': /* DECPNM -- Normal keypad */
1938 term.mode &= ~MODE_APPKEYPAD;
1939 term.esc = 0;
1940 break;
1941 case '7': /* DECSC -- Save Cursor */
1942 tcursor(CURSOR_SAVE);
1943 term.esc = 0;
1944 break;
1945 case '8': /* DECRC -- Restore Cursor */
1946 tcursor(CURSOR_LOAD);
1947 term.esc = 0;
1948 break;
1949 case '\\': /* ST -- Stop */
1950 term.esc = 0;
1951 break;
1952 default:
1953 fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n",
1954 (uchar) ascii, isprint(ascii)? ascii:'.');
1955 term.esc = 0;
1956 }
1957 }
1958 } else {
1959 if(sel.bx != -1 && BETWEEN(term.c.y, sel.by, sel.ey))
1960 sel.bx = -1;
1961 if(ascii >= '\020' || term.c.attr.mode & ATTR_GFX) {
1962 if(IS_SET(MODE_WRAP) && term.c.state & CURSOR_WRAPNEXT)
1963 tnewline(1); /* always go to first col */
1964 tsetchar(c);
1965 if(term.c.x+1 < term.col) {
1966 tmoveto(term.c.x+1, term.c.y);
1967 } else {
1968 term.c.state |= CURSOR_WRAPNEXT;
1969 }
1970 }
1971 }
1972 }
1973
1974 int
1975 tresize(int col, int row) {
1976 int i, x;
1977 int minrow = MIN(row, term.row);
1978 int mincol = MIN(col, term.col);
1979 int slide = term.c.y - row + 1;
1980 bool *bp;
1981
1982 if(col < 1 || row < 1)
1983 return 0;
1984
1985 /* free unneeded rows */
1986 i = 0;
1987 if(slide > 0) {
1988 /* slide screen to keep cursor where we expect it -
1989 * tscrollup would work here, but we can optimize to
1990 * memmove because we're freeing the earlier lines */
1991 for(/* i = 0 */; i < slide; i++) {
1992 free(term.line[i]);
1993 free(term.alt[i]);
1994 }
1995 memmove(term.line, term.line + slide, row * sizeof(Line));
1996 memmove(term.alt, term.alt + slide, row * sizeof(Line));
1997 }
1998 for(i += row; i < term.row; i++) {
1999 free(term.line[i]);
2000 free(term.alt[i]);
2001 }
2002
2003 /* resize to new height */
2004 term.line = xrealloc(term.line, row * sizeof(Line));
2005 term.alt = xrealloc(term.alt, row * sizeof(Line));
2006 term.dirty = xrealloc(term.dirty, row * sizeof(*term.dirty));
2007 term.tabs = xrealloc(term.tabs, col * sizeof(*term.tabs));
2008
2009 /* resize each row to new width, zero-pad if needed */
2010 for(i = 0; i < minrow; i++) {
2011 term.dirty[i] = 1;
2012 term.line[i] = xrealloc(term.line[i], col * sizeof(Glyph));
2013 term.alt[i] = xrealloc(term.alt[i], col * sizeof(Glyph));
2014 for(x = mincol; x < col; x++) {
2015 term.line[i][x].state = 0;
2016 term.alt[i][x].state = 0;
2017 }
2018 }
2019
2020 /* allocate any new rows */
2021 for(/* i == minrow */; i < row; i++) {
2022 term.dirty[i] = 1;
2023 term.line[i] = xcalloc(col, sizeof(Glyph));
2024 term.alt [i] = xcalloc(col, sizeof(Glyph));
2025 }
2026 if(col > term.col) {
2027 bp = term.tabs + term.col;
2028
2029 memset(bp, 0, sizeof(*term.tabs) * (col - term.col));
2030 while(--bp > term.tabs && !*bp)
2031 /* nothing */ ;
2032 for(bp += TAB; bp < term.tabs + col; bp += TAB)
2033 *bp = 1;
2034 }
2035 /* update terminal size */
2036 term.col = col, term.row = row;
2037 /* make use of the LIMIT in tmoveto */
2038 tmoveto(term.c.x, term.c.y);
2039 /* reset scrolling region */
2040 tsetscroll(0, row-1);
2041
2042 return (slide > 0);
2043 }
2044
2045 void
2046 xresize(int col, int row) {
2047 xw.tw = MAX(1, 2*BORDER + col * xw.cw);
2048 xw.th = MAX(1, 2*BORDER + row * xw.ch);
2049
2050 XftDrawChange(xw.xft_draw, xw.buf);
2051 }
2052
2053 void
2054 xloadcols(void) {
2055 int i, r, g, b;
2056 XRenderColor xft_color = { .alpha = 0 };
2057
2058 /* load colors [0-15] colors and [256-LEN(colorname)[ (config.h) */
2059 for(i = 0; i < LEN(colorname); i++) {
2060 if(!colorname[i])
2061 continue;
2062 if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, colorname[i], &dc.xft_col[i])) {
2063 die("Could not allocate color '%s'\n", colorname[i]);
2064 }
2065 }
2066
2067 /* load colors [16-255] ; same colors as xterm */
2068 for(i = 16, r = 0; r < 6; r++) {
2069 for(g = 0; g < 6; g++) {
2070 for(b = 0; b < 6; b++) {
2071 xft_color.red = r == 0 ? 0 : 0x3737 + 0x2828 * r;
2072 xft_color.green = g == 0 ? 0 : 0x3737 + 0x2828 * g;
2073 xft_color.blue = b == 0 ? 0 : 0x3737 + 0x2828 * b;
2074 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &xft_color, &dc.xft_col[i])) {
2075 die("Could not allocate color %d\n", i);
2076 }
2077 i++;
2078 }
2079 }
2080 }
2081
2082 for(r = 0; r < 24; r++, i++) {
2083 xft_color.red = xft_color.green = xft_color.blue = 0x0808 + 0x0a0a * r;
2084 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &xft_color,
2085 &dc.xft_col[i])) {
2086 die("Could not allocate color %d\n", i);
2087 }
2088 }
2089 }
2090
2091 void
2092 xtermclear(int col1, int row1, int col2, int row2) {
2093 XftDrawRect(xw.xft_draw,
2094 &dc.xft_col[IS_SET(MODE_REVERSE) ? DefaultFG : DefaultBG],
2095 BORDER + col1 * xw.cw,
2096 BORDER + row1 * xw.ch,
2097 (col2-col1+1) * xw.cw,
2098 (row2-row1+1) * xw.ch);
2099 }
2100
2101 /*
2102 * Absolute coordinates.
2103 */
2104 void
2105 xclear(int x1, int y1, int x2, int y2) {
2106 XftDrawRect(xw.xft_draw,
2107 &dc.xft_col[IS_SET(MODE_REVERSE) ? DefaultFG : DefaultBG],
2108 x1, y1, x2-x1, y2-y1);
2109 }
2110
2111 void
2112 xhints(void) {
2113 XClassHint class = {opt_class ? opt_class : TNAME, TNAME};
2114 XWMHints wm = {.flags = InputHint, .input = 1};
2115 XSizeHints *sizeh = NULL;
2116
2117 sizeh = XAllocSizeHints();
2118 if(xw.isfixed == False) {
2119 sizeh->flags = PSize | PResizeInc | PBaseSize;
2120 sizeh->height = xw.h;
2121 sizeh->width = xw.w;
2122 sizeh->height_inc = xw.ch;
2123 sizeh->width_inc = xw.cw;
2124 sizeh->base_height = 2*BORDER;
2125 sizeh->base_width = 2*BORDER;
2126 } else {
2127 sizeh->flags = PMaxSize | PMinSize;
2128 sizeh->min_width = sizeh->max_width = xw.fw;
2129 sizeh->min_height = sizeh->max_height = xw.fh;
2130 }
2131
2132 XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm, &class);
2133 XFree(sizeh);
2134 }
2135
2136 void
2137 xinitfont(Font *f, char *fontstr) {
2138 FcPattern *pattern, *match;
2139 FcResult result;
2140
2141 pattern = FcNameParse((FcChar8 *)fontstr);
2142 if(!pattern)
2143 die("st: can't open font %s\n", fontstr);
2144
2145 match = XftFontMatch(xw.dpy, xw.scr, pattern, &result);
2146 FcPatternDestroy(pattern);
2147 if(!match)
2148 die("st: can't open font %s\n", fontstr);
2149 if(!(f->xft_set = XftFontOpenPattern(xw.dpy, match))) {
2150 FcPatternDestroy(match);
2151 die("st: can't open font %s.\n", fontstr);
2152 }
2153
2154 f->ascent = f->xft_set->ascent;
2155 f->descent = f->xft_set->descent;
2156 f->lbearing = 0;
2157 f->rbearing = f->xft_set->max_advance_width;
2158
2159 f->height = f->xft_set->height;
2160 f->width = f->lbearing + f->rbearing;
2161 }
2162
2163 void
2164 initfonts(char *fontstr) {
2165 char *fstr;
2166
2167 xinitfont(&dc.font, fontstr);
2168 xw.cw = dc.font.width;
2169 xw.ch = dc.font.height;
2170
2171 fstr = smstrcat(fontstr, ":weight=bold", NULL);
2172 xinitfont(&dc.bfont, fstr);
2173 free(fstr);
2174
2175 fstr = smstrcat(fontstr, ":slant=italic,oblique", NULL);
2176 xinitfont(&dc.ifont, fstr);
2177 free(fstr);
2178
2179 fstr = smstrcat(fontstr, ":weight=bold:slant=italic,oblique", NULL);
2180 xinitfont(&dc.ibfont, fstr);
2181 free(fstr);
2182 }
2183
2184 void
2185 xinit(void) {
2186 XSetWindowAttributes attrs;
2187 Cursor cursor;
2188 Window parent;
2189 int sw, sh, major, minor;
2190
2191 if(!(xw.dpy = XOpenDisplay(NULL)))
2192 die("Can't open display\n");
2193 xw.scr = XDefaultScreen(xw.dpy);
2194 xw.vis = XDefaultVisual(xw.dpy, xw.scr);
2195
2196 /* font */
2197 initfonts((opt_font != NULL)? opt_font : FONT);
2198
2199 /* colors */
2200 xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
2201 xloadcols();
2202
2203 /* adjust fixed window geometry */
2204 if(xw.isfixed) {
2205 sw = DisplayWidth(xw.dpy, xw.scr);
2206 sh = DisplayHeight(xw.dpy, xw.scr);
2207 if(xw.fx < 0)
2208 xw.fx = sw + xw.fx - xw.fw - 1;
2209 if(xw.fy < 0)
2210 xw.fy = sh + xw.fy - xw.fh - 1;
2211
2212 xw.h = xw.fh;
2213 xw.w = xw.fw;
2214 } else {
2215 /* window - default size */
2216 xw.h = 2*BORDER + term.row * xw.ch;
2217 xw.w = 2*BORDER + term.col * xw.cw;
2218 xw.fx = 0;
2219 xw.fy = 0;
2220 }
2221
2222 attrs.background_pixel = dc.xft_col[DefaultBG].pixel;
2223 attrs.border_pixel = dc.xft_col[DefaultBG].pixel;
2224 attrs.bit_gravity = NorthWestGravity;
2225 attrs.event_mask = FocusChangeMask | KeyPressMask
2226 | ExposureMask | VisibilityChangeMask | StructureNotifyMask
2227 | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
2228 attrs.colormap = xw.cmap;
2229
2230 parent = opt_embed ? strtol(opt_embed, NULL, 0) : XRootWindow(xw.dpy, xw.scr);
2231 xw.win = XCreateWindow(xw.dpy, parent, xw.fx, xw.fy,
2232 xw.w, xw.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
2233 xw.vis,
2234 CWBackPixel | CWBorderPixel | CWBitGravity | CWEventMask
2235 | CWColormap,
2236 &attrs);
2237
2238 /* double buffering */
2239 if(!XdbeQueryExtension(xw.dpy, &major, &minor))
2240 die("Xdbe extension is not present\n");
2241 xw.buf = XdbeAllocateBackBufferName(xw.dpy, xw.win, XdbeCopied);
2242
2243 /* Xft rendering context */
2244 xw.xft_draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
2245
2246 /* input methods */
2247 xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL);
2248 xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
2249 | XIMStatusNothing, XNClientWindow, xw.win,
2250 XNFocusWindow, xw.win, NULL);
2251 /* gc */
2252 dc.gc = XCreateGC(xw.dpy, xw.win, 0, NULL);
2253
2254 /* white cursor, black outline */
2255 cursor = XCreateFontCursor(xw.dpy, XC_xterm);
2256 XDefineCursor(xw.dpy, xw.win, cursor);
2257 XRecolorCursor(xw.dpy, cursor,
2258 &(XColor){.red = 0xffff, .green = 0xffff, .blue = 0xffff},
2259 &(XColor){.red = 0x0000, .green = 0x0000, .blue = 0x0000});
2260
2261 xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
2262 xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
2263 XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
2264
2265 xresettitle();
2266 XMapWindow(xw.dpy, xw.win);
2267 xhints();
2268 XSync(xw.dpy, 0);
2269 }
2270
2271 void
2272 xdraws(char *s, Glyph base, int x, int y, int charlen, int bytelen) {
2273 int winx = BORDER + x * xw.cw, winy = BORDER + y * xw.ch,
2274 width = charlen * xw.cw;
2275 Font *font = &dc.font;
2276 XGlyphInfo extents;
2277 XftColor *fg = &dc.xft_col[base.fg], *bg = &dc.xft_col[base.bg],
2278 *temp, revfg, revbg;
2279 XRenderColor colfg, colbg;
2280
2281 if(base.mode & ATTR_REVERSE)
2282 temp = fg, fg = bg, bg = temp;
2283
2284 if(base.mode & ATTR_BOLD) {
2285 if(BETWEEN(base.fg, 0, 7)) {
2286 /* basic system colors */
2287 fg = &dc.xft_col[base.fg + 8];
2288 } else if(BETWEEN(base.fg, 16, 195)) {
2289 /* 256 colors */
2290 fg = &dc.xft_col[base.fg + 36];
2291 } else if(BETWEEN(base.fg, 232, 251)) {
2292 /* greyscale */
2293 fg = &dc.xft_col[base.fg + 4];
2294 }
2295 /*
2296 * Those ranges will not be brightened:
2297 * 8 - 15 – bright system colors
2298 * 196 - 231 – highest 256 color cube
2299 * 252 - 255 – brightest colors in grescale
2300 */
2301 font = &dc.bfont;
2302 }
2303
2304 if(base.mode & ATTR_ITALIC)
2305 font = &dc.ifont;
2306 if(base.mode & (ATTR_ITALIC|ATTR_ITALIC))
2307 font = &dc.ibfont;
2308
2309 if(IS_SET(MODE_REVERSE)) {
2310 if(fg == &dc.xft_col[DefaultFG]) {
2311 fg = &dc.xft_col[DefaultBG];
2312 } else {
2313 colfg.red = ~fg->color.red;
2314 colfg.green = ~fg->color.green;
2315 colfg.blue = ~fg->color.blue;
2316 colfg.alpha = fg->color.alpha;
2317 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
2318 fg = &revfg;
2319 }
2320
2321 if(bg == &dc.xft_col[DefaultBG]) {
2322 bg = &dc.xft_col[DefaultFG];
2323 } else {
2324 colbg.red = ~bg->color.red;
2325 colbg.green = ~bg->color.green;
2326 colbg.blue = ~bg->color.blue;
2327 colbg.alpha = bg->color.alpha;
2328 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &revbg);
2329 bg = &revbg;
2330 }
2331 }
2332
2333 XftTextExtentsUtf8(xw.dpy, font->xft_set, (FcChar8 *)s, bytelen,
2334 &extents);
2335 width = extents.xOff;
2336
2337 /* Intelligent cleaning up of the borders. */
2338 if(x == 0) {
2339 xclear(0, (y == 0)? 0 : winy, BORDER,
2340 winy + xw.ch + (y == term.row-1)? xw.h : 0);
2341 }
2342 if(x + charlen >= term.col-1) {
2343 xclear(winx + width, (y == 0)? 0 : winy, xw.w,
2344 winy + xw.ch + (y == term.row-1)? xw.h : 0);
2345 }
2346 if(y == 0)
2347 xclear(winx, 0, winx + width, BORDER);
2348 if(y == term.row-1)
2349 xclear(winx, winy + xw.ch, winx + width, xw.h);
2350
2351 XftDrawRect(xw.xft_draw, bg, winx, winy, width, xw.ch);
2352 XftDrawStringUtf8(xw.xft_draw, fg, font->xft_set, winx,
2353 winy + font->ascent, (FcChar8 *)s, bytelen);
2354
2355 if(base.mode & ATTR_UNDERLINE) {
2356 XftDrawRect(xw.xft_draw, fg, winx, winy + font->ascent + 1,
2357 width, 1);
2358 }
2359 }
2360
2361 void
2362 xdrawcursor(void) {
2363 static int oldx = 0, oldy = 0;
2364 int sl;
2365 Glyph g = {{' '}, ATTR_NULL, DefaultBG, DefaultCS, 0};
2366
2367 LIMIT(oldx, 0, term.col-1);
2368 LIMIT(oldy, 0, term.row-1);
2369
2370 if(term.line[term.c.y][term.c.x].state & GLYPH_SET)
2371 memcpy(g.c, term.line[term.c.y][term.c.x].c, UTF_SIZ);
2372
2373 /* remove the old cursor */
2374 if(term.line[oldy][oldx].state & GLYPH_SET) {
2375 sl = utf8size(term.line[oldy][oldx].c);
2376 xdraws(term.line[oldy][oldx].c, term.line[oldy][oldx], oldx,
2377 oldy, 1, sl);
2378 } else {
2379 xtermclear(oldx, oldy, oldx, oldy);
2380 }
2381
2382 /* draw the new one */
2383 if(!(term.c.state & CURSOR_HIDE)) {
2384 if(!(xw.state & WIN_FOCUSED))
2385 g.bg = DefaultUCS;
2386
2387 if(IS_SET(MODE_REVERSE))
2388 g.mode |= ATTR_REVERSE, g.fg = DefaultCS, g.bg = DefaultFG;
2389
2390 sl = utf8size(g.c);
2391 xdraws(g.c, g, term.c.x, term.c.y, 1, sl);
2392 oldx = term.c.x, oldy = term.c.y;
2393 }
2394 }
2395
2396 void
2397 xresettitle(void) {
2398 XStoreName(xw.dpy, xw.win, opt_title ? opt_title : "st");
2399 }
2400
2401 void
2402 redraw(void) {
2403 struct timespec tv = {0, REDRAW_TIMEOUT * 1000};
2404
2405 tfulldirt();
2406 draw();
2407 XSync(xw.dpy, False); /* necessary for a good tput flash */
2408 nanosleep(&tv, NULL);
2409 }
2410
2411 void
2412 draw(void) {
2413 XdbeSwapInfo swpinfo[1] = {{xw.win, XdbeCopied}};
2414
2415 drawregion(0, 0, term.col, term.row);
2416 XdbeSwapBuffers(xw.dpy, swpinfo, 1);
2417 }
2418
2419 void
2420 drawregion(int x1, int y1, int x2, int y2) {
2421 int ic, ib, x, y, ox, sl;
2422 Glyph base, new;
2423 char buf[DRAW_BUF_SIZ];
2424 bool ena_sel = sel.bx != -1, alt = IS_SET(MODE_ALTSCREEN);
2425
2426 if((sel.alt && !alt) || (!sel.alt && alt))
2427 ena_sel = 0;
2428 if(!(xw.state & WIN_VISIBLE))
2429 return;
2430
2431 for(y = y1; y < y2; y++) {
2432 if(!term.dirty[y])
2433 continue;
2434
2435 xtermclear(0, y, term.col, y);
2436 term.dirty[y] = 0;
2437 base = term.line[y][0];
2438 ic = ib = ox = 0;
2439 for(x = x1; x < x2; x++) {
2440 new = term.line[y][x];
2441 if(ena_sel && *(new.c) && selected(x, y))
2442 new.mode ^= ATTR_REVERSE;
2443 if(ib > 0 && (!(new.state & GLYPH_SET)
2444 || ATTRCMP(base, new)
2445 || ib >= DRAW_BUF_SIZ-UTF_SIZ)) {
2446 xdraws(buf, base, ox, y, ic, ib);
2447 ic = ib = 0;
2448 }
2449 if(new.state & GLYPH_SET) {
2450 if(ib == 0) {
2451 ox = x;
2452 base = new;
2453 }
2454 sl = utf8size(new.c);
2455 memcpy(buf+ib, new.c, sl);
2456 ib += sl;
2457 ++ic;
2458 }
2459 }
2460 if(ib > 0)
2461 xdraws(buf, base, ox, y, ic, ib);
2462 }
2463 xdrawcursor();
2464 }
2465
2466 void
2467 expose(XEvent *ev) {
2468 XExposeEvent *e = &ev->xexpose;
2469
2470 if(xw.state & WIN_REDRAW) {
2471 if(!e->count)
2472 xw.state &= ~WIN_REDRAW;
2473 }
2474 }
2475
2476 void
2477 visibility(XEvent *ev) {
2478 XVisibilityEvent *e = &ev->xvisibility;
2479
2480 if(e->state == VisibilityFullyObscured) {
2481 xw.state &= ~WIN_VISIBLE;
2482 } else if(!(xw.state & WIN_VISIBLE)) {
2483 /* need a full redraw for next Expose, not just a buf copy */
2484 xw.state |= WIN_VISIBLE | WIN_REDRAW;
2485 }
2486 }
2487
2488 void
2489 unmap(XEvent *ev) {
2490 xw.state &= ~WIN_VISIBLE;
2491 }
2492
2493 void
2494 xseturgency(int add) {
2495 XWMHints *h = XGetWMHints(xw.dpy, xw.win);
2496
2497 h->flags = add ? (h->flags | XUrgencyHint) : (h->flags & ~XUrgencyHint);
2498 XSetWMHints(xw.dpy, xw.win, h);
2499 XFree(h);
2500 }
2501
2502 void
2503 focus(XEvent *ev) {
2504 if(ev->type == FocusIn) {
2505 xw.state |= WIN_FOCUSED;
2506 xseturgency(0);
2507 } else {
2508 xw.state &= ~WIN_FOCUSED;
2509 }
2510 }
2511
2512 char*
2513 kmap(KeySym k, uint state) {
2514 int i;
2515 uint mask;
2516
2517 state &= ~Mod2Mask;
2518 for(i = 0; i < LEN(key); i++) {
2519 mask = key[i].mask;
2520
2521 if(key[i].k == k && ((state & mask) == mask
2522 || (mask == XK_NO_MOD && !state))) {
2523 return (char*)key[i].s;
2524 }
2525 }
2526 return NULL;
2527 }
2528
2529 void
2530 kpress(XEvent *ev) {
2531 XKeyEvent *e = &ev->xkey;
2532 KeySym ksym;
2533 char buf[32];
2534 char *customkey;
2535 int len;
2536 int meta;
2537 int shift;
2538 Status status;
2539
2540 if (IS_SET(MODE_KBDLOCK))
2541 return;
2542
2543 meta = e->state & Mod1Mask;
2544 shift = e->state & ShiftMask;
2545 len = XmbLookupString(xw.xic, e, buf, sizeof(buf), &ksym, &status);
2546
2547 /* 1. custom keys from config.h */
2548 if((customkey = kmap(ksym, e->state))) {
2549 ttywrite(customkey, strlen(customkey));
2550 /* 2. hardcoded (overrides X lookup) */
2551 } else {
2552 switch(ksym) {
2553 case XK_Up:
2554 case XK_Down:
2555 case XK_Left:
2556 case XK_Right:
2557 /* XXX: shift up/down doesn't work */
2558 sprintf(buf, "\033%c%c",
2559 IS_SET(MODE_APPKEYPAD) ? 'O' : '[',
2560 (shift ? "dacb":"DACB")[ksym - XK_Left]);
2561 ttywrite(buf, 3);
2562 break;
2563 case XK_Insert:
2564 if(shift)
2565 selpaste();
2566 break;
2567 case XK_Return:
2568 if(IS_SET(MODE_CRLF)) {
2569 ttywrite("\r\n", 2);
2570 } else {
2571 ttywrite("\r", 1);
2572 }
2573 break;
2574 /* 3. X lookup */
2575 default:
2576 if(len > 0) {
2577 if(meta && len == 1)
2578 ttywrite("\033", 1);
2579 ttywrite(buf, len);
2580 }
2581 break;
2582 }
2583 }
2584 }
2585
2586 void
2587 cmessage(XEvent *e) {
2588 /* See xembed specs
2589 http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html */
2590 if(e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
2591 if(e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
2592 xw.state |= WIN_FOCUSED;
2593 xseturgency(0);
2594 } else if(e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
2595 xw.state &= ~WIN_FOCUSED;
2596 }
2597 } else if(e->xclient.data.l[0] == xw.wmdeletewin) {
2598 /* Send SIGHUP to shell */
2599 kill(pid, SIGHUP);
2600 exit(EXIT_SUCCESS);
2601 }
2602 }
2603
2604 void
2605 resize(XEvent *e) {
2606 int col, row;
2607
2608 if(e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
2609 return;
2610
2611 xw.w = e->xconfigure.width;
2612 xw.h = e->xconfigure.height;
2613 col = (xw.w - 2*BORDER) / xw.cw;
2614 row = (xw.h - 2*BORDER) / xw.ch;
2615 if(col == term.col && row == term.row)
2616 return;
2617
2618 tresize(col, row);
2619 xresize(col, row);
2620 ttyresize();
2621 }
2622
2623 void
2624 run(void) {
2625 XEvent ev;
2626 fd_set rfd;
2627 int xfd = XConnectionNumber(xw.dpy), i;
2628 struct timeval drawtimeout, *tv = NULL;
2629
2630 for(i = 0;; i++) {
2631 FD_ZERO(&rfd);
2632 FD_SET(cmdfd, &rfd);
2633 FD_SET(xfd, &rfd);
2634 if(select(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, tv) < 0) {
2635 if(errno == EINTR)
2636 continue;
2637 die("select failed: %s\n", SERRNO);
2638 }
2639
2640 /*
2641 * Stop after a certain number of reads so the user does not
2642 * feel like the system is stuttering.
2643 */
2644 if(i < 1000 && FD_ISSET(cmdfd, &rfd)) {
2645 ttyread();
2646
2647 /*
2648 * Just wait a bit so it isn't disturbing the
2649 * user and the system is able to write something.
2650 */
2651 drawtimeout.tv_sec = 0;
2652 drawtimeout.tv_usec = 5;
2653 tv = &drawtimeout;
2654 continue;
2655 }
2656 i = 0;
2657 tv = NULL;
2658
2659 while(XPending(xw.dpy)) {
2660 XNextEvent(xw.dpy, &ev);
2661 if(XFilterEvent(&ev, xw.win))
2662 continue;
2663 if(handler[ev.type])
2664 (handler[ev.type])(&ev);
2665 }
2666
2667 draw();
2668 XFlush(xw.dpy);
2669 }
2670 }
2671
2672 int
2673 main(int argc, char *argv[]) {
2674 int i, bitm, xr, yr;
2675 uint wr, hr;
2676
2677 xw.fw = xw.fh = xw.fx = xw.fy = 0;
2678 xw.isfixed = False;
2679
2680 for(i = 1; i < argc; i++) {
2681 switch(argv[i][0] != '-' || argv[i][2] ? -1 : argv[i][1]) {
2682 case 'c':
2683 if(++i < argc)
2684 opt_class = argv[i];
2685 break;
2686 case 'e':
2687 /* eat every remaining arguments */
2688 if(++i < argc)
2689 opt_cmd = &argv[i];
2690 goto run;
2691 case 'f':
2692 if(++i < argc)
2693 opt_font = argv[i];
2694 break;
2695 case 'g':
2696 if(++i >= argc)
2697 break;
2698
2699 bitm = XParseGeometry(argv[i], &xr, &yr, &wr, &hr);
2700 if(bitm & XValue)
2701 xw.fx = xr;
2702 if(bitm & YValue)
2703 xw.fy = yr;
2704 if(bitm & WidthValue)
2705 xw.fw = (int)wr;
2706 if(bitm & HeightValue)
2707 xw.fh = (int)hr;
2708 if(bitm & XNegative && xw.fx == 0)
2709 xw.fx = -1;
2710 if(bitm & XNegative && xw.fy == 0)
2711 xw.fy = -1;
2712
2713 if(xw.fh != 0 && xw.fw != 0)
2714 xw.isfixed = True;
2715 break;
2716 case 'o':
2717 if(++i < argc)
2718 opt_io = argv[i];
2719 break;
2720 case 't':
2721 if(++i < argc)
2722 opt_title = argv[i];
2723 break;
2724 case 'v':
2725 default:
2726 die(USAGE);
2727 case 'w':
2728 if(++i < argc)
2729 opt_embed = argv[i];
2730 break;
2731 }
2732 }
2733
2734 run:
2735 setlocale(LC_CTYPE, "");
2736 tnew(80, 24);
2737 ttynew();
2738 xinit();
2739 selinit();
2740 run();
2741 return 0;
2742 }
2743