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