Xinqi Bao's Git

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