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