Xinqi Bao's Git

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