Xinqi Bao's Git

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