Xinqi Bao's Git

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