Xinqi Bao's Git

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