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