Xinqi Bao's Git

c2ee3e28b73a28864ff3f485776bf5538bfe29dd
[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 <stdarg.h>
9 #include <stdbool.h>
10 #include <stdio.h>
11 #include <stdlib.h>
12 #include <string.h>
13 #include <signal.h>
14 #include <sys/ioctl.h>
15 #include <sys/select.h>
16 #include <sys/stat.h>
17 #include <sys/time.h>
18 #include <sys/types.h>
19 #include <sys/wait.h>
20 #include <time.h>
21 #include <unistd.h>
22 #include <X11/Xatom.h>
23 #include <X11/Xlib.h>
24 #include <X11/Xutil.h>
25 #include <X11/cursorfont.h>
26 #include <X11/keysym.h>
27 #include <X11/extensions/Xdbe.h>
28
29 #if defined(__linux)
30 #include <pty.h>
31 #elif defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
32 #include <util.h>
33 #elif defined(__FreeBSD__) || defined(__DragonFly__)
34 #include <libutil.h>
35 #endif
36
37 #define USAGE \
38 "st " VERSION " (c) 2010-2012 st engineers\n" \
39 "usage: st [-t title] [-c class] [-g geometry]" \
40 " [-w windowid] [-v] [-f file] [-e command...]\n"
41
42 /* XEMBED messages */
43 #define XEMBED_FOCUS_IN 4
44 #define XEMBED_FOCUS_OUT 5
45
46 /* Arbitrary sizes */
47 #define ESC_BUF_SIZ 256
48 #define ESC_ARG_SIZ 16
49 #define STR_BUF_SIZ 256
50 #define STR_ARG_SIZ 16
51 #define DRAW_BUF_SIZ 1024
52 #define UTF_SIZ 4
53 #define XK_NO_MOD UINT_MAX
54 #define XK_ANY_MOD 0
55
56 #define SELECT_TIMEOUT (20*1000) /* 20 ms */
57 #define DRAW_TIMEOUT (20*1000) /* 20 ms */
58 #define REDRAW_TIMEOUT (80*1000) /* 80 ms */
59
60 #define SERRNO strerror(errno)
61 #define MIN(a, b) ((a) < (b) ? (a) : (b))
62 #define MAX(a, b) ((a) < (b) ? (b) : (a))
63 #define LEN(a) (sizeof(a) / sizeof(a[0]))
64 #define DEFAULT(a, b) (a) = (a) ? (a) : (b)
65 #define BETWEEN(x, a, b) ((a) <= (x) && (x) <= (b))
66 #define LIMIT(x, a, b) (x) = (x) < (a) ? (a) : (x) > (b) ? (b) : (x)
67 #define ATTRCMP(a, b) ((a).mode != (b).mode || (a).fg != (b).fg || (a).bg != (b).bg)
68 #define IS_SET(flag) (term.mode & (flag))
69 #define TIMEDIFF(t1, t2) ((t1.tv_sec-t2.tv_sec)*1000 + (t1.tv_usec-t2.tv_usec)/1000)
70 #define X2COL(x) (((x) - BORDER)/xw.cw)
71 #define Y2ROW(y) (((y) - BORDER)/xw.ch)
72
73 enum glyph_attribute {
74 ATTR_NULL = 0,
75 ATTR_REVERSE = 1,
76 ATTR_UNDERLINE = 2,
77 ATTR_BOLD = 4,
78 ATTR_GFX = 8,
79 ATTR_ITALIC = 16,
80 ATTR_BLINK = 32,
81 };
82
83 enum cursor_movement {
84 CURSOR_UP,
85 CURSOR_DOWN,
86 CURSOR_LEFT,
87 CURSOR_RIGHT,
88 CURSOR_SAVE,
89 CURSOR_LOAD
90 };
91
92 enum cursor_state {
93 CURSOR_DEFAULT = 0,
94 CURSOR_HIDE = 1,
95 CURSOR_WRAPNEXT = 2
96 };
97
98 enum glyph_state {
99 GLYPH_SET = 1,
100 GLYPH_DIRTY = 2
101 };
102
103 enum term_mode {
104 MODE_WRAP = 1,
105 MODE_INSERT = 2,
106 MODE_APPKEYPAD = 4,
107 MODE_ALTSCREEN = 8,
108 MODE_CRLF = 16,
109 MODE_MOUSEBTN = 32,
110 MODE_MOUSEMOTION = 64,
111 MODE_MOUSE = 32|64,
112 MODE_REVERSE = 128
113 };
114
115 enum escape_state {
116 ESC_START = 1,
117 ESC_CSI = 2,
118 ESC_STR = 4, /* DSC, OSC, PM, APC */
119 ESC_ALTCHARSET = 8,
120 ESC_STR_END = 16, /* a final string was encountered */
121 };
122
123 enum window_state {
124 WIN_VISIBLE = 1,
125 WIN_REDRAW = 2,
126 WIN_FOCUSED = 4
127 };
128
129 /* bit macro */
130 #undef B0
131 enum { B0=1, B1=2, B2=4, B3=8, B4=16, B5=32, B6=64, B7=128 };
132
133 typedef unsigned char uchar;
134 typedef unsigned int uint;
135 typedef unsigned long ulong;
136 typedef unsigned short ushort;
137
138 typedef struct {
139 char c[UTF_SIZ]; /* character code */
140 uchar mode; /* attribute flags */
141 ushort fg; /* foreground */
142 ushort bg; /* background */
143 uchar state; /* state flags */
144 } Glyph;
145
146 typedef Glyph* Line;
147
148 typedef struct {
149 Glyph attr; /* current char attributes */
150 int x;
151 int y;
152 char state;
153 } TCursor;
154
155 /* CSI Escape sequence structs */
156 /* ESC '[' [[ [<priv>] <arg> [;]] <mode>] */
157 typedef struct {
158 char buf[ESC_BUF_SIZ]; /* raw string */
159 int len; /* raw string length */
160 char priv;
161 int arg[ESC_ARG_SIZ];
162 int narg; /* nb of args */
163 char mode;
164 } CSIEscape;
165
166 /* STR Escape sequence structs */
167 /* ESC type [[ [<priv>] <arg> [;]] <mode>] ESC '\' */
168 typedef struct {
169 char type; /* ESC type ... */
170 char buf[STR_BUF_SIZ]; /* raw string */
171 int len; /* raw string length */
172 char *args[STR_ARG_SIZ];
173 int narg; /* nb of args */
174 } STREscape;
175
176 /* Internal representation of the screen */
177 typedef struct {
178 int row; /* nb row */
179 int col; /* nb col */
180 Line* line; /* screen */
181 Line* alt; /* alternate screen */
182 bool* dirty; /* dirtyness of lines */
183 TCursor c; /* cursor */
184 int top; /* top scroll limit */
185 int bot; /* bottom scroll limit */
186 int mode; /* terminal mode flags */
187 int esc; /* escape state flags */
188 bool *tabs;
189 } Term;
190
191 /* Purely graphic info */
192 typedef struct {
193 Display* dpy;
194 Colormap cmap;
195 Window win;
196 XdbeBackBuffer buf;
197 Atom xembed;
198 XIM xim;
199 XIC xic;
200 int scr;
201 Bool isfixed; /* is fixed geometry? */
202 int fx, fy, fw, fh; /* fixed geometry */
203 int w; /* window width */
204 int h; /* window height */
205 int ch; /* char height */
206 int cw; /* char width */
207 char state; /* focus, redraw, visible */
208 struct timeval lastdraw;
209 } XWindow;
210
211 typedef struct {
212 KeySym k;
213 uint mask;
214 char s[ESC_BUF_SIZ];
215 } Key;
216
217
218 /* TODO: use better name for vars... */
219 typedef struct {
220 int mode;
221 int bx, by;
222 int ex, ey;
223 struct {int x, y;} b, e;
224 char *clip;
225 Atom xtarget;
226 bool alt;
227 struct timeval tclick1;
228 struct timeval tclick2;
229 } Selection;
230
231 #include "config.h"
232
233 /* Drawing Context */
234 typedef struct {
235 ulong col[LEN(colorname) < 256 ? 256 : LEN(colorname)];
236 GC gc;
237 struct {
238 int ascent;
239 int descent;
240 short lbearing;
241 short rbearing;
242 XFontSet set;
243 } font, bfont, ifont;
244 } DC;
245
246 static void die(const char*, ...);
247 static void draw(void);
248 static void redraw(void);
249 static void drawregion(int, int, int, int);
250 static void execsh(void);
251 static void sigchld(int);
252 static void run(void);
253 static bool last_draw_too_old(void);
254
255 static void csidump(void);
256 static void csihandle(void);
257 static void csiparse(void);
258 static void csireset(void);
259 static void strdump(void);
260 static void strhandle(void);
261 static void strparse(void);
262 static void strreset(void);
263
264 static void tclearregion(int, int, int, int);
265 static void tcursor(int);
266 static void tdeletechar(int);
267 static void tdeleteline(int);
268 static void tinsertblank(int);
269 static void tinsertblankline(int);
270 static void tmoveto(int, int);
271 static void tnew(int, int);
272 static void tnewline(int);
273 static void tputtab(bool);
274 static void tputc(char*);
275 static void treset(void);
276 static int tresize(int, int);
277 static void tscrollup(int, int);
278 static void tscrolldown(int, int);
279 static void tsetattr(int*, int);
280 static void tsetchar(char*);
281 static void tsetscroll(int, int);
282 static void tswapscreen(void);
283 static void tsetdirt(int, int);
284 static void tsetmode(bool, bool, int *, int);
285 static void tfulldirt(void);
286
287 static void ttynew(void);
288 static void ttyread(void);
289 static void ttyresize(int, int);
290 static void ttywrite(const char *, size_t);
291
292 static void xdraws(char *, Glyph, int, int, int, int);
293 static void xhints(void);
294 static void xclear(int, int, int, int);
295 static void xcopy(void);
296 static void xdrawcursor(void);
297 static void xinit(void);
298 static void xloadcols(void);
299 static void xresettitle(void);
300 static void xseturgency(int);
301 static void xsetsel(char*);
302 static void xresize(int, int);
303
304 static void expose(XEvent *);
305 static void visibility(XEvent *);
306 static void unmap(XEvent *);
307 static char* kmap(KeySym, uint);
308 static void kpress(XEvent *);
309 static void cmessage(XEvent *);
310 static void resize(XEvent *);
311 static void focus(XEvent *);
312 static void brelease(XEvent *);
313 static void bpress(XEvent *);
314 static void bmotion(XEvent *);
315 static void selnotify(XEvent *);
316 static void selclear(XEvent *);
317 static void selrequest(XEvent *);
318
319 static void selinit(void);
320 static inline bool selected(int, int);
321 static void selcopy(void);
322 static void selpaste(void);
323 static void selscroll(int, int);
324
325 static int utf8decode(char *, long *);
326 static int utf8encode(long *, char *);
327 static int utf8size(char *);
328 static int isfullutf8(char *, int);
329
330 static void *xmalloc(size_t);
331 static void *xrealloc(void *, size_t);
332
333 static void (*handler[LASTEvent])(XEvent *) = {
334 [KeyPress] = kpress,
335 [ClientMessage] = cmessage,
336 [ConfigureNotify] = resize,
337 [VisibilityNotify] = visibility,
338 [UnmapNotify] = unmap,
339 [Expose] = expose,
340 [FocusIn] = focus,
341 [FocusOut] = focus,
342 [MotionNotify] = bmotion,
343 [ButtonPress] = bpress,
344 [ButtonRelease] = brelease,
345 [SelectionClear] = selclear,
346 [SelectionNotify] = selnotify,
347 [SelectionRequest] = selrequest,
348 };
349
350 /* Globals */
351 static DC dc;
352 static XWindow xw;
353 static Term term;
354 static CSIEscape csiescseq;
355 static STREscape strescseq;
356 static int cmdfd;
357 static pid_t pid;
358 static Selection sel;
359 static int iofd = -1;
360 static char **opt_cmd = NULL;
361 static char *opt_io = NULL;
362 static char *opt_title = NULL;
363 static char *opt_embed = NULL;
364 static char *opt_class = NULL;
365
366 void *
367 xmalloc(size_t len) {
368 void *p = malloc(len);
369 if(!p)
370 die("Out of memory");
371 return p;
372 }
373
374 void *
375 xrealloc(void *p, size_t len) {
376 if((p = realloc(p, len)) == NULL)
377 die("Out of memory");
378 return p;
379 }
380
381 int
382 utf8decode(char *s, long *u) {
383 uchar c;
384 int i, n, rtn;
385
386 rtn = 1;
387 c = *s;
388 if(~c & B7) { /* 0xxxxxxx */
389 *u = c;
390 return rtn;
391 } else if((c & (B7|B6|B5)) == (B7|B6)) { /* 110xxxxx */
392 *u = c&(B4|B3|B2|B1|B0);
393 n = 1;
394 } else if((c & (B7|B6|B5|B4)) == (B7|B6|B5)) { /* 1110xxxx */
395 *u = c&(B3|B2|B1|B0);
396 n = 2;
397 } else if((c & (B7|B6|B5|B4|B3)) == (B7|B6|B5|B4)) { /* 11110xxx */
398 *u = c & (B2|B1|B0);
399 n = 3;
400 } else
401 goto invalid;
402 for(i = n, ++s; i > 0; --i, ++rtn, ++s) {
403 c = *s;
404 if((c & (B7|B6)) != B7) /* 10xxxxxx */
405 goto invalid;
406 *u <<= 6;
407 *u |= c & (B5|B4|B3|B2|B1|B0);
408 }
409 if((n == 1 && *u < 0x80) ||
410 (n == 2 && *u < 0x800) ||
411 (n == 3 && *u < 0x10000) ||
412 (*u >= 0xD800 && *u <= 0xDFFF))
413 goto invalid;
414 return rtn;
415 invalid:
416 *u = 0xFFFD;
417 return rtn;
418 }
419
420 int
421 utf8encode(long *u, char *s) {
422 uchar *sp;
423 ulong uc;
424 int i, n;
425
426 sp = (uchar*) s;
427 uc = *u;
428 if(uc < 0x80) {
429 *sp = uc; /* 0xxxxxxx */
430 return 1;
431 } else if(*u < 0x800) {
432 *sp = (uc >> 6) | (B7|B6); /* 110xxxxx */
433 n = 1;
434 } else if(uc < 0x10000) {
435 *sp = (uc >> 12) | (B7|B6|B5); /* 1110xxxx */
436 n = 2;
437 } else if(uc <= 0x10FFFF) {
438 *sp = (uc >> 18) | (B7|B6|B5|B4); /* 11110xxx */
439 n = 3;
440 } else {
441 goto invalid;
442 }
443 for(i=n,++sp; i>0; --i,++sp)
444 *sp = ((uc >> 6*(i-1)) & (B5|B4|B3|B2|B1|B0)) | B7; /* 10xxxxxx */
445 return n+1;
446 invalid:
447 /* U+FFFD */
448 *s++ = '\xEF';
449 *s++ = '\xBF';
450 *s = '\xBD';
451 return 3;
452 }
453
454 /* use this if your buffer is less than UTF_SIZ, it returns 1 if you can decode
455 UTF-8 otherwise return 0 */
456 int
457 isfullutf8(char *s, int b) {
458 uchar *c1, *c2, *c3;
459
460 c1 = (uchar *) s;
461 c2 = (uchar *) ++s;
462 c3 = (uchar *) ++s;
463 if(b < 1)
464 return 0;
465 else if((*c1&(B7|B6|B5)) == (B7|B6) && b == 1)
466 return 0;
467 else if((*c1&(B7|B6|B5|B4)) == (B7|B6|B5) &&
468 ((b == 1) ||
469 ((b == 2) && (*c2&(B7|B6)) == B7)))
470 return 0;
471 else if((*c1&(B7|B6|B5|B4|B3)) == (B7|B6|B5|B4) &&
472 ((b == 1) ||
473 ((b == 2) && (*c2&(B7|B6)) == B7) ||
474 ((b == 3) && (*c2&(B7|B6)) == B7 && (*c3&(B7|B6)) == B7)))
475 return 0;
476 else
477 return 1;
478 }
479
480 int
481 utf8size(char *s) {
482 uchar c = *s;
483
484 if(~c&B7)
485 return 1;
486 else if((c&(B7|B6|B5)) == (B7|B6))
487 return 2;
488 else if((c&(B7|B6|B5|B4)) == (B7|B6|B5))
489 return 3;
490 else
491 return 4;
492 }
493
494 void
495 selinit(void) {
496 memset(&sel.tclick1, 0, sizeof(sel.tclick1));
497 memset(&sel.tclick2, 0, sizeof(sel.tclick2));
498 sel.mode = 0;
499 sel.bx = -1;
500 sel.clip = NULL;
501 sel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
502 if(sel.xtarget == None)
503 sel.xtarget = XA_STRING;
504 }
505
506 static inline bool
507 selected(int x, int y) {
508 if(sel.ey == y && sel.by == y) {
509 int bx = MIN(sel.bx, sel.ex);
510 int ex = MAX(sel.bx, sel.ex);
511 return BETWEEN(x, bx, ex);
512 }
513 return ((sel.b.y < y&&y < sel.e.y) || (y==sel.e.y && x<=sel.e.x))
514 || (y==sel.b.y && x>=sel.b.x && (x<=sel.e.x || sel.b.y!=sel.e.y));
515 }
516
517 void
518 getbuttoninfo(XEvent *e, int *b, int *x, int *y) {
519 if(b)
520 *b = e->xbutton.button;
521
522 *x = X2COL(e->xbutton.x);
523 *y = Y2ROW(e->xbutton.y);
524 sel.b.x = sel.by < sel.ey ? sel.bx : sel.ex;
525 sel.b.y = MIN(sel.by, sel.ey);
526 sel.e.x = sel.by < sel.ey ? sel.ex : sel.bx;
527 sel.e.y = MAX(sel.by, sel.ey);
528 }
529
530 void
531 mousereport(XEvent *e) {
532 int x = X2COL(e->xbutton.x);
533 int y = Y2ROW(e->xbutton.y);
534 int button = e->xbutton.button;
535 int state = e->xbutton.state;
536 char buf[] = { '\033', '[', 'M', 0, 32+x+1, 32+y+1 };
537 static int ob, ox, oy;
538
539 /* from urxvt */
540 if(e->xbutton.type == MotionNotify) {
541 if(!IS_SET(MODE_MOUSEMOTION) || (x == ox && y == oy))
542 return;
543 button = ob + 32;
544 ox = x, oy = y;
545 } else if(e->xbutton.type == ButtonRelease || button == AnyButton) {
546 button = 3;
547 } else {
548 button -= Button1;
549 if(button >= 3)
550 button += 64 - 3;
551 if(e->xbutton.type == ButtonPress) {
552 ob = button;
553 ox = x, oy = y;
554 }
555 }
556
557 buf[3] = 32 + button + (state & ShiftMask ? 4 : 0)
558 + (state & Mod4Mask ? 8 : 0)
559 + (state & ControlMask ? 16 : 0);
560
561 ttywrite(buf, sizeof(buf));
562 }
563
564 void
565 bpress(XEvent *e) {
566 if(IS_SET(MODE_MOUSE))
567 mousereport(e);
568 else if(e->xbutton.button == Button1) {
569 if(sel.bx != -1)
570 tsetdirt(sel.b.y, sel.e.y);
571 sel.mode = 1;
572 sel.ex = sel.bx = X2COL(e->xbutton.x);
573 sel.ey = sel.by = Y2ROW(e->xbutton.y);
574 }
575 }
576
577 void
578 selcopy(void) {
579 char *str, *ptr;
580 int x, y, bufsize, is_selected = 0;
581
582 if(sel.bx == -1)
583 str = NULL;
584
585 else {
586 bufsize = (term.col+1) * (sel.e.y-sel.b.y+1) * UTF_SIZ;
587 ptr = str = xmalloc(bufsize);
588
589 /* append every set & selected glyph to the selection */
590 for(y = 0; y < term.row; y++) {
591 for(x = 0; x < term.col; x++) {
592 is_selected = selected(x, y);
593 if((term.line[y][x].state & GLYPH_SET) && is_selected) {
594 int size = utf8size(term.line[y][x].c);
595 memcpy(ptr, term.line[y][x].c, size);
596 ptr += size;
597 }
598 }
599
600 /* \n at the end of every selected line except for the last one */
601 if(is_selected && y < sel.e.y)
602 *ptr++ = '\n';
603 }
604 *ptr = 0;
605 }
606 sel.alt = IS_SET(MODE_ALTSCREEN);
607 xsetsel(str);
608 }
609
610 void
611 selnotify(XEvent *e) {
612 ulong nitems, ofs, rem;
613 int format;
614 uchar *data;
615 Atom type;
616
617 ofs = 0;
618 do {
619 if(XGetWindowProperty(xw.dpy, xw.win, XA_PRIMARY, ofs, BUFSIZ/4,
620 False, AnyPropertyType, &type, &format,
621 &nitems, &rem, &data)) {
622 fprintf(stderr, "Clipboard allocation failed\n");
623 return;
624 }
625 ttywrite((const char *) data, nitems * format / 8);
626 XFree(data);
627 /* number of 32-bit chunks returned */
628 ofs += nitems * format / 32;
629 } while(rem > 0);
630 }
631
632 void
633 selpaste() {
634 XConvertSelection(xw.dpy, XA_PRIMARY, sel.xtarget, XA_PRIMARY, xw.win, CurrentTime);
635 }
636
637 void selclear(XEvent *e) {
638 if(sel.bx == -1)
639 return;
640 sel.bx = -1;
641 tsetdirt(sel.b.y, sel.e.y);
642 draw();
643 }
644
645 void
646 selrequest(XEvent *e) {
647 XSelectionRequestEvent *xsre;
648 XSelectionEvent xev;
649 Atom xa_targets;
650
651 xsre = (XSelectionRequestEvent *) e;
652 xev.type = SelectionNotify;
653 xev.requestor = xsre->requestor;
654 xev.selection = xsre->selection;
655 xev.target = xsre->target;
656 xev.time = xsre->time;
657 /* reject */
658 xev.property = None;
659
660 xa_targets = XInternAtom(xw.dpy, "TARGETS", 0);
661 if(xsre->target == xa_targets) {
662 /* respond with the supported type */
663 Atom string = sel.xtarget;
664 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
665 XA_ATOM, 32, PropModeReplace,
666 (uchar *) &string, 1);
667 xev.property = xsre->property;
668 } else if(xsre->target == sel.xtarget && sel.clip != NULL) {
669 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
670 xsre->target, 8, PropModeReplace,
671 (uchar *) sel.clip, strlen(sel.clip));
672 xev.property = xsre->property;
673 }
674
675 /* all done, send a notification to the listener */
676 if(!XSendEvent(xsre->display, xsre->requestor, True, 0, (XEvent *) &xev))
677 fprintf(stderr, "Error sending SelectionNotify event\n");
678 }
679
680 void
681 xsetsel(char *str) {
682 /* register the selection for both the clipboard and the primary */
683 Atom clipboard;
684
685 free(sel.clip);
686 sel.clip = str;
687
688 XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, CurrentTime);
689
690 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
691 XSetSelectionOwner(xw.dpy, clipboard, xw.win, CurrentTime);
692
693 XFlush(xw.dpy);
694 }
695
696 void
697 brelease(XEvent *e) {
698 if(IS_SET(MODE_MOUSE)) {
699 mousereport(e);
700 return;
701 }
702 if(e->xbutton.button == Button2)
703 selpaste();
704 else if(e->xbutton.button == Button1) {
705 sel.mode = 0;
706 getbuttoninfo(e, NULL, &sel.ex, &sel.ey);
707 term.dirty[sel.ey] = 1;
708 if(sel.bx == sel.ex && sel.by == sel.ey) {
709 struct timeval now;
710 sel.bx = -1;
711 gettimeofday(&now, NULL);
712
713 if(TIMEDIFF(now, sel.tclick2) <= TRIPLECLICK_TIMEOUT) {
714 /* triple click on the line */
715 sel.b.x = sel.bx = 0;
716 sel.e.x = sel.ex = term.col;
717 sel.b.y = sel.e.y = sel.ey;
718 selcopy();
719 } else if(TIMEDIFF(now, sel.tclick1) <= DOUBLECLICK_TIMEOUT) {
720 /* double click to select word */
721 sel.bx = sel.ex;
722 while(sel.bx > 0 && term.line[sel.ey][sel.bx-1].state & GLYPH_SET &&
723 term.line[sel.ey][sel.bx-1].c[0] != ' ') sel.bx--;
724 sel.b.x = sel.bx;
725 while(sel.ex < term.col-1 && term.line[sel.ey][sel.ex+1].state & GLYPH_SET &&
726 term.line[sel.ey][sel.ex+1].c[0] != ' ') sel.ex++;
727 sel.e.x = sel.ex;
728 sel.b.y = sel.e.y = sel.ey;
729 selcopy();
730 }
731 } else
732 selcopy();
733 }
734 memcpy(&sel.tclick2, &sel.tclick1, sizeof(struct timeval));
735 gettimeofday(&sel.tclick1, NULL);
736 draw();
737 }
738
739 void
740 bmotion(XEvent *e) {
741 if(IS_SET(MODE_MOUSE)) {
742 mousereport(e);
743 return;
744 }
745 if(sel.mode) {
746 int oldey = sel.ey, oldex = sel.ex;
747 getbuttoninfo(e, NULL, &sel.ex, &sel.ey);
748
749 if(oldey != sel.ey || oldex != sel.ex) {
750 int starty = MIN(oldey, sel.ey);
751 int endy = MAX(oldey, sel.ey);
752 tsetdirt(starty, endy);
753 draw();
754 }
755 }
756 }
757
758 void
759 die(const char *errstr, ...) {
760 va_list ap;
761
762 va_start(ap, errstr);
763 vfprintf(stderr, errstr, ap);
764 va_end(ap);
765 exit(EXIT_FAILURE);
766 }
767
768 void
769 execsh(void) {
770 char **args;
771 char *envshell = getenv("SHELL");
772
773 unsetenv("COLUMNS");
774 unsetenv("LINES");
775 unsetenv("TERMCAP");
776
777 signal(SIGCHLD, SIG_DFL);
778 signal(SIGHUP, SIG_DFL);
779 signal(SIGINT, SIG_DFL);
780 signal(SIGQUIT, SIG_DFL);
781 signal(SIGTERM, SIG_DFL);
782 signal(SIGALRM, SIG_DFL);
783
784 DEFAULT(envshell, SHELL);
785 putenv("TERM="TNAME);
786 args = opt_cmd ? opt_cmd : (char*[]){envshell, "-i", NULL};
787 execvp(args[0], args);
788 exit(EXIT_FAILURE);
789 }
790
791 void
792 sigchld(int a) {
793 int stat = 0;
794 if(waitpid(pid, &stat, 0) < 0)
795 die("Waiting for pid %hd failed: %s\n", pid, SERRNO);
796 if(WIFEXITED(stat))
797 exit(WEXITSTATUS(stat));
798 else
799 exit(EXIT_FAILURE);
800 }
801
802 void
803 ttynew(void) {
804 int m, s;
805
806 /* seems to work fine on linux, openbsd and freebsd */
807 struct winsize w = {term.row, term.col, 0, 0};
808 if(openpty(&m, &s, NULL, NULL, &w) < 0)
809 die("openpty failed: %s\n", SERRNO);
810
811 switch(pid = fork()) {
812 case -1:
813 die("fork failed\n");
814 break;
815 case 0:
816 setsid(); /* create a new process group */
817 dup2(s, STDIN_FILENO);
818 dup2(s, STDOUT_FILENO);
819 dup2(s, STDERR_FILENO);
820 if(ioctl(s, TIOCSCTTY, NULL) < 0)
821 die("ioctl TIOCSCTTY failed: %s\n", SERRNO);
822 close(s);
823 close(m);
824 execsh();
825 break;
826 default:
827 close(s);
828 cmdfd = m;
829 signal(SIGCHLD, sigchld);
830 if(opt_io) {
831 if(!strcmp(opt_io, "-")) {
832 iofd = STDOUT_FILENO;
833 } else {
834 if((iofd = open(opt_io, O_WRONLY | O_CREAT, 0666)) < 0) {
835 fprintf(stderr, "Error opening %s:%s\n",
836 opt_io, strerror(errno));
837 }
838 }
839 }
840 }
841 }
842
843 void
844 dump(char c) {
845 static int col;
846 fprintf(stderr, " %02x '%c' ", c, isprint(c)?c:'.');
847 if(++col % 10 == 0)
848 fprintf(stderr, "\n");
849 }
850
851 void
852 ttyread(void) {
853 static char buf[BUFSIZ];
854 static int buflen = 0;
855 char *ptr;
856 char s[UTF_SIZ];
857 int charsize; /* size of utf8 char in bytes */
858 long utf8c;
859 int ret;
860
861 /* append read bytes to unprocessed bytes */
862 if((ret = read(cmdfd, buf+buflen, LEN(buf)-buflen)) < 0)
863 die("Couldn't read from shell: %s\n", SERRNO);
864
865 /* process every complete utf8 char */
866 buflen += ret;
867 ptr = buf;
868 while(buflen >= UTF_SIZ || isfullutf8(ptr,buflen)) {
869 charsize = utf8decode(ptr, &utf8c);
870 utf8encode(&utf8c, s);
871 tputc(s);
872 ptr += charsize;
873 buflen -= charsize;
874 }
875
876 /* keep any uncomplete utf8 char for the next call */
877 memmove(buf, ptr, buflen);
878 }
879
880 void
881 ttywrite(const char *s, size_t n) {
882 if(write(cmdfd, s, n) == -1)
883 die("write error on tty: %s\n", SERRNO);
884 }
885
886 void
887 ttyresize(int x, int y) {
888 struct winsize w;
889
890 w.ws_row = term.row;
891 w.ws_col = term.col;
892 w.ws_xpixel = xw.w;
893 w.ws_ypixel = xw.h;
894 if(ioctl(cmdfd, TIOCSWINSZ, &w) < 0)
895 fprintf(stderr, "Couldn't set window size: %s\n", SERRNO);
896 }
897
898 void
899 tsetdirt(int top, int bot)
900 {
901 int i;
902
903 LIMIT(top, 0, term.row-1);
904 LIMIT(bot, 0, term.row-1);
905
906 for(i = top; i <= bot; i++)
907 term.dirty[i] = 1;
908 }
909
910 void
911 tfulldirt(void)
912 {
913 tsetdirt(0, term.row-1);
914 }
915
916 void
917 tcursor(int mode) {
918 static TCursor c;
919
920 if(mode == CURSOR_SAVE)
921 c = term.c;
922 else if(mode == CURSOR_LOAD)
923 term.c = c, tmoveto(c.x, c.y);
924 }
925
926 void
927 treset(void) {
928 unsigned i;
929 term.c = (TCursor){{
930 .mode = ATTR_NULL,
931 .fg = DefaultFG,
932 .bg = DefaultBG
933 }, .x = 0, .y = 0, .state = CURSOR_DEFAULT};
934
935 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
936 for(i = TAB; i < term.col; i += TAB)
937 term.tabs[i] = 1;
938 term.top = 0, term.bot = term.row - 1;
939 term.mode = MODE_WRAP;
940 tclearregion(0, 0, term.col-1, term.row-1);
941 }
942
943 void
944 tnew(int col, int row) {
945 /* set screen size */
946 term.row = row, term.col = col;
947 term.line = xmalloc(term.row * sizeof(Line));
948 term.alt = xmalloc(term.row * sizeof(Line));
949 term.dirty = xmalloc(term.row * sizeof(*term.dirty));
950 term.tabs = xmalloc(term.col * sizeof(*term.tabs));
951
952 for(row = 0; row < term.row; row++) {
953 term.line[row] = xmalloc(term.col * sizeof(Glyph));
954 term.alt [row] = xmalloc(term.col * sizeof(Glyph));
955 term.dirty[row] = 0;
956 }
957 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
958 /* setup screen */
959 treset();
960 }
961
962 void
963 tswapscreen(void) {
964 Line* tmp = term.line;
965 term.line = term.alt;
966 term.alt = tmp;
967 term.mode ^= MODE_ALTSCREEN;
968 tfulldirt();
969 }
970
971 void
972 tscrolldown(int orig, int n) {
973 int i;
974 Line temp;
975
976 LIMIT(n, 0, term.bot-orig+1);
977
978 tclearregion(0, term.bot-n+1, term.col-1, term.bot);
979
980 for(i = term.bot; i >= orig+n; i--) {
981 temp = term.line[i];
982 term.line[i] = term.line[i-n];
983 term.line[i-n] = temp;
984
985 term.dirty[i] = 1;
986 term.dirty[i-n] = 1;
987 }
988
989 selscroll(orig, n);
990 }
991
992 void
993 tscrollup(int orig, int n) {
994 int i;
995 Line temp;
996 LIMIT(n, 0, term.bot-orig+1);
997
998 tclearregion(0, orig, term.col-1, orig+n-1);
999
1000 for(i = orig; i <= term.bot-n; i++) {
1001 temp = term.line[i];
1002 term.line[i] = term.line[i+n];
1003 term.line[i+n] = temp;
1004
1005 term.dirty[i] = 1;
1006 term.dirty[i+n] = 1;
1007 }
1008
1009 selscroll(orig, -n);
1010 }
1011
1012 void
1013 selscroll(int orig, int n) {
1014 if(sel.bx == -1)
1015 return;
1016
1017 if(BETWEEN(sel.by, orig, term.bot) || BETWEEN(sel.ey, orig, term.bot)) {
1018 if((sel.by += n) > term.bot || (sel.ey += n) < term.top) {
1019 sel.bx = -1;
1020 return;
1021 }
1022 if(sel.by < term.top) {
1023 sel.by = term.top;
1024 sel.bx = 0;
1025 }
1026 if(sel.ey > term.bot) {
1027 sel.ey = term.bot;
1028 sel.ex = term.col;
1029 }
1030 sel.b.y = sel.by, sel.b.x = sel.bx;
1031 sel.e.y = sel.ey, sel.e.x = sel.ex;
1032 }
1033 }
1034
1035 void
1036 tnewline(int first_col) {
1037 int y = term.c.y;
1038 if(y == term.bot)
1039 tscrollup(term.top, 1);
1040 else
1041 y++;
1042 tmoveto(first_col ? 0 : term.c.x, y);
1043 }
1044
1045 void
1046 csiparse(void) {
1047 /* int noarg = 1; */
1048 char *p = csiescseq.buf;
1049
1050 csiescseq.narg = 0;
1051 if(*p == '?')
1052 csiescseq.priv = 1, p++;
1053
1054 while(p < csiescseq.buf+csiescseq.len) {
1055 while(isdigit(*p)) {
1056 csiescseq.arg[csiescseq.narg] *= 10;
1057 csiescseq.arg[csiescseq.narg] += *p++ - '0'/*, noarg = 0 */;
1058 }
1059 if(*p == ';' && csiescseq.narg+1 < ESC_ARG_SIZ)
1060 csiescseq.narg++, p++;
1061 else {
1062 csiescseq.mode = *p;
1063 csiescseq.narg++;
1064 return;
1065 }
1066 }
1067 }
1068
1069 void
1070 tmoveto(int x, int y) {
1071 LIMIT(x, 0, term.col-1);
1072 LIMIT(y, 0, term.row-1);
1073 term.c.state &= ~CURSOR_WRAPNEXT;
1074 term.c.x = x;
1075 term.c.y = y;
1076 }
1077
1078 void
1079 tsetchar(char *c) {
1080 term.dirty[term.c.y] = 1;
1081 term.line[term.c.y][term.c.x] = term.c.attr;
1082 memcpy(term.line[term.c.y][term.c.x].c, c, UTF_SIZ);
1083 term.line[term.c.y][term.c.x].state |= GLYPH_SET;
1084 }
1085
1086 void
1087 tclearregion(int x1, int y1, int x2, int y2) {
1088 int x, y, temp;
1089
1090 if(x1 > x2)
1091 temp = x1, x1 = x2, x2 = temp;
1092 if(y1 > y2)
1093 temp = y1, y1 = y2, y2 = temp;
1094
1095 LIMIT(x1, 0, term.col-1);
1096 LIMIT(x2, 0, term.col-1);
1097 LIMIT(y1, 0, term.row-1);
1098 LIMIT(y2, 0, term.row-1);
1099
1100 for(y = y1; y <= y2; y++) {
1101 term.dirty[y] = 1;
1102 for(x = x1; x <= x2; x++)
1103 term.line[y][x].state = 0;
1104 }
1105 }
1106
1107 void
1108 tdeletechar(int n) {
1109 int src = term.c.x + n;
1110 int dst = term.c.x;
1111 int size = term.col - src;
1112
1113 term.dirty[term.c.y] = 1;
1114
1115 if(src >= term.col) {
1116 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1117 return;
1118 }
1119 memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src], size * sizeof(Glyph));
1120 tclearregion(term.col-n, term.c.y, term.col-1, term.c.y);
1121 }
1122
1123 void
1124 tinsertblank(int n) {
1125 int src = term.c.x;
1126 int dst = src + n;
1127 int size = term.col - dst;
1128
1129 term.dirty[term.c.y] = 1;
1130
1131 if(dst >= term.col) {
1132 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1133 return;
1134 }
1135 memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src], size * sizeof(Glyph));
1136 tclearregion(src, term.c.y, dst - 1, term.c.y);
1137 }
1138
1139 void
1140 tinsertblankline(int n) {
1141 if(term.c.y < term.top || term.c.y > term.bot)
1142 return;
1143
1144 tscrolldown(term.c.y, n);
1145 }
1146
1147 void
1148 tdeleteline(int n) {
1149 if(term.c.y < term.top || term.c.y > term.bot)
1150 return;
1151
1152 tscrollup(term.c.y, n);
1153 }
1154
1155 void
1156 tsetattr(int *attr, int l) {
1157 int i;
1158
1159 for(i = 0; i < l; i++) {
1160 switch(attr[i]) {
1161 case 0:
1162 term.c.attr.mode &= ~(ATTR_REVERSE | ATTR_UNDERLINE | ATTR_BOLD \
1163 | ATTR_ITALIC | ATTR_BLINK);
1164 term.c.attr.fg = DefaultFG;
1165 term.c.attr.bg = DefaultBG;
1166 break;
1167 case 1:
1168 term.c.attr.mode |= ATTR_BOLD;
1169 break;
1170 case 3: /* enter standout (highlight) */
1171 term.c.attr.mode |= ATTR_ITALIC;
1172 break;
1173 case 4:
1174 term.c.attr.mode |= ATTR_UNDERLINE;
1175 break;
1176 case 5:
1177 term.c.attr.mode |= ATTR_BLINK;
1178 break;
1179 case 7:
1180 term.c.attr.mode |= ATTR_REVERSE;
1181 break;
1182 case 21:
1183 case 22:
1184 term.c.attr.mode &= ~ATTR_BOLD;
1185 break;
1186 case 23: /* leave standout (highlight) mode */
1187 term.c.attr.mode &= ~ATTR_ITALIC;
1188 break;
1189 case 24:
1190 term.c.attr.mode &= ~ATTR_UNDERLINE;
1191 break;
1192 case 25:
1193 term.c.attr.mode &= ~ATTR_BLINK;
1194 break;
1195 case 27:
1196 term.c.attr.mode &= ~ATTR_REVERSE;
1197 break;
1198 case 38:
1199 if(i + 2 < l && attr[i + 1] == 5) {
1200 i += 2;
1201 if(BETWEEN(attr[i], 0, 255))
1202 term.c.attr.fg = attr[i];
1203 else
1204 fprintf(stderr, "erresc: bad fgcolor %d\n", attr[i]);
1205 }
1206 else
1207 fprintf(stderr, "erresc(38): gfx attr %d unknown\n", attr[i]);
1208 break;
1209 case 39:
1210 term.c.attr.fg = DefaultFG;
1211 break;
1212 case 48:
1213 if(i + 2 < l && attr[i + 1] == 5) {
1214 i += 2;
1215 if(BETWEEN(attr[i], 0, 255))
1216 term.c.attr.bg = attr[i];
1217 else
1218 fprintf(stderr, "erresc: bad bgcolor %d\n", attr[i]);
1219 }
1220 else
1221 fprintf(stderr, "erresc(48): gfx attr %d unknown\n", attr[i]);
1222 break;
1223 case 49:
1224 term.c.attr.bg = DefaultBG;
1225 break;
1226 default:
1227 if(BETWEEN(attr[i], 30, 37))
1228 term.c.attr.fg = attr[i] - 30;
1229 else if(BETWEEN(attr[i], 40, 47))
1230 term.c.attr.bg = attr[i] - 40;
1231 else if(BETWEEN(attr[i], 90, 97))
1232 term.c.attr.fg = attr[i] - 90 + 8;
1233 else if(BETWEEN(attr[i], 100, 107))
1234 term.c.attr.bg = attr[i] - 100 + 8;
1235 else
1236 fprintf(stderr, "erresc(default): gfx attr %d unknown\n", attr[i]), csidump();
1237 break;
1238 }
1239 }
1240 }
1241
1242 void
1243 tsetscroll(int t, int b) {
1244 int temp;
1245
1246 LIMIT(t, 0, term.row-1);
1247 LIMIT(b, 0, term.row-1);
1248 if(t > b) {
1249 temp = t;
1250 t = b;
1251 b = temp;
1252 }
1253 term.top = t;
1254 term.bot = b;
1255 }
1256
1257 #define MODBIT(x, set, bit) ((set) ? ((x) |= (bit)) : ((x) &= ~(bit)))
1258
1259 void
1260 tsetmode(bool priv, bool set, int *args, int narg) {
1261 int *lim, mode;
1262
1263 for(lim = args + narg; args < lim; ++args) {
1264 if(priv) {
1265 switch(*args) {
1266 case 1:
1267 MODBIT(term.mode, set, MODE_APPKEYPAD);
1268 break;
1269 case 5: /* DECSCNM -- Reverve video */
1270 mode = term.mode;
1271 MODBIT(term.mode,set, MODE_REVERSE);
1272 if(mode != term.mode)
1273 redraw();
1274 break;
1275 case 7:
1276 MODBIT(term.mode, set, MODE_WRAP);
1277 break;
1278 case 20:
1279 MODBIT(term.mode, set, MODE_CRLF);
1280 break;
1281 case 12: /* att610 -- Start blinking cursor (IGNORED) */
1282 break;
1283 case 25:
1284 MODBIT(term.c.state, !set, CURSOR_HIDE);
1285 break;
1286 case 1000: /* 1000,1002: enable xterm mouse report */
1287 MODBIT(term.mode, set, MODE_MOUSEBTN);
1288 break;
1289 case 1002:
1290 MODBIT(term.mode, set, MODE_MOUSEMOTION);
1291 break;
1292 case 1049: /* = 1047 and 1048 */
1293 case 47:
1294 case 1047:
1295 if(IS_SET(MODE_ALTSCREEN))
1296 tclearregion(0, 0, term.col-1, term.row-1);
1297 if((set && !IS_SET(MODE_ALTSCREEN)) ||
1298 (!set && IS_SET(MODE_ALTSCREEN))) {
1299 tswapscreen();
1300 }
1301 if(*args != 1049)
1302 break;
1303 /* pass through */
1304 case 1048:
1305 tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
1306 break;
1307 default:
1308 fprintf(stderr,
1309 "erresc: unknown private set/reset mode %d\n",
1310 *args);
1311 break;
1312 }
1313 } else {
1314 switch(*args) {
1315 case 4:
1316 MODBIT(term.mode, set, MODE_INSERT);
1317 break;
1318 default:
1319 fprintf(stderr,
1320 "erresc: unknown set/reset mode %d\n",
1321 *args);
1322 break;
1323 }
1324 }
1325 }
1326 }
1327 #undef MODBIT
1328
1329
1330 void
1331 csihandle(void) {
1332 switch(csiescseq.mode) {
1333 default:
1334 unknown:
1335 fprintf(stderr, "erresc: unknown csi ");
1336 csidump();
1337 /* die(""); */
1338 break;
1339 case '@': /* ICH -- Insert <n> blank char */
1340 DEFAULT(csiescseq.arg[0], 1);
1341 tinsertblank(csiescseq.arg[0]);
1342 break;
1343 case 'A': /* CUU -- Cursor <n> Up */
1344 case 'e':
1345 DEFAULT(csiescseq.arg[0], 1);
1346 tmoveto(term.c.x, term.c.y-csiescseq.arg[0]);
1347 break;
1348 case 'B': /* CUD -- Cursor <n> Down */
1349 DEFAULT(csiescseq.arg[0], 1);
1350 tmoveto(term.c.x, term.c.y+csiescseq.arg[0]);
1351 break;
1352 case 'C': /* CUF -- Cursor <n> Forward */
1353 case 'a':
1354 DEFAULT(csiescseq.arg[0], 1);
1355 tmoveto(term.c.x+csiescseq.arg[0], term.c.y);
1356 break;
1357 case 'D': /* CUB -- Cursor <n> Backward */
1358 DEFAULT(csiescseq.arg[0], 1);
1359 tmoveto(term.c.x-csiescseq.arg[0], term.c.y);
1360 break;
1361 case 'E': /* CNL -- Cursor <n> Down and first col */
1362 DEFAULT(csiescseq.arg[0], 1);
1363 tmoveto(0, term.c.y+csiescseq.arg[0]);
1364 break;
1365 case 'F': /* CPL -- Cursor <n> Up and first col */
1366 DEFAULT(csiescseq.arg[0], 1);
1367 tmoveto(0, term.c.y-csiescseq.arg[0]);
1368 break;
1369 case 'g': /* TBC -- Tabulation clear */
1370 switch (csiescseq.arg[0]) {
1371 case 0: /* clear current tab stop */
1372 term.tabs[term.c.x] = 0;
1373 break;
1374 case 3: /* clear all the tabs */
1375 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1376 break;
1377 default:
1378 goto unknown;
1379 }
1380 break;
1381 case 'G': /* CHA -- Move to <col> */
1382 case '`': /* HPA */
1383 DEFAULT(csiescseq.arg[0], 1);
1384 tmoveto(csiescseq.arg[0]-1, term.c.y);
1385 break;
1386 case 'H': /* CUP -- Move to <row> <col> */
1387 case 'f': /* HVP */
1388 DEFAULT(csiescseq.arg[0], 1);
1389 DEFAULT(csiescseq.arg[1], 1);
1390 tmoveto(csiescseq.arg[1]-1, csiescseq.arg[0]-1);
1391 break;
1392 case 'I': /* CHT -- Cursor Forward Tabulation <n> tab stops */
1393 DEFAULT(csiescseq.arg[0], 1);
1394 while(csiescseq.arg[0]--)
1395 tputtab(1);
1396 break;
1397 case 'J': /* ED -- Clear screen */
1398 sel.bx = -1;
1399 switch(csiescseq.arg[0]) {
1400 case 0: /* below */
1401 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1402 if(term.c.y < term.row-1)
1403 tclearregion(0, term.c.y+1, term.col-1, term.row-1);
1404 break;
1405 case 1: /* above */
1406 if(term.c.y > 1)
1407 tclearregion(0, 0, term.col-1, term.c.y-1);
1408 tclearregion(0, term.c.y, term.c.x, term.c.y);
1409 break;
1410 case 2: /* all */
1411 tclearregion(0, 0, term.col-1, term.row-1);
1412 break;
1413 default:
1414 goto unknown;
1415 }
1416 break;
1417 case 'K': /* EL -- Clear line */
1418 switch(csiescseq.arg[0]) {
1419 case 0: /* right */
1420 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
1421 break;
1422 case 1: /* left */
1423 tclearregion(0, term.c.y, term.c.x, term.c.y);
1424 break;
1425 case 2: /* all */
1426 tclearregion(0, term.c.y, term.col-1, term.c.y);
1427 break;
1428 }
1429 break;
1430 case 'S': /* SU -- Scroll <n> line up */
1431 DEFAULT(csiescseq.arg[0], 1);
1432 tscrollup(term.top, csiescseq.arg[0]);
1433 break;
1434 case 'T': /* SD -- Scroll <n> line down */
1435 DEFAULT(csiescseq.arg[0], 1);
1436 tscrolldown(term.top, csiescseq.arg[0]);
1437 break;
1438 case 'L': /* IL -- Insert <n> blank lines */
1439 DEFAULT(csiescseq.arg[0], 1);
1440 tinsertblankline(csiescseq.arg[0]);
1441 break;
1442 case 'l': /* RM -- Reset Mode */
1443 tsetmode(csiescseq.priv, 0, csiescseq.arg, csiescseq.narg);
1444 break;
1445 case 'M': /* DL -- Delete <n> lines */
1446 DEFAULT(csiescseq.arg[0], 1);
1447 tdeleteline(csiescseq.arg[0]);
1448 break;
1449 case 'X': /* ECH -- Erase <n> char */
1450 DEFAULT(csiescseq.arg[0], 1);
1451 tclearregion(term.c.x, term.c.y, term.c.x + csiescseq.arg[0], term.c.y);
1452 break;
1453 case 'P': /* DCH -- Delete <n> char */
1454 DEFAULT(csiescseq.arg[0], 1);
1455 tdeletechar(csiescseq.arg[0]);
1456 break;
1457 case 'Z': /* CBT -- Cursor Backward Tabulation <n> tab stops */
1458 DEFAULT(csiescseq.arg[0], 1);
1459 while(csiescseq.arg[0]--)
1460 tputtab(0);
1461 break;
1462 case 'd': /* VPA -- Move to <row> */
1463 DEFAULT(csiescseq.arg[0], 1);
1464 tmoveto(term.c.x, csiescseq.arg[0]-1);
1465 break;
1466 case 'h': /* SM -- Set terminal mode */
1467 tsetmode(csiescseq.priv, 1, csiescseq.arg, csiescseq.narg);
1468 break;
1469 case 'm': /* SGR -- Terminal attribute (color) */
1470 tsetattr(csiescseq.arg, csiescseq.narg);
1471 break;
1472 case 'r': /* DECSTBM -- Set Scrolling Region */
1473 if(csiescseq.priv)
1474 goto unknown;
1475 else {
1476 DEFAULT(csiescseq.arg[0], 1);
1477 DEFAULT(csiescseq.arg[1], term.row);
1478 tsetscroll(csiescseq.arg[0]-1, csiescseq.arg[1]-1);
1479 tmoveto(0, 0);
1480 }
1481 break;
1482 case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
1483 tcursor(CURSOR_SAVE);
1484 break;
1485 case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
1486 tcursor(CURSOR_LOAD);
1487 break;
1488 }
1489 }
1490
1491 void
1492 csidump(void) {
1493 int i;
1494 printf("ESC[");
1495 for(i = 0; i < csiescseq.len; i++) {
1496 uint c = csiescseq.buf[i] & 0xff;
1497 if(isprint(c)) putchar(c);
1498 else if(c == '\n') printf("(\\n)");
1499 else if(c == '\r') printf("(\\r)");
1500 else if(c == 0x1b) printf("(\\e)");
1501 else printf("(%02x)", c);
1502 }
1503 putchar('\n');
1504 }
1505
1506 void
1507 csireset(void) {
1508 memset(&csiescseq, 0, sizeof(csiescseq));
1509 }
1510
1511 void
1512 strhandle(void) {
1513 char *p;
1514
1515 /*
1516 * TODO: make this being useful in case of color palette change.
1517 */
1518 strparse();
1519
1520 p = strescseq.buf;
1521
1522 switch(strescseq.type) {
1523 case ']': /* OSC -- Operating System Command */
1524 switch(p[0]) {
1525 case '0':
1526 case '1':
1527 case '2':
1528 /*
1529 * TODO: Handle special chars in string, like umlauts.
1530 */
1531 if(p[1] == ';') {
1532 XStoreName(xw.dpy, xw.win, strescseq.buf+2);
1533 }
1534 break;
1535 case ';':
1536 XStoreName(xw.dpy, xw.win, strescseq.buf+1);
1537 break;
1538 case '4': /* TODO: Set color (arg0) to "rgb:%hexr/$hexg/$hexb" (arg1) */
1539 break;
1540 default:
1541 fprintf(stderr, "erresc: unknown str ");
1542 strdump();
1543 break;
1544 }
1545 break;
1546 case 'k': /* old title set compatibility */
1547 XStoreName(xw.dpy, xw.win, strescseq.buf);
1548 break;
1549 case 'P': /* DSC -- Device Control String */
1550 case '_': /* APC -- Application Program Command */
1551 case '^': /* PM -- Privacy Message */
1552 default:
1553 fprintf(stderr, "erresc: unknown str ");
1554 strdump();
1555 /* die(""); */
1556 break;
1557 }
1558 }
1559
1560 void
1561 strparse(void) {
1562 /*
1563 * TODO: Implement parsing like for CSI when required.
1564 * Format: ESC type cmd ';' arg0 [';' argn] ESC \
1565 */
1566 return;
1567 }
1568
1569 void
1570 strdump(void) {
1571 int i;
1572 printf("ESC%c", strescseq.type);
1573 for(i = 0; i < strescseq.len; i++) {
1574 uint c = strescseq.buf[i] & 0xff;
1575 if(isprint(c)) putchar(c);
1576 else if(c == '\n') printf("(\\n)");
1577 else if(c == '\r') printf("(\\r)");
1578 else if(c == 0x1b) printf("(\\e)");
1579 else printf("(%02x)", c);
1580 }
1581 printf("ESC\\\n");
1582 }
1583
1584 void
1585 strreset(void) {
1586 memset(&strescseq, 0, sizeof(strescseq));
1587 }
1588
1589 void
1590 tputtab(bool forward) {
1591 unsigned x = term.c.x;
1592
1593 if(forward) {
1594 if(x == term.col)
1595 return;
1596 for(++x; x < term.col && !term.tabs[x]; ++x)
1597 /* nothing */ ;
1598 } else {
1599 if(x == 0)
1600 return;
1601 for(--x; x > 0 && !term.tabs[x]; --x)
1602 /* nothing */ ;
1603 }
1604 tmoveto(x, term.c.y);
1605 }
1606
1607 void
1608 tputc(char *c) {
1609 char ascii = *c;
1610
1611 if(iofd != -1)
1612 write(iofd, c, 1);
1613
1614 if(term.esc & ESC_START) {
1615 if(term.esc & ESC_CSI) {
1616 csiescseq.buf[csiescseq.len++] = ascii;
1617 if(BETWEEN(ascii, 0x40, 0x7E) || csiescseq.len >= ESC_BUF_SIZ) {
1618 term.esc = 0;
1619 csiparse(), csihandle();
1620 }
1621 } else if(term.esc & ESC_STR) {
1622 switch(ascii) {
1623 case '\033':
1624 term.esc = ESC_START | ESC_STR_END;
1625 break;
1626 case '\a': /* backwards compatibility to xterm */
1627 term.esc = 0;
1628 strhandle();
1629 break;
1630 default:
1631 strescseq.buf[strescseq.len++] = ascii;
1632 if(strescseq.len+1 >= STR_BUF_SIZ) {
1633 term.esc = 0;
1634 strhandle();
1635 }
1636 }
1637 } else if(term.esc & ESC_STR_END) {
1638 term.esc = 0;
1639 if(ascii == '\\')
1640 strhandle();
1641 } else if(term.esc & ESC_ALTCHARSET) {
1642 switch(ascii) {
1643 case '0': /* Line drawing crap */
1644 term.c.attr.mode |= ATTR_GFX;
1645 break;
1646 case 'B': /* Back to regular text */
1647 term.c.attr.mode &= ~ATTR_GFX;
1648 break;
1649 default:
1650 fprintf(stderr, "esc unhandled charset: ESC ( %c\n", ascii);
1651 }
1652 term.esc = 0;
1653 } else {
1654 switch(ascii) {
1655 case '[':
1656 term.esc |= ESC_CSI;
1657 break;
1658 case 'P': /* DCS -- Device Control String */
1659 case '_': /* APC -- Application Program Command */
1660 case '^': /* PM -- Privacy Message */
1661 case ']': /* OSC -- Operating System Command */
1662 case 'k': /* old title set compatibility */
1663 strreset();
1664 strescseq.type = ascii;
1665 term.esc |= ESC_STR;
1666 break;
1667 case '(':
1668 term.esc |= ESC_ALTCHARSET;
1669 break;
1670 case 'D': /* IND -- Linefeed */
1671 if(term.c.y == term.bot)
1672 tscrollup(term.top, 1);
1673 else
1674 tmoveto(term.c.x, term.c.y+1);
1675 term.esc = 0;
1676 break;
1677 case 'E': /* NEL -- Next line */
1678 tnewline(1); /* always go to first col */
1679 term.esc = 0;
1680 break;
1681 case 'H': /* HTS -- Horizontal tab stop */
1682 term.tabs[term.c.x] = 1;
1683 term.esc = 0;
1684 break;
1685 case 'M': /* RI -- Reverse index */
1686 if(term.c.y == term.top)
1687 tscrolldown(term.top, 1);
1688 else
1689 tmoveto(term.c.x, term.c.y-1);
1690 term.esc = 0;
1691 break;
1692 case 'c': /* RIS -- Reset to inital state */
1693 treset();
1694 term.esc = 0;
1695 xresettitle();
1696 break;
1697 case '=': /* DECPAM -- Application keypad */
1698 term.mode |= MODE_APPKEYPAD;
1699 term.esc = 0;
1700 break;
1701 case '>': /* DECPNM -- Normal keypad */
1702 term.mode &= ~MODE_APPKEYPAD;
1703 term.esc = 0;
1704 break;
1705 case '7': /* DECSC -- Save Cursor */
1706 tcursor(CURSOR_SAVE);
1707 term.esc = 0;
1708 break;
1709 case '8': /* DECRC -- Restore Cursor */
1710 tcursor(CURSOR_LOAD);
1711 term.esc = 0;
1712 break;
1713 case '\\': /* ST -- Stop */
1714 term.esc = 0;
1715 break;
1716 default:
1717 fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n",
1718 (uchar) ascii, isprint(ascii)?ascii:'.');
1719 term.esc = 0;
1720 }
1721 }
1722 } else {
1723 if(sel.bx != -1 && BETWEEN(term.c.y, sel.by, sel.ey))
1724 sel.bx = -1;
1725 switch(ascii) {
1726 case '\t':
1727 tputtab(1);
1728 break;
1729 case '\b':
1730 tmoveto(term.c.x-1, term.c.y);
1731 break;
1732 case '\r':
1733 tmoveto(0, term.c.y);
1734 break;
1735 case '\f':
1736 case '\v':
1737 case '\n':
1738 /* go to first col if the mode is set */
1739 tnewline(IS_SET(MODE_CRLF));
1740 break;
1741 case '\a':
1742 if(!(xw.state & WIN_FOCUSED))
1743 xseturgency(1);
1744 break;
1745 case '\033':
1746 csireset();
1747 term.esc = ESC_START;
1748 break;
1749 default:
1750 if(IS_SET(MODE_WRAP) && term.c.state & CURSOR_WRAPNEXT)
1751 tnewline(1); /* always go to first col */
1752 tsetchar(c);
1753 if(term.c.x+1 < term.col)
1754 tmoveto(term.c.x+1, term.c.y);
1755 else
1756 term.c.state |= CURSOR_WRAPNEXT;
1757 }
1758 }
1759 }
1760
1761 int
1762 tresize(int col, int row) {
1763 int i, x;
1764 int minrow = MIN(row, term.row);
1765 int mincol = MIN(col, term.col);
1766 int slide = term.c.y - row + 1;
1767
1768 if(col < 1 || row < 1)
1769 return 0;
1770
1771 /* free unneeded rows */
1772 i = 0;
1773 if(slide > 0) {
1774 /* slide screen to keep cursor where we expect it -
1775 * tscrollup would work here, but we can optimize to
1776 * memmove because we're freeing the earlier lines */
1777 for(/* i = 0 */; i < slide; i++) {
1778 free(term.line[i]);
1779 free(term.alt[i]);
1780 }
1781 memmove(term.line, term.line + slide, row * sizeof(Line));
1782 memmove(term.alt, term.alt + slide, row * sizeof(Line));
1783 }
1784 for(i += row; i < term.row; i++) {
1785 free(term.line[i]);
1786 free(term.alt[i]);
1787 }
1788
1789 /* resize to new height */
1790 term.line = xrealloc(term.line, row * sizeof(Line));
1791 term.alt = xrealloc(term.alt, row * sizeof(Line));
1792 term.dirty = xrealloc(term.dirty, row * sizeof(*term.dirty));
1793 term.tabs = xrealloc(term.tabs, col * sizeof(*term.tabs));
1794
1795 /* resize each row to new width, zero-pad if needed */
1796 for(i = 0; i < minrow; i++) {
1797 term.dirty[i] = 1;
1798 term.line[i] = xrealloc(term.line[i], col * sizeof(Glyph));
1799 term.alt[i] = xrealloc(term.alt[i], col * sizeof(Glyph));
1800 for(x = mincol; x < col; x++) {
1801 term.line[i][x].state = 0;
1802 term.alt[i][x].state = 0;
1803 }
1804 }
1805
1806 /* allocate any new rows */
1807 for(/* i == minrow */; i < row; i++) {
1808 term.dirty[i] = 1;
1809 term.line[i] = calloc(col, sizeof(Glyph));
1810 term.alt [i] = calloc(col, sizeof(Glyph));
1811 }
1812 if(col > term.col) {
1813 bool *bp = term.tabs + term.col;
1814
1815 memset(bp, 0, sizeof(*term.tabs) * (col - term.col));
1816 while(--bp > term.tabs && !*bp)
1817 /* nothing */ ;
1818 for(bp += TAB; bp < term.tabs + col; bp += TAB)
1819 *bp = 1;
1820 }
1821 /* update terminal size */
1822 term.col = col, term.row = row;
1823 /* make use of the LIMIT in tmoveto */
1824 tmoveto(term.c.x, term.c.y);
1825 /* reset scrolling region */
1826 tsetscroll(0, row-1);
1827
1828 return (slide > 0);
1829 }
1830
1831 void
1832 xresize(int col, int row) {
1833 xw.w = MAX(1, 2*BORDER + col * xw.cw);
1834 xw.h = MAX(1, 2*BORDER + row * xw.ch);
1835 }
1836
1837 void
1838 xloadcols(void) {
1839 int i, r, g, b;
1840 XColor color;
1841 ulong white = WhitePixel(xw.dpy, xw.scr);
1842
1843 /* load colors [0-15] colors and [256-LEN(colorname)[ (config.h) */
1844 for(i = 0; i < LEN(colorname); i++) {
1845 if(!colorname[i])
1846 continue;
1847 if(!XAllocNamedColor(xw.dpy, xw.cmap, colorname[i], &color, &color)) {
1848 dc.col[i] = white;
1849 fprintf(stderr, "Could not allocate color '%s'\n", colorname[i]);
1850 } else
1851 dc.col[i] = color.pixel;
1852 }
1853
1854 /* load colors [16-255] ; same colors as xterm */
1855 for(i = 16, r = 0; r < 6; r++)
1856 for(g = 0; g < 6; g++)
1857 for(b = 0; b < 6; b++) {
1858 color.red = r == 0 ? 0 : 0x3737 + 0x2828 * r;
1859 color.green = g == 0 ? 0 : 0x3737 + 0x2828 * g;
1860 color.blue = b == 0 ? 0 : 0x3737 + 0x2828 * b;
1861 if(!XAllocColor(xw.dpy, xw.cmap, &color)) {
1862 dc.col[i] = white;
1863 fprintf(stderr, "Could not allocate color %d\n", i);
1864 } else
1865 dc.col[i] = color.pixel;
1866 i++;
1867 }
1868
1869 for(r = 0; r < 24; r++, i++) {
1870 color.red = color.green = color.blue = 0x0808 + 0x0a0a * r;
1871 if(!XAllocColor(xw.dpy, xw.cmap, &color)) {
1872 dc.col[i] = white;
1873 fprintf(stderr, "Could not allocate color %d\n", i);
1874 } else
1875 dc.col[i] = color.pixel;
1876 }
1877 }
1878
1879 void
1880 xclear(int x1, int y1, int x2, int y2) {
1881 XSetForeground(xw.dpy, dc.gc, dc.col[IS_SET(MODE_REVERSE) ? DefaultFG : DefaultBG]);
1882 XFillRectangle(xw.dpy, xw.buf, dc.gc,
1883 BORDER + x1 * xw.cw, BORDER + y1 * xw.ch,
1884 (x2-x1+1) * xw.cw, (y2-y1+1) * xw.ch);
1885 }
1886
1887 void
1888 xhints(void) {
1889 XClassHint class = {opt_class ? opt_class : TNAME, TNAME};
1890 XWMHints wm = {.flags = InputHint, .input = 1};
1891 XSizeHints *sizeh = NULL;
1892
1893 sizeh = XAllocSizeHints();
1894 if(xw.isfixed == False) {
1895 sizeh->flags = PSize | PResizeInc | PBaseSize;
1896 sizeh->height = xw.h;
1897 sizeh->width = xw.w;
1898 sizeh->height_inc = xw.ch;
1899 sizeh->width_inc = xw.cw;
1900 sizeh->base_height = 2*BORDER;
1901 sizeh->base_width = 2*BORDER;
1902 } else {
1903 sizeh->flags = PMaxSize | PMinSize;
1904 sizeh->min_width = sizeh->max_width = xw.fw;
1905 sizeh->min_height = sizeh->max_height = xw.fh;
1906 }
1907
1908 XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm, &class);
1909 XFree(sizeh);
1910 }
1911
1912 XFontSet
1913 xinitfont(char *fontstr) {
1914 XFontSet set;
1915 char *def, **missing;
1916 int n;
1917
1918 missing = NULL;
1919 set = XCreateFontSet(xw.dpy, fontstr, &missing, &n, &def);
1920 if(missing) {
1921 while(n--)
1922 fprintf(stderr, "st: missing fontset: %s\n", missing[n]);
1923 XFreeStringList(missing);
1924 }
1925 return set;
1926 }
1927
1928 void
1929 xgetfontinfo(XFontSet set, int *ascent, int *descent, short *lbearing, short *rbearing) {
1930 XFontStruct **xfonts;
1931 char **font_names;
1932 int i, n;
1933
1934 *ascent = *descent = *lbearing = *rbearing = 0;
1935 n = XFontsOfFontSet(set, &xfonts, &font_names);
1936 for(i = 0; i < n; i++) {
1937 *ascent = MAX(*ascent, (*xfonts)->ascent);
1938 *descent = MAX(*descent, (*xfonts)->descent);
1939 *lbearing = MAX(*lbearing, (*xfonts)->min_bounds.lbearing);
1940 *rbearing = MAX(*rbearing, (*xfonts)->max_bounds.rbearing);
1941 xfonts++;
1942 }
1943 }
1944
1945 void
1946 initfonts(char *fontstr, char *bfontstr, char *ifontstr) {
1947 if((dc.font.set = xinitfont(fontstr)) == NULL)
1948 die("Can't load font %s\n", fontstr);
1949 if((dc.bfont.set = xinitfont(bfontstr)) == NULL)
1950 die("Can't load bfont %s\n", bfontstr);
1951 if((dc.ifont.set = xinitfont(ifontstr)) == NULL)
1952 die("Can't load ifont %s\n", ifontstr);
1953
1954 xgetfontinfo(dc.font.set, &dc.font.ascent, &dc.font.descent,
1955 &dc.font.lbearing, &dc.font.rbearing);
1956 xgetfontinfo(dc.bfont.set, &dc.bfont.ascent, &dc.bfont.descent,
1957 &dc.bfont.lbearing, &dc.bfont.rbearing);
1958 xgetfontinfo(dc.ifont.set, &dc.ifont.ascent, &dc.ifont.descent,
1959 &dc.ifont.lbearing, &dc.ifont.rbearing);
1960 }
1961
1962 void
1963 xinit(void) {
1964 XSetWindowAttributes attrs;
1965 Cursor cursor;
1966 Window parent;
1967 int sw, sh;
1968
1969 if(!(xw.dpy = XOpenDisplay(NULL)))
1970 die("Can't open display\n");
1971 xw.scr = XDefaultScreen(xw.dpy);
1972
1973 /* font */
1974 initfonts(FONT, BOLDFONT, ITALICFONT);
1975
1976 /* XXX: Assuming same size for bold font */
1977 xw.cw = dc.font.rbearing - dc.font.lbearing;
1978 xw.ch = dc.font.ascent + dc.font.descent;
1979
1980 /* colors */
1981 xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
1982 xloadcols();
1983
1984 /* adjust fixed window geometry */
1985 if(xw.isfixed) {
1986 sw = DisplayWidth(xw.dpy, xw.scr);
1987 sh = DisplayHeight(xw.dpy, xw.scr);
1988 if(xw.fx < 0)
1989 xw.fx = sw + xw.fx - xw.fw - 1;
1990 if(xw.fy < 0)
1991 xw.fy = sh + xw.fy - xw.fh - 1;
1992
1993 xw.h = xw.fh;
1994 xw.w = xw.fw;
1995 } else {
1996 /* window - default size */
1997 xw.h = 2*BORDER + term.row * xw.ch;
1998 xw.w = 2*BORDER + term.col * xw.cw;
1999 xw.fx = 0;
2000 xw.fy = 0;
2001 }
2002
2003 attrs.background_pixel = dc.col[DefaultBG];
2004 attrs.border_pixel = dc.col[DefaultBG];
2005 attrs.bit_gravity = NorthWestGravity;
2006 attrs.event_mask = FocusChangeMask | KeyPressMask
2007 | ExposureMask | VisibilityChangeMask | StructureNotifyMask
2008 | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
2009 attrs.colormap = xw.cmap;
2010
2011 parent = opt_embed ? strtol(opt_embed, NULL, 0) : XRootWindow(xw.dpy, xw.scr);
2012 xw.win = XCreateWindow(xw.dpy, parent, xw.fx, xw.fy,
2013 xw.w, xw.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
2014 XDefaultVisual(xw.dpy, xw.scr),
2015 CWBackPixel | CWBorderPixel | CWBitGravity | CWEventMask
2016 | CWColormap,
2017 &attrs);
2018 xw.buf = XdbeAllocateBackBufferName(xw.dpy, xw.win, XdbeCopied);
2019
2020
2021 /* input methods */
2022 xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL);
2023 xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
2024 | XIMStatusNothing, XNClientWindow, xw.win,
2025 XNFocusWindow, xw.win, NULL);
2026 /* gc */
2027 dc.gc = XCreateGC(xw.dpy, xw.win, 0, NULL);
2028
2029 /* white cursor, black outline */
2030 cursor = XCreateFontCursor(xw.dpy, XC_xterm);
2031 XDefineCursor(xw.dpy, xw.win, cursor);
2032 XRecolorCursor(xw.dpy, cursor,
2033 &(XColor){.red = 0xffff, .green = 0xffff, .blue = 0xffff},
2034 &(XColor){.red = 0x0000, .green = 0x0000, .blue = 0x0000});
2035
2036 xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
2037
2038 xresettitle();
2039 XMapWindow(xw.dpy, xw.win);
2040 xhints();
2041 XSync(xw.dpy, 0);
2042 }
2043
2044 void
2045 xdraws(char *s, Glyph base, int x, int y, int charlen, int bytelen) {
2046 int fg = base.fg, bg = base.bg, temp;
2047 int winx = BORDER+x*xw.cw, winy = BORDER+y*xw.ch + dc.font.ascent, width = charlen*xw.cw;
2048 XFontSet fontset = dc.font.set;
2049 int i;
2050
2051 /* only switch default fg/bg if term is in RV mode */
2052 if(IS_SET(MODE_REVERSE)) {
2053 if(fg == DefaultFG)
2054 fg = DefaultBG;
2055 if(bg == DefaultBG)
2056 bg = DefaultFG;
2057 }
2058
2059 if(base.mode & ATTR_REVERSE)
2060 temp = fg, fg = bg, bg = temp;
2061
2062 if(base.mode & ATTR_BOLD) {
2063 fg += 8;
2064 fontset = dc.bfont.set;
2065 }
2066
2067 if(base.mode & ATTR_ITALIC)
2068 fontset = dc.ifont.set;
2069
2070 XSetBackground(xw.dpy, dc.gc, dc.col[bg]);
2071 XSetForeground(xw.dpy, dc.gc, dc.col[fg]);
2072
2073 if(base.mode & ATTR_GFX) {
2074 for(i = 0; i < bytelen; i++) {
2075 char c = gfx[(uint)s[i] % 256];
2076 if(c)
2077 s[i] = c;
2078 else if(s[i] > 0x5f)
2079 s[i] -= 0x5f;
2080 }
2081 }
2082
2083 XmbDrawImageString(xw.dpy, xw.buf, fontset, dc.gc, winx, winy, s, bytelen);
2084
2085 if(base.mode & ATTR_UNDERLINE)
2086 XDrawLine(xw.dpy, xw.buf, dc.gc, winx, winy+1, winx+width-1, winy+1);
2087 }
2088
2089 /* copy buffer pixmap to screen pixmap */
2090 void
2091 xcopy() {
2092 XdbeSwapInfo swpinfo[1] = {{xw.win, XdbeCopied}};
2093 XdbeSwapBuffers(xw.dpy, swpinfo, 1);
2094 }
2095
2096 void
2097 xdrawcursor(void) {
2098 static int oldx = 0;
2099 static int oldy = 0;
2100 int sl;
2101 Glyph g = {{' '}, ATTR_NULL, DefaultBG, DefaultCS, 0};
2102
2103 LIMIT(oldx, 0, term.col-1);
2104 LIMIT(oldy, 0, term.row-1);
2105
2106 if(term.line[term.c.y][term.c.x].state & GLYPH_SET)
2107 memcpy(g.c, term.line[term.c.y][term.c.x].c, UTF_SIZ);
2108
2109 /* remove the old cursor */
2110 if(term.line[oldy][oldx].state & GLYPH_SET) {
2111 sl = utf8size(term.line[oldy][oldx].c);
2112 xdraws(term.line[oldy][oldx].c, term.line[oldy][oldx], oldx, oldy, 1, sl);
2113 } else
2114 xclear(oldx, oldy, oldx, oldy);
2115
2116 xcopy();
2117
2118 /* draw the new one */
2119 if(!(term.c.state & CURSOR_HIDE)) {
2120 if(!(xw.state & WIN_FOCUSED))
2121 g.bg = DefaultUCS;
2122
2123 if(IS_SET(MODE_REVERSE))
2124 g.mode |= ATTR_REVERSE, g.fg = DefaultCS, g.bg = DefaultFG;
2125
2126 sl = utf8size(g.c);
2127 xdraws(g.c, g, term.c.x, term.c.y, 1, sl);
2128 oldx = term.c.x, oldy = term.c.y;
2129 }
2130
2131 xcopy();
2132 }
2133
2134 void
2135 xresettitle(void) {
2136 XStoreName(xw.dpy, xw.win, opt_title ? opt_title : "st");
2137 }
2138
2139 void
2140 redraw(void) {
2141 struct timespec tv = {0, REDRAW_TIMEOUT * 1000};
2142 tfulldirt();
2143 draw();
2144 nanosleep(&tv, NULL);
2145 }
2146
2147 void
2148 draw() {
2149 drawregion(0, 0, term.col, term.row);
2150 xcopy();
2151 gettimeofday(&xw.lastdraw, NULL);
2152 }
2153
2154 void
2155 drawregion(int x1, int y1, int x2, int y2) {
2156 int ic, ib, x, y, ox, sl;
2157 Glyph base, new;
2158 char buf[DRAW_BUF_SIZ];
2159 bool ena_sel = sel.bx != -1, alt = IS_SET(MODE_ALTSCREEN);
2160
2161 if((sel.alt && !alt) || (!sel.alt && alt))
2162 ena_sel = 0;
2163 if(!(xw.state & WIN_VISIBLE))
2164 return;
2165
2166 for(y = y1; y < y2; y++) {
2167 if(!term.dirty[y])
2168 continue;
2169 xclear(0, y, term.col, y);
2170 term.dirty[y] = 0;
2171 base = term.line[y][0];
2172 ic = ib = ox = 0;
2173 for(x = x1; x < x2; x++) {
2174 new = term.line[y][x];
2175 if(ena_sel && *(new.c) && selected(x, y))
2176 new.mode ^= ATTR_REVERSE;
2177 if(ib > 0 && (!(new.state & GLYPH_SET) || ATTRCMP(base, new) ||
2178 ib >= DRAW_BUF_SIZ-UTF_SIZ)) {
2179 xdraws(buf, base, ox, y, ic, ib);
2180 ic = ib = 0;
2181 }
2182 if(new.state & GLYPH_SET) {
2183 if(ib == 0) {
2184 ox = x;
2185 base = new;
2186 }
2187 sl = utf8size(new.c);
2188 memcpy(buf+ib, new.c, sl);
2189 ib += sl;
2190 ++ic;
2191 }
2192 }
2193 if(ib > 0)
2194 xdraws(buf, base, ox, y, ic, ib);
2195 }
2196 xdrawcursor();
2197 }
2198
2199 void
2200 expose(XEvent *ev) {
2201 XExposeEvent *e = &ev->xexpose;
2202 if(xw.state & WIN_REDRAW) {
2203 if(!e->count)
2204 xw.state &= ~WIN_REDRAW;
2205 }
2206 xcopy();
2207 }
2208
2209 void
2210 visibility(XEvent *ev) {
2211 XVisibilityEvent *e = &ev->xvisibility;
2212 if(e->state == VisibilityFullyObscured)
2213 xw.state &= ~WIN_VISIBLE;
2214 else if(!(xw.state & WIN_VISIBLE))
2215 /* need a full redraw for next Expose, not just a buf copy */
2216 xw.state |= WIN_VISIBLE | WIN_REDRAW;
2217 }
2218
2219 void
2220 unmap(XEvent *ev) {
2221 xw.state &= ~WIN_VISIBLE;
2222 }
2223
2224 void
2225 xseturgency(int add) {
2226 XWMHints *h = XGetWMHints(xw.dpy, xw.win);
2227 h->flags = add ? (h->flags | XUrgencyHint) : (h->flags & ~XUrgencyHint);
2228 XSetWMHints(xw.dpy, xw.win, h);
2229 XFree(h);
2230 }
2231
2232 void
2233 focus(XEvent *ev) {
2234 if(ev->type == FocusIn) {
2235 xw.state |= WIN_FOCUSED;
2236 xseturgency(0);
2237 } else
2238 xw.state &= ~WIN_FOCUSED;
2239 draw();
2240 }
2241
2242 char*
2243 kmap(KeySym k, uint state) {
2244 int i;
2245 state &= ~Mod2Mask;
2246 for(i = 0; i < LEN(key); i++) {
2247 uint mask = key[i].mask;
2248 if(key[i].k == k && ((state & mask) == mask || (mask == XK_NO_MOD && !state)))
2249 return (char*)key[i].s;
2250 }
2251 return NULL;
2252 }
2253
2254 void
2255 kpress(XEvent *ev) {
2256 XKeyEvent *e = &ev->xkey;
2257 KeySym ksym;
2258 char buf[32];
2259 char *customkey;
2260 int len;
2261 int meta;
2262 int shift;
2263 Status status;
2264
2265 meta = e->state & Mod1Mask;
2266 shift = e->state & ShiftMask;
2267 len = XmbLookupString(xw.xic, e, buf, sizeof(buf), &ksym, &status);
2268
2269 /* 1. custom keys from config.h */
2270 if((customkey = kmap(ksym, e->state)))
2271 ttywrite(customkey, strlen(customkey));
2272 /* 2. hardcoded (overrides X lookup) */
2273 else
2274 switch(ksym) {
2275 case XK_Up:
2276 case XK_Down:
2277 case XK_Left:
2278 case XK_Right:
2279 /* XXX: shift up/down doesn't work */
2280 sprintf(buf, "\033%c%c", IS_SET(MODE_APPKEYPAD) ? 'O' : '[', (shift ? "dacb":"DACB")[ksym - XK_Left]);
2281 ttywrite(buf, 3);
2282 break;
2283 case XK_Insert:
2284 if(shift)
2285 selpaste();
2286 break;
2287 case XK_Return:
2288 if(IS_SET(MODE_CRLF))
2289 ttywrite("\r\n", 2);
2290 else
2291 ttywrite("\r", 1);
2292 break;
2293 /* 3. X lookup */
2294 default:
2295 if(len > 0) {
2296 if(meta && len == 1)
2297 ttywrite("\033", 1);
2298 ttywrite(buf, len);
2299 }
2300 break;
2301 }
2302 }
2303
2304 void
2305 cmessage(XEvent *e) {
2306 /* See xembed specs
2307 http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html */
2308 if(e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
2309 if(e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
2310 xw.state |= WIN_FOCUSED;
2311 xseturgency(0);
2312 } else if(e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
2313 xw.state &= ~WIN_FOCUSED;
2314 }
2315 draw();
2316 }
2317 }
2318
2319 void
2320 resize(XEvent *e) {
2321 int col, row;
2322
2323 if(e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
2324 return;
2325
2326 xw.w = e->xconfigure.width;
2327 xw.h = e->xconfigure.height;
2328 col = (xw.w - 2*BORDER) / xw.cw;
2329 row = (xw.h - 2*BORDER) / xw.ch;
2330 if(col == term.col && row == term.row)
2331 return;
2332 if(tresize(col, row))
2333 draw();
2334 xresize(col, row);
2335 ttyresize(col, row);
2336 }
2337
2338 bool
2339 last_draw_too_old(void) {
2340 struct timeval now;
2341 gettimeofday(&now, NULL);
2342 return TIMEDIFF(now, xw.lastdraw) >= DRAW_TIMEOUT/1000;
2343 }
2344
2345 void
2346 run(void) {
2347 XEvent ev;
2348 fd_set rfd;
2349 int xfd = XConnectionNumber(xw.dpy);
2350 struct timeval timeout = {0};
2351 bool stuff_to_print = 0;
2352
2353 for(;;) {
2354 FD_ZERO(&rfd);
2355 FD_SET(cmdfd, &rfd);
2356 FD_SET(xfd, &rfd);
2357 timeout.tv_sec = 0;
2358 timeout.tv_usec = SELECT_TIMEOUT;
2359 if(select(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, &timeout) < 0) {
2360 if(errno == EINTR)
2361 continue;
2362 die("select failed: %s\n", SERRNO);
2363 }
2364 if(FD_ISSET(cmdfd, &rfd)) {
2365 ttyread();
2366 stuff_to_print = 1;
2367 }
2368
2369 if(stuff_to_print && last_draw_too_old()) {
2370 stuff_to_print = 0;
2371 draw();
2372 }
2373
2374 while(XPending(xw.dpy)) {
2375 XNextEvent(xw.dpy, &ev);
2376 if(XFilterEvent(&ev, xw.win))
2377 continue;
2378 if(handler[ev.type])
2379 (handler[ev.type])(&ev);
2380 }
2381 }
2382 }
2383
2384 int
2385 main(int argc, char *argv[]) {
2386 int i, bitm, xr, yr;
2387 unsigned int wr, hr;
2388
2389 xw.fw = xw.fh = xw.fx = xw.fy = 0;
2390 xw.isfixed = False;
2391
2392 for(i = 1; i < argc; i++) {
2393 switch(argv[i][0] != '-' || argv[i][2] ? -1 : argv[i][1]) {
2394 case 't':
2395 if(++i < argc) opt_title = argv[i];
2396 break;
2397 case 'c':
2398 if(++i < argc) opt_class = argv[i];
2399 break;
2400 case 'w':
2401 if(++i < argc) opt_embed = argv[i];
2402 break;
2403 case 'f':
2404 if(++i < argc) opt_io = argv[i];
2405 break;
2406 case 'e':
2407 /* eat every remaining arguments */
2408 if(++i < argc) opt_cmd = &argv[i];
2409 goto run;
2410 case 'g':
2411 if(++i >= argc)
2412 break;
2413
2414 bitm = XParseGeometry(argv[i], &xr, &yr, &wr, &hr);
2415 if(bitm & XValue)
2416 xw.fx = xr;
2417 if(bitm & YValue)
2418 xw.fy = yr;
2419 if(bitm & WidthValue)
2420 xw.fw = (int)wr;
2421 if(bitm & HeightValue)
2422 xw.fh = (int)hr;
2423 if(bitm & XNegative && xw.fx == 0)
2424 xw.fx = -1;
2425 if(bitm & XNegative && xw.fy == 0)
2426 xw.fy = -1;
2427
2428 if(xw.fh != 0 && xw.fw != 0)
2429 xw.isfixed = True;
2430 break;
2431 case 'v':
2432 default:
2433 die(USAGE);
2434 }
2435 }
2436
2437 run:
2438 setlocale(LC_CTYPE, "");
2439 tnew(80, 24);
2440 ttynew();
2441 xinit();
2442 selinit();
2443 run();
2444 return 0;
2445 }
2446