Xinqi Bao's Git

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