Xinqi Bao's Git

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