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