Xinqi Bao's Git

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