Xinqi Bao's Git

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