JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
cf329fd385b8961b2ac3e6cb20a2f2771adbdddf
[st.git] / st.c
1 /* See LICENSE for licence details. */
2 #define _XOPEN_SOURCE 600
3 #include <ctype.h>
4 #include <errno.h>
5 #include <fcntl.h>
6 #include <limits.h>
7 #include <locale.h>
8 #include <stdarg.h>
9 #include <stdbool.h>
10 #include <stdio.h>
11 #include <stdlib.h>
12 #include <string.h>
13 #include <signal.h>
14 #include <sys/ioctl.h>
15 #include <sys/select.h>
16 #include <sys/stat.h>
17 #include <sys/time.h>
18 #include <sys/types.h>
19 #include <sys/wait.h>
20 #include <time.h>
21 #include <unistd.h>
22 #include <X11/Xatom.h>
23 #include <X11/Xlib.h>
24 #include <X11/Xutil.h>
25 #include <X11/cursorfont.h>
26 #include <X11/keysym.h>
27 #include <X11/extensions/Xdbe.h>
28
29 #if   defined(__linux)
30  #include <pty.h>
31 #elif defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
32  #include <util.h>
33 #elif defined(__FreeBSD__) || defined(__DragonFly__)
34  #include <libutil.h>
35 #endif
36
37 #define USAGE \
38         "st " VERSION " (c) 2010-2012 st engineers\n" \
39         "usage: st [-t title] [-c class] [-g geometry]" \
40         " [-w windowid] [-v] [-f file] [-e command...]\n"
41
42 /* XEMBED messages */
43 #define XEMBED_FOCUS_IN  4
44 #define XEMBED_FOCUS_OUT 5
45
46 /* Arbitrary sizes */
47 #define ESC_BUF_SIZ   256
48 #define ESC_ARG_SIZ   16
49 #define STR_BUF_SIZ   256
50 #define STR_ARG_SIZ   16
51 #define DRAW_BUF_SIZ  1024
52 #define UTF_SIZ       4
53 #define XK_NO_MOD     UINT_MAX
54 #define XK_ANY_MOD    0
55
56 #define SELECT_TIMEOUT (20*1000) /* 20 ms */
57 #define DRAW_TIMEOUT  (20*1000) /* 20 ms */
58 #define REDRAW_TIMEOUT (80*1000) /* 80 ms */
59
60 #define SERRNO strerror(errno)
61 #define MIN(a, b)  ((a) < (b) ? (a) : (b))
62 #define MAX(a, b)  ((a) < (b) ? (b) : (a))
63 #define LEN(a)     (sizeof(a) / sizeof(a[0]))
64 #define DEFAULT(a, b)     (a) = (a) ? (a) : (b)
65 #define BETWEEN(x, a, b)  ((a) <= (x) && (x) <= (b))
66 #define LIMIT(x, a, b)    (x) = (x) < (a) ? (a) : (x) > (b) ? (b) : (x)
67 #define ATTRCMP(a, b) ((a).mode != (b).mode || (a).fg != (b).fg || (a).bg != (b).bg)
68 #define IS_SET(flag) (term.mode & (flag))
69 #define TIMEDIFF(t1, t2) ((t1.tv_sec-t2.tv_sec)*1000 + (t1.tv_usec-t2.tv_usec)/1000)
70 #define X2COL(x) (((x) - BORDER)/xw.cw)
71 #define Y2ROW(y) (((y) - BORDER)/xw.ch)
72
73 enum glyph_attribute {
74         ATTR_NULL      = 0,
75         ATTR_REVERSE   = 1,
76         ATTR_UNDERLINE = 2,
77         ATTR_BOLD      = 4,
78         ATTR_GFX       = 8,
79 };
80
81 enum cursor_movement {
82         CURSOR_UP,
83         CURSOR_DOWN,
84         CURSOR_LEFT,
85         CURSOR_RIGHT,
86         CURSOR_SAVE,
87         CURSOR_LOAD
88 };
89
90 enum cursor_state {
91         CURSOR_DEFAULT  = 0,
92         CURSOR_HIDE     = 1,
93         CURSOR_WRAPNEXT = 2
94 };
95
96 enum glyph_state {
97         GLYPH_SET   = 1,
98         GLYPH_DIRTY = 2
99 };
100
101 enum term_mode {
102         MODE_WRAP       = 1,
103         MODE_INSERT      = 2,
104         MODE_APPKEYPAD   = 4,
105         MODE_ALTSCREEN   = 8,
106         MODE_CRLF       = 16,
107         MODE_MOUSEBTN    = 32,
108         MODE_MOUSEMOTION = 64,
109         MODE_MOUSE       = 32|64,
110         MODE_REVERSE     = 128
111 };
112
113 enum escape_state {
114         ESC_START      = 1,
115         ESC_CSI = 2,
116         ESC_STR = 4, /* DSC, OSC, PM, APC */
117         ESC_ALTCHARSET = 8,
118         ESC_STR_END    = 16, /* a final string was encountered */
119 };
120
121 enum window_state {
122         WIN_VISIBLE = 1,
123         WIN_REDRAW  = 2,
124         WIN_FOCUSED = 4
125 };
126
127 /* bit macro */
128 #undef B0
129 enum { B0=1, B1=2, B2=4, B3=8, B4=16, B5=32, B6=64, B7=128 };
130
131 typedef unsigned char uchar;
132 typedef unsigned int uint;
133 typedef unsigned long ulong;
134 typedef unsigned short ushort;
135
136 typedef struct {
137         char c[UTF_SIZ];     /* character code */
138         uchar mode;  /* attribute flags */
139         ushort fg;   /* foreground  */
140         ushort bg;   /* background  */
141         uchar state; /* state flags    */
142 } Glyph;
143
144 typedef Glyph* Line;
145
146 typedef struct {
147         Glyph attr;      /* current char attributes */
148         int x;
149         int y;
150         char state;
151 } TCursor;
152
153 /* CSI Escape sequence structs */
154 /* ESC '[' [[ [<priv>] <arg> [;]] <mode>] */
155 typedef struct {
156         char buf[ESC_BUF_SIZ]; /* raw string */
157         int len;               /* raw string length */
158         char priv;
159         int arg[ESC_ARG_SIZ];
160         int narg;             /* nb of args */
161         char mode;
162 } CSIEscape;
163
164 /* STR Escape sequence structs */
165 /* ESC type [[ [<priv>] <arg> [;]] <mode>] ESC '\' */
166 typedef struct {
167         char type;           /* ESC type ... */
168         char buf[STR_BUF_SIZ]; /* raw string */
169         int len;               /* raw string length */
170         char *args[STR_ARG_SIZ];
171         int narg;             /* nb of args */
172 } STREscape;
173
174 /* Internal representation of the screen */
175 typedef struct {
176         int row;        /* nb row */
177         int col;        /* nb col */
178         Line* line;     /* screen */
179         Line* alt;      /* alternate screen */
180         bool* dirty;    /* dirtyness of lines */
181         TCursor c;      /* cursor */
182         int top;        /* top    scroll limit */
183         int bot;        /* bottom scroll limit */
184         int mode;       /* terminal mode flags */
185         int esc;        /* escape state flags */
186         bool *tabs;
187 } Term;
188
189 /* Purely graphic info */
190 typedef struct {
191         Display* dpy;
192         Colormap cmap;
193         Window win;
194         XdbeBackBuffer buf;
195         Atom xembed;
196         XIM xim;
197         XIC xic;
198         int scr;
199         Bool isfixed; /* is fixed geometry? */
200         int fx, fy, fw, fh; /* fixed geometry */
201         int w;  /* window width */
202         int h;  /* window height */
203         int ch; /* char height */
204         int cw; /* char width  */
205         char state; /* focus, redraw, visible */
206         struct timeval lastdraw;
207 } XWindow;
208
209 typedef struct {
210         KeySym k;
211         uint mask;
212         char s[ESC_BUF_SIZ];
213 } Key;
214
215
216 /* TODO: use better name for vars... */
217 typedef struct {
218         int mode;
219         int bx, by;
220         int ex, ey;
221         struct {int x, y;} b, e;
222         char *clip;
223         Atom xtarget;
224         bool alt;
225         struct timeval tclick1;
226         struct timeval tclick2;
227 } Selection;
228
229 #include "config.h"
230
231 /* Drawing Context */
232 typedef struct {
233         ulong col[LEN(colorname) < 256 ? 256 : LEN(colorname)];
234         GC gc;
235         struct {
236                 int ascent;
237                 int descent;
238                 short lbearing;
239                 short rbearing;
240                 XFontSet set;
241         } font, bfont;
242 } DC;
243
244 static void die(const char*, ...);
245 static void draw(void);
246 static void redraw(void);
247 static void drawregion(int, int, int, int);
248 static void execsh(void);
249 static void sigchld(int);
250 static void run(void);
251 static bool last_draw_too_old(void);
252
253 static void csidump(void);
254 static void csihandle(void);
255 static void csiparse(void);
256 static void csireset(void);
257 static void strdump(void);
258 static void strhandle(void);
259 static void strparse(void);
260 static void strreset(void);
261
262 static void tclearregion(int, int, int, int);
263 static void tcursor(int);
264 static void tdeletechar(int);
265 static void tdeleteline(int);
266 static void tinsertblank(int);
267 static void tinsertblankline(int);
268 static void tmoveto(int, int);
269 static void tnew(int, int);
270 static void tnewline(int);
271 static void tputtab(bool);
272 static void tputc(char*);
273 static void treset(void);
274 static int tresize(int, int);
275 static void tscrollup(int, int);
276 static void tscrolldown(int, int);
277 static void tsetattr(int*, int);
278 static void tsetchar(char*);
279 static void tsetscroll(int, int);
280 static void tswapscreen(void);
281 static void tsetdirt(int, int);
282 static void tsetmode(bool, bool, int *, int);
283 static void tfulldirt(void);
284
285 static void ttynew(void);
286 static void ttyread(void);
287 static void ttyresize(int, int);
288 static void ttywrite(const char *, size_t);
289
290 static void xdraws(char *, Glyph, int, int, int, int);
291 static void xhints(void);
292 static void xclear(int, int, int, int);
293 static void xcopy();
294 static void xdrawcursor(void);
295 static void xinit(void);
296 static void xloadcols(void);
297 static void xseturgency(int);
298 static void xsetsel(char*);
299 static void xresize(int, int);
300
301 static void expose(XEvent *);
302 static void visibility(XEvent *);
303 static void unmap(XEvent *);
304 static char* kmap(KeySym, uint);
305 static void kpress(XEvent *);
306 static void cmessage(XEvent *);
307 static void resize(XEvent *);
308 static void focus(XEvent *);
309 static void brelease(XEvent *);
310 static void bpress(XEvent *);
311 static void bmotion(XEvent *);
312 static void selnotify(XEvent *);
313 static void selrequest(XEvent *);
314
315 static void selinit(void);
316 static inline bool selected(int, int);
317 static void selcopy(void);
318 static void selpaste();
319 static void selscroll(int, int);
320
321 static int utf8decode(char *, long *);
322 static int utf8encode(long *, char *);
323 static int utf8size(char *);
324 static int isfullutf8(char *, int);
325
326 static void (*handler[LASTEvent])(XEvent *) = {
327         [KeyPress] = kpress,
328         [ClientMessage] = cmessage,
329         [ConfigureNotify] = resize,
330         [VisibilityNotify] = visibility,
331         [UnmapNotify] = unmap,
332         [Expose] = expose,
333         [FocusIn] = focus,
334         [FocusOut] = focus,
335         [MotionNotify] = bmotion,
336         [ButtonPress] = bpress,
337         [ButtonRelease] = brelease,
338         [SelectionNotify] = selnotify,
339         [SelectionRequest] = selrequest,
340 };
341
342 /* Globals */
343 static DC dc;
344 static XWindow xw;
345 static Term term;
346 static CSIEscape csiescseq;
347 static STREscape strescseq;
348 static int cmdfd;
349 static pid_t pid;
350 static Selection sel;
351 static FILE *fileio;
352 static char **opt_cmd  = NULL;
353 static char *opt_io    = NULL;
354 static char *opt_title = NULL;
355 static char *opt_embed = NULL;
356 static char *opt_class = NULL;
357
358 int
359 utf8decode(char *s, long *u) {
360         uchar c;
361         int i, n, rtn;
362
363         rtn = 1;
364         c = *s;
365         if(~c & B7) { /* 0xxxxxxx */
366                 *u = c;
367                 return rtn;
368         } else if((c & (B7|B6|B5)) == (B7|B6)) { /* 110xxxxx */
369                 *u = c&(B4|B3|B2|B1|B0);
370                 n = 1;
371         } else if((c & (B7|B6|B5|B4)) == (B7|B6|B5)) { /* 1110xxxx */
372                 *u = c&(B3|B2|B1|B0);
373                 n = 2;
374         } else if((c & (B7|B6|B5|B4|B3)) == (B7|B6|B5|B4)) { /* 11110xxx */
375                 *u = c & (B2|B1|B0);
376                 n = 3;
377         } else
378                 goto invalid;
379         for(i = n, ++s; i > 0; --i, ++rtn, ++s) {
380                 c = *s;
381                 if((c & (B7|B6)) != B7) /* 10xxxxxx */
382                         goto invalid;
383                 *u <<= 6;
384                 *u |= c & (B5|B4|B3|B2|B1|B0);
385         }
386         if((n == 1 && *u < 0x80) ||
387            (n == 2 && *u < 0x800) ||
388            (n == 3 && *u < 0x10000) ||
389            (*u >= 0xD800 && *u <= 0xDFFF))
390                 goto invalid;
391         return rtn;
392 invalid:
393         *u = 0xFFFD;
394         return rtn;
395 }
396
397 int
398 utf8encode(long *u, char *s) {
399         uchar *sp;
400         ulong uc;
401         int i, n;
402
403         sp = (uchar*) s;
404         uc = *u;
405         if(uc < 0x80) {
406                 *sp = uc; /* 0xxxxxxx */
407                 return 1;
408         } else if(*u < 0x800) {
409                 *sp = (uc >> 6) | (B7|B6); /* 110xxxxx */
410                 n = 1;
411         } else if(uc < 0x10000) {
412                 *sp = (uc >> 12) | (B7|B6|B5); /* 1110xxxx */
413                 n = 2;
414         } else if(uc <= 0x10FFFF) {
415                 *sp = (uc >> 18) | (B7|B6|B5|B4); /* 11110xxx */
416                 n = 3;
417         } else {
418                 goto invalid;
419         }
420         for(i=n,++sp; i>0; --i,++sp)
421                 *sp = ((uc >> 6*(i-1)) & (B5|B4|B3|B2|B1|B0)) | B7; /* 10xxxxxx */
422         return n+1;
423 invalid:
424         /* U+FFFD */
425         *s++ = '\xEF';
426         *s++ = '\xBF';
427         *s = '\xBD';
428         return 3;
429 }
430
431 /* use this if your buffer is less than UTF_SIZ, it returns 1 if you can decode
432    UTF-8 otherwise return 0 */
433 int
434 isfullutf8(char *s, int b) {
435         uchar *c1, *c2, *c3;
436
437         c1 = (uchar *) s;
438         c2 = (uchar *) ++s;
439         c3 = (uchar *) ++s;
440         if(b < 1)
441                 return 0;
442         else if((*c1&(B7|B6|B5)) == (B7|B6) && b == 1)
443                 return 0;
444         else if((*c1&(B7|B6|B5|B4)) == (B7|B6|B5) &&
445             ((b == 1) ||
446             ((b == 2) && (*c2&(B7|B6)) == B7)))
447                 return 0;
448         else if((*c1&(B7|B6|B5|B4|B3)) == (B7|B6|B5|B4) &&
449             ((b == 1) ||
450             ((b == 2) && (*c2&(B7|B6)) == B7) ||
451             ((b == 3) && (*c2&(B7|B6)) == B7 && (*c3&(B7|B6)) == B7)))
452                 return 0;
453         else
454                 return 1;
455 }
456
457 int
458 utf8size(char *s) {
459         uchar c = *s;
460
461         if(~c&B7)
462                 return 1;
463         else if((c&(B7|B6|B5)) == (B7|B6))
464                 return 2;
465         else if((c&(B7|B6|B5|B4)) == (B7|B6|B5))
466                 return 3;
467         else
468                 return 4;
469 }
470
471 void
472 selinit(void) {
473         memset(&sel.tclick1, 0, sizeof(sel.tclick1));
474         memset(&sel.tclick2, 0, sizeof(sel.tclick2));
475         sel.mode = 0;
476         sel.bx = -1;
477         sel.clip = NULL;
478         sel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
479         if(sel.xtarget == None)
480                 sel.xtarget = XA_STRING;
481 }
482
483 static inline bool
484 selected(int x, int y) {
485         if(sel.ey == y && sel.by == y) {
486                 int bx = MIN(sel.bx, sel.ex);
487                 int ex = MAX(sel.bx, sel.ex);
488                 return BETWEEN(x, bx, ex);
489         }
490         return ((sel.b.y < y&&y < sel.e.y) || (y==sel.e.y && x<=sel.e.x))
491                 || (y==sel.b.y && x>=sel.b.x && (x<=sel.e.x || sel.b.y!=sel.e.y));
492 }
493
494 void
495 getbuttoninfo(XEvent *e, int *b, int *x, int *y) {
496         if(b)
497                 *b = e->xbutton.button;
498
499         *x = X2COL(e->xbutton.x);
500         *y = Y2ROW(e->xbutton.y);
501         sel.b.x = sel.by < sel.ey ? sel.bx : sel.ex;
502         sel.b.y = MIN(sel.by, sel.ey);
503         sel.e.x = sel.by < sel.ey ? sel.ex : sel.bx;
504         sel.e.y = MAX(sel.by, sel.ey);
505 }
506
507 void
508 mousereport(XEvent *e) {
509         int x = X2COL(e->xbutton.x);
510         int y = Y2ROW(e->xbutton.y);
511         int button = e->xbutton.button;
512         int state = e->xbutton.state;
513         char buf[] = { '\033', '[', 'M', 0, 32+x+1, 32+y+1 };
514         static int ob, ox, oy;
515
516         /* from urxvt */
517         if(e->xbutton.type == MotionNotify) {
518                 if(!IS_SET(MODE_MOUSEMOTION) || (x == ox && y == oy))
519                         return;
520                 button = ob + 32;
521                 ox = x, oy = y;
522         } else if(e->xbutton.type == ButtonRelease || button == AnyButton) {
523                 button = 3;
524         } else {
525                 button -= Button1;
526                 if(button >= 3)
527                         button += 64 - 3;
528                 if(e->xbutton.type == ButtonPress) {
529                         ob = button;
530                         ox = x, oy = y;
531                 }
532         }
533
534         buf[3] = 32 + button + (state & ShiftMask ? 4 : 0)
535                 + (state & Mod4Mask    ? 8  : 0)
536                 + (state & ControlMask ? 16 : 0);
537
538         ttywrite(buf, sizeof(buf));
539 }
540
541 void
542 bpress(XEvent *e) {
543         if(IS_SET(MODE_MOUSE))
544                 mousereport(e);
545         else if(e->xbutton.button == Button1) {
546                 if(sel.bx != -1)
547                         tsetdirt(sel.b.y, sel.e.y);
548                 sel.mode = 1;
549                 sel.ex = sel.bx = X2COL(e->xbutton.x);
550                 sel.ey = sel.by = Y2ROW(e->xbutton.y);
551         }
552 }
553
554 void
555 selcopy(void) {
556         char *str, *ptr;
557         int x, y, bufsize, is_selected = 0;
558
559         if(sel.bx == -1)
560                 str = NULL;
561
562         else {
563                 bufsize = (term.col+1) * (sel.e.y-sel.b.y+1) * UTF_SIZ;
564                 ptr = str = malloc(bufsize);
565
566                 /* append every set & selected glyph to the selection */
567                 for(y = 0; y < term.row; y++) {
568                         for(x = 0; x < term.col; x++) {
569                                 is_selected = selected(x, y);
570                                 if((term.line[y][x].state & GLYPH_SET) && is_selected) {
571                                         int size = utf8size(term.line[y][x].c);
572                                         memcpy(ptr, term.line[y][x].c, size);
573                                         ptr += size;
574                                 }
575                         }
576
577                         /* \n at the end of every selected line except for the last one */
578                         if(is_selected && y < sel.e.y)
579                                 *ptr++ = '\n';
580                 }
581                 *ptr = 0;
582         }
583         sel.alt = IS_SET(MODE_ALTSCREEN);
584         xsetsel(str);
585 }
586
587 void
588 selnotify(XEvent *e) {
589         ulong nitems, ofs, rem;
590         int format;
591         uchar *data;
592         Atom type;
593
594         ofs = 0;
595         do {
596                 if(XGetWindowProperty(xw.dpy, xw.win, XA_PRIMARY, ofs, BUFSIZ/4,
597                                         False, AnyPropertyType, &type, &format,
598                                         &nitems, &rem, &data)) {
599                         fprintf(stderr, "Clipboard allocation failed\n");
600                         return;
601                 }
602                 ttywrite((const char *) data, nitems * format / 8);
603                 XFree(data);
604                 /* number of 32-bit chunks returned */
605                 ofs += nitems * format / 32;
606         } while(rem > 0);
607 }
608
609 void
610 selpaste() {
611         XConvertSelection(xw.dpy, XA_PRIMARY, sel.xtarget, XA_PRIMARY, xw.win, CurrentTime);
612 }
613
614 void
615 selrequest(XEvent *e) {
616         XSelectionRequestEvent *xsre;
617         XSelectionEvent xev;
618         Atom xa_targets;
619
620         xsre = (XSelectionRequestEvent *) e;
621         xev.type = SelectionNotify;
622         xev.requestor = xsre->requestor;
623         xev.selection = xsre->selection;
624         xev.target = xsre->target;
625         xev.time = xsre->time;
626         /* reject */
627         xev.property = None;
628
629         xa_targets = XInternAtom(xw.dpy, "TARGETS", 0);
630         if(xsre->target == xa_targets) {
631                 /* respond with the supported type */
632                 Atom string = sel.xtarget;
633                 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
634                                 XA_ATOM, 32, PropModeReplace,
635                                 (uchar *) &string, 1);
636                 xev.property = xsre->property;
637         } else if(xsre->target == sel.xtarget && sel.clip != NULL) {
638                 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
639                                 xsre->target, 8, PropModeReplace,
640                                 (uchar *) sel.clip, strlen(sel.clip));
641                 xev.property = xsre->property;
642         }
643
644         /* all done, send a notification to the listener */
645         if(!XSendEvent(xsre->display, xsre->requestor, True, 0, (XEvent *) &xev))
646                 fprintf(stderr, "Error sending SelectionNotify event\n");
647 }
648
649 void
650 xsetsel(char *str) {
651         /* register the selection for both the clipboard and the primary */
652         Atom clipboard;
653
654         free(sel.clip);
655         sel.clip = str;
656
657         XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, CurrentTime);
658
659         clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
660         XSetSelectionOwner(xw.dpy, clipboard, xw.win, CurrentTime);
661
662         XFlush(xw.dpy);
663 }
664
665 void
666 brelease(XEvent *e) {
667         if(IS_SET(MODE_MOUSE)) {
668                 mousereport(e);
669                 return;
670         }
671         if(e->xbutton.button == Button2)
672                 selpaste();
673         else if(e->xbutton.button == Button1) {
674                 sel.mode = 0;
675                 getbuttoninfo(e, NULL, &sel.ex, &sel.ey);
676                 term.dirty[sel.ey] = 1;
677                 if(sel.bx == sel.ex && sel.by == sel.ey) {
678                         struct timeval now;
679                         sel.bx = -1;
680                         gettimeofday(&now, NULL);
681
682                         if(TIMEDIFF(now, sel.tclick2) <= TRIPLECLICK_TIMEOUT) {
683                                 /* triple click on the line */
684                                 sel.b.x = sel.bx = 0;
685                                 sel.e.x = sel.ex = term.col;
686                                 sel.b.y = sel.e.y = sel.ey;
687                                 selcopy();
688                         } else if(TIMEDIFF(now, sel.tclick1) <= DOUBLECLICK_TIMEOUT) {
689                                 /* double click to select word */
690                                 sel.bx = sel.ex;
691                                 while(sel.bx > 0 && term.line[sel.ey][sel.bx-1].state & GLYPH_SET &&
692                                           term.line[sel.ey][sel.bx-1].c[0] != ' ') sel.bx--;
693                                 sel.b.x = sel.bx;
694                                 while(sel.ex < term.col-1 && term.line[sel.ey][sel.ex+1].state & GLYPH_SET &&
695                                           term.line[sel.ey][sel.ex+1].c[0] != ' ') sel.ex++;
696                                 sel.e.x = sel.ex;
697                                 sel.b.y = sel.e.y = sel.ey;
698                                 selcopy();
699                         }
700                 } else
701                         selcopy();
702         }
703         memcpy(&sel.tclick2, &sel.tclick1, sizeof(struct timeval));
704         gettimeofday(&sel.tclick1, NULL);
705         draw();
706 }
707
708 void
709 bmotion(XEvent *e) {
710         if(IS_SET(MODE_MOUSE)) {
711                 mousereport(e);
712                 return;
713         }
714         if(sel.mode) {
715                 int oldey = sel.ey, oldex = sel.ex;
716                 getbuttoninfo(e, NULL, &sel.ex, &sel.ey);
717
718                 if(oldey != sel.ey || oldex != sel.ex) {
719                         int starty = MIN(oldey, sel.ey);
720                         int endy = MAX(oldey, sel.ey);
721                         tsetdirt(starty, endy);
722                         draw();
723                 }
724         }
725 }
726
727 void
728 die(const char *errstr, ...) {
729         va_list ap;
730
731         va_start(ap, errstr);
732         vfprintf(stderr, errstr, ap);
733         va_end(ap);
734         exit(EXIT_FAILURE);
735 }
736
737 void
738 execsh(void) {
739         char **args;
740         char *envshell = getenv("SHELL");
741
742         unsetenv("COLUMNS");
743         unsetenv("LINES");
744         unsetenv("TERMCAP");
745
746         DEFAULT(envshell, SHELL);
747         putenv("TERM="TNAME);
748         args = opt_cmd ? opt_cmd : (char*[]){envshell, "-i", NULL};
749         execvp(args[0], args);
750         exit(EXIT_FAILURE);
751 }
752
753 void
754 sigchld(int a) {
755         int stat = 0;
756         if(waitpid(pid, &stat, 0) < 0)
757                 die("Waiting for pid %hd failed: %s\n", pid, SERRNO);
758         if(WIFEXITED(stat))
759                 exit(WEXITSTATUS(stat));
760         else
761                 exit(EXIT_FAILURE);
762 }
763
764 void
765 ttynew(void) {
766         int m, s;
767
768         /* seems to work fine on linux, openbsd and freebsd */
769         struct winsize w = {term.row, term.col, 0, 0};
770         if(openpty(&m, &s, NULL, NULL, &w) < 0)
771                 die("openpty failed: %s\n", SERRNO);
772
773         switch(pid = fork()) {
774         case -1:
775                 die("fork failed\n");
776                 break;
777         case 0:
778                 setsid(); /* create a new process group */
779                 dup2(s, STDIN_FILENO);
780                 dup2(s, STDOUT_FILENO);
781                 dup2(s, STDERR_FILENO);
782                 if(ioctl(s, TIOCSCTTY, NULL) < 0)
783                         die("ioctl TIOCSCTTY failed: %s\n", SERRNO);
784                 close(s);
785                 close(m);
786                 execsh();
787                 break;
788         default:
789                 close(s);
790                 cmdfd = m;
791                 signal(SIGCHLD, sigchld);
792                 if(opt_io && !(fileio = fopen(opt_io, "w"))) {
793                         fprintf(stderr, "Error opening %s:%s\n",
794                                 opt_io, strerror(errno));
795                 }
796         }
797 }
798
799 void
800 dump(char c) {
801         static int col;
802         fprintf(stderr, " %02x '%c' ", c, isprint(c)?c:'.');
803         if(++col % 10 == 0)
804                 fprintf(stderr, "\n");
805 }
806
807 void
808 ttyread(void) {
809         static char buf[BUFSIZ];
810         static int buflen = 0;
811         char *ptr;
812         char s[UTF_SIZ];
813         int charsize; /* size of utf8 char in bytes */
814         long utf8c;
815         int ret;
816
817         /* append read bytes to unprocessed bytes */
818         if((ret = read(cmdfd, buf+buflen, LEN(buf)-buflen)) < 0)
819                 die("Couldn't read from shell: %s\n", SERRNO);
820
821         /* process every complete utf8 char */
822         buflen += ret;
823         ptr = buf;
824         while(buflen >= UTF_SIZ || isfullutf8(ptr,buflen)) {
825                 charsize = utf8decode(ptr, &utf8c);
826                 utf8encode(&utf8c, s);
827                 tputc(s);
828                 ptr    += charsize;
829                 buflen -= charsize;
830         }
831
832         /* keep any uncomplete utf8 char for the next call */
833         memmove(buf, ptr, buflen);
834 }
835
836 void
837 ttywrite(const char *s, size_t n) {
838         if(write(cmdfd, s, n) == -1)
839                 die("write error on tty: %s\n", SERRNO);
840 }
841
842 void
843 ttyresize(int x, int y) {
844         struct winsize w;
845
846         w.ws_row = term.row;
847         w.ws_col = term.col;
848         w.ws_xpixel = xw.w;
849         w.ws_ypixel = xw.h;
850         if(ioctl(cmdfd, TIOCSWINSZ, &w) < 0)
851                 fprintf(stderr, "Couldn't set window size: %s\n", SERRNO);
852 }
853
854 void
855 tsetdirt(int top, int bot)
856 {
857         int i;
858
859         LIMIT(top, 0, term.row-1);
860         LIMIT(bot, 0, term.row-1);
861
862         for(i = top; i <= bot; i++)
863                 term.dirty[i] = 1;
864 }
865
866 void
867 tfulldirt(void)
868 {
869         tsetdirt(0, term.row-1);
870 }
871
872 void
873 tcursor(int mode) {
874         static TCursor c;
875
876         if(mode == CURSOR_SAVE)
877                 c = term.c;
878         else if(mode == CURSOR_LOAD)
879                 term.c = c, tmoveto(c.x, c.y);
880 }
881
882 void
883 treset(void) {
884         unsigned i;
885         term.c = (TCursor){{
886                 .mode = ATTR_NULL,
887                 .fg = DefaultFG,
888                 .bg = DefaultBG
889         }, .x = 0, .y = 0, .state = CURSOR_DEFAULT};
890
891         memset(term.tabs, 0, term.col * sizeof(*term.tabs));
892         for(i = TAB; i < term.col; i += TAB)
893                 term.tabs[i] = 1;
894         term.top = 0, term.bot = term.row - 1;
895         term.mode = MODE_WRAP;
896         tclearregion(0, 0, term.col-1, term.row-1);
897 }
898
899 void
900 tnew(int col, int row) {
901         /* set screen size */
902         term.row = row, term.col = col;
903         term.line = malloc(term.row * sizeof(Line));
904         term.alt  = malloc(term.row * sizeof(Line));
905         term.dirty = malloc(term.row * sizeof(*term.dirty));
906         term.tabs = malloc(term.col * sizeof(*term.tabs));
907
908         for(row = 0; row < term.row; row++) {
909                 term.line[row] = malloc(term.col * sizeof(Glyph));
910                 term.alt [row] = malloc(term.col * sizeof(Glyph));
911                 term.dirty[row] = 0;
912         }
913         memset(term.tabs, 0, term.col * sizeof(*term.tabs));
914         /* setup screen */
915         treset();
916 }
917
918 void
919 tswapscreen(void) {
920         Line* tmp = term.line;
921         term.line = term.alt;
922         term.alt = tmp;
923         term.mode ^= MODE_ALTSCREEN;
924         tfulldirt();
925 }
926
927 void
928 tscrolldown(int orig, int n) {
929         int i;
930         Line temp;
931
932         LIMIT(n, 0, term.bot-orig+1);
933
934         tclearregion(0, term.bot-n+1, term.col-1, term.bot);
935
936         for(i = term.bot; i >= orig+n; i--) {
937                 temp = term.line[i];
938                 term.line[i] = term.line[i-n];
939                 term.line[i-n] = temp;
940
941                 term.dirty[i] = 1;
942                 term.dirty[i-n] = 1;
943         }
944
945         selscroll(orig, n);
946 }
947
948 void
949 tscrollup(int orig, int n) {
950         int i;
951         Line temp;
952         LIMIT(n, 0, term.bot-orig+1);
953
954         tclearregion(0, orig, term.col-1, orig+n-1);
955
956         for(i = orig; i <= term.bot-n; i++) {
957                  temp = term.line[i];
958                  term.line[i] = term.line[i+n];
959                  term.line[i+n] = temp;
960
961                  term.dirty[i] = 1;
962                  term.dirty[i+n] = 1;
963         }
964
965         selscroll(orig, -n);
966 }
967
968 void
969 selscroll(int orig, int n) {
970         if(sel.bx == -1)
971                 return;
972
973         if(BETWEEN(sel.by, orig, term.bot) || BETWEEN(sel.ey, orig, term.bot)) {
974                 if((sel.by += n) > term.bot || (sel.ey += n) < term.top) {
975                         sel.bx = -1;
976                         return;
977                 }
978                 if(sel.by < term.top) {
979                         sel.by = term.top;
980                         sel.bx = 0;
981                 }
982                 if(sel.ey > term.bot) {
983                         sel.ey = term.bot;
984                         sel.ex = term.col;
985                 }
986                 sel.b.y = sel.by, sel.b.x = sel.bx;
987                 sel.e.y = sel.ey, sel.e.x = sel.ex;
988         }
989 }
990
991 void
992 tnewline(int first_col) {
993         int y = term.c.y;
994         if(y == term.bot)
995                 tscrollup(term.top, 1);
996         else
997                 y++;
998         tmoveto(first_col ? 0 : term.c.x, y);
999 }
1000
1001 void
1002 csiparse(void) {
1003         /* int noarg = 1; */
1004         char *p = csiescseq.buf;
1005
1006         csiescseq.narg = 0;
1007         if(*p == '?')
1008                 csiescseq.priv = 1, p++;
1009
1010         while(p < csiescseq.buf+csiescseq.len) {
1011                 while(isdigit(*p)) {
1012                         csiescseq.arg[csiescseq.narg] *= 10;
1013                         csiescseq.arg[csiescseq.narg] += *p++ - '0'/*, noarg = 0 */;
1014                 }
1015                 if(*p == ';' && csiescseq.narg+1 < ESC_ARG_SIZ)
1016                         csiescseq.narg++, p++;
1017                 else {
1018                         csiescseq.mode = *p;
1019                         csiescseq.narg++;
1020                         return;
1021                 }
1022         }
1023 }
1024
1025 void
1026 tmoveto(int x, int y) {
1027         LIMIT(x, 0, term.col-1);
1028         LIMIT(y, 0, term.row-1);
1029         term.c.state &= ~CURSOR_WRAPNEXT;
1030         term.c.x = x;
1031         term.c.y = y;
1032 }
1033
1034 void
1035 tsetchar(char *c) {
1036         term.dirty[term.c.y] = 1;
1037         term.line[term.c.y][term.c.x] = term.c.attr;
1038         memcpy(term.line[term.c.y][term.c.x].c, c, UTF_SIZ);
1039         term.line[term.c.y][term.c.x].state |= GLYPH_SET;
1040 }
1041
1042 void
1043 tclearregion(int x1, int y1, int x2, int y2) {
1044         int x, y, temp;
1045
1046         if(x1 > x2)
1047                 temp = x1, x1 = x2, x2 = temp;
1048         if(y1 > y2)
1049                 temp = y1, y1 = y2, y2 = temp;
1050
1051         LIMIT(x1, 0, term.col-1);
1052         LIMIT(x2, 0, term.col-1);
1053         LIMIT(y1, 0, term.row-1);
1054         LIMIT(y2, 0, term.row-1);
1055
1056         for(y = y1; y <= y2; y++) {
1057                 term.dirty[y] = 1;
1058                 for(x = x1; x <= x2; x++)
1059                         term.line[y][x].state = 0;
1060         }
1061 }
1062
1063 void
1064 tdeletechar(int n) {
1065         int src = term.c.x + n;
1066         int dst = term.c.x;
1067         int size = term.col - src;
1068
1069         term.dirty[term.c.y] = 1;
1070
1071         if(src >= term.col) {
1072                 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1073                 return;
1074         }
1075         memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src], size * sizeof(Glyph));
1076         tclearregion(term.col-n, term.c.y, term.col-1, term.c.y);
1077 }
1078
1079 void
1080 tinsertblank(int n) {
1081         int src = term.c.x;
1082         int dst = src + n;
1083         int size = term.col - dst;
1084
1085         term.dirty[term.c.y] = 1;
1086
1087         if(dst >= term.col) {
1088                 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1089                 return;
1090         }
1091         memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src], size * sizeof(Glyph));
1092         tclearregion(src, term.c.y, dst - 1, term.c.y);
1093 }
1094
1095 void
1096 tinsertblankline(int n) {
1097         if(term.c.y < term.top || term.c.y > term.bot)
1098                 return;
1099
1100         tscrolldown(term.c.y, n);
1101 }
1102
1103 void
1104 tdeleteline(int n) {
1105         if(term.c.y < term.top || term.c.y > term.bot)
1106                 return;
1107
1108         tscrollup(term.c.y, n);
1109 }
1110
1111 void
1112 tsetattr(int *attr, int l) {
1113         int i;
1114
1115         for(i = 0; i < l; i++) {
1116                 switch(attr[i]) {
1117                 case 0:
1118                         term.c.attr.mode &= ~(ATTR_REVERSE | ATTR_UNDERLINE | ATTR_BOLD);
1119                         term.c.attr.fg = DefaultFG;
1120                         term.c.attr.bg = DefaultBG;
1121                         break;
1122                 case 1:
1123                         term.c.attr.mode |= ATTR_BOLD;
1124                         break;
1125                 case 3: /* enter standout (highlight) mode TODO: make it italic */
1126                         term.c.attr.mode |= ATTR_REVERSE;
1127                         break;
1128                 case 4:
1129                         term.c.attr.mode |= ATTR_UNDERLINE;
1130                         break;
1131                 case 7:
1132                         term.c.attr.mode |= ATTR_REVERSE;
1133                         break;
1134                 case 22:
1135                         term.c.attr.mode &= ~ATTR_BOLD;
1136                         break;
1137                 case 23: /* leave standout (highlight) mode TODO: make it italic */
1138                         term.c.attr.mode &= ~ATTR_REVERSE;
1139                         break;
1140                 case 24:
1141                         term.c.attr.mode &= ~ATTR_UNDERLINE;
1142                         break;
1143                 case 27:
1144                         term.c.attr.mode &= ~ATTR_REVERSE;
1145                         break;
1146                 case 38:
1147                         if(i + 2 < l && attr[i + 1] == 5) {
1148                                 i += 2;
1149                                 if(BETWEEN(attr[i], 0, 255))
1150                                         term.c.attr.fg = attr[i];
1151                                 else
1152                                         fprintf(stderr, "erresc: bad fgcolor %d\n", attr[i]);
1153                         }
1154                         else
1155                                 fprintf(stderr, "erresc(38): gfx attr %d unknown\n", attr[i]);
1156                         break;
1157                 case 39:
1158                         term.c.attr.fg = DefaultFG;
1159                         break;
1160                 case 48:
1161                         if(i + 2 < l && attr[i + 1] == 5) {
1162                                 i += 2;
1163                                 if(BETWEEN(attr[i], 0, 255))
1164                                         term.c.attr.bg = attr[i];
1165                                 else
1166                                         fprintf(stderr, "erresc: bad bgcolor %d\n", attr[i]);
1167                         }
1168                         else
1169                                 fprintf(stderr, "erresc(48): gfx attr %d unknown\n", attr[i]);
1170                         break;
1171                 case 49:
1172                         term.c.attr.bg = DefaultBG;
1173                         break;
1174                 default:
1175                         if(BETWEEN(attr[i], 30, 37))
1176                                 term.c.attr.fg = attr[i] - 30;
1177                         else if(BETWEEN(attr[i], 40, 47))
1178                                 term.c.attr.bg = attr[i] - 40;
1179                         else if(BETWEEN(attr[i], 90, 97))
1180                                 term.c.attr.fg = attr[i] - 90 + 8;
1181                         else if(BETWEEN(attr[i], 100, 107))
1182                                 term.c.attr.fg = attr[i] - 100 + 8;
1183                         else
1184                                 fprintf(stderr, "erresc(default): gfx attr %d unknown\n", attr[i]), csidump();
1185                         break;
1186                 }
1187         }
1188 }
1189
1190 void
1191 tsetscroll(int t, int b) {
1192         int temp;
1193
1194         LIMIT(t, 0, term.row-1);
1195         LIMIT(b, 0, term.row-1);
1196         if(t > b) {
1197                 temp = t;
1198                 t = b;
1199                 b = temp;
1200         }
1201         term.top = t;
1202         term.bot = b;
1203 }
1204
1205 #define MODBIT(x, set, bit) ((set) ? ((x) |= (bit)) : ((x) &= ~(bit)))
1206
1207 void
1208 tsetmode(bool priv, bool set, int *args, int narg) {
1209         int *lim, mode;
1210
1211         for(lim = args + narg; args < lim; ++args) {
1212                 if(priv) {
1213                         switch(*args) {
1214                         case 1:
1215                                 MODBIT(term.mode, set, MODE_APPKEYPAD);
1216                                 break;
1217                         case 5: /* DECSCNM -- Reverve video */
1218                                 mode = term.mode;
1219                                 MODBIT(term.mode,set, MODE_REVERSE);
1220                                 if(mode != term.mode)
1221                                         redraw();
1222                                 break;
1223                         case 7:
1224                                 MODBIT(term.mode, set, MODE_WRAP);
1225                                 break;
1226                         case 20:
1227                                 MODBIT(term.mode, set, MODE_CRLF);
1228                                 break;
1229                         case 12: /* att610 -- Start blinking cursor (IGNORED) */
1230                                 break;
1231                         case 25:
1232                                 MODBIT(term.c.state, !set, CURSOR_HIDE);
1233                                 break;
1234                         case 1000: /* 1000,1002: enable xterm mouse report */
1235                                 MODBIT(term.mode, set, MODE_MOUSEBTN);
1236                                 break;
1237                         case 1002:
1238                                 MODBIT(term.mode, set, MODE_MOUSEMOTION);
1239                                 break;
1240                         case 1049: /* = 1047 and 1048 */
1241                         case 47:
1242                         case 1047:
1243                                 if(IS_SET(MODE_ALTSCREEN))
1244                                         tclearregion(0, 0, term.col-1, term.row-1);
1245                                 if((set && !IS_SET(MODE_ALTSCREEN)) ||
1246                                     (!set && IS_SET(MODE_ALTSCREEN))) {
1247                                             tswapscreen();
1248                                 }
1249                                 if(*args != 1049)
1250                                         break;
1251                                 /* pass through */
1252                         case 1048:
1253                                 tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
1254                                 break;
1255                         default:
1256                                 fprintf(stderr,
1257                                         "erresc: unknown private set/reset mode %d\n",
1258                                         *args);
1259                                 break;
1260                         }
1261                 } else {
1262                         switch(*args) {
1263                         case 4:
1264                                 MODBIT(term.mode, set, MODE_INSERT);
1265                                 break;
1266                         default:
1267                                 fprintf(stderr,
1268                                         "erresc: unknown set/reset mode %d\n",
1269                                         *args);
1270                                 break;
1271                         }
1272                 }
1273         }
1274 }
1275 #undef MODBIT
1276
1277
1278 void
1279 csihandle(void) {
1280         switch(csiescseq.mode) {
1281         default:
1282         unknown:
1283                 fprintf(stderr, "erresc: unknown csi ");
1284                 csidump();
1285                 /* die(""); */
1286                 break;
1287         case '@': /* ICH -- Insert <n> blank char */
1288                 DEFAULT(csiescseq.arg[0], 1);
1289                 tinsertblank(csiescseq.arg[0]);
1290                 break;
1291         case 'A': /* CUU -- Cursor <n> Up */
1292         case 'e':
1293                 DEFAULT(csiescseq.arg[0], 1);
1294                 tmoveto(term.c.x, term.c.y-csiescseq.arg[0]);
1295                 break;
1296         case 'B': /* CUD -- Cursor <n> Down */
1297                 DEFAULT(csiescseq.arg[0], 1);
1298                 tmoveto(term.c.x, term.c.y+csiescseq.arg[0]);
1299                 break;
1300         case 'C': /* CUF -- Cursor <n> Forward */
1301         case 'a':
1302                 DEFAULT(csiescseq.arg[0], 1);
1303                 tmoveto(term.c.x+csiescseq.arg[0], term.c.y);
1304                 break;
1305         case 'D': /* CUB -- Cursor <n> Backward */
1306                 DEFAULT(csiescseq.arg[0], 1);
1307                 tmoveto(term.c.x-csiescseq.arg[0], term.c.y);
1308                 break;
1309         case 'E': /* CNL -- Cursor <n> Down and first col */
1310                 DEFAULT(csiescseq.arg[0], 1);
1311                 tmoveto(0, term.c.y+csiescseq.arg[0]);
1312                 break;
1313         case 'F': /* CPL -- Cursor <n> Up and first col */
1314                 DEFAULT(csiescseq.arg[0], 1);
1315                 tmoveto(0, term.c.y-csiescseq.arg[0]);
1316                 break;
1317         case 'g': /* TBC -- Tabulation clear */
1318                 switch (csiescseq.arg[0]) {
1319                 case 0: /* clear current tab stop */
1320                         term.tabs[term.c.x] = 0;
1321                         break;
1322                 case 3: /* clear all the tabs */
1323                         memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1324                         break;
1325                 default:
1326                         goto unknown;
1327                 }
1328                 break;
1329         case 'G': /* CHA -- Move to <col> */
1330         case '`': /* HPA */
1331                 DEFAULT(csiescseq.arg[0], 1);
1332                 tmoveto(csiescseq.arg[0]-1, term.c.y);
1333                 break;
1334         case 'H': /* CUP -- Move to <row> <col> */
1335         case 'f': /* HVP */
1336                 DEFAULT(csiescseq.arg[0], 1);
1337                 DEFAULT(csiescseq.arg[1], 1);
1338                 tmoveto(csiescseq.arg[1]-1, csiescseq.arg[0]-1);
1339                 break;
1340         case 'I': /* CHT -- Cursor Forward Tabulation <n> tab stops */
1341                 DEFAULT(csiescseq.arg[0], 1);
1342                 while(csiescseq.arg[0]--)
1343                         tputtab(1);
1344                 break;
1345         case 'J': /* ED -- Clear screen */
1346                 sel.bx = -1;
1347                 switch(csiescseq.arg[0]) {
1348                 case 0: /* below */
1349                         tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1350                         if(term.c.y < term.row-1)
1351                                 tclearregion(0, term.c.y+1, term.col-1, term.row-1);
1352                         break;
1353                 case 1: /* above */
1354                         if(term.c.y > 1)
1355                                 tclearregion(0, 0, term.col-1, term.c.y-1);
1356                         tclearregion(0, term.c.y, term.c.x, term.c.y);
1357                         break;
1358                 case 2: /* all */
1359                         tclearregion(0, 0, term.col-1, term.row-1);
1360                         break;
1361                 default:
1362                         goto unknown;
1363                 }
1364                 break;
1365         case 'K': /* EL -- Clear line */
1366                 switch(csiescseq.arg[0]) {
1367                 case 0: /* right */
1368                         tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1369                         break;
1370                 case 1: /* left */
1371                         tclearregion(0, term.c.y, term.c.x, term.c.y);
1372                         break;
1373                 case 2: /* all */
1374                         tclearregion(0, term.c.y, term.col-1, term.c.y);
1375                         break;
1376                 }
1377                 break;
1378         case 'S': /* SU -- Scroll <n> line up */
1379                 DEFAULT(csiescseq.arg[0], 1);
1380                 tscrollup(term.top, csiescseq.arg[0]);
1381                 break;
1382         case 'T': /* SD -- Scroll <n> line down */
1383                 DEFAULT(csiescseq.arg[0], 1);
1384                 tscrolldown(term.top, csiescseq.arg[0]);
1385                 break;
1386         case 'L': /* IL -- Insert <n> blank lines */
1387                 DEFAULT(csiescseq.arg[0], 1);
1388                 tinsertblankline(csiescseq.arg[0]);
1389                 break;
1390         case 'l': /* RM -- Reset Mode */
1391                 tsetmode(csiescseq.priv, 0, csiescseq.arg, csiescseq.narg);
1392                 break;
1393         case 'M': /* DL -- Delete <n> lines */
1394                 DEFAULT(csiescseq.arg[0], 1);
1395                 tdeleteline(csiescseq.arg[0]);
1396                 break;
1397         case 'X': /* ECH -- Erase <n> char */
1398                 DEFAULT(csiescseq.arg[0], 1);
1399                 tclearregion(term.c.x, term.c.y, term.c.x + csiescseq.arg[0], term.c.y);
1400                 break;
1401         case 'P': /* DCH -- Delete <n> char */
1402                 DEFAULT(csiescseq.arg[0], 1);
1403                 tdeletechar(csiescseq.arg[0]);
1404                 break;
1405         case 'Z': /* CBT -- Cursor Backward Tabulation <n> tab stops */
1406                 DEFAULT(csiescseq.arg[0], 1);
1407                 while(csiescseq.arg[0]--)
1408                         tputtab(0);
1409                 break;
1410         case 'd': /* VPA -- Move to <row> */
1411                 DEFAULT(csiescseq.arg[0], 1);
1412                 tmoveto(term.c.x, csiescseq.arg[0]-1);
1413                 break;
1414         case 'h': /* SM -- Set terminal mode */
1415                 tsetmode(csiescseq.priv, 1, csiescseq.arg, csiescseq.narg);
1416                 break;
1417         case 'm': /* SGR -- Terminal attribute (color) */
1418                 tsetattr(csiescseq.arg, csiescseq.narg);
1419                 break;
1420         case 'r': /* DECSTBM -- Set Scrolling Region */
1421                 if(csiescseq.priv)
1422                         goto unknown;
1423                 else {
1424                         DEFAULT(csiescseq.arg[0], 1);
1425                         DEFAULT(csiescseq.arg[1], term.row);
1426                         tsetscroll(csiescseq.arg[0]-1, csiescseq.arg[1]-1);
1427                         tmoveto(0, 0);
1428                 }
1429                 break;
1430         case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
1431                 tcursor(CURSOR_SAVE);
1432                 break;
1433         case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
1434                 tcursor(CURSOR_LOAD);
1435                 break;
1436         }
1437 }
1438
1439 void
1440 csidump(void) {
1441         int i;
1442         printf("ESC[");
1443         for(i = 0; i < csiescseq.len; i++) {
1444                 uint c = csiescseq.buf[i] & 0xff;
1445                 if(isprint(c)) putchar(c);
1446                 else if(c == '\n') printf("(\\n)");
1447                 else if(c == '\r') printf("(\\r)");
1448                 else if(c == 0x1b) printf("(\\e)");
1449                 else printf("(%02x)", c);
1450         }
1451         putchar('\n');
1452 }
1453
1454 void
1455 csireset(void) {
1456         memset(&csiescseq, 0, sizeof(csiescseq));
1457 }
1458
1459 void
1460 strhandle(void) {
1461         char *p;
1462
1463         /*
1464          * TODO: make this being useful in case of color palette change.
1465          */
1466         strparse();
1467
1468         p = strescseq.buf;
1469
1470         switch(strescseq.type) {
1471         case ']': /* OSC -- Operating System Command */
1472                 switch(p[0]) {
1473                 case '0':
1474                 case '1':
1475                 case '2':
1476                         /*
1477                          * TODO: Handle special chars in string, like umlauts.
1478                          */
1479                         if(p[1] == ';') {
1480                                 XStoreName(xw.dpy, xw.win, strescseq.buf+2);
1481                         }
1482                         break;
1483                 case ';':
1484                         XStoreName(xw.dpy, xw.win, strescseq.buf+1);
1485                         break;
1486                 case '4': /* TODO: Set color (arg0) to "rgb:%hexr/$hexg/$hexb" (arg1) */
1487                         break;
1488                 default:
1489                         fprintf(stderr, "erresc: unknown str ");
1490                         strdump();
1491                         break;
1492                 }
1493                 break;
1494         case 'P': /* DSC -- Device Control String */
1495         case '_': /* APC -- Application Program Command */
1496         case '^': /* PM -- Privacy Message */
1497         default:
1498                 fprintf(stderr, "erresc: unknown str ");
1499                 strdump();
1500                 /* die(""); */
1501                 break;
1502         }
1503 }
1504
1505 void
1506 strparse(void) {
1507         /*
1508          * TODO: Implement parsing like for CSI when required.
1509          * Format: ESC type cmd ';' arg0 [';' argn] ESC \
1510          */
1511         return;
1512 }
1513
1514 void
1515 strdump(void) {
1516         int i;
1517         printf("ESC%c", strescseq.type);
1518         for(i = 0; i < strescseq.len; i++) {
1519                 uint c = strescseq.buf[i] & 0xff;
1520                 if(isprint(c)) putchar(c);
1521                 else if(c == '\n') printf("(\\n)");
1522                 else if(c == '\r') printf("(\\r)");
1523                 else if(c == 0x1b) printf("(\\e)");
1524                 else printf("(%02x)", c);
1525         }
1526         printf("ESC\\\n");
1527 }
1528
1529 void
1530 strreset(void) {
1531         memset(&strescseq, 0, sizeof(strescseq));
1532 }
1533
1534 void
1535 tputtab(bool forward) {
1536         unsigned x = term.c.x;
1537
1538         if(forward) {
1539                 if(x == term.col)
1540                         return;
1541                 for(++x; x < term.col && !term.tabs[x]; ++x)
1542                         /* nothing */ ;
1543         } else {
1544                 if(x == 0)
1545                         return;
1546                 for(--x; x > 0 && !term.tabs[x]; --x)
1547                         /* nothing */ ;
1548         }
1549         tmoveto(x, term.c.y);
1550 }
1551
1552 void
1553 tputc(char *c) {
1554         char ascii = *c;
1555
1556         if(fileio)
1557                 putc(ascii, fileio);
1558
1559         if(term.esc & ESC_START) {
1560                 if(term.esc & ESC_CSI) {
1561                         csiescseq.buf[csiescseq.len++] = ascii;
1562                         if(BETWEEN(ascii, 0x40, 0x7E) || csiescseq.len >= ESC_BUF_SIZ) {
1563                                 term.esc = 0;
1564                                 csiparse(), csihandle();
1565                         }
1566                 } else if(term.esc & ESC_STR) {
1567                         switch(ascii) {
1568                         case '\033':
1569                                 term.esc = ESC_START | ESC_STR_END;
1570                                 break;
1571                         case '\a': /* backwards compatibility to xterm */
1572                                 term.esc = 0;
1573                                 strhandle();
1574                                 break;
1575                         default:
1576                                 strescseq.buf[strescseq.len++] = ascii;
1577                                 if(strescseq.len+1 >= STR_BUF_SIZ) {
1578                                         term.esc = 0;
1579                                         strhandle();
1580                                 }
1581                         }
1582                 } else if(term.esc & ESC_STR_END) {
1583                         term.esc = 0;
1584                         if(ascii == '\\')
1585                                 strhandle();
1586                 } else if(term.esc & ESC_ALTCHARSET) {
1587                         switch(ascii) {
1588                         case '0': /* Line drawing crap */
1589                                 term.c.attr.mode |= ATTR_GFX;
1590                                 break;
1591                         case 'B': /* Back to regular text */
1592                                 term.c.attr.mode &= ~ATTR_GFX;
1593                                 break;
1594                         default:
1595                                 fprintf(stderr, "esc unhandled charset: ESC ( %c\n", ascii);
1596                         }
1597                         term.esc = 0;
1598                 } else {
1599                         switch(ascii) {
1600                         case '[':
1601                                 term.esc |= ESC_CSI;
1602                                 break;
1603                         case 'P': /* DCS -- Device Control String */
1604                         case '_': /* APC -- Application Program Command */
1605                         case '^': /* PM -- Privacy Message */
1606                         case ']': /* OSC -- Operating System Command */
1607                                 strreset();
1608                                 strescseq.type = ascii;
1609                                 term.esc |= ESC_STR;
1610                                 break;
1611                         case '(':
1612                                 term.esc |= ESC_ALTCHARSET;
1613                                 break;
1614                         case 'D': /* IND -- Linefeed */
1615                                 if(term.c.y == term.bot)
1616                                         tscrollup(term.top, 1);
1617                                 else
1618                                         tmoveto(term.c.x, term.c.y+1);
1619                                 term.esc = 0;
1620                                 break;
1621                         case 'E': /* NEL -- Next line */
1622                                 tnewline(1); /* always go to first col */
1623                                 term.esc = 0;
1624                                 break;
1625                         case 'H': /* HTS -- Horizontal tab stop */
1626                                 term.tabs[term.c.x] = 1;
1627                                 term.esc = 0;
1628                                 break;
1629                         case 'M': /* RI -- Reverse index */
1630                                 if(term.c.y == term.top)
1631                                         tscrolldown(term.top, 1);
1632                                 else
1633                                         tmoveto(term.c.x, term.c.y-1);
1634                                 term.esc = 0;
1635                                 break;
1636                         case 'c': /* RIS -- Reset to inital state */
1637                                 treset();
1638                                 term.esc = 0;
1639                                 break;
1640                         case '=': /* DECPAM -- Application keypad */
1641                                 term.mode |= MODE_APPKEYPAD;
1642                                 term.esc = 0;
1643                                 break;
1644                         case '>': /* DECPNM -- Normal keypad */
1645                                 term.mode &= ~MODE_APPKEYPAD;
1646                                 term.esc = 0;
1647                                 break;
1648                         case '7': /* DECSC -- Save Cursor */
1649                                 tcursor(CURSOR_SAVE);
1650                                 term.esc = 0;
1651                                 break;
1652                         case '8': /* DECRC -- Restore Cursor */
1653                                 tcursor(CURSOR_LOAD);
1654                                 term.esc = 0;
1655                                 break;
1656                         case '\\': /* ST -- Stop */
1657                                 term.esc = 0;
1658                                 break;
1659                         default:
1660                                 fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n",
1661                                     (uchar) ascii, isprint(ascii)?ascii:'.');
1662                                 term.esc = 0;
1663                         }
1664                 }
1665         } else {
1666                 if(sel.bx != -1 && BETWEEN(term.c.y, sel.by, sel.ey))
1667                         sel.bx = -1;
1668                 switch(ascii) {
1669                 case '\t':
1670                         tputtab(1);
1671                         break;
1672                 case '\b':
1673                         tmoveto(term.c.x-1, term.c.y);
1674                         break;
1675                 case '\r':
1676                         tmoveto(0, term.c.y);
1677                         break;
1678                 case '\f':
1679                 case '\v':
1680                 case '\n':
1681                         /* go to first col if the mode is set */
1682                         tnewline(IS_SET(MODE_CRLF));
1683                         break;
1684                 case '\a':
1685                         if(!(xw.state & WIN_FOCUSED))
1686                                 xseturgency(1);
1687                         break;
1688                 case '\033':
1689                         csireset();
1690                         term.esc = ESC_START;
1691                         break;
1692                 default:
1693                         if(IS_SET(MODE_WRAP) && term.c.state & CURSOR_WRAPNEXT)
1694                                 tnewline(1); /* always go to first col */
1695                         tsetchar(c);
1696                         if(term.c.x+1 < term.col)
1697                                 tmoveto(term.c.x+1, term.c.y);
1698                         else
1699                                 term.c.state |= CURSOR_WRAPNEXT;
1700                 }
1701         }
1702 }
1703
1704 int
1705 tresize(int col, int row) {
1706         int i, x;
1707         int minrow = MIN(row, term.row);
1708         int mincol = MIN(col, term.col);
1709         int slide = term.c.y - row + 1;
1710
1711         if(col < 1 || row < 1)
1712                 return 0;
1713
1714         /* free unneeded rows */
1715         i = 0;
1716         if(slide > 0) {
1717                 /* slide screen to keep cursor where we expect it -
1718                  * tscrollup would work here, but we can optimize to
1719                  * memmove because we're freeing the earlier lines */
1720                 for(/* i = 0 */; i < slide; i++) {
1721                         free(term.line[i]);
1722                         free(term.alt[i]);
1723                 }
1724                 memmove(term.line, term.line + slide, row * sizeof(Line));
1725                 memmove(term.alt, term.alt + slide, row * sizeof(Line));
1726         }
1727         for(i += row; i < term.row; i++) {
1728                 free(term.line[i]);
1729                 free(term.alt[i]);
1730         }
1731
1732         /* resize to new height */
1733         term.line = realloc(term.line, row * sizeof(Line));
1734         term.alt  = realloc(term.alt,  row * sizeof(Line));
1735         term.dirty = realloc(term.dirty, row * sizeof(*term.dirty));
1736         term.tabs = realloc(term.tabs, col * sizeof(*term.tabs));
1737
1738         /* resize each row to new width, zero-pad if needed */
1739         for(i = 0; i < minrow; i++) {
1740                 term.dirty[i] = 1;
1741                 term.line[i] = realloc(term.line[i], col * sizeof(Glyph));
1742                 term.alt[i]  = realloc(term.alt[i],  col * sizeof(Glyph));
1743                 for(x = mincol; x < col; x++) {
1744                         term.line[i][x].state = 0;
1745                         term.alt[i][x].state = 0;
1746                 }
1747         }
1748
1749         /* allocate any new rows */
1750         for(/* i == minrow */; i < row; i++) {
1751                 term.dirty[i] = 1;
1752                 term.line[i] = calloc(col, sizeof(Glyph));
1753                 term.alt [i] = calloc(col, sizeof(Glyph));
1754         }
1755         if(col > term.col) {
1756                 bool *bp = term.tabs + term.col;
1757
1758                 memset(bp, 0, sizeof(*term.tabs) * (col - term.col));
1759                 while(--bp > term.tabs && !*bp)
1760                         /* nothing */ ;
1761                 for(bp += TAB; bp < term.tabs + col; bp += TAB)
1762                         *bp = 1;
1763         }
1764         /* update terminal size */
1765         term.col = col, term.row = row;
1766         /* make use of the LIMIT in tmoveto */
1767         tmoveto(term.c.x, term.c.y);
1768         /* reset scrolling region */
1769         tsetscroll(0, row-1);
1770
1771         return (slide > 0);
1772 }
1773
1774 void
1775 xresize(int col, int row) {
1776         xw.w = MAX(1, 2*BORDER + col * xw.cw);
1777         xw.h = MAX(1, 2*BORDER + row * xw.ch);
1778 }
1779
1780 void
1781 xloadcols(void) {
1782         int i, r, g, b;
1783         XColor color;
1784         ulong white = WhitePixel(xw.dpy, xw.scr);
1785
1786         /* load colors [0-15] colors and [256-LEN(colorname)[ (config.h) */
1787         for(i = 0; i < LEN(colorname); i++) {
1788                 if(!colorname[i])
1789                         continue;
1790                 if(!XAllocNamedColor(xw.dpy, xw.cmap, colorname[i], &color, &color)) {
1791                         dc.col[i] = white;
1792                         fprintf(stderr, "Could not allocate color '%s'\n", colorname[i]);
1793                 } else
1794                         dc.col[i] = color.pixel;
1795         }
1796
1797         /* load colors [16-255] ; same colors as xterm */
1798         for(i = 16, r = 0; r < 6; r++)
1799                 for(g = 0; g < 6; g++)
1800                         for(b = 0; b < 6; b++) {
1801                                 color.red = r == 0 ? 0 : 0x3737 + 0x2828 * r;
1802                                 color.green = g == 0 ? 0 : 0x3737 + 0x2828 * g;
1803                                 color.blue = b == 0 ? 0 : 0x3737 + 0x2828 * b;
1804                                 if(!XAllocColor(xw.dpy, xw.cmap, &color)) {
1805                                         dc.col[i] = white;
1806                                         fprintf(stderr, "Could not allocate color %d\n", i);
1807                                 } else
1808                                         dc.col[i] = color.pixel;
1809                                 i++;
1810                         }
1811
1812         for(r = 0; r < 24; r++, i++) {
1813                 color.red = color.green = color.blue = 0x0808 + 0x0a0a * r;
1814                 if(!XAllocColor(xw.dpy, xw.cmap, &color)) {
1815                         dc.col[i] = white;
1816                         fprintf(stderr, "Could not allocate color %d\n", i);
1817                 } else
1818                         dc.col[i] = color.pixel;
1819         }
1820 }
1821
1822 void
1823 xclear(int x1, int y1, int x2, int y2) {
1824         XSetForeground(xw.dpy, dc.gc, dc.col[IS_SET(MODE_REVERSE) ? DefaultFG : DefaultBG]);
1825         XFillRectangle(xw.dpy, xw.buf, dc.gc,
1826                        BORDER + x1 * xw.cw, BORDER + y1 * xw.ch,
1827                        (x2-x1+1) * xw.cw, (y2-y1+1) * xw.ch);
1828 }
1829
1830 void
1831 xhints(void) {
1832         XClassHint class = {opt_class ? opt_class : TNAME, TNAME};
1833         XWMHints wm = {.flags = InputHint, .input = 1};
1834         XSizeHints *sizeh = NULL;
1835
1836         sizeh = XAllocSizeHints();
1837         if(xw.isfixed == False) {
1838                 sizeh->flags = PSize | PResizeInc | PBaseSize;
1839                 sizeh->height = xw.h;
1840                 sizeh->width = xw.w;
1841                 sizeh->height_inc = xw.ch;
1842                 sizeh->width_inc = xw.cw;
1843                 sizeh->base_height = 2*BORDER;
1844                 sizeh->base_width = 2*BORDER;
1845         } else {
1846                 sizeh->flags = PMaxSize | PMinSize;
1847                 sizeh->min_width = sizeh->max_width = xw.fw;
1848                 sizeh->min_height = sizeh->max_height = xw.fh;
1849         }
1850
1851         XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm, &class);
1852         XFree(sizeh);
1853 }
1854
1855 XFontSet
1856 xinitfont(char *fontstr) {
1857         XFontSet set;
1858         char *def, **missing;
1859         int n;
1860
1861         missing = NULL;
1862         set = XCreateFontSet(xw.dpy, fontstr, &missing, &n, &def);
1863         if(missing) {
1864                 while(n--)
1865                         fprintf(stderr, "st: missing fontset: %s\n", missing[n]);
1866                 XFreeStringList(missing);
1867         }
1868         return set;
1869 }
1870
1871 void
1872 xgetfontinfo(XFontSet set, int *ascent, int *descent, short *lbearing, short *rbearing) {
1873         XFontStruct **xfonts;
1874         char **font_names;
1875         int i, n;
1876
1877         *ascent = *descent = *lbearing = *rbearing = 0;
1878         n = XFontsOfFontSet(set, &xfonts, &font_names);
1879         for(i = 0; i < n; i++) {
1880                 *ascent = MAX(*ascent, (*xfonts)->ascent);
1881                 *descent = MAX(*descent, (*xfonts)->descent);
1882                 *lbearing = MAX(*lbearing, (*xfonts)->min_bounds.lbearing);
1883                 *rbearing = MAX(*rbearing, (*xfonts)->max_bounds.rbearing);
1884                 xfonts++;
1885         }
1886 }
1887
1888 void
1889 initfonts(char *fontstr, char *bfontstr) {
1890         if((dc.font.set = xinitfont(fontstr)) == NULL ||
1891            (dc.bfont.set = xinitfont(bfontstr)) == NULL)
1892                 die("Can't load font %s\n", dc.font.set ? BOLDFONT : FONT);
1893         xgetfontinfo(dc.font.set, &dc.font.ascent, &dc.font.descent,
1894             &dc.font.lbearing, &dc.font.rbearing);
1895         xgetfontinfo(dc.bfont.set, &dc.bfont.ascent, &dc.bfont.descent,
1896             &dc.bfont.lbearing, &dc.bfont.rbearing);
1897 }
1898
1899 void
1900 xinit(void) {
1901         XSetWindowAttributes attrs;
1902         Cursor cursor;
1903         Window parent;
1904         int sw, sh;
1905
1906         if(!(xw.dpy = XOpenDisplay(NULL)))
1907                 die("Can't open display\n");
1908         xw.scr = XDefaultScreen(xw.dpy);
1909
1910         /* adjust fixed window geometry */
1911         if(xw.isfixed) {
1912                 sw = DisplayWidth(xw.dpy, xw.scr);
1913                 sh = DisplayHeight(xw.dpy, xw.scr);
1914                 if(xw.fx < 0)
1915                         xw.fx = sw + xw.fx - xw.fw - 1;
1916                 if(xw.fy < 0)
1917                         xw.fy = sh + xw.fy - xw.fh - 1;
1918
1919                 xw.h = xw.fh;
1920                 xw.w = xw.fw;
1921         } else {
1922                 /* window - default size */
1923                 xw.h = 2*BORDER + term.row * xw.ch;
1924                 xw.w = 2*BORDER + term.col * xw.cw;
1925                 xw.fx = 0;
1926                 xw.fy = 0;
1927         }
1928
1929         /* font */
1930         initfonts(FONT, BOLDFONT);
1931
1932         /* XXX: Assuming same size for bold font */
1933         xw.cw = dc.font.rbearing - dc.font.lbearing;
1934         xw.ch = dc.font.ascent + dc.font.descent;
1935
1936         /* colors */
1937         xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
1938         xloadcols();
1939
1940         attrs.background_pixel = dc.col[DefaultBG];
1941         attrs.border_pixel = dc.col[DefaultBG];
1942         attrs.bit_gravity = NorthWestGravity;
1943         attrs.event_mask = FocusChangeMask | KeyPressMask
1944                 | ExposureMask | VisibilityChangeMask | StructureNotifyMask
1945                 | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask
1946                 | EnterWindowMask | LeaveWindowMask;
1947         attrs.colormap = xw.cmap;
1948
1949         parent = opt_embed ? strtol(opt_embed, NULL, 0) : XRootWindow(xw.dpy, xw.scr);
1950         xw.win = XCreateWindow(xw.dpy, parent, xw.fx, xw.fy,
1951                         xw.w, xw.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
1952                         XDefaultVisual(xw.dpy, xw.scr),
1953                         CWBackPixel | CWBorderPixel | CWBitGravity | CWEventMask
1954                         | CWColormap,
1955                         &attrs);
1956         xw.buf = XdbeAllocateBackBufferName(xw.dpy, xw.win, XdbeCopied);
1957
1958
1959         /* input methods */
1960         xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL);
1961         xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
1962                                            | XIMStatusNothing, XNClientWindow, xw.win,
1963                                            XNFocusWindow, xw.win, NULL);
1964         /* gc */
1965         dc.gc = XCreateGC(xw.dpy, xw.win, 0, NULL);
1966
1967         /* white cursor, black outline */
1968         cursor = XCreateFontCursor(xw.dpy, XC_xterm);
1969         XDefineCursor(xw.dpy, xw.win, cursor);
1970         XRecolorCursor(xw.dpy, cursor,
1971                 &(XColor){.red = 0xffff, .green = 0xffff, .blue = 0xffff},
1972                 &(XColor){.red = 0x0000, .green = 0x0000, .blue = 0x0000});
1973
1974         xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
1975
1976         XStoreName(xw.dpy, xw.win, opt_title ? opt_title : "st");
1977         XMapWindow(xw.dpy, xw.win);
1978         xhints();
1979         XSync(xw.dpy, 0);
1980 }
1981
1982 void
1983 xdraws(char *s, Glyph base, int x, int y, int charlen, int bytelen) {
1984         int fg = base.fg, bg = base.bg, temp;
1985         int winx = BORDER+x*xw.cw, winy = BORDER+y*xw.ch + dc.font.ascent, width = charlen*xw.cw;
1986         XFontSet fontset = dc.font.set;
1987         int i;
1988
1989         /* only switch default fg/bg if term is in RV mode */
1990         if(IS_SET(MODE_REVERSE)) {
1991                 if(fg == DefaultFG)
1992                         fg = DefaultBG;
1993                 if(bg == DefaultBG)
1994                         bg = DefaultFG;
1995         }
1996
1997         if(base.mode & ATTR_REVERSE)
1998                 temp = fg, fg = bg, bg = temp;
1999
2000         if(base.mode & ATTR_BOLD) {
2001                 fg += 8;
2002                 fontset = dc.bfont.set;
2003         }
2004
2005         XSetBackground(xw.dpy, dc.gc, dc.col[bg]);
2006         XSetForeground(xw.dpy, dc.gc, dc.col[fg]);
2007
2008         if(base.mode & ATTR_GFX) {
2009                 for(i = 0; i < bytelen; i++) {
2010                         char c = gfx[(uint)s[i] % 256];
2011                         if(c)
2012                                 s[i] = c;
2013                         else if(s[i] > 0x5f)
2014                                 s[i] -= 0x5f;
2015                 }
2016         }
2017
2018         XmbDrawImageString(xw.dpy, xw.buf, fontset, dc.gc, winx, winy, s, bytelen);
2019
2020         if(base.mode & ATTR_UNDERLINE)
2021                 XDrawLine(xw.dpy, xw.buf, dc.gc, winx, winy+1, winx+width-1, winy+1);
2022 }
2023
2024 /* copy buffer pixmap to screen pixmap */
2025 void
2026 xcopy() {
2027         XdbeSwapInfo swpinfo[1] = {{xw.win, XdbeCopied}};
2028         XdbeSwapBuffers(xw.dpy, swpinfo, 1);
2029
2030 }
2031
2032 void
2033 xdrawcursor(void) {
2034         static int oldx = 0;
2035         static int oldy = 0;
2036         int sl;
2037         Glyph g = {{' '}, ATTR_NULL, DefaultBG, DefaultCS, 0};
2038
2039         LIMIT(oldx, 0, term.col-1);
2040         LIMIT(oldy, 0, term.row-1);
2041
2042         if(term.line[term.c.y][term.c.x].state & GLYPH_SET)
2043                 memcpy(g.c, term.line[term.c.y][term.c.x].c, UTF_SIZ);
2044
2045         /* remove the old cursor */
2046         if(term.line[oldy][oldx].state & GLYPH_SET) {
2047                 sl = utf8size(term.line[oldy][oldx].c);
2048                 xdraws(term.line[oldy][oldx].c, term.line[oldy][oldx], oldx, oldy, 1, sl);
2049         } else
2050                 xclear(oldx, oldy, oldx, oldy);
2051
2052         xcopy(oldx, oldy, 1, 1);
2053
2054         /* draw the new one */
2055         if(!(term.c.state & CURSOR_HIDE)) {
2056                 if(!(xw.state & WIN_FOCUSED))
2057                         g.bg = DefaultUCS;
2058
2059                 if(IS_SET(MODE_REVERSE))
2060                         g.mode |= ATTR_REVERSE, g.fg = DefaultCS, g.bg = DefaultFG;
2061
2062                 sl = utf8size(g.c);
2063                 xdraws(g.c, g, term.c.x, term.c.y, 1, sl);
2064                 oldx = term.c.x, oldy = term.c.y;
2065         }
2066
2067         xcopy(term.c.x, term.c.y, 1, 1);
2068 }
2069
2070 void
2071 redraw(void) {
2072         struct timespec tv = {0, REDRAW_TIMEOUT * 1000};
2073         tfulldirt();
2074         draw();
2075         nanosleep(&tv, NULL);
2076 }
2077
2078 void
2079 draw() {
2080         drawregion(0, 0, term.col, term.row);
2081         xcopy();
2082         gettimeofday(&xw.lastdraw, NULL);
2083 }
2084
2085 void
2086 drawregion(int x1, int y1, int x2, int y2) {
2087         int ic, ib, x, y, ox, sl;
2088         Glyph base, new;
2089         char buf[DRAW_BUF_SIZ];
2090         bool ena_sel = sel.bx != -1, alt = IS_SET(MODE_ALTSCREEN);
2091
2092         if((sel.alt && !alt) || (!sel.alt && alt))
2093                 ena_sel = 0;
2094         if(!(xw.state & WIN_VISIBLE))
2095                 return;
2096
2097         for(y = y1; y < y2; y++) {
2098                 if(!term.dirty[y])
2099                         continue;
2100                 xclear(0, y, term.col, y);
2101                 term.dirty[y] = 0;
2102                 base = term.line[y][0];
2103                 ic = ib = ox = 0;
2104                 for(x = x1; x < x2; x++) {
2105                         new = term.line[y][x];
2106                         if(ena_sel && *(new.c) && selected(x, y))
2107                                 new.mode ^= ATTR_REVERSE;
2108                         if(ib > 0 && (!(new.state & GLYPH_SET) || ATTRCMP(base, new) ||
2109                                                   ib >= DRAW_BUF_SIZ-UTF_SIZ)) {
2110                                 xdraws(buf, base, ox, y, ic, ib);
2111                                 ic = ib = 0;
2112                         }
2113                         if(new.state & GLYPH_SET) {
2114                                 if(ib == 0) {
2115                                         ox = x;
2116                                         base = new;
2117                                 }
2118                                 sl = utf8size(new.c);
2119                                 memcpy(buf+ib, new.c, sl);
2120                                 ib += sl;
2121                                 ++ic;
2122                         }
2123                 }
2124                 if(ib > 0)
2125                         xdraws(buf, base, ox, y, ic, ib);
2126         }
2127         xdrawcursor();
2128 }
2129
2130 void
2131 expose(XEvent *ev) {
2132         XExposeEvent *e = &ev->xexpose;
2133         if(xw.state & WIN_REDRAW) {
2134                 if(!e->count)
2135                         xw.state &= ~WIN_REDRAW;
2136         }
2137         xcopy();
2138 }
2139
2140 void
2141 visibility(XEvent *ev) {
2142         XVisibilityEvent *e = &ev->xvisibility;
2143         if(e->state == VisibilityFullyObscured)
2144                 xw.state &= ~WIN_VISIBLE;
2145         else if(!(xw.state & WIN_VISIBLE))
2146                 /* need a full redraw for next Expose, not just a buf copy */
2147                 xw.state |= WIN_VISIBLE | WIN_REDRAW;
2148 }
2149
2150 void
2151 unmap(XEvent *ev) {
2152         xw.state &= ~WIN_VISIBLE;
2153 }
2154
2155 void
2156 xseturgency(int add) {
2157         XWMHints *h = XGetWMHints(xw.dpy, xw.win);
2158         h->flags = add ? (h->flags | XUrgencyHint) : (h->flags & ~XUrgencyHint);
2159         XSetWMHints(xw.dpy, xw.win, h);
2160         XFree(h);
2161 }
2162
2163 void
2164 focus(XEvent *ev) {
2165         if(ev->type == FocusIn) {
2166                 xw.state |= WIN_FOCUSED;
2167                 xseturgency(0);
2168         } else
2169                 xw.state &= ~WIN_FOCUSED;
2170         draw();
2171 }
2172
2173 char*
2174 kmap(KeySym k, uint state) {
2175         int i;
2176         state &= ~Mod2Mask;
2177         for(i = 0; i < LEN(key); i++) {
2178                 uint mask = key[i].mask;
2179                 if(key[i].k == k && ((state & mask) == mask || (mask == XK_NO_MOD && !state)))
2180                         return (char*)key[i].s;
2181         }
2182         return NULL;
2183 }
2184
2185 void
2186 kpress(XEvent *ev) {
2187         XKeyEvent *e = &ev->xkey;
2188         KeySym ksym;
2189         char buf[32];
2190         char *customkey;
2191         int len;
2192         int meta;
2193         int shift;
2194         Status status;
2195
2196         meta = e->state & Mod1Mask;
2197         shift = e->state & ShiftMask;
2198         len = XmbLookupString(xw.xic, e, buf, sizeof(buf), &ksym, &status);
2199
2200         /* 1. custom keys from config.h */
2201         if((customkey = kmap(ksym, e->state)))
2202                 ttywrite(customkey, strlen(customkey));
2203         /* 2. hardcoded (overrides X lookup) */
2204         else
2205                 switch(ksym) {
2206                 case XK_Up:
2207                 case XK_Down:
2208                 case XK_Left:
2209                 case XK_Right:
2210                         /* XXX: shift up/down doesn't work */
2211                         sprintf(buf, "\033%c%c", IS_SET(MODE_APPKEYPAD) ? 'O' : '[', (shift ? "dacb":"DACB")[ksym - XK_Left]);
2212                         ttywrite(buf, 3);
2213                         break;
2214                 case XK_Insert:
2215                         if(shift)
2216                                 selpaste();
2217                         break;
2218                 case XK_Return:
2219                         if(IS_SET(MODE_CRLF))
2220                                 ttywrite("\r\n", 2);
2221                         else
2222                                 ttywrite("\r", 1);
2223                         break;
2224                         /* 3. X lookup  */
2225                 default:
2226                         if(len > 0) {
2227                                 if(meta && len == 1)
2228                                         ttywrite("\033", 1);
2229                                 ttywrite(buf, len);
2230                         }
2231                         break;
2232                 }
2233 }
2234
2235 void
2236 cmessage(XEvent *e) {
2237         /* See xembed specs
2238            http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html */
2239         if(e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
2240                 if(e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
2241                         xw.state |= WIN_FOCUSED;
2242                         xseturgency(0);
2243                 } else if(e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
2244                         xw.state &= ~WIN_FOCUSED;
2245                 }
2246                 draw();
2247         }
2248 }
2249
2250 void
2251 resize(XEvent *e) {
2252         int col, row;
2253
2254         if(e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
2255                 return;
2256
2257         xw.w = e->xconfigure.width;
2258         xw.h = e->xconfigure.height;
2259         col = (xw.w - 2*BORDER) / xw.cw;
2260         row = (xw.h - 2*BORDER) / xw.ch;
2261         if(col == term.col && row == term.row)
2262                 return;
2263         if(tresize(col, row))
2264                 draw();
2265         xresize(col, row);
2266         ttyresize(col, row);
2267 }
2268
2269 bool
2270 last_draw_too_old(void) {
2271         struct timeval now;
2272         gettimeofday(&now, NULL);
2273         return TIMEDIFF(now, xw.lastdraw) >= DRAW_TIMEOUT/1000;
2274 }
2275
2276 void
2277 run(void) {
2278         XEvent ev;
2279         fd_set rfd;
2280         int xfd = XConnectionNumber(xw.dpy);
2281         struct timeval timeout = {0};
2282         bool stuff_to_print = 0;
2283
2284         for(;;) {
2285                 FD_ZERO(&rfd);
2286                 FD_SET(cmdfd, &rfd);
2287                 FD_SET(xfd, &rfd);
2288                 timeout.tv_sec  = 0;
2289                 timeout.tv_usec = SELECT_TIMEOUT;
2290                 if(select(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, &timeout) < 0) {
2291                         if(errno == EINTR)
2292                                 continue;
2293                         die("select failed: %s\n", SERRNO);
2294                 }
2295                 if(FD_ISSET(cmdfd, &rfd)) {
2296                         ttyread();
2297                         stuff_to_print = 1;
2298                 }
2299
2300                 if(stuff_to_print && last_draw_too_old()) {
2301                         stuff_to_print = 0;
2302                         draw();
2303                 }
2304
2305                 while(XPending(xw.dpy)) {
2306                         XNextEvent(xw.dpy, &ev);
2307                         if(XFilterEvent(&ev, xw.win))
2308                                 continue;
2309                         if(handler[ev.type])
2310                                 (handler[ev.type])(&ev);
2311                 }
2312         }
2313 }
2314
2315 int
2316 main(int argc, char *argv[]) {
2317         int i, bitm, xr, yr;
2318         unsigned int wr, hr;
2319
2320         xw.fw = xw.fh = xw.fx = xw.fy = 0;
2321         xw.isfixed = False;
2322
2323         for(i = 1; i < argc; i++) {
2324                 switch(argv[i][0] != '-' || argv[i][2] ? -1 : argv[i][1]) {
2325                 case 't':
2326                         if(++i < argc) opt_title = argv[i];
2327                         break;
2328                 case 'c':
2329                         if(++i < argc) opt_class = argv[i];
2330                         break;
2331                 case 'w':
2332                         if(++i < argc) opt_embed = argv[i];
2333                         break;
2334                 case 'f':
2335                         if(++i < argc) opt_io = argv[i];
2336                         break;
2337                 case 'e':
2338                         /* eat every remaining arguments */
2339                         if(++i < argc) opt_cmd = &argv[i];
2340                         goto run;
2341                 case 'g':
2342                         if(++i >= argc)
2343                                 break;
2344
2345                         bitm = XParseGeometry(argv[i], &xr, &yr, &wr, &hr);
2346                         if(bitm & XValue)
2347                                 xw.fx = xr;
2348                         if(bitm & YValue)
2349                                 xw.fy = yr;
2350                         if(bitm & WidthValue)
2351                                 xw.fw = (int)wr;
2352                         if(bitm & HeightValue)
2353                                 xw.fh = (int)hr;
2354                         if(bitm & XNegative && xw.fx == 0)
2355                                 xw.fx = -1;
2356                         if(bitm & XNegative && xw.fy == 0)
2357                                 xw.fy = -1;
2358
2359                         if(xw.fh != 0 && xw.fw != 0)
2360                                 xw.isfixed = True;
2361                         break;
2362                 case 'v':
2363                 default:
2364                         die(USAGE);
2365                 }
2366         }
2367
2368  run:
2369         setlocale(LC_CTYPE, "");
2370         tnew(80, 24);
2371         ttynew();
2372         xinit();
2373         selinit();
2374         run();
2375         return 0;
2376 }
2377