Xinqi Bao's Git

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