Xinqi Bao's Git

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