Xinqi Bao's Git

Remove duplicated code in strhandle
[st.git] / st.c
1 /* See LICENSE for licence details. */
2 #include <ctype.h>
3 #include <errno.h>
4 #include <fcntl.h>
5 #include <limits.h>
6 #include <locale.h>
7 #include <pwd.h>
8 #include <stdarg.h>
9 #include <stdbool.h>
10 #include <stdio.h>
11 #include <stdlib.h>
12 #include <string.h>
13 #include <signal.h>
14 #include <stdint.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 <libgen.h>
24 #include <X11/Xatom.h>
25 #include <X11/Xlib.h>
26 #include <X11/Xutil.h>
27 #include <X11/cursorfont.h>
28 #include <X11/keysym.h>
29 #include <X11/Xft/Xft.h>
30 #include <fontconfig/fontconfig.h>
31 #include <wchar.h>
32
33 #include "arg.h"
34
35 char *argv0;
36
37 #define Glyph Glyph_
38 #define Font Font_
39 #define Draw XftDraw *
40 #define Colour XftColor
41 #define Colourmap Colormap
42 #define Rectangle XRectangle
43
44 #if defined(__linux)
45 #include <pty.h>
46 #elif defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
47 #include <util.h>
48 #elif defined(__FreeBSD__) || defined(__DragonFly__)
49 #include <libutil.h>
50 #endif
51
52
53 /* XEMBED messages */
54 #define XEMBED_FOCUS_IN 4
55 #define XEMBED_FOCUS_OUT 5
56
57 /* Arbitrary sizes */
58 #define UTF_SIZ 4
59 #define ESC_BUF_SIZ (128*UTF_SIZ)
60 #define ESC_ARG_SIZ 16
61 #define STR_BUF_SIZ ESC_BUF_SIZ
62 #define STR_ARG_SIZ ESC_ARG_SIZ
63 #define DRAW_BUF_SIZ 20*1024
64 #define XK_ANY_MOD UINT_MAX
65 #define XK_NO_MOD 0
66 #define XK_SWITCH_MOD (1<<13)
67
68 #define REDRAW_TIMEOUT (80*1000) /* 80 ms */
69
70 /* macros */
71 #define SERRNO strerror(errno)
72 #define MIN(a, b) ((a) < (b) ? (a) : (b))
73 #define MAX(a, b) ((a) < (b) ? (b) : (a))
74 #define LEN(a) (sizeof(a) / sizeof(a[0]))
75 #define DEFAULT(a, b) (a) = (a) ? (a) : (b)
76 #define BETWEEN(x, a, b) ((a) <= (x) && (x) <= (b))
77 #define LIMIT(x, a, b) (x) = (x) < (a) ? (a) : (x) > (b) ? (b) : (x)
78 #define ATTRCMP(a, b) ((a).mode != (b).mode || (a).fg != (b).fg || (a).bg != (b).bg)
79 #define IS_SET(flag) ((term.mode & (flag)) != 0)
80 #define TIMEDIFF(t1, t2) ((t1.tv_sec-t2.tv_sec)*1000 + (t1.tv_usec-t2.tv_usec)/1000)
81 #define CEIL(x) (((x) != (int) (x)) ? (x) + 1 : (x))
82
83 #define TRUECOLOR(r,g,b) (1 << 24 | (r) << 16 | (g) << 8 | (b))
84 #define IS_TRUECOL(x) (1 << 24 & (x))
85 #define TRUERED(x) (((x) & 0xff0000) >> 8)
86 #define TRUEGREEN(x) (((x) & 0xff00))
87 #define TRUEBLUE(x) (((x) & 0xff) << 8)
88
89
90 #define VT102ID "\033[?6c"
91
92 enum glyph_attribute {
93 ATTR_NULL = 0,
94 ATTR_REVERSE = 1,
95 ATTR_UNDERLINE = 2,
96 ATTR_BOLD = 4,
97 ATTR_GFX = 8,
98 ATTR_ITALIC = 16,
99 ATTR_BLINK = 32,
100 ATTR_WRAP = 64,
101 ATTR_WIDE = 128,
102 ATTR_WDUMMY = 256,
103 };
104
105 enum cursor_movement {
106 CURSOR_SAVE,
107 CURSOR_LOAD
108 };
109
110 enum cursor_state {
111 CURSOR_DEFAULT = 0,
112 CURSOR_WRAPNEXT = 1,
113 CURSOR_ORIGIN = 2
114 };
115
116 enum term_mode {
117 MODE_WRAP = 1,
118 MODE_INSERT = 2,
119 MODE_APPKEYPAD = 4,
120 MODE_ALTSCREEN = 8,
121 MODE_CRLF = 16,
122 MODE_MOUSEBTN = 32,
123 MODE_MOUSEMOTION = 64,
124 MODE_REVERSE = 128,
125 MODE_KBDLOCK = 256,
126 MODE_HIDE = 512,
127 MODE_ECHO = 1024,
128 MODE_APPCURSOR = 2048,
129 MODE_MOUSESGR = 4096,
130 MODE_8BIT = 8192,
131 MODE_BLINK = 16384,
132 MODE_FBLINK = 32768,
133 MODE_FOCUS = 65536,
134 MODE_MOUSEX10 = 131072,
135 MODE_MOUSEMANY = 262144,
136 MODE_BRCKTPASTE = 524288,
137 MODE_MOUSE = MODE_MOUSEBTN|MODE_MOUSEMOTION|MODE_MOUSEX10\
138 |MODE_MOUSEMANY,
139 };
140
141 enum charset {
142 CS_GRAPHIC0,
143 CS_GRAPHIC1,
144 CS_UK,
145 CS_USA,
146 CS_MULTI,
147 CS_GER,
148 CS_FIN
149 };
150
151 enum escape_state {
152 ESC_START = 1,
153 ESC_CSI = 2,
154 ESC_STR = 4, /* DSC, OSC, PM, APC */
155 ESC_ALTCHARSET = 8,
156 ESC_STR_END = 16, /* a final string was encountered */
157 ESC_TEST = 32, /* Enter in test mode */
158 };
159
160 enum window_state {
161 WIN_VISIBLE = 1,
162 WIN_REDRAW = 2,
163 WIN_FOCUSED = 4
164 };
165
166 enum selection_type {
167 SEL_REGULAR = 1,
168 SEL_RECTANGULAR = 2
169 };
170
171 enum selection_snap {
172 SNAP_WORD = 1,
173 SNAP_LINE = 2
174 };
175
176 typedef unsigned char uchar;
177 typedef unsigned int uint;
178 typedef unsigned long ulong;
179 typedef unsigned short ushort;
180
181 typedef struct {
182 char c[UTF_SIZ]; /* character code */
183 ushort mode; /* attribute flags */
184 uint32_t fg; /* foreground */
185 uint32_t bg; /* background */
186 } Glyph;
187
188 typedef Glyph *Line;
189
190 typedef struct {
191 Glyph attr; /* current char attributes */
192 int x;
193 int y;
194 char state;
195 } TCursor;
196
197 /* CSI Escape sequence structs */
198 /* ESC '[' [[ [<priv>] <arg> [;]] <mode>] */
199 typedef struct {
200 char buf[ESC_BUF_SIZ]; /* raw string */
201 int len; /* raw string length */
202 char priv;
203 int arg[ESC_ARG_SIZ];
204 int narg; /* nb of args */
205 char mode;
206 } CSIEscape;
207
208 /* STR Escape sequence structs */
209 /* ESC type [[ [<priv>] <arg> [;]] <mode>] ESC '\' */
210 typedef struct {
211 char type; /* ESC type ... */
212 char buf[STR_BUF_SIZ]; /* raw string */
213 int len; /* raw string length */
214 char *args[STR_ARG_SIZ];
215 int narg; /* nb of args */
216 } STREscape;
217
218 /* Internal representation of the screen */
219 typedef struct {
220 int row; /* nb row */
221 int col; /* nb col */
222 Line *line; /* screen */
223 Line *alt; /* alternate screen */
224 bool *dirty; /* dirtyness of lines */
225 TCursor c; /* cursor */
226 int top; /* top scroll limit */
227 int bot; /* bottom scroll limit */
228 int mode; /* terminal mode flags */
229 int esc; /* escape state flags */
230 char trantbl[4]; /* charset table translation */
231 int charset; /* current charset */
232 int icharset; /* selected charset for sequence */
233 bool numlock; /* lock numbers in keyboard */
234 bool *tabs;
235 } Term;
236
237 /* Purely graphic info */
238 typedef struct {
239 Display *dpy;
240 Colourmap cmap;
241 Window win;
242 Drawable buf;
243 Atom xembed, wmdeletewin, netwmname, netwmpid;
244 XIM xim;
245 XIC xic;
246 Draw draw;
247 Visual *vis;
248 XSetWindowAttributes attrs;
249 int scr;
250 bool isfixed; /* is fixed geometry? */
251 int fx, fy, fw, fh; /* fixed geometry */
252 int tw, th; /* tty width and height */
253 int w, h; /* window width and height */
254 int ch; /* char height */
255 int cw; /* char width */
256 char state; /* focus, redraw, visible */
257 } XWindow;
258
259 typedef struct {
260 uint b;
261 uint mask;
262 char *s;
263 } Mousekey;
264
265 typedef struct {
266 KeySym k;
267 uint mask;
268 char *s;
269 /* three valued logic variables: 0 indifferent, 1 on, -1 off */
270 signed char appkey; /* application keypad */
271 signed char appcursor; /* application cursor */
272 signed char crlf; /* crlf mode */
273 } Key;
274
275 typedef struct {
276 int mode;
277 int type;
278 int snap;
279 /*
280 * Selection variables:
281 * nb – normalized coordinates of the beginning of the selection
282 * ne – normalized coordinates of the end of the selection
283 * ob – original coordinates of the beginning of the selection
284 * oe – original coordinates of the end of the selection
285 */
286 struct {
287 int x, y;
288 } nb, ne, ob, oe;
289
290 char *clip;
291 Atom xtarget;
292 bool alt;
293 struct timeval tclick1;
294 struct timeval tclick2;
295 } Selection;
296
297 typedef union {
298 int i;
299 unsigned int ui;
300 float f;
301 const void *v;
302 } Arg;
303
304 typedef struct {
305 unsigned int mod;
306 KeySym keysym;
307 void (*func)(const Arg *);
308 const Arg arg;
309 } Shortcut;
310
311 /* function definitions used in config.h */
312 static void clippaste(const Arg *);
313 static void numlock(const Arg *);
314 static void selpaste(const Arg *);
315 static void xzoom(const Arg *);
316
317 /* Config.h for applying patches and the configuration. */
318 #include "config.h"
319
320 /* Font structure */
321 typedef struct {
322 int height;
323 int width;
324 int ascent;
325 int descent;
326 short lbearing;
327 short rbearing;
328 XftFont *match;
329 FcFontSet *set;
330 FcPattern *pattern;
331 } Font;
332
333 /* Drawing Context */
334 typedef struct {
335 Colour col[LEN(colorname) < 256 ? 256 : LEN(colorname)];
336 Font font, bfont, ifont, ibfont;
337 GC gc;
338 } DC;
339
340 static void die(const char *, ...);
341 static void draw(void);
342 static void redraw(int);
343 static void drawregion(int, int, int, int);
344 static void execsh(void);
345 static void sigchld(int);
346 static void run(void);
347
348 static void csidump(void);
349 static void csihandle(void);
350 static void csiparse(void);
351 static void csireset(void);
352 static void strdump(void);
353 static void strhandle(void);
354 static void strparse(void);
355 static void strreset(void);
356
357 static int tattrset(int);
358 static void tclearregion(int, int, int, int);
359 static void tcursor(int);
360 static void tdeletechar(int);
361 static void tdeleteline(int);
362 static void tinsertblank(int);
363 static void tinsertblankline(int);
364 static void tmoveto(int, int);
365 static void tmoveato(int x, int y);
366 static void tnew(int, int);
367 static void tnewline(int);
368 static void tputtab(bool);
369 static void tputc(char *, int);
370 static void treset(void);
371 static int tresize(int, int);
372 static void tscrollup(int, int);
373 static void tscrolldown(int, int);
374 static void tsetattr(int*, int);
375 static void tsetchar(char *, Glyph *, int, int);
376 static void tsetscroll(int, int);
377 static void tswapscreen(void);
378 static void tsetdirt(int, int);
379 static void tsetdirtattr(int);
380 static void tsetmode(bool, bool, int *, int);
381 static void tfulldirt(void);
382 static void techo(char *, int);
383 static int32_t tdefcolor(int *, int *, int);
384 static void tselcs(void);
385 static void tdeftran(char);
386 static inline bool match(uint, uint);
387 static void ttynew(void);
388 static void ttyread(void);
389 static void ttyresize(void);
390 static void ttysend(char *, size_t);
391 static void ttywrite(const char *, size_t);
392
393 static void xdraws(char *, Glyph, int, int, int, int);
394 static void xhints(void);
395 static void xclear(int, int, int, int);
396 static void xdrawcursor(void);
397 static void xinit(void);
398 static void xloadcols(void);
399 static int xsetcolorname(int, const char *);
400 static int xloadfont(Font *, FcPattern *);
401 static void xloadfonts(char *, double);
402 static int xloadfontset(Font *);
403 static void xsettitle(char *);
404 static void xresettitle(void);
405 static void xsetpointermotion(int);
406 static void xseturgency(int);
407 static void xsetsel(char*);
408 static void xtermclear(int, int, int, int);
409 static void xunloadfont(Font *f);
410 static void xunloadfonts(void);
411 static void xresize(int, int);
412
413 static void expose(XEvent *);
414 static void visibility(XEvent *);
415 static void unmap(XEvent *);
416 static char *kmap(KeySym, uint);
417 static void kpress(XEvent *);
418 static void cmessage(XEvent *);
419 static void cresize(int, int);
420 static void resize(XEvent *);
421 static void focus(XEvent *);
422 static void brelease(XEvent *);
423 static void bpress(XEvent *);
424 static void bmotion(XEvent *);
425 static void selnotify(XEvent *);
426 static void selclear(XEvent *);
427 static void selrequest(XEvent *);
428
429 static void selinit(void);
430 static void selsort(void);
431 static inline bool selected(int, int);
432 static void selcopy(void);
433 static void selscroll(int, int);
434 static void selsnap(int, int *, int *, int);
435
436 static int utf8decode(char *, long *);
437 static int utf8encode(long *, char *);
438 static int utf8size(char *);
439 static int isfullutf8(char *, int);
440
441 static ssize_t xwrite(int, char *, size_t);
442 static void *xmalloc(size_t);
443 static void *xrealloc(void *, size_t);
444
445 static void (*handler[LASTEvent])(XEvent *) = {
446 [KeyPress] = kpress,
447 [ClientMessage] = cmessage,
448 [ConfigureNotify] = resize,
449 [VisibilityNotify] = visibility,
450 [UnmapNotify] = unmap,
451 [Expose] = expose,
452 [FocusIn] = focus,
453 [FocusOut] = focus,
454 [MotionNotify] = bmotion,
455 [ButtonPress] = bpress,
456 [ButtonRelease] = brelease,
457 [SelectionClear] = selclear,
458 [SelectionNotify] = selnotify,
459 [SelectionRequest] = selrequest,
460 };
461
462 /* Globals */
463 static DC dc;
464 static XWindow xw;
465 static Term term;
466 static CSIEscape csiescseq;
467 static STREscape strescseq;
468 static int cmdfd;
469 static pid_t pid;
470 static Selection sel;
471 static int iofd = -1;
472 static char **opt_cmd = NULL;
473 static char *opt_io = NULL;
474 static char *opt_title = NULL;
475 static char *opt_embed = NULL;
476 static char *opt_class = NULL;
477 static char *opt_font = NULL;
478 static int oldbutton = 3; /* button event on startup: 3 = release */
479
480 static char *usedfont = NULL;
481 static double usedfontsize = 0;
482
483 /* Font Ring Cache */
484 enum {
485 FRC_NORMAL,
486 FRC_ITALIC,
487 FRC_BOLD,
488 FRC_ITALICBOLD
489 };
490
491 typedef struct {
492 XftFont *font;
493 int flags;
494 } Fontcache;
495
496 /* Fontcache is an array now. A new font will be appended to the array. */
497 static Fontcache frc[16];
498 static int frclen = 0;
499
500 ssize_t
501 xwrite(int fd, char *s, size_t len) {
502 size_t aux = len;
503
504 while(len > 0) {
505 ssize_t r = write(fd, s, len);
506 if(r < 0)
507 return r;
508 len -= r;
509 s += r;
510 }
511 return aux;
512 }
513
514 void *
515 xmalloc(size_t len) {
516 void *p = malloc(len);
517
518 if(!p)
519 die("Out of memory\n");
520
521 return p;
522 }
523
524 void *
525 xrealloc(void *p, size_t len) {
526 if((p = realloc(p, len)) == NULL)
527 die("Out of memory\n");
528
529 return p;
530 }
531
532 int
533 utf8decode(char *s, long *u) {
534 uchar c;
535 int i, n, rtn;
536
537 rtn = 1;
538 c = *s;
539 if(~c & 0x80) { /* 0xxxxxxx */
540 *u = c;
541 return rtn;
542 } else if((c & 0xE0) == 0xC0) { /* 110xxxxx */
543 *u = c & 0x1F;
544 n = 1;
545 } else if((c & 0xF0) == 0xE0) { /* 1110xxxx */
546 *u = c & 0x0F;
547 n = 2;
548 } else if((c & 0xF8) == 0xF0) { /* 11110xxx */
549 *u = c & 0x07;
550 n = 3;
551 } else {
552 goto invalid;
553 }
554
555 for(i = n, ++s; i > 0; --i, ++rtn, ++s) {
556 c = *s;
557 if((c & 0xC0) != 0x80) /* 10xxxxxx */
558 goto invalid;
559 *u <<= 6;
560 *u |= c & 0x3F;
561 }
562
563 if((n == 1 && *u < 0x80) ||
564 (n == 2 && *u < 0x800) ||
565 (n == 3 && *u < 0x10000) ||
566 (*u >= 0xD800 && *u <= 0xDFFF)) {
567 goto invalid;
568 }
569
570 return rtn;
571 invalid:
572 *u = 0xFFFD;
573
574 return rtn;
575 }
576
577 int
578 utf8encode(long *u, char *s) {
579 uchar *sp;
580 ulong uc;
581 int i, n;
582
583 sp = (uchar *)s;
584 uc = *u;
585 if(uc < 0x80) {
586 *sp = uc; /* 0xxxxxxx */
587 return 1;
588 } else if(*u < 0x800) {
589 *sp = (uc >> 6) | 0xC0; /* 110xxxxx */
590 n = 1;
591 } else if(uc < 0x10000) {
592 *sp = (uc >> 12) | 0xE0; /* 1110xxxx */
593 n = 2;
594 } else if(uc <= 0x10FFFF) {
595 *sp = (uc >> 18) | 0xF0; /* 11110xxx */
596 n = 3;
597 } else {
598 goto invalid;
599 }
600
601 for(i=n,++sp; i>0; --i,++sp)
602 *sp = ((uc >> 6*(i-1)) & 0x3F) | 0x80; /* 10xxxxxx */
603
604 return n+1;
605 invalid:
606 /* U+FFFD */
607 *s++ = '\xEF';
608 *s++ = '\xBF';
609 *s = '\xBD';
610
611 return 3;
612 }
613
614 /* use this if your buffer is less than UTF_SIZ, it returns 1 if you can decode
615 UTF-8 otherwise return 0 */
616 int
617 isfullutf8(char *s, int b) {
618 uchar *c1, *c2, *c3;
619
620 c1 = (uchar *)s;
621 c2 = (uchar *)++s;
622 c3 = (uchar *)++s;
623 if(b < 1) {
624 return 0;
625 } else if((*c1 & 0xE0) == 0xC0 && b == 1) {
626 return 0;
627 } else if((*c1 & 0xF0) == 0xE0 &&
628 ((b == 1) ||
629 ((b == 2) && (*c2 & 0xC0) == 0x80))) {
630 return 0;
631 } else if((*c1 & 0xF8) == 0xF0 &&
632 ((b == 1) ||
633 ((b == 2) && (*c2 & 0xC0) == 0x80) ||
634 ((b == 3) && (*c2 & 0xC0) == 0x80 && (*c3 & 0xC0) == 0x80))) {
635 return 0;
636 } else {
637 return 1;
638 }
639 }
640
641 int
642 utf8size(char *s) {
643 uchar c = *s;
644
645 if(~c & 0x80) {
646 return 1;
647 } else if((c & 0xE0) == 0xC0) {
648 return 2;
649 } else if((c & 0xF0) == 0xE0) {
650 return 3;
651 } else {
652 return 4;
653 }
654 }
655
656 static void
657 selinit(void) {
658 memset(&sel.tclick1, 0, sizeof(sel.tclick1));
659 memset(&sel.tclick2, 0, sizeof(sel.tclick2));
660 sel.mode = 0;
661 sel.ob.x = -1;
662 sel.clip = NULL;
663 sel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
664 if(sel.xtarget == None)
665 sel.xtarget = XA_STRING;
666 }
667
668 static int
669 x2col(int x) {
670 x -= borderpx;
671 x /= xw.cw;
672
673 return LIMIT(x, 0, term.col-1);
674 }
675
676 static int
677 y2row(int y) {
678 y -= borderpx;
679 y /= xw.ch;
680
681 return LIMIT(y, 0, term.row-1);
682 }
683
684 static void
685 selsort(void) {
686 if(sel.ob.y == sel.oe.y) {
687 sel.nb.x = MIN(sel.ob.x, sel.oe.x);
688 sel.ne.x = MAX(sel.ob.x, sel.oe.x);
689 } else {
690 sel.nb.x = sel.ob.y < sel.oe.y ? sel.ob.x : sel.oe.x;
691 sel.ne.x = sel.ob.y < sel.oe.y ? sel.oe.x : sel.ob.x;
692 }
693 sel.nb.y = MIN(sel.ob.y, sel.oe.y);
694 sel.ne.y = MAX(sel.ob.y, sel.oe.y);
695 }
696
697 static inline bool
698 selected(int x, int y) {
699 if(sel.ne.y == y && sel.nb.y == y)
700 return BETWEEN(x, sel.nb.x, sel.ne.x);
701
702 if(sel.type == SEL_RECTANGULAR) {
703 return ((sel.nb.y <= y && y <= sel.ne.y)
704 && (sel.nb.x <= x && x <= sel.ne.x));
705 }
706
707 return ((sel.nb.y < y && y < sel.ne.y)
708 || (y == sel.ne.y && x <= sel.ne.x))
709 || (y == sel.nb.y && x >= sel.nb.x
710 && (x <= sel.ne.x || sel.nb.y != sel.ne.y));
711 }
712
713 void
714 selsnap(int mode, int *x, int *y, int direction) {
715 int i;
716
717 switch(mode) {
718 case SNAP_WORD:
719 /*
720 * Snap around if the word wraps around at the end or
721 * beginning of a line.
722 */
723 for(;;) {
724 if(direction < 0 && *x <= 0) {
725 if(*y > 0 && term.line[*y - 1][term.col-1].mode
726 & ATTR_WRAP) {
727 *y -= 1;
728 *x = term.col-1;
729 } else {
730 break;
731 }
732 }
733 if(direction > 0 && *x >= term.col-1) {
734 if(*y < term.row-1 && term.line[*y][*x].mode
735 & ATTR_WRAP) {
736 *y += 1;
737 *x = 0;
738 } else {
739 break;
740 }
741 }
742
743 if(term.line[*y][*x+direction].mode & ATTR_WDUMMY) {
744 *x += direction;
745 continue;
746 }
747
748 if(strchr(worddelimiters,
749 term.line[*y][*x+direction].c[0])) {
750 break;
751 }
752
753 *x += direction;
754 }
755 break;
756 case SNAP_LINE:
757 /*
758 * Snap around if the the previous line or the current one
759 * has set ATTR_WRAP at its end. Then the whole next or
760 * previous line will be selected.
761 */
762 *x = (direction < 0) ? 0 : term.col - 1;
763 if(direction < 0 && *y > 0) {
764 for(; *y > 0; *y += direction) {
765 if(!(term.line[*y-1][term.col-1].mode
766 & ATTR_WRAP)) {
767 break;
768 }
769 }
770 } else if(direction > 0 && *y < term.row-1) {
771 for(; *y < term.row; *y += direction) {
772 if(!(term.line[*y][term.col-1].mode
773 & ATTR_WRAP)) {
774 break;
775 }
776 }
777 }
778 break;
779 default:
780 /*
781 * Select the whole line when the end of line is reached.
782 */
783 if(direction > 0) {
784 i = term.col;
785 while(--i > 0 && term.line[*y][i].c[0] == ' ')
786 /* nothing */;
787 if(i > 0 && i < *x)
788 *x = term.col - 1;
789 }
790 break;
791 }
792 }
793
794 void
795 getbuttoninfo(XEvent *e) {
796 int type;
797 uint state = e->xbutton.state &~Button1Mask;
798
799 sel.alt = IS_SET(MODE_ALTSCREEN);
800
801 sel.oe.x = x2col(e->xbutton.x);
802 sel.oe.y = y2row(e->xbutton.y);
803
804 if(sel.ob.y < sel.oe.y
805 || (sel.ob.y == sel.oe.y && sel.ob.x < sel.oe.x)) {
806 selsnap(sel.snap, &sel.ob.x, &sel.ob.y, -1);
807 selsnap(sel.snap, &sel.oe.x, &sel.oe.y, +1);
808 } else {
809 selsnap(sel.snap, &sel.oe.x, &sel.oe.y, -1);
810 selsnap(sel.snap, &sel.ob.x, &sel.ob.y, +1);
811 }
812 selsort();
813
814 sel.type = SEL_REGULAR;
815 for(type = 1; type < LEN(selmasks); ++type) {
816 if(match(selmasks[type], state)) {
817 sel.type = type;
818 break;
819 }
820 }
821 }
822
823 void
824 mousereport(XEvent *e) {
825 int x = x2col(e->xbutton.x), y = y2row(e->xbutton.y),
826 button = e->xbutton.button, state = e->xbutton.state,
827 len;
828 char buf[40];
829 static int ox, oy;
830
831 /* from urxvt */
832 if(e->xbutton.type == MotionNotify) {
833 if(x == ox && y == oy)
834 return;
835 if(!IS_SET(MODE_MOUSEMOTION) && !IS_SET(MODE_MOUSEMANY))
836 return;
837 /* MOUSE_MOTION: no reporting if no button is pressed */
838 if(IS_SET(MODE_MOUSEMOTION) && oldbutton == 3)
839 return;
840
841 button = oldbutton + 32;
842 ox = x;
843 oy = y;
844 } else {
845 if(!IS_SET(MODE_MOUSESGR) && e->xbutton.type == ButtonRelease) {
846 button = 3;
847 } else {
848 button -= Button1;
849 if(button >= 3)
850 button += 64 - 3;
851 }
852 if(e->xbutton.type == ButtonPress) {
853 oldbutton = button;
854 ox = x;
855 oy = y;
856 } else if(e->xbutton.type == ButtonRelease) {
857 oldbutton = 3;
858 /* MODE_MOUSEX10: no button release reporting */
859 if(IS_SET(MODE_MOUSEX10))
860 return;
861 }
862 }
863
864 if(!IS_SET(MODE_MOUSEX10)) {
865 button += (state & ShiftMask ? 4 : 0)
866 + (state & Mod4Mask ? 8 : 0)
867 + (state & ControlMask ? 16 : 0);
868 }
869
870 len = 0;
871 if(IS_SET(MODE_MOUSESGR)) {
872 len = snprintf(buf, sizeof(buf), "\033[<%d;%d;%d%c",
873 button, x+1, y+1,
874 e->xbutton.type == ButtonRelease ? 'm' : 'M');
875 } else if(x < 223 && y < 223) {
876 len = snprintf(buf, sizeof(buf), "\033[M%c%c%c",
877 32+button, 32+x+1, 32+y+1);
878 } else {
879 return;
880 }
881
882 ttywrite(buf, len);
883 }
884
885 void
886 bpress(XEvent *e) {
887 struct timeval now;
888 Mousekey *mk;
889
890 if(IS_SET(MODE_MOUSE)) {
891 mousereport(e);
892 return;
893 }
894
895 for(mk = mshortcuts; mk < mshortcuts + LEN(mshortcuts); mk++) {
896 if(e->xbutton.button == mk->b
897 && match(mk->mask, e->xbutton.state)) {
898 ttysend(mk->s, strlen(mk->s));
899 return;
900 }
901 }
902
903 if(e->xbutton.button == Button1) {
904 gettimeofday(&now, NULL);
905
906 /* Clear previous selection, logically and visually. */
907 selclear(NULL);
908 sel.mode = 1;
909 sel.type = SEL_REGULAR;
910 sel.oe.x = sel.ob.x = x2col(e->xbutton.x);
911 sel.oe.y = sel.ob.y = y2row(e->xbutton.y);
912
913 /*
914 * If the user clicks below predefined timeouts specific
915 * snapping behaviour is exposed.
916 */
917 if(TIMEDIFF(now, sel.tclick2) <= tripleclicktimeout) {
918 sel.snap = SNAP_LINE;
919 } else if(TIMEDIFF(now, sel.tclick1) <= doubleclicktimeout) {
920 sel.snap = SNAP_WORD;
921 } else {
922 sel.snap = 0;
923 }
924 selsnap(sel.snap, &sel.ob.x, &sel.ob.y, -1);
925 selsnap(sel.snap, &sel.oe.x, &sel.oe.y, +1);
926 selsort();
927
928 /*
929 * Draw selection, unless it's regular and we don't want to
930 * make clicks visible
931 */
932 if(sel.snap != 0) {
933 sel.mode++;
934 tsetdirt(sel.nb.y, sel.ne.y);
935 }
936 sel.tclick2 = sel.tclick1;
937 sel.tclick1 = now;
938 }
939 }
940
941 void
942 selcopy(void) {
943 char *str, *ptr;
944 int x, y, bufsize, size, i, ex;
945 Glyph *gp, *last;
946
947 if(sel.ob.x == -1) {
948 str = NULL;
949 } else {
950 bufsize = (term.col+1) * (sel.ne.y-sel.nb.y+1) * UTF_SIZ;
951 ptr = str = xmalloc(bufsize);
952
953 /* append every set & selected glyph to the selection */
954 for(y = sel.nb.y; y < sel.ne.y + 1; y++) {
955 gp = &term.line[y][0];
956 last = gp + term.col;
957
958 while(--last >= gp && !(selected(last - gp, y) && \
959 strcmp(last->c, " ") != 0))
960 /* nothing */;
961
962 for(x = 0; gp <= last; x++, ++gp) {
963 if(!selected(x, y) || (gp->mode & ATTR_WDUMMY))
964 continue;
965
966 size = utf8size(gp->c);
967 memcpy(ptr, gp->c, size);
968 ptr += size;
969 }
970
971 /*
972 * Copy and pasting of line endings is inconsistent
973 * in the inconsistent terminal and GUI world.
974 * The best solution seems like to produce '\n' when
975 * something is copied from st and convert '\n' to
976 * '\r', when something to be pasted is received by
977 * st.
978 * FIXME: Fix the computer world.
979 */
980 if(y < sel.ne.y && x > 0 && !((gp-1)->mode & ATTR_WRAP))
981 *ptr++ = '\n';
982
983 /*
984 * If the last selected line expands in the selection
985 * after the visible text '\n' is appended.
986 */
987 if(y == sel.ne.y) {
988 i = term.col;
989 while(--i > 0 && term.line[y][i].c[0] == ' ')
990 /* nothing */;
991 ex = sel.ne.x;
992 if(sel.nb.y == sel.ne.y && sel.ne.x < sel.nb.x)
993 ex = sel.nb.x;
994 if(i < ex)
995 *ptr++ = '\n';
996 }
997 }
998 *ptr = 0;
999 }
1000 xsetsel(str);
1001 }
1002
1003 void
1004 selnotify(XEvent *e) {
1005 ulong nitems, ofs, rem;
1006 int format;
1007 uchar *data, *last, *repl;
1008 Atom type;
1009
1010 ofs = 0;
1011 do {
1012 if(XGetWindowProperty(xw.dpy, xw.win, XA_PRIMARY, ofs, BUFSIZ/4,
1013 False, AnyPropertyType, &type, &format,
1014 &nitems, &rem, &data)) {
1015 fprintf(stderr, "Clipboard allocation failed\n");
1016 return;
1017 }
1018
1019 /*
1020 * As seen in selcopy:
1021 * Line endings are inconsistent in the terminal and GUI world
1022 * copy and pasting. When receiving some selection data,
1023 * replace all '\n' with '\r'.
1024 * FIXME: Fix the computer world.
1025 */
1026 repl = data;
1027 last = data + nitems * format / 8;
1028 while((repl = memchr(repl, '\n', last - repl))) {
1029 *repl++ = '\r';
1030 }
1031
1032 if(IS_SET(MODE_BRCKTPASTE))
1033 ttywrite("\033[200~", 6);
1034 ttysend((char *)data, nitems * format / 8);
1035 if(IS_SET(MODE_BRCKTPASTE))
1036 ttywrite("\033[201~", 6);
1037 XFree(data);
1038 /* number of 32-bit chunks returned */
1039 ofs += nitems * format / 32;
1040 } while(rem > 0);
1041 }
1042
1043 void
1044 selpaste(const Arg *dummy) {
1045 XConvertSelection(xw.dpy, XA_PRIMARY, sel.xtarget, XA_PRIMARY,
1046 xw.win, CurrentTime);
1047 }
1048
1049 void
1050 clippaste(const Arg *dummy) {
1051 Atom clipboard;
1052
1053 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
1054 XConvertSelection(xw.dpy, clipboard, sel.xtarget, XA_PRIMARY,
1055 xw.win, CurrentTime);
1056 }
1057
1058 void
1059 selclear(XEvent *e) {
1060 if(sel.ob.x == -1)
1061 return;
1062 sel.ob.x = -1;
1063 tsetdirt(sel.nb.y, sel.ne.y);
1064 }
1065
1066 void
1067 selrequest(XEvent *e) {
1068 XSelectionRequestEvent *xsre;
1069 XSelectionEvent xev;
1070 Atom xa_targets, string;
1071
1072 xsre = (XSelectionRequestEvent *) e;
1073 xev.type = SelectionNotify;
1074 xev.requestor = xsre->requestor;
1075 xev.selection = xsre->selection;
1076 xev.target = xsre->target;
1077 xev.time = xsre->time;
1078 /* reject */
1079 xev.property = None;
1080
1081 xa_targets = XInternAtom(xw.dpy, "TARGETS", 0);
1082 if(xsre->target == xa_targets) {
1083 /* respond with the supported type */
1084 string = sel.xtarget;
1085 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
1086 XA_ATOM, 32, PropModeReplace,
1087 (uchar *) &string, 1);
1088 xev.property = xsre->property;
1089 } else if(xsre->target == sel.xtarget && sel.clip != NULL) {
1090 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
1091 xsre->target, 8, PropModeReplace,
1092 (uchar *) sel.clip, strlen(sel.clip));
1093 xev.property = xsre->property;
1094 }
1095
1096 /* all done, send a notification to the listener */
1097 if(!XSendEvent(xsre->display, xsre->requestor, True, 0, (XEvent *) &xev))
1098 fprintf(stderr, "Error sending SelectionNotify event\n");
1099 }
1100
1101 void
1102 xsetsel(char *str) {
1103 /* register the selection for both the clipboard and the primary */
1104 Atom clipboard;
1105
1106 free(sel.clip);
1107 sel.clip = str;
1108
1109 XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, CurrentTime);
1110
1111 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
1112 XSetSelectionOwner(xw.dpy, clipboard, xw.win, CurrentTime);
1113 }
1114
1115 void
1116 brelease(XEvent *e) {
1117 if(IS_SET(MODE_MOUSE)) {
1118 mousereport(e);
1119 return;
1120 }
1121
1122 if(e->xbutton.button == Button2) {
1123 selpaste(NULL);
1124 } else if(e->xbutton.button == Button1) {
1125 if(sel.mode < 2) {
1126 selclear(NULL);
1127 } else {
1128 getbuttoninfo(e);
1129 selcopy();
1130 }
1131 sel.mode = 0;
1132 tsetdirt(sel.nb.y, sel.ne.y);
1133 }
1134 }
1135
1136 void
1137 bmotion(XEvent *e) {
1138 int oldey, oldex, oldsby, oldsey;
1139
1140 if(IS_SET(MODE_MOUSE)) {
1141 mousereport(e);
1142 return;
1143 }
1144
1145 if(!sel.mode)
1146 return;
1147
1148 sel.mode++;
1149 oldey = sel.oe.y;
1150 oldex = sel.oe.x;
1151 oldsby = sel.nb.y;
1152 oldsey = sel.ne.y;
1153 getbuttoninfo(e);
1154
1155 if(oldey != sel.oe.y || oldex != sel.oe.x)
1156 tsetdirt(MIN(sel.nb.y, oldsby), MAX(sel.ne.y, oldsey));
1157 }
1158
1159 void
1160 die(const char *errstr, ...) {
1161 va_list ap;
1162
1163 va_start(ap, errstr);
1164 vfprintf(stderr, errstr, ap);
1165 va_end(ap);
1166 exit(EXIT_FAILURE);
1167 }
1168
1169 void
1170 execsh(void) {
1171 char **args;
1172 char *envshell = getenv("SHELL");
1173 const struct passwd *pass = getpwuid(getuid());
1174 char buf[sizeof(long) * 8 + 1];
1175
1176 unsetenv("COLUMNS");
1177 unsetenv("LINES");
1178 unsetenv("TERMCAP");
1179
1180 if(pass) {
1181 setenv("LOGNAME", pass->pw_name, 1);
1182 setenv("USER", pass->pw_name, 1);
1183 setenv("SHELL", pass->pw_shell, 0);
1184 setenv("HOME", pass->pw_dir, 0);
1185 }
1186
1187 snprintf(buf, sizeof(buf), "%lu", xw.win);
1188 setenv("WINDOWID", buf, 1);
1189
1190 signal(SIGCHLD, SIG_DFL);
1191 signal(SIGHUP, SIG_DFL);
1192 signal(SIGINT, SIG_DFL);
1193 signal(SIGQUIT, SIG_DFL);
1194 signal(SIGTERM, SIG_DFL);
1195 signal(SIGALRM, SIG_DFL);
1196
1197 DEFAULT(envshell, shell);
1198 setenv("TERM", termname, 1);
1199 args = opt_cmd ? opt_cmd : (char *[]){envshell, "-i", NULL};
1200 execvp(args[0], args);
1201 exit(EXIT_FAILURE);
1202 }
1203
1204 void
1205 sigchld(int a) {
1206 int stat = 0;
1207
1208 if(waitpid(pid, &stat, 0) < 0)
1209 die("Waiting for pid %hd failed: %s\n", pid, SERRNO);
1210
1211 if(WIFEXITED(stat)) {
1212 exit(WEXITSTATUS(stat));
1213 } else {
1214 exit(EXIT_FAILURE);
1215 }
1216 }
1217
1218 void
1219 ttynew(void) {
1220 int m, s;
1221 struct winsize w = {term.row, term.col, 0, 0};
1222
1223 /* seems to work fine on linux, openbsd and freebsd */
1224 if(openpty(&m, &s, NULL, NULL, &w) < 0)
1225 die("openpty failed: %s\n", SERRNO);
1226
1227 switch(pid = fork()) {
1228 case -1:
1229 die("fork failed\n");
1230 break;
1231 case 0:
1232 setsid(); /* create a new process group */
1233 dup2(s, STDIN_FILENO);
1234 dup2(s, STDOUT_FILENO);
1235 dup2(s, STDERR_FILENO);
1236 if(ioctl(s, TIOCSCTTY, NULL) < 0)
1237 die("ioctl TIOCSCTTY failed: %s\n", SERRNO);
1238 close(s);
1239 close(m);
1240 execsh();
1241 break;
1242 default:
1243 close(s);
1244 cmdfd = m;
1245 signal(SIGCHLD, sigchld);
1246 if(opt_io) {
1247 iofd = (!strcmp(opt_io, "-")) ?
1248 STDOUT_FILENO :
1249 open(opt_io, O_WRONLY | O_CREAT, 0666);
1250 if(iofd < 0) {
1251 fprintf(stderr, "Error opening %s:%s\n",
1252 opt_io, strerror(errno));
1253 }
1254 }
1255 }
1256 }
1257
1258 void
1259 dump(char c) {
1260 static int col;
1261
1262 fprintf(stderr, " %02x '%c' ", c, isprint(c)?c:'.');
1263 if(++col % 10 == 0)
1264 fprintf(stderr, "\n");
1265 }
1266
1267 void
1268 ttyread(void) {
1269 static char buf[BUFSIZ];
1270 static int buflen = 0;
1271 char *ptr;
1272 char s[UTF_SIZ];
1273 int charsize; /* size of utf8 char in bytes */
1274 long utf8c;
1275 int ret;
1276
1277 /* append read bytes to unprocessed bytes */
1278 if((ret = read(cmdfd, buf+buflen, LEN(buf)-buflen)) < 0)
1279 die("Couldn't read from shell: %s\n", SERRNO);
1280
1281 /* process every complete utf8 char */
1282 buflen += ret;
1283 ptr = buf;
1284 while(buflen >= UTF_SIZ || isfullutf8(ptr,buflen)) {
1285 charsize = utf8decode(ptr, &utf8c);
1286 utf8encode(&utf8c, s);
1287 tputc(s, charsize);
1288 ptr += charsize;
1289 buflen -= charsize;
1290 }
1291
1292 /* keep any uncomplete utf8 char for the next call */
1293 memmove(buf, ptr, buflen);
1294 }
1295
1296 void
1297 ttywrite(const char *s, size_t n) {
1298 if(write(cmdfd, s, n) == -1)
1299 die("write error on tty: %s\n", SERRNO);
1300 }
1301
1302 void
1303 ttysend(char *s, size_t n) {
1304 ttywrite(s, n);
1305 if(IS_SET(MODE_ECHO))
1306 techo(s, n);
1307 }
1308
1309 void
1310 ttyresize(void) {
1311 struct winsize w;
1312
1313 w.ws_row = term.row;
1314 w.ws_col = term.col;
1315 w.ws_xpixel = xw.tw;
1316 w.ws_ypixel = xw.th;
1317 if(ioctl(cmdfd, TIOCSWINSZ, &w) < 0)
1318 fprintf(stderr, "Couldn't set window size: %s\n", SERRNO);
1319 }
1320
1321 int
1322 tattrset(int attr) {
1323 int i, j;
1324
1325 for(i = 0; i < term.row-1; i++) {
1326 for(j = 0; j < term.col-1; j++) {
1327 if(term.line[i][j].mode & attr)
1328 return 1;
1329 }
1330 }
1331
1332 return 0;
1333 }
1334
1335 void
1336 tsetdirt(int top, int bot) {
1337 int i;
1338
1339 LIMIT(top, 0, term.row-1);
1340 LIMIT(bot, 0, term.row-1);
1341
1342 for(i = top; i <= bot; i++)
1343 term.dirty[i] = 1;
1344 }
1345
1346 void
1347 tsetdirtattr(int attr) {
1348 int i, j;
1349
1350 for(i = 0; i < term.row-1; i++) {
1351 for(j = 0; j < term.col-1; j++) {
1352 if(term.line[i][j].mode & attr) {
1353 tsetdirt(i, i);
1354 break;
1355 }
1356 }
1357 }
1358 }
1359
1360 void
1361 tfulldirt(void) {
1362 tsetdirt(0, term.row-1);
1363 }
1364
1365 void
1366 tcursor(int mode) {
1367 static TCursor c[2];
1368 bool alt = IS_SET(MODE_ALTSCREEN);
1369
1370 if(mode == CURSOR_SAVE) {
1371 c[alt] = term.c;
1372 } else if(mode == CURSOR_LOAD) {
1373 term.c = c[alt];
1374 tmoveto(c[alt].x, c[alt].y);
1375 }
1376 }
1377
1378 void
1379 treset(void) {
1380 uint i;
1381
1382 term.c = (TCursor){{
1383 .mode = ATTR_NULL,
1384 .fg = defaultfg,
1385 .bg = defaultbg
1386 }, .x = 0, .y = 0, .state = CURSOR_DEFAULT};
1387
1388 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1389 for(i = tabspaces; i < term.col; i += tabspaces)
1390 term.tabs[i] = 1;
1391 term.top = 0;
1392 term.bot = term.row - 1;
1393 term.mode = MODE_WRAP;
1394 memset(term.trantbl, sizeof(term.trantbl), CS_USA);
1395 term.charset = 0;
1396
1397 tclearregion(0, 0, term.col-1, term.row-1);
1398 tmoveto(0, 0);
1399 tcursor(CURSOR_SAVE);
1400 }
1401
1402 void
1403 tnew(int col, int row) {
1404 term = (Term){ .c = { .attr = { .fg = defaultfg, .bg = defaultbg } } };
1405 tresize(col, row);
1406 term.numlock = 1;
1407
1408 treset();
1409 }
1410
1411 void
1412 tswapscreen(void) {
1413 Line *tmp = term.line;
1414
1415 term.line = term.alt;
1416 term.alt = tmp;
1417 term.mode ^= MODE_ALTSCREEN;
1418 tfulldirt();
1419 }
1420
1421 void
1422 tscrolldown(int orig, int n) {
1423 int i;
1424 Line temp;
1425
1426 LIMIT(n, 0, term.bot-orig+1);
1427
1428 tclearregion(0, term.bot-n+1, term.col-1, term.bot);
1429
1430 for(i = term.bot; i >= orig+n; i--) {
1431 temp = term.line[i];
1432 term.line[i] = term.line[i-n];
1433 term.line[i-n] = temp;
1434
1435 term.dirty[i] = 1;
1436 term.dirty[i-n] = 1;
1437 }
1438
1439 selscroll(orig, n);
1440 }
1441
1442 void
1443 tscrollup(int orig, int n) {
1444 int i;
1445 Line temp;
1446 LIMIT(n, 0, term.bot-orig+1);
1447
1448 tclearregion(0, orig, term.col-1, orig+n-1);
1449
1450 for(i = orig; i <= term.bot-n; i++) {
1451 temp = term.line[i];
1452 term.line[i] = term.line[i+n];
1453 term.line[i+n] = temp;
1454
1455 term.dirty[i] = 1;
1456 term.dirty[i+n] = 1;
1457 }
1458
1459 selscroll(orig, -n);
1460 }
1461
1462 void
1463 selscroll(int orig, int n) {
1464 if(sel.ob.x == -1)
1465 return;
1466
1467 if(BETWEEN(sel.ob.y, orig, term.bot) || BETWEEN(sel.oe.y, orig, term.bot)) {
1468 if((sel.ob.y += n) > term.bot || (sel.oe.y += n) < term.top) {
1469 selclear(NULL);
1470 return;
1471 }
1472 if(sel.type == SEL_RECTANGULAR) {
1473 if(sel.ob.y < term.top)
1474 sel.ob.y = term.top;
1475 if(sel.oe.y > term.bot)
1476 sel.oe.y = term.bot;
1477 } else {
1478 if(sel.ob.y < term.top) {
1479 sel.ob.y = term.top;
1480 sel.ob.x = 0;
1481 }
1482 if(sel.oe.y > term.bot) {
1483 sel.oe.y = term.bot;
1484 sel.oe.x = term.col;
1485 }
1486 }
1487 selsort();
1488 }
1489 }
1490
1491 void
1492 tnewline(int first_col) {
1493 int y = term.c.y;
1494
1495 if(y == term.bot) {
1496 tscrollup(term.top, 1);
1497 } else {
1498 y++;
1499 }
1500 tmoveto(first_col ? 0 : term.c.x, y);
1501 }
1502
1503 void
1504 csiparse(void) {
1505 char *p = csiescseq.buf, *np;
1506 long int v;
1507
1508 csiescseq.narg = 0;
1509 if(*p == '?') {
1510 csiescseq.priv = 1;
1511 p++;
1512 }
1513
1514 csiescseq.buf[csiescseq.len] = '\0';
1515 while(p < csiescseq.buf+csiescseq.len) {
1516 np = NULL;
1517 v = strtol(p, &np, 10);
1518 if(np == p)
1519 v = 0;
1520 if(v == LONG_MAX || v == LONG_MIN)
1521 v = -1;
1522 csiescseq.arg[csiescseq.narg++] = v;
1523 p = np;
1524 if(*p != ';' || csiescseq.narg == ESC_ARG_SIZ)
1525 break;
1526 p++;
1527 }
1528 csiescseq.mode = *p;
1529 }
1530
1531 /* for absolute user moves, when decom is set */
1532 void
1533 tmoveato(int x, int y) {
1534 tmoveto(x, y + ((term.c.state & CURSOR_ORIGIN) ? term.top: 0));
1535 }
1536
1537 void
1538 tmoveto(int x, int y) {
1539 int miny, maxy;
1540
1541 if(term.c.state & CURSOR_ORIGIN) {
1542 miny = term.top;
1543 maxy = term.bot;
1544 } else {
1545 miny = 0;
1546 maxy = term.row - 1;
1547 }
1548 LIMIT(x, 0, term.col-1);
1549 LIMIT(y, miny, maxy);
1550 term.c.state &= ~CURSOR_WRAPNEXT;
1551 term.c.x = x;
1552 term.c.y = y;
1553 }
1554
1555 void
1556 tsetchar(char *c, Glyph *attr, int x, int y) {
1557 static char *vt100_0[62] = { /* 0x41 - 0x7e */
1558 "↑", "↓", "→", "←", "█", "▚", "☃", /* A - G */
1559 0, 0, 0, 0, 0, 0, 0, 0, /* H - O */
1560 0, 0, 0, 0, 0, 0, 0, 0, /* P - W */
1561 0, 0, 0, 0, 0, 0, 0, " ", /* X - _ */
1562 "◆", "▒", "␉", "␌", "␍", "␊", "°", "±", /* ` - g */
1563 "␤", "␋", "┘", "┐", "┌", "└", "┼", "⎺", /* h - o */
1564 "⎻", "─", "⎼", "⎽", "├", "┤", "┴", "┬", /* p - w */
1565 "│", "≤", "≥", "π", "≠", "£", "·", /* x - ~ */
1566 };
1567
1568 /*
1569 * The table is proudly stolen from rxvt.
1570 */
1571 if(attr->mode & ATTR_GFX) {
1572 if(c[0] >= 0x41 && c[0] <= 0x7e
1573 && vt100_0[c[0] - 0x41]) {
1574 c = vt100_0[c[0] - 0x41];
1575 }
1576 }
1577
1578 if(term.line[y][x].mode & ATTR_WIDE) {
1579 if(x+1 < term.col) {
1580 term.line[y][x+1].c[0] = ' ';
1581 term.line[y][x+1].mode &= ~ATTR_WDUMMY;
1582 }
1583 } else if(term.line[y][x].mode & ATTR_WDUMMY) {
1584 term.line[y][x-1].c[0] = ' ';
1585 term.line[y][x-1].mode &= ~ATTR_WIDE;
1586 }
1587
1588 term.dirty[y] = 1;
1589 term.line[y][x] = *attr;
1590 memcpy(term.line[y][x].c, c, UTF_SIZ);
1591 }
1592
1593 void
1594 tclearregion(int x1, int y1, int x2, int y2) {
1595 int x, y, temp;
1596
1597 if(x1 > x2)
1598 temp = x1, x1 = x2, x2 = temp;
1599 if(y1 > y2)
1600 temp = y1, y1 = y2, y2 = temp;
1601
1602 LIMIT(x1, 0, term.col-1);
1603 LIMIT(x2, 0, term.col-1);
1604 LIMIT(y1, 0, term.row-1);
1605 LIMIT(y2, 0, term.row-1);
1606
1607 for(y = y1; y <= y2; y++) {
1608 term.dirty[y] = 1;
1609 for(x = x1; x <= x2; x++) {
1610 if(selected(x, y))
1611 selclear(NULL);
1612 term.line[y][x] = term.c.attr;
1613 memcpy(term.line[y][x].c, " ", 2);
1614 }
1615 }
1616 }
1617
1618 void
1619 tdeletechar(int n) {
1620 int src = term.c.x + n;
1621 int dst = term.c.x;
1622 int size = term.col - src;
1623
1624 term.dirty[term.c.y] = 1;
1625
1626 if(src >= term.col) {
1627 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1628 return;
1629 }
1630
1631 memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src],
1632 size * sizeof(Glyph));
1633 tclearregion(term.col-n, term.c.y, term.col-1, term.c.y);
1634 }
1635
1636 void
1637 tinsertblank(int n) {
1638 int src = term.c.x;
1639 int dst = src + n;
1640 int size = term.col - dst;
1641
1642 term.dirty[term.c.y] = 1;
1643
1644 if(dst >= term.col) {
1645 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1646 return;
1647 }
1648
1649 memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src],
1650 size * sizeof(Glyph));
1651 tclearregion(src, term.c.y, dst - 1, term.c.y);
1652 }
1653
1654 void
1655 tinsertblankline(int n) {
1656 if(term.c.y < term.top || term.c.y > term.bot)
1657 return;
1658
1659 tscrolldown(term.c.y, n);
1660 }
1661
1662 void
1663 tdeleteline(int n) {
1664 if(term.c.y < term.top || term.c.y > term.bot)
1665 return;
1666
1667 tscrollup(term.c.y, n);
1668 }
1669
1670 int32_t
1671 tdefcolor(int *attr, int *npar, int l) {
1672 int32_t idx = -1;
1673 uint r, g, b;
1674
1675 switch (attr[*npar + 1]) {
1676 case 2: /* direct colour in RGB space */
1677 if (*npar + 4 >= l) {
1678 fprintf(stderr,
1679 "erresc(38): Incorrect number of parameters (%d)\n",
1680 *npar);
1681 break;
1682 }
1683 r = attr[*npar + 2];
1684 g = attr[*npar + 3];
1685 b = attr[*npar + 4];
1686 *npar += 4;
1687 if(!BETWEEN(r, 0, 255) || !BETWEEN(g, 0, 255) || !BETWEEN(b, 0, 255))
1688 fprintf(stderr, "erresc: bad rgb color (%d,%d,%d)\n",
1689 r, g, b);
1690 else
1691 idx = TRUECOLOR(r, g, b);
1692 break;
1693 case 5: /* indexed colour */
1694 if (*npar + 2 >= l) {
1695 fprintf(stderr,
1696 "erresc(38): Incorrect number of parameters (%d)\n",
1697 *npar);
1698 break;
1699 }
1700 *npar += 2;
1701 if(!BETWEEN(attr[*npar], 0, 255))
1702 fprintf(stderr, "erresc: bad fgcolor %d\n", attr[*npar]);
1703 else
1704 idx = attr[*npar];
1705 break;
1706 case 0: /* implemented defined (only foreground) */
1707 case 1: /* transparent */
1708 case 3: /* direct colour in CMY space */
1709 case 4: /* direct colour in CMYK space */
1710 default:
1711 fprintf(stderr,
1712 "erresc(38): gfx attr %d unknown\n", attr[*npar]);
1713 }
1714
1715 return idx;
1716 }
1717
1718 void
1719 tsetattr(int *attr, int l) {
1720 int i;
1721 int32_t idx;
1722
1723 for(i = 0; i < l; i++) {
1724 switch(attr[i]) {
1725 case 0:
1726 term.c.attr.mode &= ~(ATTR_REVERSE | ATTR_UNDERLINE \
1727 | ATTR_BOLD | ATTR_ITALIC \
1728 | ATTR_BLINK);
1729 term.c.attr.fg = defaultfg;
1730 term.c.attr.bg = defaultbg;
1731 break;
1732 case 1:
1733 term.c.attr.mode |= ATTR_BOLD;
1734 break;
1735 case 3:
1736 term.c.attr.mode |= ATTR_ITALIC;
1737 break;
1738 case 4:
1739 term.c.attr.mode |= ATTR_UNDERLINE;
1740 break;
1741 case 5: /* slow blink */
1742 case 6: /* rapid blink */
1743 term.c.attr.mode |= ATTR_BLINK;
1744 break;
1745 case 7:
1746 term.c.attr.mode |= ATTR_REVERSE;
1747 break;
1748 case 21:
1749 case 22:
1750 term.c.attr.mode &= ~ATTR_BOLD;
1751 break;
1752 case 23:
1753 term.c.attr.mode &= ~ATTR_ITALIC;
1754 break;
1755 case 24:
1756 term.c.attr.mode &= ~ATTR_UNDERLINE;
1757 break;
1758 case 25:
1759 case 26:
1760 term.c.attr.mode &= ~ATTR_BLINK;
1761 break;
1762 case 27:
1763 term.c.attr.mode &= ~ATTR_REVERSE;
1764 break;
1765 case 38:
1766 if ((idx = tdefcolor(attr, &i, l)) >= 0)
1767 term.c.attr.fg = idx;
1768 break;
1769 case 39:
1770 term.c.attr.fg = defaultfg;
1771 break;
1772 case 48:
1773 if ((idx = tdefcolor(attr, &i, l)) >= 0)
1774 term.c.attr.bg = idx;
1775 break;
1776 case 49:
1777 term.c.attr.bg = defaultbg;
1778 break;
1779 default:
1780 if(BETWEEN(attr[i], 30, 37)) {
1781 term.c.attr.fg = attr[i] - 30;
1782 } else if(BETWEEN(attr[i], 40, 47)) {
1783 term.c.attr.bg = attr[i] - 40;
1784 } else if(BETWEEN(attr[i], 90, 97)) {
1785 term.c.attr.fg = attr[i] - 90 + 8;
1786 } else if(BETWEEN(attr[i], 100, 107)) {
1787 term.c.attr.bg = attr[i] - 100 + 8;
1788 } else {
1789 fprintf(stderr,
1790 "erresc(default): gfx attr %d unknown\n",
1791 attr[i]), csidump();
1792 }
1793 break;
1794 }
1795 }
1796 }
1797
1798 void
1799 tsetscroll(int t, int b) {
1800 int temp;
1801
1802 LIMIT(t, 0, term.row-1);
1803 LIMIT(b, 0, term.row-1);
1804 if(t > b) {
1805 temp = t;
1806 t = b;
1807 b = temp;
1808 }
1809 term.top = t;
1810 term.bot = b;
1811 }
1812
1813 #define MODBIT(x, set, bit) ((set) ? ((x) |= (bit)) : ((x) &= ~(bit)))
1814
1815 void
1816 tsetmode(bool priv, bool set, int *args, int narg) {
1817 int *lim, mode;
1818 bool alt;
1819
1820 for(lim = args + narg; args < lim; ++args) {
1821 if(priv) {
1822 switch(*args) {
1823 break;
1824 case 1: /* DECCKM -- Cursor key */
1825 MODBIT(term.mode, set, MODE_APPCURSOR);
1826 break;
1827 case 5: /* DECSCNM -- Reverse video */
1828 mode = term.mode;
1829 MODBIT(term.mode, set, MODE_REVERSE);
1830 if(mode != term.mode)
1831 redraw(REDRAW_TIMEOUT);
1832 break;
1833 case 6: /* DECOM -- Origin */
1834 MODBIT(term.c.state, set, CURSOR_ORIGIN);
1835 tmoveato(0, 0);
1836 break;
1837 case 7: /* DECAWM -- Auto wrap */
1838 MODBIT(term.mode, set, MODE_WRAP);
1839 break;
1840 case 0: /* Error (IGNORED) */
1841 case 2: /* DECANM -- ANSI/VT52 (IGNORED) */
1842 case 3: /* DECCOLM -- Column (IGNORED) */
1843 case 4: /* DECSCLM -- Scroll (IGNORED) */
1844 case 8: /* DECARM -- Auto repeat (IGNORED) */
1845 case 18: /* DECPFF -- Printer feed (IGNORED) */
1846 case 19: /* DECPEX -- Printer extent (IGNORED) */
1847 case 42: /* DECNRCM -- National characters (IGNORED) */
1848 case 12: /* att610 -- Start blinking cursor (IGNORED) */
1849 break;
1850 case 25: /* DECTCEM -- Text Cursor Enable Mode */
1851 MODBIT(term.mode, !set, MODE_HIDE);
1852 break;
1853 case 9: /* X10 mouse compatibility mode */
1854 xsetpointermotion(0);
1855 MODBIT(term.mode, 0, MODE_MOUSE);
1856 MODBIT(term.mode, set, MODE_MOUSEX10);
1857 break;
1858 case 1000: /* 1000: report button press */
1859 xsetpointermotion(0);
1860 MODBIT(term.mode, 0, MODE_MOUSE);
1861 MODBIT(term.mode, set, MODE_MOUSEBTN);
1862 break;
1863 case 1002: /* 1002: report motion on button press */
1864 xsetpointermotion(0);
1865 MODBIT(term.mode, 0, MODE_MOUSE);
1866 MODBIT(term.mode, set, MODE_MOUSEMOTION);
1867 break;
1868 case 1003: /* 1003: enable all mouse motions */
1869 xsetpointermotion(set);
1870 MODBIT(term.mode, 0, MODE_MOUSE);
1871 MODBIT(term.mode, set, MODE_MOUSEMANY);
1872 break;
1873 case 1004: /* 1004: send focus events to tty */
1874 MODBIT(term.mode, set, MODE_FOCUS);
1875 break;
1876 case 1006: /* 1006: extended reporting mode */
1877 MODBIT(term.mode, set, MODE_MOUSESGR);
1878 break;
1879 case 1034:
1880 MODBIT(term.mode, set, MODE_8BIT);
1881 break;
1882 case 1049: /* swap screen & set/restore cursor as xterm */
1883 tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
1884 case 47: /* swap screen */
1885 case 1047:
1886 if (!allowaltscreen)
1887 break;
1888 alt = IS_SET(MODE_ALTSCREEN);
1889 if(alt) {
1890 tclearregion(0, 0, term.col-1,
1891 term.row-1);
1892 }
1893 if(set ^ alt) /* set is always 1 or 0 */
1894 tswapscreen();
1895 if(*args != 1049)
1896 break;
1897 /* FALLTRU */
1898 case 1048:
1899 tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
1900 break;
1901 case 2004: /* 2004: bracketed paste mode */
1902 MODBIT(term.mode, set, MODE_BRCKTPASTE);
1903 break;
1904 /* Not implemented mouse modes. See comments there. */
1905 case 1001: /* mouse highlight mode; can hang the
1906 terminal by design when implemented. */
1907 case 1005: /* UTF-8 mouse mode; will confuse
1908 applications not supporting UTF-8
1909 and luit. */
1910 case 1015: /* urxvt mangled mouse mode; incompatible
1911 and can be mistaken for other control
1912 codes. */
1913 default:
1914 fprintf(stderr,
1915 "erresc: unknown private set/reset mode %d\n",
1916 *args);
1917 break;
1918 }
1919 } else {
1920 switch(*args) {
1921 case 0: /* Error (IGNORED) */
1922 break;
1923 case 2: /* KAM -- keyboard action */
1924 MODBIT(term.mode, set, MODE_KBDLOCK);
1925 break;
1926 case 4: /* IRM -- Insertion-replacement */
1927 MODBIT(term.mode, set, MODE_INSERT);
1928 break;
1929 case 12: /* SRM -- Send/Receive */
1930 MODBIT(term.mode, !set, MODE_ECHO);
1931 break;
1932 case 20: /* LNM -- Linefeed/new line */
1933 MODBIT(term.mode, set, MODE_CRLF);
1934 break;
1935 default:
1936 fprintf(stderr,
1937 "erresc: unknown set/reset mode %d\n",
1938 *args);
1939 break;
1940 }
1941 }
1942 }
1943 }
1944
1945 void
1946 csihandle(void) {
1947 char buf[40];
1948 int len;
1949
1950 switch(csiescseq.mode) {
1951 default:
1952 unknown:
1953 fprintf(stderr, "erresc: unknown csi ");
1954 csidump();
1955 /* die(""); */
1956 break;
1957 case '@': /* ICH -- Insert <n> blank char */
1958 DEFAULT(csiescseq.arg[0], 1);
1959 tinsertblank(csiescseq.arg[0]);
1960 break;
1961 case 'A': /* CUU -- Cursor <n> Up */
1962 DEFAULT(csiescseq.arg[0], 1);
1963 tmoveto(term.c.x, term.c.y-csiescseq.arg[0]);
1964 break;
1965 case 'B': /* CUD -- Cursor <n> Down */
1966 case 'e': /* VPR --Cursor <n> Down */
1967 DEFAULT(csiescseq.arg[0], 1);
1968 tmoveto(term.c.x, term.c.y+csiescseq.arg[0]);
1969 break;
1970 case 'c': /* DA -- Device Attributes */
1971 if(csiescseq.arg[0] == 0)
1972 ttywrite(VT102ID, sizeof(VT102ID) - 1);
1973 break;
1974 case 'C': /* CUF -- Cursor <n> Forward */
1975 case 'a': /* HPR -- Cursor <n> Forward */
1976 DEFAULT(csiescseq.arg[0], 1);
1977 tmoveto(term.c.x+csiescseq.arg[0], term.c.y);
1978 break;
1979 case 'D': /* CUB -- Cursor <n> Backward */
1980 DEFAULT(csiescseq.arg[0], 1);
1981 tmoveto(term.c.x-csiescseq.arg[0], term.c.y);
1982 break;
1983 case 'E': /* CNL -- Cursor <n> Down and first col */
1984 DEFAULT(csiescseq.arg[0], 1);
1985 tmoveto(0, term.c.y+csiescseq.arg[0]);
1986 break;
1987 case 'F': /* CPL -- Cursor <n> Up and first col */
1988 DEFAULT(csiescseq.arg[0], 1);
1989 tmoveto(0, term.c.y-csiescseq.arg[0]);
1990 break;
1991 case 'g': /* TBC -- Tabulation clear */
1992 switch(csiescseq.arg[0]) {
1993 case 0: /* clear current tab stop */
1994 term.tabs[term.c.x] = 0;
1995 break;
1996 case 3: /* clear all the tabs */
1997 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1998 break;
1999 default:
2000 goto unknown;
2001 }
2002 break;
2003 case 'G': /* CHA -- Move to <col> */
2004 case '`': /* HPA */
2005 DEFAULT(csiescseq.arg[0], 1);
2006 tmoveto(csiescseq.arg[0]-1, term.c.y);
2007 break;
2008 case 'H': /* CUP -- Move to <row> <col> */
2009 case 'f': /* HVP */
2010 DEFAULT(csiescseq.arg[0], 1);
2011 DEFAULT(csiescseq.arg[1], 1);
2012 tmoveato(csiescseq.arg[1]-1, csiescseq.arg[0]-1);
2013 break;
2014 case 'I': /* CHT -- Cursor Forward Tabulation <n> tab stops */
2015 DEFAULT(csiescseq.arg[0], 1);
2016 while(csiescseq.arg[0]--)
2017 tputtab(1);
2018 break;
2019 case 'J': /* ED -- Clear screen */
2020 selclear(NULL);
2021 switch(csiescseq.arg[0]) {
2022 case 0: /* below */
2023 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
2024 if(term.c.y < term.row-1) {
2025 tclearregion(0, term.c.y+1, term.col-1,
2026 term.row-1);
2027 }
2028 break;
2029 case 1: /* above */
2030 if(term.c.y > 1)
2031 tclearregion(0, 0, term.col-1, term.c.y-1);
2032 tclearregion(0, term.c.y, term.c.x, term.c.y);
2033 break;
2034 case 2: /* all */
2035 tclearregion(0, 0, term.col-1, term.row-1);
2036 break;
2037 default:
2038 goto unknown;
2039 }
2040 break;
2041 case 'K': /* EL -- Clear line */
2042 switch(csiescseq.arg[0]) {
2043 case 0: /* right */
2044 tclearregion(term.c.x, term.c.y, term.col-1,
2045 term.c.y);
2046 break;
2047 case 1: /* left */
2048 tclearregion(0, term.c.y, term.c.x, term.c.y);
2049 break;
2050 case 2: /* all */
2051 tclearregion(0, term.c.y, term.col-1, term.c.y);
2052 break;
2053 }
2054 break;
2055 case 'S': /* SU -- Scroll <n> line up */
2056 DEFAULT(csiescseq.arg[0], 1);
2057 tscrollup(term.top, csiescseq.arg[0]);
2058 break;
2059 case 'T': /* SD -- Scroll <n> line down */
2060 DEFAULT(csiescseq.arg[0], 1);
2061 tscrolldown(term.top, csiescseq.arg[0]);
2062 break;
2063 case 'L': /* IL -- Insert <n> blank lines */
2064 DEFAULT(csiescseq.arg[0], 1);
2065 tinsertblankline(csiescseq.arg[0]);
2066 break;
2067 case 'l': /* RM -- Reset Mode */
2068 tsetmode(csiescseq.priv, 0, csiescseq.arg, csiescseq.narg);
2069 break;
2070 case 'M': /* DL -- Delete <n> lines */
2071 DEFAULT(csiescseq.arg[0], 1);
2072 tdeleteline(csiescseq.arg[0]);
2073 break;
2074 case 'X': /* ECH -- Erase <n> char */
2075 DEFAULT(csiescseq.arg[0], 1);
2076 tclearregion(term.c.x, term.c.y,
2077 term.c.x + csiescseq.arg[0] - 1, term.c.y);
2078 break;
2079 case 'P': /* DCH -- Delete <n> char */
2080 DEFAULT(csiescseq.arg[0], 1);
2081 tdeletechar(csiescseq.arg[0]);
2082 break;
2083 case 'Z': /* CBT -- Cursor Backward Tabulation <n> tab stops */
2084 DEFAULT(csiescseq.arg[0], 1);
2085 while(csiescseq.arg[0]--)
2086 tputtab(0);
2087 break;
2088 case 'd': /* VPA -- Move to <row> */
2089 DEFAULT(csiescseq.arg[0], 1);
2090 tmoveato(term.c.x, csiescseq.arg[0]-1);
2091 break;
2092 case 'h': /* SM -- Set terminal mode */
2093 tsetmode(csiescseq.priv, 1, csiescseq.arg, csiescseq.narg);
2094 break;
2095 case 'm': /* SGR -- Terminal attribute (color) */
2096 tsetattr(csiescseq.arg, csiescseq.narg);
2097 break;
2098 case 'n': /* DSR – Device Status Report (cursor position) */
2099 if (csiescseq.arg[0] == 6) {
2100 len = snprintf(buf, sizeof(buf),"\033[%i;%iR",
2101 term.c.y+1, term.c.x+1);
2102 ttywrite(buf, len);
2103 break;
2104 }
2105 case 'r': /* DECSTBM -- Set Scrolling Region */
2106 if(csiescseq.priv) {
2107 goto unknown;
2108 } else {
2109 DEFAULT(csiescseq.arg[0], 1);
2110 DEFAULT(csiescseq.arg[1], term.row);
2111 tsetscroll(csiescseq.arg[0]-1, csiescseq.arg[1]-1);
2112 tmoveato(0, 0);
2113 }
2114 break;
2115 case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
2116 tcursor(CURSOR_SAVE);
2117 break;
2118 case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
2119 tcursor(CURSOR_LOAD);
2120 break;
2121 }
2122 }
2123
2124 void
2125 csidump(void) {
2126 int i;
2127 uint c;
2128
2129 printf("ESC[");
2130 for(i = 0; i < csiescseq.len; i++) {
2131 c = csiescseq.buf[i] & 0xff;
2132 if(isprint(c)) {
2133 putchar(c);
2134 } else if(c == '\n') {
2135 printf("(\\n)");
2136 } else if(c == '\r') {
2137 printf("(\\r)");
2138 } else if(c == 0x1b) {
2139 printf("(\\e)");
2140 } else {
2141 printf("(%02x)", c);
2142 }
2143 }
2144 putchar('\n');
2145 }
2146
2147 void
2148 csireset(void) {
2149 memset(&csiescseq, 0, sizeof(csiescseq));
2150 }
2151
2152 void
2153 strhandle(void) {
2154 char *p = NULL;
2155 int j, narg, par;
2156
2157 strparse();
2158 narg = strescseq.narg;
2159 par = atoi(strescseq.args[0]);
2160
2161 switch(strescseq.type) {
2162 case ']': /* OSC -- Operating System Command */
2163 switch(par) {
2164 case 0:
2165 case 1:
2166 case 2:
2167 if(narg > 1)
2168 xsettitle(strescseq.args[1]);
2169 return;
2170 case 4: /* color set */
2171 if(narg < 3)
2172 break;
2173 p = strescseq.args[2];
2174 /* fall through */
2175 case 104: /* color reset, here p = NULL */
2176 j = (narg > 1) ? atoi(strescseq.args[1]) : -1;
2177 if (!xsetcolorname(j, p)) {
2178 fprintf(stderr, "erresc: invalid color %s\n", p);
2179 } else {
2180 /*
2181 * TODO if defaultbg color is changed, borders
2182 * are dirty
2183 */
2184 redraw(0);
2185 }
2186 return;
2187 }
2188 break;
2189 case 'k': /* old title set compatibility */
2190 xsettitle(strescseq.args[0]);
2191 return;
2192 case 'P': /* DSC -- Device Control String */
2193 case '_': /* APC -- Application Program Command */
2194 case '^': /* PM -- Privacy Message */
2195 return;
2196 }
2197
2198 fprintf(stderr, "erresc: unknown str ");
2199 strdump();
2200 }
2201
2202 void
2203 strparse(void) {
2204 char *p = strescseq.buf;
2205
2206 strescseq.narg = 0;
2207 strescseq.buf[strescseq.len] = '\0';
2208 while(p && strescseq.narg < STR_ARG_SIZ)
2209 strescseq.args[strescseq.narg++] = strsep(&p, ";");
2210 }
2211
2212 void
2213 strdump(void) {
2214 int i;
2215 uint c;
2216
2217 printf("ESC%c", strescseq.type);
2218 for(i = 0; i < strescseq.len; i++) {
2219 c = strescseq.buf[i] & 0xff;
2220 if(c == '\0') {
2221 return;
2222 } else if(isprint(c)) {
2223 putchar(c);
2224 } else if(c == '\n') {
2225 printf("(\\n)");
2226 } else if(c == '\r') {
2227 printf("(\\r)");
2228 } else if(c == 0x1b) {
2229 printf("(\\e)");
2230 } else {
2231 printf("(%02x)", c);
2232 }
2233 }
2234 printf("ESC\\\n");
2235 }
2236
2237 void
2238 strreset(void) {
2239 memset(&strescseq, 0, sizeof(strescseq));
2240 }
2241
2242 void
2243 tputtab(bool forward) {
2244 uint x = term.c.x;
2245
2246 if(forward) {
2247 if(x == term.col)
2248 return;
2249 for(++x; x < term.col && !term.tabs[x]; ++x)
2250 /* nothing */ ;
2251 } else {
2252 if(x == 0)
2253 return;
2254 for(--x; x > 0 && !term.tabs[x]; --x)
2255 /* nothing */ ;
2256 }
2257 tmoveto(x, term.c.y);
2258 }
2259
2260 void
2261 techo(char *buf, int len) {
2262 for(; len > 0; buf++, len--) {
2263 char c = *buf;
2264
2265 if(c == '\033') { /* escape */
2266 tputc("^", 1);
2267 tputc("[", 1);
2268 } else if(c < '\x20') { /* control code */
2269 if(c != '\n' && c != '\r' && c != '\t') {
2270 c |= '\x40';
2271 tputc("^", 1);
2272 }
2273 tputc(&c, 1);
2274 } else {
2275 break;
2276 }
2277 }
2278 if(len)
2279 tputc(buf, len);
2280 }
2281
2282 void
2283 tdeftran(char ascii) {
2284 char c, (*bp)[2];
2285 static char tbl[][2] = {
2286 {'0', CS_GRAPHIC0}, {'1', CS_GRAPHIC1}, {'A', CS_UK},
2287 {'B', CS_USA}, {'<', CS_MULTI}, {'K', CS_GER},
2288 {'5', CS_FIN}, {'C', CS_FIN},
2289 {0, 0}
2290 };
2291
2292 for (bp = &tbl[0]; (c = (*bp)[0]) && c != ascii; ++bp)
2293 /* nothing */;
2294
2295 if (c == 0)
2296 fprintf(stderr, "esc unhandled charset: ESC ( %c\n", ascii);
2297 else
2298 term.trantbl[term.icharset] = (*bp)[1];
2299 }
2300
2301 void
2302 tselcs(void) {
2303 if (term.trantbl[term.charset] == CS_GRAPHIC0)
2304 term.c.attr.mode |= ATTR_GFX;
2305 else
2306 term.c.attr.mode &= ~ATTR_GFX;
2307 }
2308
2309 void
2310 tputc(char *c, int len) {
2311 uchar ascii = *c;
2312 bool control = ascii < '\x20' || ascii == 0177;
2313 long u8char;
2314 int width;
2315
2316 if(len == 1) {
2317 width = 1;
2318 } else {
2319 utf8decode(c, &u8char);
2320 width = wcwidth(u8char);
2321 }
2322
2323 if(iofd != -1) {
2324 if(xwrite(iofd, c, len) < 0) {
2325 fprintf(stderr, "Error writing in %s:%s\n",
2326 opt_io, strerror(errno));
2327 close(iofd);
2328 iofd = -1;
2329 }
2330 }
2331
2332 /*
2333 * STR sequences must be checked before anything else
2334 * because it can use some control codes as part of the sequence.
2335 */
2336 if(term.esc & ESC_STR) {
2337 switch(ascii) {
2338 case '\033':
2339 term.esc = ESC_START | ESC_STR_END;
2340 break;
2341 case '\a': /* backwards compatibility to xterm */
2342 term.esc = 0;
2343 strhandle();
2344 break;
2345 default:
2346 if(strescseq.len + len < sizeof(strescseq.buf) - 1) {
2347 memmove(&strescseq.buf[strescseq.len], c, len);
2348 strescseq.len += len;
2349 } else {
2350 /*
2351 * Here is a bug in terminals. If the user never sends
2352 * some code to stop the str or esc command, then st
2353 * will stop responding. But this is better than
2354 * silently failing with unknown characters. At least
2355 * then users will report back.
2356 *
2357 * In the case users ever get fixed, here is the code:
2358 */
2359 /*
2360 * term.esc = 0;
2361 * strhandle();
2362 */
2363 }
2364 }
2365 return;
2366 }
2367
2368 /*
2369 * Actions of control codes must be performed as soon they arrive
2370 * because they can be embedded inside a control sequence, and
2371 * they must not cause conflicts with sequences.
2372 */
2373 if(control) {
2374 switch(ascii) {
2375 case '\t': /* HT */
2376 tputtab(1);
2377 return;
2378 case '\b': /* BS */
2379 tmoveto(term.c.x-1, term.c.y);
2380 return;
2381 case '\r': /* CR */
2382 tmoveto(0, term.c.y);
2383 return;
2384 case '\f': /* LF */
2385 case '\v': /* VT */
2386 case '\n': /* LF */
2387 /* go to first col if the mode is set */
2388 tnewline(IS_SET(MODE_CRLF));
2389 return;
2390 case '\a': /* BEL */
2391 if(!(xw.state & WIN_FOCUSED))
2392 xseturgency(1);
2393 if (bellvolume)
2394 XBell(xw.dpy, bellvolume);
2395 return;
2396 case '\033': /* ESC */
2397 csireset();
2398 term.esc = ESC_START;
2399 return;
2400 case '\016': /* SO */
2401 term.charset = 0;
2402 tselcs();
2403 return;
2404 case '\017': /* SI */
2405 term.charset = 1;
2406 tselcs();
2407 return;
2408 case '\032': /* SUB */
2409 case '\030': /* CAN */
2410 csireset();
2411 return;
2412 case '\005': /* ENQ (IGNORED) */
2413 case '\000': /* NUL (IGNORED) */
2414 case '\021': /* XON (IGNORED) */
2415 case '\023': /* XOFF (IGNORED) */
2416 case 0177: /* DEL (IGNORED) */
2417 return;
2418 }
2419 } else if(term.esc & ESC_START) {
2420 if(term.esc & ESC_CSI) {
2421 csiescseq.buf[csiescseq.len++] = ascii;
2422 if(BETWEEN(ascii, 0x40, 0x7E)
2423 || csiescseq.len >= \
2424 sizeof(csiescseq.buf)-1) {
2425 term.esc = 0;
2426 csiparse();
2427 csihandle();
2428 }
2429 } else if(term.esc & ESC_STR_END) {
2430 term.esc = 0;
2431 if(ascii == '\\')
2432 strhandle();
2433 } else if(term.esc & ESC_ALTCHARSET) {
2434 tdeftran(ascii);
2435 tselcs();
2436 term.esc = 0;
2437 } else if(term.esc & ESC_TEST) {
2438 if(ascii == '8') { /* DEC screen alignment test. */
2439 char E[UTF_SIZ] = "E";
2440 int x, y;
2441
2442 for(x = 0; x < term.col; ++x) {
2443 for(y = 0; y < term.row; ++y)
2444 tsetchar(E, &term.c.attr, x, y);
2445 }
2446 }
2447 term.esc = 0;
2448 } else {
2449 switch(ascii) {
2450 case '[':
2451 term.esc |= ESC_CSI;
2452 break;
2453 case '#':
2454 term.esc |= ESC_TEST;
2455 break;
2456 case 'P': /* DCS -- Device Control String */
2457 case '_': /* APC -- Application Program Command */
2458 case '^': /* PM -- Privacy Message */
2459 case ']': /* OSC -- Operating System Command */
2460 case 'k': /* old title set compatibility */
2461 strreset();
2462 strescseq.type = ascii;
2463 term.esc |= ESC_STR;
2464 break;
2465 case '(': /* set primary charset G0 */
2466 case ')': /* set secondary charset G1 */
2467 case '*': /* set tertiary charset G2 */
2468 case '+': /* set quaternary charset G3 */
2469 term.icharset = ascii - '(';
2470 term.esc |= ESC_ALTCHARSET;
2471 break;
2472 case 'D': /* IND -- Linefeed */
2473 if(term.c.y == term.bot) {
2474 tscrollup(term.top, 1);
2475 } else {
2476 tmoveto(term.c.x, term.c.y+1);
2477 }
2478 term.esc = 0;
2479 break;
2480 case 'E': /* NEL -- Next line */
2481 tnewline(1); /* always go to first col */
2482 term.esc = 0;
2483 break;
2484 case 'H': /* HTS -- Horizontal tab stop */
2485 term.tabs[term.c.x] = 1;
2486 term.esc = 0;
2487 break;
2488 case 'M': /* RI -- Reverse index */
2489 if(term.c.y == term.top) {
2490 tscrolldown(term.top, 1);
2491 } else {
2492 tmoveto(term.c.x, term.c.y-1);
2493 }
2494 term.esc = 0;
2495 break;
2496 case 'Z': /* DECID -- Identify Terminal */
2497 ttywrite(VT102ID, sizeof(VT102ID) - 1);
2498 term.esc = 0;
2499 break;
2500 case 'c': /* RIS -- Reset to inital state */
2501 treset();
2502 term.esc = 0;
2503 xresettitle();
2504 xloadcols();
2505 break;
2506 case '=': /* DECPAM -- Application keypad */
2507 term.mode |= MODE_APPKEYPAD;
2508 term.esc = 0;
2509 break;
2510 case '>': /* DECPNM -- Normal keypad */
2511 term.mode &= ~MODE_APPKEYPAD;
2512 term.esc = 0;
2513 break;
2514 case '7': /* DECSC -- Save Cursor */
2515 tcursor(CURSOR_SAVE);
2516 term.esc = 0;
2517 break;
2518 case '8': /* DECRC -- Restore Cursor */
2519 tcursor(CURSOR_LOAD);
2520 term.esc = 0;
2521 break;
2522 case '\\': /* ST -- Stop */
2523 term.esc = 0;
2524 break;
2525 default:
2526 fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n",
2527 (uchar) ascii, isprint(ascii)? ascii:'.');
2528 term.esc = 0;
2529 }
2530 }
2531 /*
2532 * All characters which form part of a sequence are not
2533 * printed
2534 */
2535 return;
2536 }
2537 /*
2538 * Display control codes only if we are in graphic mode
2539 */
2540 if(control && !(term.c.attr.mode & ATTR_GFX))
2541 return;
2542 if(sel.ob.x != -1 && BETWEEN(term.c.y, sel.ob.y, sel.oe.y))
2543 selclear(NULL);
2544 if(IS_SET(MODE_WRAP) && (term.c.state & CURSOR_WRAPNEXT)) {
2545 term.line[term.c.y][term.c.x].mode |= ATTR_WRAP;
2546 tnewline(1);
2547 }
2548
2549 if(IS_SET(MODE_INSERT) && term.c.x+1 < term.col) {
2550 memmove(&term.line[term.c.y][term.c.x+1],
2551 &term.line[term.c.y][term.c.x],
2552 (term.col - term.c.x - 1) * sizeof(Glyph));
2553 }
2554
2555 if(term.c.x+width > term.col)
2556 tnewline(1);
2557
2558 tsetchar(c, &term.c.attr, term.c.x, term.c.y);
2559
2560 if(width == 2) {
2561 term.line[term.c.y][term.c.x].mode |= ATTR_WIDE;
2562 if(term.c.x+1 < term.col) {
2563 term.line[term.c.y][term.c.x+1].c[0] = '\0';
2564 term.line[term.c.y][term.c.x+1].mode = ATTR_WDUMMY;
2565 }
2566 }
2567 if(term.c.x+width < term.col) {
2568 tmoveto(term.c.x+width, term.c.y);
2569 } else {
2570 term.c.state |= CURSOR_WRAPNEXT;
2571 }
2572 }
2573
2574 int
2575 tresize(int col, int row) {
2576 int i;
2577 int minrow = MIN(row, term.row);
2578 int mincol = MIN(col, term.col);
2579 int slide = term.c.y - row + 1;
2580 bool *bp;
2581 Line *orig;
2582
2583 if(col < 1 || row < 1)
2584 return 0;
2585
2586 /* free unneeded rows */
2587 i = 0;
2588 if(slide > 0) {
2589 /*
2590 * slide screen to keep cursor where we expect it -
2591 * tscrollup would work here, but we can optimize to
2592 * memmove because we're freeing the earlier lines
2593 */
2594 for(/* i = 0 */; i < slide; i++) {
2595 free(term.line[i]);
2596 free(term.alt[i]);
2597 }
2598 memmove(term.line, term.line + slide, row * sizeof(Line));
2599 memmove(term.alt, term.alt + slide, row * sizeof(Line));
2600 }
2601 for(i += row; i < term.row; i++) {
2602 free(term.line[i]);
2603 free(term.alt[i]);
2604 }
2605
2606 /* resize to new height */
2607 term.line = xrealloc(term.line, row * sizeof(Line));
2608 term.alt = xrealloc(term.alt, row * sizeof(Line));
2609 term.dirty = xrealloc(term.dirty, row * sizeof(*term.dirty));
2610 term.tabs = xrealloc(term.tabs, col * sizeof(*term.tabs));
2611
2612 /* resize each row to new width, zero-pad if needed */
2613 for(i = 0; i < minrow; i++) {
2614 term.dirty[i] = 1;
2615 term.line[i] = xrealloc(term.line[i], col * sizeof(Glyph));
2616 term.alt[i] = xrealloc(term.alt[i], col * sizeof(Glyph));
2617 }
2618
2619 /* allocate any new rows */
2620 for(/* i == minrow */; i < row; i++) {
2621 term.dirty[i] = 1;
2622 term.line[i] = xmalloc(col * sizeof(Glyph));
2623 term.alt[i] = xmalloc(col * sizeof(Glyph));
2624 }
2625 if(col > term.col) {
2626 bp = term.tabs + term.col;
2627
2628 memset(bp, 0, sizeof(*term.tabs) * (col - term.col));
2629 while(--bp > term.tabs && !*bp)
2630 /* nothing */ ;
2631 for(bp += tabspaces; bp < term.tabs + col; bp += tabspaces)
2632 *bp = 1;
2633 }
2634 /* update terminal size */
2635 term.col = col;
2636 term.row = row;
2637 /* reset scrolling region */
2638 tsetscroll(0, row-1);
2639 /* make use of the LIMIT in tmoveto */
2640 tmoveto(term.c.x, term.c.y);
2641 /* Clearing both screens */
2642 orig = term.line;
2643 do {
2644 if(mincol < col && 0 < minrow) {
2645 tclearregion(mincol, 0, col - 1, minrow - 1);
2646 }
2647 if(0 < col && minrow < row) {
2648 tclearregion(0, minrow, col - 1, row - 1);
2649 }
2650 tswapscreen();
2651 } while(orig != term.line);
2652
2653 return (slide > 0);
2654 }
2655
2656 void
2657 xresize(int col, int row) {
2658 xw.tw = MAX(1, col * xw.cw);
2659 xw.th = MAX(1, row * xw.ch);
2660
2661 XFreePixmap(xw.dpy, xw.buf);
2662 xw.buf = XCreatePixmap(xw.dpy, xw.win, xw.w, xw.h,
2663 DefaultDepth(xw.dpy, xw.scr));
2664 XftDrawChange(xw.draw, xw.buf);
2665 xclear(0, 0, xw.w, xw.h);
2666 }
2667
2668 static inline ushort
2669 sixd_to_16bit(int x) {
2670 return x == 0 ? 0 : 0x3737 + 0x2828 * x;
2671 }
2672
2673 void
2674 xloadcols(void) {
2675 int i, r, g, b;
2676 XRenderColor color = { .alpha = 0xffff };
2677 static bool loaded;
2678 Colour *cp;
2679
2680 if(loaded) {
2681 for (cp = dc.col; cp < dc.col + LEN(dc.col); ++cp)
2682 XftColorFree(xw.dpy, xw.vis, xw.cmap, cp);
2683 }
2684
2685 /* load colors [0-15] colors and [256-LEN(colorname)[ (config.h) */
2686 for(i = 0; i < LEN(colorname); i++) {
2687 if(!colorname[i])
2688 continue;
2689 if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, colorname[i], &dc.col[i])) {
2690 die("Could not allocate color '%s'\n", colorname[i]);
2691 }
2692 }
2693
2694 /* load colors [16-255] ; same colors as xterm */
2695 for(i = 16, r = 0; r < 6; r++) {
2696 for(g = 0; g < 6; g++) {
2697 for(b = 0; b < 6; b++) {
2698 color.red = sixd_to_16bit(r);
2699 color.green = sixd_to_16bit(g);
2700 color.blue = sixd_to_16bit(b);
2701 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &dc.col[i])) {
2702 die("Could not allocate color %d\n", i);
2703 }
2704 i++;
2705 }
2706 }
2707 }
2708
2709 for(r = 0; r < 24; r++, i++) {
2710 color.red = color.green = color.blue = 0x0808 + 0x0a0a * r;
2711 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color,
2712 &dc.col[i])) {
2713 die("Could not allocate color %d\n", i);
2714 }
2715 }
2716 loaded = true;
2717 }
2718
2719 int
2720 xsetcolorname(int x, const char *name) {
2721 XRenderColor color = { .alpha = 0xffff };
2722 Colour colour;
2723 if (x < 0 || x > LEN(colorname))
2724 return -1;
2725 if(!name) {
2726 if(16 <= x && x < 16 + 216) {
2727 int r = (x - 16) / 36, g = ((x - 16) % 36) / 6, b = (x - 16) % 6;
2728 color.red = sixd_to_16bit(r);
2729 color.green = sixd_to_16bit(g);
2730 color.blue = sixd_to_16bit(b);
2731 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &colour))
2732 return 0; /* something went wrong */
2733 dc.col[x] = colour;
2734 return 1;
2735 } else if (16 + 216 <= x && x < 256) {
2736 color.red = color.green = color.blue = 0x0808 + 0x0a0a * (x - (16 + 216));
2737 if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &colour))
2738 return 0; /* something went wrong */
2739 dc.col[x] = colour;
2740 return 1;
2741 } else {
2742 name = colorname[x];
2743 }
2744 }
2745 if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, name, &colour))
2746 return 0;
2747 dc.col[x] = colour;
2748 return 1;
2749 }
2750
2751 void
2752 xtermclear(int col1, int row1, int col2, int row2) {
2753 XftDrawRect(xw.draw,
2754 &dc.col[IS_SET(MODE_REVERSE) ? defaultfg : defaultbg],
2755 borderpx + col1 * xw.cw,
2756 borderpx + row1 * xw.ch,
2757 (col2-col1+1) * xw.cw,
2758 (row2-row1+1) * xw.ch);
2759 }
2760
2761 /*
2762 * Absolute coordinates.
2763 */
2764 void
2765 xclear(int x1, int y1, int x2, int y2) {
2766 XftDrawRect(xw.draw,
2767 &dc.col[IS_SET(MODE_REVERSE)? defaultfg : defaultbg],
2768 x1, y1, x2-x1, y2-y1);
2769 }
2770
2771 void
2772 xhints(void) {
2773 XClassHint class = {opt_class ? opt_class : termname, termname};
2774 XWMHints wm = {.flags = InputHint, .input = 1};
2775 XSizeHints *sizeh = NULL;
2776
2777 sizeh = XAllocSizeHints();
2778 if(xw.isfixed == False) {
2779 sizeh->flags = PSize | PResizeInc | PBaseSize;
2780 sizeh->height = xw.h;
2781 sizeh->width = xw.w;
2782 sizeh->height_inc = xw.ch;
2783 sizeh->width_inc = xw.cw;
2784 sizeh->base_height = 2 * borderpx;
2785 sizeh->base_width = 2 * borderpx;
2786 } else {
2787 sizeh->flags = PMaxSize | PMinSize;
2788 sizeh->min_width = sizeh->max_width = xw.fw;
2789 sizeh->min_height = sizeh->max_height = xw.fh;
2790 }
2791
2792 XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm, &class);
2793 XFree(sizeh);
2794 }
2795
2796 int
2797 xloadfont(Font *f, FcPattern *pattern) {
2798 FcPattern *match;
2799 FcResult result;
2800
2801 match = FcFontMatch(NULL, pattern, &result);
2802 if(!match)
2803 return 1;
2804
2805 if(!(f->match = XftFontOpenPattern(xw.dpy, match))) {
2806 FcPatternDestroy(match);
2807 return 1;
2808 }
2809
2810 f->set = NULL;
2811 f->pattern = FcPatternDuplicate(pattern);
2812
2813 f->ascent = f->match->ascent;
2814 f->descent = f->match->descent;
2815 f->lbearing = 0;
2816 f->rbearing = f->match->max_advance_width;
2817
2818 f->height = f->ascent + f->descent;
2819 f->width = f->lbearing + f->rbearing;
2820
2821 return 0;
2822 }
2823
2824 void
2825 xloadfonts(char *fontstr, double fontsize) {
2826 FcPattern *pattern;
2827 FcResult r_sz, r_psz;
2828 double fontval;
2829
2830 if(fontstr[0] == '-') {
2831 pattern = XftXlfdParse(fontstr, False, False);
2832 } else {
2833 pattern = FcNameParse((FcChar8 *)fontstr);
2834 }
2835
2836 if(!pattern)
2837 die("st: can't open font %s\n", fontstr);
2838
2839 if(fontsize > 0) {
2840 FcPatternDel(pattern, FC_PIXEL_SIZE);
2841 FcPatternDel(pattern, FC_SIZE);
2842 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, (double)fontsize);
2843 usedfontsize = fontsize;
2844 } else {
2845 r_psz = FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &fontval);
2846 r_sz = FcPatternGetDouble(pattern, FC_SIZE, 0, &fontval);
2847 if(r_psz == FcResultMatch) {
2848 usedfontsize = fontval;
2849 } else if(r_sz == FcResultMatch) {
2850 usedfontsize = -1;
2851 } else {
2852 /*
2853 * Default font size is 12, if none given. This is to
2854 * have a known usedfontsize value.
2855 */
2856 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, 12);
2857 usedfontsize = 12;
2858 }
2859 }
2860
2861 FcConfigSubstitute(0, pattern, FcMatchPattern);
2862 FcDefaultSubstitute(pattern);
2863
2864 if(xloadfont(&dc.font, pattern))
2865 die("st: can't open font %s\n", fontstr);
2866
2867 if(usedfontsize < 0) {
2868 FcPatternGetDouble(dc.font.match->pattern,
2869 FC_PIXEL_SIZE, 0, &fontval);
2870 usedfontsize = fontval;
2871 }
2872
2873 /* Setting character width and height. */
2874 xw.cw = CEIL(dc.font.width * cwscale);
2875 xw.ch = CEIL(dc.font.height * chscale);
2876
2877 FcPatternDel(pattern, FC_SLANT);
2878 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC);
2879 if(xloadfont(&dc.ifont, pattern))
2880 die("st: can't open font %s\n", fontstr);
2881
2882 FcPatternDel(pattern, FC_WEIGHT);
2883 FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD);
2884 if(xloadfont(&dc.ibfont, pattern))
2885 die("st: can't open font %s\n", fontstr);
2886
2887 FcPatternDel(pattern, FC_SLANT);
2888 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ROMAN);
2889 if(xloadfont(&dc.bfont, pattern))
2890 die("st: can't open font %s\n", fontstr);
2891
2892 FcPatternDestroy(pattern);
2893 }
2894
2895 int
2896 xloadfontset(Font *f) {
2897 FcResult result;
2898
2899 if(!(f->set = FcFontSort(0, f->pattern, FcTrue, 0, &result)))
2900 return 1;
2901 return 0;
2902 }
2903
2904 void
2905 xunloadfont(Font *f) {
2906 XftFontClose(xw.dpy, f->match);
2907 FcPatternDestroy(f->pattern);
2908 if(f->set)
2909 FcFontSetDestroy(f->set);
2910 }
2911
2912 void
2913 xunloadfonts(void) {
2914 int i;
2915
2916 /* Free the loaded fonts in the font cache. */
2917 for(i = 0; i < frclen; i++) {
2918 XftFontClose(xw.dpy, frc[i].font);
2919 }
2920 frclen = 0;
2921
2922 xunloadfont(&dc.font);
2923 xunloadfont(&dc.bfont);
2924 xunloadfont(&dc.ifont);
2925 xunloadfont(&dc.ibfont);
2926 }
2927
2928 void
2929 xzoom(const Arg *arg) {
2930 xunloadfonts();
2931 xloadfonts(usedfont, usedfontsize + arg->i);
2932 cresize(0, 0);
2933 redraw(0);
2934 }
2935
2936 void
2937 xinit(void) {
2938 XGCValues gcvalues;
2939 Cursor cursor;
2940 Window parent;
2941 int sw, sh;
2942 pid_t thispid = getpid();
2943
2944 if(!(xw.dpy = XOpenDisplay(NULL)))
2945 die("Can't open display\n");
2946 xw.scr = XDefaultScreen(xw.dpy);
2947 xw.vis = XDefaultVisual(xw.dpy, xw.scr);
2948
2949 /* font */
2950 if(!FcInit())
2951 die("Could not init fontconfig.\n");
2952
2953 usedfont = (opt_font == NULL)? font : opt_font;
2954 xloadfonts(usedfont, 0);
2955
2956 /* colors */
2957 xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
2958 xloadcols();
2959
2960 /* adjust fixed window geometry */
2961 if(xw.isfixed) {
2962 sw = DisplayWidth(xw.dpy, xw.scr);
2963 sh = DisplayHeight(xw.dpy, xw.scr);
2964 if(xw.fx < 0)
2965 xw.fx = sw + xw.fx - xw.fw - 1;
2966 if(xw.fy < 0)
2967 xw.fy = sh + xw.fy - xw.fh - 1;
2968
2969 xw.h = xw.fh;
2970 xw.w = xw.fw;
2971 } else {
2972 /* window - default size */
2973 xw.h = 2 * borderpx + term.row * xw.ch;
2974 xw.w = 2 * borderpx + term.col * xw.cw;
2975 xw.fx = 0;
2976 xw.fy = 0;
2977 }
2978
2979 /* Events */
2980 xw.attrs.background_pixel = dc.col[defaultbg].pixel;
2981 xw.attrs.border_pixel = dc.col[defaultbg].pixel;
2982 xw.attrs.bit_gravity = NorthWestGravity;
2983 xw.attrs.event_mask = FocusChangeMask | KeyPressMask
2984 | ExposureMask | VisibilityChangeMask | StructureNotifyMask
2985 | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
2986 xw.attrs.colormap = xw.cmap;
2987
2988 parent = opt_embed ? strtol(opt_embed, NULL, 0) : \
2989 XRootWindow(xw.dpy, xw.scr);
2990 xw.win = XCreateWindow(xw.dpy, parent, xw.fx, xw.fy,
2991 xw.w, xw.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
2992 xw.vis, CWBackPixel | CWBorderPixel | CWBitGravity
2993 | CWEventMask | CWColormap, &xw.attrs);
2994
2995 memset(&gcvalues, 0, sizeof(gcvalues));
2996 gcvalues.graphics_exposures = False;
2997 dc.gc = XCreateGC(xw.dpy, parent, GCGraphicsExposures,
2998 &gcvalues);
2999 xw.buf = XCreatePixmap(xw.dpy, xw.win, xw.w, xw.h,
3000 DefaultDepth(xw.dpy, xw.scr));
3001 XSetForeground(xw.dpy, dc.gc, dc.col[defaultbg].pixel);
3002 XFillRectangle(xw.dpy, xw.buf, dc.gc, 0, 0, xw.w, xw.h);
3003
3004 /* Xft rendering context */
3005 xw.draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
3006
3007 /* input methods */
3008 if((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
3009 XSetLocaleModifiers("@im=local");
3010 if((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
3011 XSetLocaleModifiers("@im=");
3012 if((xw.xim = XOpenIM(xw.dpy,
3013 NULL, NULL, NULL)) == NULL) {
3014 die("XOpenIM failed. Could not open input"
3015 " device.\n");
3016 }
3017 }
3018 }
3019 xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
3020 | XIMStatusNothing, XNClientWindow, xw.win,
3021 XNFocusWindow, xw.win, NULL);
3022 if(xw.xic == NULL)
3023 die("XCreateIC failed. Could not obtain input method.\n");
3024
3025 /* white cursor, black outline */
3026 cursor = XCreateFontCursor(xw.dpy, XC_xterm);
3027 XDefineCursor(xw.dpy, xw.win, cursor);
3028 XRecolorCursor(xw.dpy, cursor,
3029 &(XColor){.red = 0xffff, .green = 0xffff, .blue = 0xffff},
3030 &(XColor){.red = 0x0000, .green = 0x0000, .blue = 0x0000});
3031
3032 xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
3033 xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
3034 xw.netwmname = XInternAtom(xw.dpy, "_NET_WM_NAME", False);
3035 XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
3036
3037 xw.netwmpid = XInternAtom(xw.dpy, "_NET_WM_PID", False);
3038 XChangeProperty(xw.dpy, xw.win, xw.netwmpid, XA_CARDINAL, 32,
3039 PropModeReplace, (unsigned char *)&thispid, 1);
3040
3041 xresettitle();
3042 XMapWindow(xw.dpy, xw.win);
3043 xhints();
3044 XSync(xw.dpy, 0);
3045 }
3046
3047 void
3048 xdraws(char *s, Glyph base, int x, int y, int charlen, int bytelen) {
3049 int winx = borderpx + x * xw.cw, winy = borderpx + y * xw.ch,
3050 width = charlen * xw.cw, xp, i;
3051 int frcflags;
3052 int u8fl, u8fblen, u8cblen, doesexist;
3053 char *u8c, *u8fs;
3054 long u8char;
3055 Font *font = &dc.font;
3056 FcResult fcres;
3057 FcPattern *fcpattern, *fontpattern;
3058 FcFontSet *fcsets[] = { NULL };
3059 FcCharSet *fccharset;
3060 Colour *fg, *bg, *temp, revfg, revbg, truefg, truebg;
3061 XRenderColor colfg, colbg;
3062 Rectangle r;
3063 int oneatatime;
3064
3065 frcflags = FRC_NORMAL;
3066
3067 if(base.mode & ATTR_ITALIC) {
3068 if(base.fg == defaultfg)
3069 base.fg = defaultitalic;
3070 font = &dc.ifont;
3071 frcflags = FRC_ITALIC;
3072 } else if((base.mode & ATTR_ITALIC) && (base.mode & ATTR_BOLD)) {
3073 if(base.fg == defaultfg)
3074 base.fg = defaultitalic;
3075 font = &dc.ibfont;
3076 frcflags = FRC_ITALICBOLD;
3077 } else if(base.mode & ATTR_UNDERLINE) {
3078 if(base.fg == defaultfg)
3079 base.fg = defaultunderline;
3080 }
3081 if(IS_TRUECOL(base.fg)) {
3082 colfg.alpha = 0xffff;
3083 colfg.red = TRUERED(base.fg);
3084 colfg.green = TRUEGREEN(base.fg);
3085 colfg.blue = TRUEBLUE(base.fg);
3086 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &truefg);
3087 fg = &truefg;
3088 } else {
3089 fg = &dc.col[base.fg];
3090 }
3091
3092 if(IS_TRUECOL(base.bg)) {
3093 colbg.alpha = 0xffff;
3094 colbg.green = TRUEGREEN(base.bg);
3095 colbg.red = TRUERED(base.bg);
3096 colbg.blue = TRUEBLUE(base.bg);
3097 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &truebg);
3098 bg = &truebg;
3099 } else {
3100 bg = &dc.col[base.bg];
3101 }
3102
3103
3104
3105 if(base.mode & ATTR_BOLD) {
3106 if(BETWEEN(base.fg, 0, 7)) {
3107 /* basic system colors */
3108 fg = &dc.col[base.fg + 8];
3109 } else if(BETWEEN(base.fg, 16, 195)) {
3110 /* 256 colors */
3111 fg = &dc.col[base.fg + 36];
3112 } else if(BETWEEN(base.fg, 232, 251)) {
3113 /* greyscale */
3114 fg = &dc.col[base.fg + 4];
3115 }
3116 /*
3117 * Those ranges will not be brightened:
3118 * 8 - 15 – bright system colors
3119 * 196 - 231 – highest 256 color cube
3120 * 252 - 255 – brightest colors in greyscale
3121 */
3122 font = &dc.bfont;
3123 frcflags = FRC_BOLD;
3124 }
3125
3126 if(IS_SET(MODE_REVERSE)) {
3127 if(fg == &dc.col[defaultfg]) {
3128 fg = &dc.col[defaultbg];
3129 } else {
3130 colfg.red = ~fg->color.red;
3131 colfg.green = ~fg->color.green;
3132 colfg.blue = ~fg->color.blue;
3133 colfg.alpha = fg->color.alpha;
3134 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
3135 fg = &revfg;
3136 }
3137
3138 if(bg == &dc.col[defaultbg]) {
3139 bg = &dc.col[defaultfg];
3140 } else {
3141 colbg.red = ~bg->color.red;
3142 colbg.green = ~bg->color.green;
3143 colbg.blue = ~bg->color.blue;
3144 colbg.alpha = bg->color.alpha;
3145 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &revbg);
3146 bg = &revbg;
3147 }
3148 }
3149
3150 if(base.mode & ATTR_REVERSE) {
3151 temp = fg;
3152 fg = bg;
3153 bg = temp;
3154 }
3155
3156 if(base.mode & ATTR_BLINK && term.mode & MODE_BLINK)
3157 fg = bg;
3158
3159 /* Intelligent cleaning up of the borders. */
3160 if(x == 0) {
3161 xclear(0, (y == 0)? 0 : winy, borderpx,
3162 winy + xw.ch + ((y >= term.row-1)? xw.h : 0));
3163 }
3164 if(x + charlen >= term.col) {
3165 xclear(winx + width, (y == 0)? 0 : winy, xw.w,
3166 ((y >= term.row-1)? xw.h : (winy + xw.ch)));
3167 }
3168 if(y == 0)
3169 xclear(winx, 0, winx + width, borderpx);
3170 if(y == term.row-1)
3171 xclear(winx, winy + xw.ch, winx + width, xw.h);
3172
3173 /* Clean up the region we want to draw to. */
3174 XftDrawRect(xw.draw, bg, winx, winy, width, xw.ch);
3175
3176 /* Set the clip region because Xft is sometimes dirty. */
3177 r.x = 0;
3178 r.y = 0;
3179 r.height = xw.ch;
3180 r.width = width;
3181 XftDrawSetClipRectangles(xw.draw, winx, winy, &r, 1);
3182
3183 for(xp = winx; bytelen > 0;) {
3184 /*
3185 * Search for the range in the to be printed string of glyphs
3186 * that are in the main font. Then print that range. If
3187 * some glyph is found that is not in the font, do the
3188 * fallback dance.
3189 */
3190 u8fs = s;
3191 u8fblen = 0;
3192 u8fl = 0;
3193 oneatatime = font->width != xw.cw;
3194 for(;;) {
3195 u8c = s;
3196 u8cblen = utf8decode(s, &u8char);
3197 s += u8cblen;
3198 bytelen -= u8cblen;
3199
3200 doesexist = XftCharExists(xw.dpy, font->match, u8char);
3201 if(oneatatime || !doesexist || bytelen <= 0) {
3202 if(oneatatime || bytelen <= 0) {
3203 if(doesexist) {
3204 u8fl++;
3205 u8fblen += u8cblen;
3206 }
3207 }
3208
3209 if(u8fl > 0) {
3210 XftDrawStringUtf8(xw.draw, fg,
3211 font->match, xp,
3212 winy + font->ascent,
3213 (FcChar8 *)u8fs,
3214 u8fblen);
3215 xp += xw.cw * u8fl;
3216
3217 }
3218 break;
3219 }
3220
3221 u8fl++;
3222 u8fblen += u8cblen;
3223 }
3224 if(doesexist) {
3225 if (oneatatime)
3226 continue;
3227 break;
3228 }
3229
3230 /* Search the font cache. */
3231 for(i = 0; i < frclen; i++) {
3232 if(XftCharExists(xw.dpy, frc[i].font, u8char)
3233 && frc[i].flags == frcflags) {
3234 break;
3235 }
3236 }
3237
3238 /* Nothing was found. */
3239 if(i >= frclen) {
3240 if(!font->set)
3241 xloadfontset(font);
3242 fcsets[0] = font->set;
3243
3244 /*
3245 * Nothing was found in the cache. Now use
3246 * some dozen of Fontconfig calls to get the
3247 * font for one single character.
3248 */
3249 fcpattern = FcPatternDuplicate(font->pattern);
3250 fccharset = FcCharSetCreate();
3251
3252 FcCharSetAddChar(fccharset, u8char);
3253 FcPatternAddCharSet(fcpattern, FC_CHARSET,
3254 fccharset);
3255 FcPatternAddBool(fcpattern, FC_SCALABLE,
3256 FcTrue);
3257
3258 FcConfigSubstitute(0, fcpattern,
3259 FcMatchPattern);
3260 FcDefaultSubstitute(fcpattern);
3261
3262 fontpattern = FcFontSetMatch(0, fcsets,
3263 FcTrue, fcpattern, &fcres);
3264
3265 /*
3266 * Overwrite or create the new cache entry.
3267 */
3268 if(frclen >= LEN(frc)) {
3269 frclen = LEN(frc) - 1;
3270 XftFontClose(xw.dpy, frc[frclen].font);
3271 }
3272
3273 frc[frclen].font = XftFontOpenPattern(xw.dpy,
3274 fontpattern);
3275 frc[frclen].flags = frcflags;
3276
3277 i = frclen;
3278 frclen++;
3279
3280 FcPatternDestroy(fcpattern);
3281 FcCharSetDestroy(fccharset);
3282 }
3283
3284 XftDrawStringUtf8(xw.draw, fg, frc[i].font,
3285 xp, winy + frc[i].font->ascent,
3286 (FcChar8 *)u8c, u8cblen);
3287
3288 xp += xw.cw * wcwidth(u8char);
3289 }
3290
3291 /*
3292 XftDrawStringUtf8(xw.draw, fg, font->set, winx,
3293 winy + font->ascent, (FcChar8 *)s, bytelen);
3294 */
3295
3296 if(base.mode & ATTR_UNDERLINE) {
3297 XftDrawRect(xw.draw, fg, winx, winy + font->ascent + 1,
3298 width, 1);
3299 }
3300 XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, winx, winy, width,
3301 CEIL((font->ascent + font->descent) * chscale), winx, winy);
3302
3303 /* Reset clip to none. */
3304 XftDrawSetClip(xw.draw, 0);
3305 }
3306
3307 void
3308 xdrawcursor(void) {
3309 static int oldx = 0, oldy = 0;
3310 int sl, width, curx;
3311 Glyph g = {{' '}, ATTR_NULL, defaultbg, defaultcs};
3312
3313 LIMIT(oldx, 0, term.col-1);
3314 LIMIT(oldy, 0, term.row-1);
3315
3316 curx = term.c.x;
3317
3318 /* adjust position if in dummy */
3319 if(term.line[oldy][oldx].mode & ATTR_WDUMMY)
3320 oldx--;
3321 if(term.line[term.c.y][curx].mode & ATTR_WDUMMY)
3322 curx--;
3323
3324 memcpy(g.c, term.line[term.c.y][term.c.x].c, UTF_SIZ);
3325
3326 /* remove the old cursor */
3327 sl = utf8size(term.line[oldy][oldx].c);
3328 width = (term.line[oldy][oldx].mode & ATTR_WIDE)? 2 : 1;
3329 xdraws(term.line[oldy][oldx].c, term.line[oldy][oldx], oldx,
3330 oldy, width, sl);
3331
3332 /* draw the new one */
3333 if(!(IS_SET(MODE_HIDE))) {
3334 if(xw.state & WIN_FOCUSED) {
3335 if(IS_SET(MODE_REVERSE)) {
3336 g.mode |= ATTR_REVERSE;
3337 g.fg = defaultcs;
3338 g.bg = defaultfg;
3339 }
3340
3341 sl = utf8size(g.c);
3342 width = (term.line[term.c.y][curx].mode & ATTR_WIDE)\
3343 ? 2 : 1;
3344 xdraws(g.c, g, term.c.x, term.c.y, width, sl);
3345 } else {
3346 XftDrawRect(xw.draw, &dc.col[defaultcs],
3347 borderpx + curx * xw.cw,
3348 borderpx + term.c.y * xw.ch,
3349 xw.cw - 1, 1);
3350 XftDrawRect(xw.draw, &dc.col[defaultcs],
3351 borderpx + curx * xw.cw,
3352 borderpx + term.c.y * xw.ch,
3353 1, xw.ch - 1);
3354 XftDrawRect(xw.draw, &dc.col[defaultcs],
3355 borderpx + (curx + 1) * xw.cw - 1,
3356 borderpx + term.c.y * xw.ch,
3357 1, xw.ch - 1);
3358 XftDrawRect(xw.draw, &dc.col[defaultcs],
3359 borderpx + curx * xw.cw,
3360 borderpx + (term.c.y + 1) * xw.ch - 1,
3361 xw.cw, 1);
3362 }
3363 oldx = curx, oldy = term.c.y;
3364 }
3365 }
3366
3367
3368 void
3369 xsettitle(char *p) {
3370 XTextProperty prop;
3371
3372 Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle,
3373 &prop);
3374 XSetWMName(xw.dpy, xw.win, &prop);
3375 XSetTextProperty(xw.dpy, xw.win, &prop, xw.netwmname);
3376 XFree(prop.value);
3377 }
3378
3379 void
3380 xresettitle(void) {
3381 xsettitle(opt_title ? opt_title : "st");
3382 }
3383
3384 void
3385 redraw(int timeout) {
3386 struct timespec tv = {0, timeout * 1000};
3387
3388 tfulldirt();
3389 draw();
3390
3391 if(timeout > 0) {
3392 nanosleep(&tv, NULL);
3393 XSync(xw.dpy, False); /* necessary for a good tput flash */
3394 }
3395 }
3396
3397 void
3398 draw(void) {
3399 drawregion(0, 0, term.col, term.row);
3400 XSetForeground(xw.dpy, dc.gc,
3401 dc.col[IS_SET(MODE_REVERSE)?
3402 defaultfg : defaultbg].pixel);
3403 }
3404
3405 void
3406 drawregion(int x1, int y1, int x2, int y2) {
3407 int ic, ib, x, y, ox, sl;
3408 Glyph base, new;
3409 char buf[DRAW_BUF_SIZ];
3410 bool ena_sel = sel.ob.x != -1;
3411 long u8char;
3412
3413 if(sel.alt ^ IS_SET(MODE_ALTSCREEN))
3414 ena_sel = 0;
3415
3416 if(!(xw.state & WIN_VISIBLE))
3417 return;
3418
3419 for(y = y1; y < y2; y++) {
3420 if(!term.dirty[y])
3421 continue;
3422
3423 xtermclear(0, y, term.col, y);
3424 term.dirty[y] = 0;
3425 base = term.line[y][0];
3426 ic = ib = ox = 0;
3427 for(x = x1; x < x2; x++) {
3428 new = term.line[y][x];
3429 if(new.mode == ATTR_WDUMMY)
3430 continue;
3431 if(ena_sel && selected(x, y))
3432 new.mode ^= ATTR_REVERSE;
3433 if(ib > 0 && (ATTRCMP(base, new)
3434 || ib >= DRAW_BUF_SIZ-UTF_SIZ)) {
3435 xdraws(buf, base, ox, y, ic, ib);
3436 ic = ib = 0;
3437 }
3438 if(ib == 0) {
3439 ox = x;
3440 base = new;
3441 }
3442
3443 sl = utf8decode(new.c, &u8char);
3444 memcpy(buf+ib, new.c, sl);
3445 ib += sl;
3446 ic += (new.mode & ATTR_WIDE)? 2 : 1;
3447 }
3448 if(ib > 0)
3449 xdraws(buf, base, ox, y, ic, ib);
3450 }
3451 xdrawcursor();
3452 }
3453
3454 void
3455 expose(XEvent *ev) {
3456 XExposeEvent *e = &ev->xexpose;
3457
3458 if(xw.state & WIN_REDRAW) {
3459 if(!e->count)
3460 xw.state &= ~WIN_REDRAW;
3461 }
3462 redraw(0);
3463 }
3464
3465 void
3466 visibility(XEvent *ev) {
3467 XVisibilityEvent *e = &ev->xvisibility;
3468
3469 if(e->state == VisibilityFullyObscured) {
3470 xw.state &= ~WIN_VISIBLE;
3471 } else if(!(xw.state & WIN_VISIBLE)) {
3472 /* need a full redraw for next Expose, not just a buf copy */
3473 xw.state |= WIN_VISIBLE | WIN_REDRAW;
3474 }
3475 }
3476
3477 void
3478 unmap(XEvent *ev) {
3479 xw.state &= ~WIN_VISIBLE;
3480 }
3481
3482 void
3483 xsetpointermotion(int set) {
3484 MODBIT(xw.attrs.event_mask, set, PointerMotionMask);
3485 XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask, &xw.attrs);
3486 }
3487
3488 void
3489 xseturgency(int add) {
3490 XWMHints *h = XGetWMHints(xw.dpy, xw.win);
3491
3492 h->flags = add ? (h->flags | XUrgencyHint) : (h->flags & ~XUrgencyHint);
3493 XSetWMHints(xw.dpy, xw.win, h);
3494 XFree(h);
3495 }
3496
3497 void
3498 focus(XEvent *ev) {
3499 XFocusChangeEvent *e = &ev->xfocus;
3500
3501 if(e->mode == NotifyGrab)
3502 return;
3503
3504 if(ev->type == FocusIn) {
3505 XSetICFocus(xw.xic);
3506 xw.state |= WIN_FOCUSED;
3507 xseturgency(0);
3508 if(IS_SET(MODE_FOCUS))
3509 ttywrite("\033[I", 3);
3510 } else {
3511 XUnsetICFocus(xw.xic);
3512 xw.state &= ~WIN_FOCUSED;
3513 if(IS_SET(MODE_FOCUS))
3514 ttywrite("\033[O", 3);
3515 }
3516 }
3517
3518 static inline bool
3519 match(uint mask, uint state) {
3520 return mask == XK_ANY_MOD || mask == (state & ~ignoremod);
3521 }
3522
3523 void
3524 numlock(const Arg *dummy) {
3525 term.numlock ^= 1;
3526 }
3527
3528 char*
3529 kmap(KeySym k, uint state) {
3530 Key *kp;
3531 int i;
3532
3533 /* Check for mapped keys out of X11 function keys. */
3534 for(i = 0; i < LEN(mappedkeys); i++) {
3535 if(mappedkeys[i] == k)
3536 break;
3537 }
3538 if(i == LEN(mappedkeys)) {
3539 if((k & 0xFFFF) < 0xFD00)
3540 return NULL;
3541 }
3542
3543 for(kp = key; kp < key + LEN(key); kp++) {
3544 if(kp->k != k)
3545 continue;
3546
3547 if(!match(kp->mask, state))
3548 continue;
3549
3550 if(IS_SET(MODE_APPKEYPAD) ? kp->appkey < 0 : kp->appkey > 0)
3551 continue;
3552 if(term.numlock && kp->appkey == 2)
3553 continue;
3554
3555 if(IS_SET(MODE_APPCURSOR) ? kp->appcursor < 0 : kp->appcursor > 0)
3556 continue;
3557
3558 if(IS_SET(MODE_CRLF) ? kp->crlf < 0 : kp->crlf > 0)
3559 continue;
3560
3561 return kp->s;
3562 }
3563
3564 return NULL;
3565 }
3566
3567 void
3568 kpress(XEvent *ev) {
3569 XKeyEvent *e = &ev->xkey;
3570 KeySym ksym;
3571 char buf[32], *customkey;
3572 int len;
3573 long c;
3574 Status status;
3575 Shortcut *bp;
3576
3577 if(IS_SET(MODE_KBDLOCK))
3578 return;
3579
3580 len = XmbLookupString(xw.xic, e, buf, sizeof buf, &ksym, &status);
3581 /* 1. shortcuts */
3582 for(bp = shortcuts; bp < shortcuts + LEN(shortcuts); bp++) {
3583 if(ksym == bp->keysym && match(bp->mod, e->state)) {
3584 bp->func(&(bp->arg));
3585 return;
3586 }
3587 }
3588
3589 /* 2. custom keys from config.h */
3590 if((customkey = kmap(ksym, e->state))) {
3591 ttysend(customkey, strlen(customkey));
3592 return;
3593 }
3594
3595 /* 3. composed string from input method */
3596 if(len == 0)
3597 return;
3598 if(len == 1 && e->state & Mod1Mask) {
3599 if(IS_SET(MODE_8BIT)) {
3600 if(*buf < 0177) {
3601 c = *buf | 0x80;
3602 len = utf8encode(&c, buf);
3603 }
3604 } else {
3605 buf[1] = buf[0];
3606 buf[0] = '\033';
3607 len = 2;
3608 }
3609 }
3610 ttysend(buf, len);
3611 }
3612
3613
3614 void
3615 cmessage(XEvent *e) {
3616 /*
3617 * See xembed specs
3618 * http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html
3619 */
3620 if(e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
3621 if(e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
3622 xw.state |= WIN_FOCUSED;
3623 xseturgency(0);
3624 } else if(e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
3625 xw.state &= ~WIN_FOCUSED;
3626 }
3627 } else if(e->xclient.data.l[0] == xw.wmdeletewin) {
3628 /* Send SIGHUP to shell */
3629 kill(pid, SIGHUP);
3630 exit(EXIT_SUCCESS);
3631 }
3632 }
3633
3634 void
3635 cresize(int width, int height) {
3636 int col, row;
3637
3638 if(width != 0)
3639 xw.w = width;
3640 if(height != 0)
3641 xw.h = height;
3642
3643 col = (xw.w - 2 * borderpx) / xw.cw;
3644 row = (xw.h - 2 * borderpx) / xw.ch;
3645
3646 tresize(col, row);
3647 xresize(col, row);
3648 ttyresize();
3649 }
3650
3651 void
3652 resize(XEvent *e) {
3653 if(e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
3654 return;
3655
3656 cresize(e->xconfigure.width, e->xconfigure.height);
3657 }
3658
3659 void
3660 run(void) {
3661 XEvent ev;
3662 int w = xw.w, h = xw.h;
3663 fd_set rfd;
3664 int xfd = XConnectionNumber(xw.dpy), xev, blinkset = 0, dodraw = 0;
3665 struct timeval drawtimeout, *tv = NULL, now, last, lastblink;
3666
3667 /* Waiting for window mapping */
3668 while(1) {
3669 XNextEvent(xw.dpy, &ev);
3670 if(ev.type == ConfigureNotify) {
3671 w = ev.xconfigure.width;
3672 h = ev.xconfigure.height;
3673 } else if(ev.type == MapNotify) {
3674 break;
3675 }
3676 }
3677
3678 ttynew();
3679 if(!xw.isfixed)
3680 cresize(w, h);
3681 else
3682 cresize(xw.fw, xw.fh);
3683
3684 gettimeofday(&lastblink, NULL);
3685 gettimeofday(&last, NULL);
3686
3687 for(xev = actionfps;;) {
3688 long deltatime;
3689
3690 FD_ZERO(&rfd);
3691 FD_SET(cmdfd, &rfd);
3692 FD_SET(xfd, &rfd);
3693
3694 if(select(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, tv) < 0) {
3695 if(errno == EINTR)
3696 continue;
3697 die("select failed: %s\n", SERRNO);
3698 }
3699 if(FD_ISSET(cmdfd, &rfd)) {
3700 ttyread();
3701 if(blinktimeout) {
3702 blinkset = tattrset(ATTR_BLINK);
3703 if(!blinkset)
3704 MODBIT(term.mode, 0, MODE_BLINK);
3705 }
3706 }
3707
3708 if(FD_ISSET(xfd, &rfd))
3709 xev = actionfps;
3710
3711 gettimeofday(&now, NULL);
3712 drawtimeout.tv_sec = 0;
3713 drawtimeout.tv_usec = (1000/xfps) * 1000;
3714 tv = &drawtimeout;
3715
3716 dodraw = 0;
3717 if(blinktimeout && TIMEDIFF(now, lastblink) > blinktimeout) {
3718 tsetdirtattr(ATTR_BLINK);
3719 term.mode ^= MODE_BLINK;
3720 gettimeofday(&lastblink, NULL);
3721 dodraw = 1;
3722 }
3723 deltatime = TIMEDIFF(now, last);
3724 if(deltatime > (xev? (1000/xfps) : (1000/actionfps))
3725 || deltatime < 0) {
3726 dodraw = 1;
3727 last = now;
3728 }
3729
3730 if(dodraw) {
3731 while(XPending(xw.dpy)) {
3732 XNextEvent(xw.dpy, &ev);
3733 if(XFilterEvent(&ev, None))
3734 continue;
3735 if(handler[ev.type])
3736 (handler[ev.type])(&ev);
3737 }
3738
3739 draw();
3740 XFlush(xw.dpy);
3741
3742 if(xev && !FD_ISSET(xfd, &rfd))
3743 xev--;
3744 if(!FD_ISSET(cmdfd, &rfd) && !FD_ISSET(xfd, &rfd)) {
3745 if(blinkset) {
3746 if(TIMEDIFF(now, lastblink) \
3747 > blinktimeout) {
3748 drawtimeout.tv_usec = 1;
3749 } else {
3750 drawtimeout.tv_usec = (1000 * \
3751 (blinktimeout - \
3752 TIMEDIFF(now,
3753 lastblink)));
3754 }
3755 } else {
3756 tv = NULL;
3757 }
3758 }
3759 }
3760 }
3761 }
3762
3763 void
3764 usage(void) {
3765 die("%s " VERSION " (c) 2010-2013 st engineers\n" \
3766 "usage: st [-a] [-v] [-c class] [-f font] [-g geometry] [-o file]" \
3767 " [-t title] [-w windowid] [-e command ...]\n", argv0);
3768 }
3769
3770 int
3771 main(int argc, char *argv[]) {
3772 int bitm, xr, yr;
3773 uint wr, hr;
3774 char *titles;
3775
3776 xw.fw = xw.fh = xw.fx = xw.fy = 0;
3777 xw.isfixed = False;
3778
3779 ARGBEGIN {
3780 case 'a':
3781 allowaltscreen = false;
3782 break;
3783 case 'c':
3784 opt_class = EARGF(usage());
3785 break;
3786 case 'e':
3787 /* eat all remaining arguments */
3788 if(argc > 1) {
3789 opt_cmd = &argv[1];
3790 if(argv[1] != NULL && opt_title == NULL) {
3791 titles = strdup(argv[1]);
3792 opt_title = basename(titles);
3793 }
3794 }
3795 goto run;
3796 case 'f':
3797 opt_font = EARGF(usage());
3798 break;
3799 case 'g':
3800 bitm = XParseGeometry(EARGF(usage()), &xr, &yr, &wr, &hr);
3801 if(bitm & XValue)
3802 xw.fx = xr;
3803 if(bitm & YValue)
3804 xw.fy = yr;
3805 if(bitm & WidthValue)
3806 xw.fw = (int)wr;
3807 if(bitm & HeightValue)
3808 xw.fh = (int)hr;
3809 if(bitm & XNegative && xw.fx == 0)
3810 xw.fx = -1;
3811 if(bitm & YNegative && xw.fy == 0)
3812 xw.fy = -1;
3813
3814 if(xw.fh != 0 && xw.fw != 0)
3815 xw.isfixed = True;
3816 break;
3817 case 'o':
3818 opt_io = EARGF(usage());
3819 break;
3820 case 't':
3821 opt_title = EARGF(usage());
3822 break;
3823 case 'w':
3824 opt_embed = EARGF(usage());
3825 break;
3826 case 'v':
3827 default:
3828 usage();
3829 } ARGEND;
3830
3831 run:
3832 setlocale(LC_CTYPE, "");
3833 XSetLocaleModifiers("");
3834 tnew(80, 24);
3835 xinit();
3836 selinit();
3837 run();
3838
3839 return 0;
3840 }
3841