Xinqi Bao's Git

Don't read if we chunked the input data.
[st.git] / st.c
1 /* See LICENSE for license details. */
2 #include <ctype.h>
3 #include <errno.h>
4 #include <fcntl.h>
5 #include <limits.h>
6 #include <locale.h>
7 #include <pwd.h>
8 #include <stdarg.h>
9 #include <stdio.h>
10 #include <stdlib.h>
11 #include <string.h>
12 #include <signal.h>
13 #include <stdint.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 <libgen.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/Xft/Xft.h>
29 #include <X11/XKBlib.h>
30 #include <fontconfig/fontconfig.h>
31 #include <wchar.h>
32
33 #include "arg.h"
34
35 char *argv0;
36
37 #define Glyph Glyph_
38 #define Font Font_
39
40 #if defined(__linux)
41 #include <pty.h>
42 #elif defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
43 #include <util.h>
44 #elif defined(__FreeBSD__) || defined(__DragonFly__)
45 #include <libutil.h>
46 #endif
47
48
49 /* XEMBED messages */
50 #define XEMBED_FOCUS_IN 4
51 #define XEMBED_FOCUS_OUT 5
52
53 /* Arbitrary sizes */
54 #define UTF_INVALID 0xFFFD
55 #define UTF_SIZ 4
56 #define ESC_BUF_SIZ (128*UTF_SIZ)
57 #define ESC_ARG_SIZ 16
58 #define STR_BUF_SIZ ESC_BUF_SIZ
59 #define STR_ARG_SIZ ESC_ARG_SIZ
60 #define XK_ANY_MOD UINT_MAX
61 #define XK_NO_MOD 0
62 #define XK_SWITCH_MOD (1<<13)
63
64 /* macros */
65 #define MIN(a, b) ((a) < (b) ? (a) : (b))
66 #define MAX(a, b) ((a) < (b) ? (b) : (a))
67 #define LEN(a) (sizeof(a) / sizeof(a)[0])
68 #define DEFAULT(a, b) (a) = (a) ? (a) : (b)
69 #define BETWEEN(x, a, b) ((a) <= (x) && (x) <= (b))
70 #define ISCONTROLC0(c) (BETWEEN(c, 0, 0x1f) || (c) == '\177')
71 #define ISCONTROLC1(c) (BETWEEN(c, 0x80, 0x9f))
72 #define ISCONTROL(c) (ISCONTROLC0(c) || ISCONTROLC1(c))
73 #define ISDELIM(u) (utf8strchr(worddelimiters, u) != NULL)
74 #define LIMIT(x, a, b) (x) = (x) < (a) ? (a) : (x) > (b) ? (b) : (x)
75 #define ATTRCMP(a, b) ((a).mode != (b).mode || (a).fg != (b).fg || \
76 (a).bg != (b).bg)
77 #define IS_SET(flag) ((term.mode & (flag)) != 0)
78 #define TIMEDIFF(t1, t2) ((t1.tv_sec-t2.tv_sec)*1000 + \
79 (t1.tv_nsec-t2.tv_nsec)/1E6)
80 #define MODBIT(x, set, bit) ((set) ? ((x) |= (bit)) : ((x) &= ~(bit)))
81
82 #define TRUECOLOR(r,g,b) (1 << 24 | (r) << 16 | (g) << 8 | (b))
83 #define IS_TRUECOL(x) (1 << 24 & (x))
84 #define TRUERED(x) (((x) & 0xff0000) >> 8)
85 #define TRUEGREEN(x) (((x) & 0xff00))
86 #define TRUEBLUE(x) (((x) & 0xff) << 8)
87
88
89 enum glyph_attribute {
90 ATTR_NULL = 0,
91 ATTR_BOLD = 1 << 0,
92 ATTR_FAINT = 1 << 1,
93 ATTR_ITALIC = 1 << 2,
94 ATTR_UNDERLINE = 1 << 3,
95 ATTR_BLINK = 1 << 4,
96 ATTR_REVERSE = 1 << 5,
97 ATTR_INVISIBLE = 1 << 6,
98 ATTR_STRUCK = 1 << 7,
99 ATTR_WRAP = 1 << 8,
100 ATTR_WIDE = 1 << 9,
101 ATTR_WDUMMY = 1 << 10,
102 ATTR_BOLD_FAINT = ATTR_BOLD | ATTR_FAINT,
103 };
104
105 enum cursor_movement {
106 CURSOR_SAVE,
107 CURSOR_LOAD
108 };
109
110 enum cursor_state {
111 CURSOR_DEFAULT = 0,
112 CURSOR_WRAPNEXT = 1,
113 CURSOR_ORIGIN = 2
114 };
115
116 enum term_mode {
117 MODE_WRAP = 1 << 0,
118 MODE_INSERT = 1 << 1,
119 MODE_APPKEYPAD = 1 << 2,
120 MODE_ALTSCREEN = 1 << 3,
121 MODE_CRLF = 1 << 4,
122 MODE_MOUSEBTN = 1 << 5,
123 MODE_MOUSEMOTION = 1 << 6,
124 MODE_REVERSE = 1 << 7,
125 MODE_KBDLOCK = 1 << 8,
126 MODE_HIDE = 1 << 9,
127 MODE_ECHO = 1 << 10,
128 MODE_APPCURSOR = 1 << 11,
129 MODE_MOUSESGR = 1 << 12,
130 MODE_8BIT = 1 << 13,
131 MODE_BLINK = 1 << 14,
132 MODE_FBLINK = 1 << 15,
133 MODE_FOCUS = 1 << 16,
134 MODE_MOUSEX10 = 1 << 17,
135 MODE_MOUSEMANY = 1 << 18,
136 MODE_BRCKTPASTE = 1 << 19,
137 MODE_PRINT = 1 << 20,
138 MODE_MOUSE = MODE_MOUSEBTN|MODE_MOUSEMOTION|MODE_MOUSEX10\
139 |MODE_MOUSEMANY,
140 };
141
142 enum charset {
143 CS_GRAPHIC0,
144 CS_GRAPHIC1,
145 CS_UK,
146 CS_USA,
147 CS_MULTI,
148 CS_GER,
149 CS_FIN
150 };
151
152 enum escape_state {
153 ESC_START = 1,
154 ESC_CSI = 2,
155 ESC_STR = 4, /* DCS, OSC, PM, APC */
156 ESC_ALTCHARSET = 8,
157 ESC_STR_END = 16, /* a final string was encountered */
158 ESC_TEST = 32, /* Enter in test mode */
159 };
160
161 enum window_state {
162 WIN_VISIBLE = 1,
163 WIN_FOCUSED = 2
164 };
165
166 enum selection_mode {
167 SEL_IDLE = 0,
168 SEL_EMPTY = 1,
169 SEL_READY = 2
170 };
171
172 enum selection_type {
173 SEL_REGULAR = 1,
174 SEL_RECTANGULAR = 2
175 };
176
177 enum selection_snap {
178 SNAP_WORD = 1,
179 SNAP_LINE = 2
180 };
181
182 typedef unsigned char uchar;
183 typedef unsigned int uint;
184 typedef unsigned long ulong;
185 typedef unsigned short ushort;
186
187 typedef uint_least32_t Rune;
188
189 typedef XftDraw *Draw;
190 typedef XftColor Color;
191
192 typedef struct {
193 Rune u; /* character code */
194 ushort mode; /* attribute flags */
195 uint32_t fg; /* foreground */
196 uint32_t bg; /* background */
197 } Glyph;
198
199 typedef Glyph *Line;
200
201 typedef struct {
202 Glyph attr; /* current char attributes */
203 int x;
204 int y;
205 char state;
206 } TCursor;
207
208 /* CSI Escape sequence structs */
209 /* ESC '[' [[ [<priv>] <arg> [;]] <mode> [<mode>]] */
210 typedef struct {
211 char buf[ESC_BUF_SIZ]; /* raw string */
212 int len; /* raw string length */
213 char priv;
214 int arg[ESC_ARG_SIZ];
215 int narg; /* nb of args */
216 char mode[2];
217 } CSIEscape;
218
219 /* STR Escape sequence structs */
220 /* ESC type [[ [<priv>] <arg> [;]] <mode>] ESC '\' */
221 typedef struct {
222 char type; /* ESC type ... */
223 char buf[STR_BUF_SIZ]; /* raw string */
224 int len; /* raw string length */
225 char *args[STR_ARG_SIZ];
226 int narg; /* nb of args */
227 } STREscape;
228
229 /* Internal representation of the screen */
230 typedef struct {
231 int row; /* nb row */
232 int col; /* nb col */
233 Line *line; /* screen */
234 Line *alt; /* alternate screen */
235 int *dirty; /* dirtyness of lines */
236 XftGlyphFontSpec *specbuf; /* font spec buffer used for rendering */
237 TCursor c; /* cursor */
238 int top; /* top scroll limit */
239 int bot; /* bottom scroll limit */
240 int mode; /* terminal mode flags */
241 int esc; /* escape state flags */
242 char trantbl[4]; /* charset table translation */
243 int charset; /* current charset */
244 int icharset; /* selected charset for sequence */
245 int numlock; /* lock numbers in keyboard */
246 int *tabs;
247 } Term;
248
249 /* Purely graphic info */
250 typedef struct {
251 Display *dpy;
252 Colormap cmap;
253 Window win;
254 Drawable buf;
255 Atom xembed, wmdeletewin, netwmname, netwmpid;
256 XIM xim;
257 XIC xic;
258 Draw draw;
259 Visual *vis;
260 XSetWindowAttributes attrs;
261 int scr;
262 int isfixed; /* is fixed geometry? */
263 int l, t; /* left and top offset */
264 int gm; /* geometry mask */
265 int tw, th; /* tty width and height */
266 int w, h; /* window width and height */
267 int ch; /* char height */
268 int cw; /* char width */
269 char state; /* focus, redraw, visible */
270 int cursor; /* cursor style */
271 } XWindow;
272
273 typedef struct {
274 uint b;
275 uint mask;
276 char *s;
277 } Mousekey;
278
279 typedef struct {
280 KeySym k;
281 uint mask;
282 char *s;
283 /* three valued logic variables: 0 indifferent, 1 on, -1 off */
284 signed char appkey; /* application keypad */
285 signed char appcursor; /* application cursor */
286 signed char crlf; /* crlf mode */
287 } Key;
288
289 typedef struct {
290 int mode;
291 int type;
292 int snap;
293 /*
294 * Selection variables:
295 * nb – normalized coordinates of the beginning of the selection
296 * ne – normalized coordinates of the end of the selection
297 * ob – original coordinates of the beginning of the selection
298 * oe – original coordinates of the end of the selection
299 */
300 struct {
301 int x, y;
302 } nb, ne, ob, oe;
303
304 char *primary, *clipboard;
305 Atom xtarget;
306 int alt;
307 struct timespec tclick1;
308 struct timespec tclick2;
309 } Selection;
310
311 typedef union {
312 int i;
313 uint ui;
314 float f;
315 const void *v;
316 } Arg;
317
318 typedef struct {
319 uint mod;
320 KeySym keysym;
321 void (*func)(const Arg *);
322 const Arg arg;
323 } Shortcut;
324
325 /* function definitions used in config.h */
326 static void clipcopy(const Arg *);
327 static void clippaste(const Arg *);
328 static void numlock(const Arg *);
329 static void selpaste(const Arg *);
330 static void xzoom(const Arg *);
331 static void xzoomabs(const Arg *);
332 static void xzoomreset(const Arg *);
333 static void printsel(const Arg *);
334 static void printscreen(const Arg *) ;
335 static void toggleprinter(const Arg *);
336
337 /* Config.h for applying patches and the configuration. */
338 #include "config.h"
339
340 /* Font structure */
341 typedef struct {
342 int height;
343 int width;
344 int ascent;
345 int descent;
346 short lbearing;
347 short rbearing;
348 XftFont *match;
349 FcFontSet *set;
350 FcPattern *pattern;
351 } Font;
352
353 /* Drawing Context */
354 typedef struct {
355 Color col[MAX(LEN(colorname), 256)];
356 Font font, bfont, ifont, ibfont;
357 GC gc;
358 } DC;
359
360 static void die(const char *, ...);
361 static void draw(void);
362 static void redraw(void);
363 static void drawregion(int, int, int, int);
364 static void execsh(void);
365 static void stty(void);
366 static void sigchld(int);
367 static void run(void);
368
369 static void csidump(void);
370 static void csihandle(void);
371 static void csiparse(void);
372 static void csireset(void);
373 static int eschandle(uchar);
374 static void strdump(void);
375 static void strhandle(void);
376 static void strparse(void);
377 static void strreset(void);
378
379 static int tattrset(int);
380 static void tprinter(char *, size_t);
381 static void tdumpsel(void);
382 static void tdumpline(int);
383 static void tdump(void);
384 static void tclearregion(int, int, int, int);
385 static void tcursor(int);
386 static void tdeletechar(int);
387 static void tdeleteline(int);
388 static void tinsertblank(int);
389 static void tinsertblankline(int);
390 static int tlinelen(int);
391 static void tmoveto(int, int);
392 static void tmoveato(int, int);
393 static void tnew(int, int);
394 static void tnewline(int);
395 static void tputtab(int);
396 static void tputc(Rune);
397 static void treset(void);
398 static void tresize(int, int);
399 static void tscrollup(int, int);
400 static void tscrolldown(int, int);
401 static void tsetattr(int *, int);
402 static void tsetchar(Rune, Glyph *, int, int);
403 static void tsetscroll(int, int);
404 static void tswapscreen(void);
405 static void tsetdirt(int, int);
406 static void tsetdirtattr(int);
407 static void tsetmode(int, int, int *, int);
408 static void tfulldirt(void);
409 static void techo(Rune);
410 static void tcontrolcode(uchar );
411 static void tdectest(char );
412 static int32_t tdefcolor(int *, int *, int);
413 static void tdeftran(char);
414 static inline int match(uint, uint);
415 static void ttynew(void);
416 static void ttyread(void);
417 static void ttyresize(void);
418 static void ttysend(char *, size_t);
419 static void ttywrite(const char *, size_t);
420 static void tstrsequence(uchar);
421
422 static inline ushort sixd_to_16bit(int);
423 static int xmakeglyphfontspecs(XftGlyphFontSpec *, const Glyph *, int, int, int);
424 static void xdrawglyphfontspecs(const XftGlyphFontSpec *, Glyph, int, int, int);
425 static void xdrawglyph(Glyph, int, int);
426 static void xhints(void);
427 static void xclear(int, int, int, int);
428 static void xdrawcursor(void);
429 static void xinit(void);
430 static void xloadcols(void);
431 static int xsetcolorname(int, const char *);
432 static int xgeommasktogravity(int);
433 static int xloadfont(Font *, FcPattern *);
434 static void xloadfonts(char *, double);
435 static void xsettitle(char *);
436 static void xresettitle(void);
437 static void xsetpointermotion(int);
438 static void xseturgency(int);
439 static void xsetsel(char *, Time);
440 static void xtermclear(int, int, int, int);
441 static void xunloadfont(Font *);
442 static void xunloadfonts(void);
443 static void xresize(int, int);
444
445 static void expose(XEvent *);
446 static void visibility(XEvent *);
447 static void unmap(XEvent *);
448 static char *kmap(KeySym, uint);
449 static void kpress(XEvent *);
450 static void cmessage(XEvent *);
451 static void cresize(int, int);
452 static void resize(XEvent *);
453 static void focus(XEvent *);
454 static void brelease(XEvent *);
455 static void bpress(XEvent *);
456 static void bmotion(XEvent *);
457 static void propnotify(XEvent *);
458 static void selnotify(XEvent *);
459 static void selclear(XEvent *);
460 static void selrequest(XEvent *);
461
462 static void selinit(void);
463 static void selnormalize(void);
464 static inline int selected(int, int);
465 static char *getsel(void);
466 static void selcopy(Time);
467 static void selscroll(int, int);
468 static void selsnap(int *, int *, int);
469 static int x2col(int);
470 static int y2row(int);
471 static void getbuttoninfo(XEvent *);
472 static void mousereport(XEvent *);
473
474 static size_t utf8decode(char *, Rune *, size_t);
475 static Rune utf8decodebyte(char, size_t *);
476 static size_t utf8encode(Rune, char *);
477 static char utf8encodebyte(Rune, size_t);
478 static char *utf8strchr(char *s, Rune u);
479 static size_t utf8validate(Rune *, size_t);
480
481 static ssize_t xwrite(int, const char *, size_t);
482 static void *xmalloc(size_t);
483 static void *xrealloc(void *, size_t);
484 static char *xstrdup(char *);
485
486 static void usage(void);
487
488 static void (*handler[LASTEvent])(XEvent *) = {
489 [KeyPress] = kpress,
490 [ClientMessage] = cmessage,
491 [ConfigureNotify] = resize,
492 [VisibilityNotify] = visibility,
493 [UnmapNotify] = unmap,
494 [Expose] = expose,
495 [FocusIn] = focus,
496 [FocusOut] = focus,
497 [MotionNotify] = bmotion,
498 [ButtonPress] = bpress,
499 [ButtonRelease] = brelease,
500 /*
501 * Uncomment if you want the selection to disappear when you select something
502 * different in another window.
503 */
504 /* [SelectionClear] = selclear, */
505 [SelectionNotify] = selnotify,
506 /*
507 * PropertyNotify is only turned on when there is some INCR transfer happening
508 * for the selection retrieval.
509 */
510 [PropertyNotify] = propnotify,
511 [SelectionRequest] = selrequest,
512 };
513
514 /* Globals */
515 static DC dc;
516 static XWindow xw;
517 static Term term;
518 static CSIEscape csiescseq;
519 static STREscape strescseq;
520 static int cmdfd;
521 static pid_t pid;
522 static Selection sel;
523 static int iofd = 1;
524 static char **opt_cmd = NULL;
525 static char *opt_io = NULL;
526 static char *opt_title = NULL;
527 static char *opt_embed = NULL;
528 static char *opt_class = NULL;
529 static char *opt_font = NULL;
530 static char *opt_line = NULL;
531 static int oldbutton = 3; /* button event on startup: 3 = release */
532
533 static char *usedfont = NULL;
534 static double usedfontsize = 0;
535 static double defaultfontsize = 0;
536
537 static uchar utfbyte[UTF_SIZ + 1] = {0x80, 0, 0xC0, 0xE0, 0xF0};
538 static uchar utfmask[UTF_SIZ + 1] = {0xC0, 0x80, 0xE0, 0xF0, 0xF8};
539 static Rune utfmin[UTF_SIZ + 1] = { 0, 0, 0x80, 0x800, 0x10000};
540 static Rune utfmax[UTF_SIZ + 1] = {0x10FFFF, 0x7F, 0x7FF, 0xFFFF, 0x10FFFF};
541
542 /* Font Ring Cache */
543 enum {
544 FRC_NORMAL,
545 FRC_ITALIC,
546 FRC_BOLD,
547 FRC_ITALICBOLD
548 };
549
550 typedef struct {
551 XftFont *font;
552 int flags;
553 Rune unicodep;
554 } Fontcache;
555
556 /* Fontcache is an array now. A new font will be appended to the array. */
557 static Fontcache frc[16];
558 static int frclen = 0;
559
560 ssize_t
561 xwrite(int fd, const char *s, size_t len)
562 {
563 size_t aux = len;
564 ssize_t r;
565
566 while (len > 0) {
567 r = write(fd, s, len);
568 if (r < 0)
569 return r;
570 len -= r;
571 s += r;
572 }
573
574 return aux;
575 }
576
577 void *
578 xmalloc(size_t len)
579 {
580 void *p = malloc(len);
581
582 if (!p)
583 die("Out of memory\n");
584
585 return p;
586 }
587
588 void *
589 xrealloc(void *p, size_t len)
590 {
591 if ((p = realloc(p, len)) == NULL)
592 die("Out of memory\n");
593
594 return p;
595 }
596
597 char *
598 xstrdup(char *s)
599 {
600 if ((s = strdup(s)) == NULL)
601 die("Out of memory\n");
602
603 return s;
604 }
605
606 size_t
607 utf8decode(char *c, Rune *u, size_t clen)
608 {
609 size_t i, j, len, type;
610 Rune udecoded;
611
612 *u = UTF_INVALID;
613 if (!clen)
614 return 0;
615 udecoded = utf8decodebyte(c[0], &len);
616 if (!BETWEEN(len, 1, UTF_SIZ))
617 return 1;
618 for (i = 1, j = 1; i < clen && j < len; ++i, ++j) {
619 udecoded = (udecoded << 6) | utf8decodebyte(c[i], &type);
620 if (type != 0)
621 return j;
622 }
623 if (j < len)
624 return 0;
625 *u = udecoded;
626 utf8validate(u, len);
627
628 return len;
629 }
630
631 Rune
632 utf8decodebyte(char c, size_t *i)
633 {
634 for (*i = 0; *i < LEN(utfmask); ++(*i))
635 if (((uchar)c & utfmask[*i]) == utfbyte[*i])
636 return (uchar)c & ~utfmask[*i];
637
638 return 0;
639 }
640
641 size_t
642 utf8encode(Rune u, char *c)
643 {
644 size_t len, i;
645
646 len = utf8validate(&u, 0);
647 if (len > UTF_SIZ)
648 return 0;
649
650 for (i = len - 1; i != 0; --i) {
651 c[i] = utf8encodebyte(u, 0);
652 u >>= 6;
653 }
654 c[0] = utf8encodebyte(u, len);
655
656 return len;
657 }
658
659 char
660 utf8encodebyte(Rune u, size_t i)
661 {
662 return utfbyte[i] | (u & ~utfmask[i]);
663 }
664
665 char *
666 utf8strchr(char *s, Rune u)
667 {
668 Rune r;
669 size_t i, j, len;
670
671 len = strlen(s);
672 for (i = 0, j = 0; i < len; i += j) {
673 if (!(j = utf8decode(&s[i], &r, len - i)))
674 break;
675 if (r == u)
676 return &(s[i]);
677 }
678
679 return NULL;
680 }
681
682 size_t
683 utf8validate(Rune *u, size_t i)
684 {
685 if (!BETWEEN(*u, utfmin[i], utfmax[i]) || BETWEEN(*u, 0xD800, 0xDFFF))
686 *u = UTF_INVALID;
687 for (i = 1; *u > utfmax[i]; ++i)
688 ;
689
690 return i;
691 }
692
693 void
694 selinit(void)
695 {
696 memset(&sel.tclick1, 0, sizeof(sel.tclick1));
697 memset(&sel.tclick2, 0, sizeof(sel.tclick2));
698 sel.mode = SEL_IDLE;
699 sel.ob.x = -1;
700 sel.primary = NULL;
701 sel.clipboard = NULL;
702 sel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
703 if (sel.xtarget == None)
704 sel.xtarget = XA_STRING;
705 }
706
707 int
708 x2col(int x)
709 {
710 x -= borderpx;
711 x /= xw.cw;
712
713 return LIMIT(x, 0, term.col-1);
714 }
715
716 int
717 y2row(int y)
718 {
719 y -= borderpx;
720 y /= xw.ch;
721
722 return LIMIT(y, 0, term.row-1);
723 }
724
725 int
726 tlinelen(int y)
727 {
728 int i = term.col;
729
730 if (term.line[y][i - 1].mode & ATTR_WRAP)
731 return i;
732
733 while (i > 0 && term.line[y][i - 1].u == ' ')
734 --i;
735
736 return i;
737 }
738
739 void
740 selnormalize(void)
741 {
742 int i;
743
744 if (sel.type == SEL_REGULAR && sel.ob.y != sel.oe.y) {
745 sel.nb.x = sel.ob.y < sel.oe.y ? sel.ob.x : sel.oe.x;
746 sel.ne.x = sel.ob.y < sel.oe.y ? sel.oe.x : sel.ob.x;
747 } else {
748 sel.nb.x = MIN(sel.ob.x, sel.oe.x);
749 sel.ne.x = MAX(sel.ob.x, sel.oe.x);
750 }
751 sel.nb.y = MIN(sel.ob.y, sel.oe.y);
752 sel.ne.y = MAX(sel.ob.y, sel.oe.y);
753
754 selsnap(&sel.nb.x, &sel.nb.y, -1);
755 selsnap(&sel.ne.x, &sel.ne.y, +1);
756
757 /* expand selection over line breaks */
758 if (sel.type == SEL_RECTANGULAR)
759 return;
760 i = tlinelen(sel.nb.y);
761 if (i < sel.nb.x)
762 sel.nb.x = i;
763 if (tlinelen(sel.ne.y) <= sel.ne.x)
764 sel.ne.x = term.col - 1;
765 }
766
767 int
768 selected(int x, int y)
769 {
770 if (sel.mode == SEL_EMPTY)
771 return 0;
772
773 if (sel.type == SEL_RECTANGULAR)
774 return BETWEEN(y, sel.nb.y, sel.ne.y)
775 && BETWEEN(x, sel.nb.x, sel.ne.x);
776
777 return BETWEEN(y, sel.nb.y, sel.ne.y)
778 && (y != sel.nb.y || x >= sel.nb.x)
779 && (y != sel.ne.y || x <= sel.ne.x);
780 }
781
782 void
783 selsnap(int *x, int *y, int direction)
784 {
785 int newx, newy, xt, yt;
786 int delim, prevdelim;
787 Glyph *gp, *prevgp;
788
789 switch (sel.snap) {
790 case SNAP_WORD:
791 /*
792 * Snap around if the word wraps around at the end or
793 * beginning of a line.
794 */
795 prevgp = &term.line[*y][*x];
796 prevdelim = ISDELIM(prevgp->u);
797 for (;;) {
798 newx = *x + direction;
799 newy = *y;
800 if (!BETWEEN(newx, 0, term.col - 1)) {
801 newy += direction;
802 newx = (newx + term.col) % term.col;
803 if (!BETWEEN(newy, 0, term.row - 1))
804 break;
805
806 if (direction > 0)
807 yt = *y, xt = *x;
808 else
809 yt = newy, xt = newx;
810 if (!(term.line[yt][xt].mode & ATTR_WRAP))
811 break;
812 }
813
814 if (newx >= tlinelen(newy))
815 break;
816
817 gp = &term.line[newy][newx];
818 delim = ISDELIM(gp->u);
819 if (!(gp->mode & ATTR_WDUMMY) && (delim != prevdelim
820 || (delim && gp->u != prevgp->u)))
821 break;
822
823 *x = newx;
824 *y = newy;
825 prevgp = gp;
826 prevdelim = delim;
827 }
828 break;
829 case SNAP_LINE:
830 /*
831 * Snap around if the the previous line or the current one
832 * has set ATTR_WRAP at its end. Then the whole next or
833 * previous line will be selected.
834 */
835 *x = (direction < 0) ? 0 : term.col - 1;
836 if (direction < 0) {
837 for (; *y > 0; *y += direction) {
838 if (!(term.line[*y-1][term.col-1].mode
839 & ATTR_WRAP)) {
840 break;
841 }
842 }
843 } else if (direction > 0) {
844 for (; *y < term.row-1; *y += direction) {
845 if (!(term.line[*y][term.col-1].mode
846 & ATTR_WRAP)) {
847 break;
848 }
849 }
850 }
851 break;
852 }
853 }
854
855 void
856 getbuttoninfo(XEvent *e)
857 {
858 int type;
859 uint state = e->xbutton.state & ~(Button1Mask | forceselmod);
860
861 sel.alt = IS_SET(MODE_ALTSCREEN);
862
863 sel.oe.x = x2col(e->xbutton.x);
864 sel.oe.y = y2row(e->xbutton.y);
865 selnormalize();
866
867 sel.type = SEL_REGULAR;
868 for (type = 1; type < LEN(selmasks); ++type) {
869 if (match(selmasks[type], state)) {
870 sel.type = type;
871 break;
872 }
873 }
874 }
875
876 void
877 mousereport(XEvent *e)
878 {
879 int x = x2col(e->xbutton.x), y = y2row(e->xbutton.y),
880 button = e->xbutton.button, state = e->xbutton.state,
881 len;
882 char buf[40];
883 static int ox, oy;
884
885 /* from urxvt */
886 if (e->xbutton.type == MotionNotify) {
887 if (x == ox && y == oy)
888 return;
889 if (!IS_SET(MODE_MOUSEMOTION) && !IS_SET(MODE_MOUSEMANY))
890 return;
891 /* MOUSE_MOTION: no reporting if no button is pressed */
892 if (IS_SET(MODE_MOUSEMOTION) && oldbutton == 3)
893 return;
894
895 button = oldbutton + 32;
896 ox = x;
897 oy = y;
898 } else {
899 if (!IS_SET(MODE_MOUSESGR) && e->xbutton.type == ButtonRelease) {
900 button = 3;
901 } else {
902 button -= Button1;
903 if (button >= 3)
904 button += 64 - 3;
905 }
906 if (e->xbutton.type == ButtonPress) {
907 oldbutton = button;
908 ox = x;
909 oy = y;
910 } else if (e->xbutton.type == ButtonRelease) {
911 oldbutton = 3;
912 /* MODE_MOUSEX10: no button release reporting */
913 if (IS_SET(MODE_MOUSEX10))
914 return;
915 if (button == 64 || button == 65)
916 return;
917 }
918 }
919
920 if (!IS_SET(MODE_MOUSEX10)) {
921 button += ((state & ShiftMask ) ? 4 : 0)
922 + ((state & Mod4Mask ) ? 8 : 0)
923 + ((state & ControlMask) ? 16 : 0);
924 }
925
926 if (IS_SET(MODE_MOUSESGR)) {
927 len = snprintf(buf, sizeof(buf), "\033[<%d;%d;%d%c",
928 button, x+1, y+1,
929 e->xbutton.type == ButtonRelease ? 'm' : 'M');
930 } else if (x < 223 && y < 223) {
931 len = snprintf(buf, sizeof(buf), "\033[M%c%c%c",
932 32+button, 32+x+1, 32+y+1);
933 } else {
934 return;
935 }
936
937 ttywrite(buf, len);
938 }
939
940 void
941 bpress(XEvent *e)
942 {
943 struct timespec now;
944 Mousekey *mk;
945
946 if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forceselmod)) {
947 mousereport(e);
948 return;
949 }
950
951 for (mk = mshortcuts; mk < mshortcuts + LEN(mshortcuts); mk++) {
952 if (e->xbutton.button == mk->b
953 && match(mk->mask, e->xbutton.state)) {
954 ttysend(mk->s, strlen(mk->s));
955 return;
956 }
957 }
958
959 if (e->xbutton.button == Button1) {
960 clock_gettime(CLOCK_MONOTONIC, &now);
961
962 /* Clear previous selection, logically and visually. */
963 selclear(NULL);
964 sel.mode = SEL_EMPTY;
965 sel.type = SEL_REGULAR;
966 sel.oe.x = sel.ob.x = x2col(e->xbutton.x);
967 sel.oe.y = sel.ob.y = y2row(e->xbutton.y);
968
969 /*
970 * If the user clicks below predefined timeouts specific
971 * snapping behaviour is exposed.
972 */
973 if (TIMEDIFF(now, sel.tclick2) <= tripleclicktimeout) {
974 sel.snap = SNAP_LINE;
975 } else if (TIMEDIFF(now, sel.tclick1) <= doubleclicktimeout) {
976 sel.snap = SNAP_WORD;
977 } else {
978 sel.snap = 0;
979 }
980 selnormalize();
981
982 if (sel.snap != 0)
983 sel.mode = SEL_READY;
984 tsetdirt(sel.nb.y, sel.ne.y);
985 sel.tclick2 = sel.tclick1;
986 sel.tclick1 = now;
987 }
988 }
989
990 char *
991 getsel(void)
992 {
993 char *str, *ptr;
994 int y, bufsize, lastx, linelen;
995 Glyph *gp, *last;
996
997 if (sel.ob.x == -1)
998 return NULL;
999
1000 bufsize = (term.col+1) * (sel.ne.y-sel.nb.y+1) * UTF_SIZ;
1001 ptr = str = xmalloc(bufsize);
1002
1003 /* append every set & selected glyph to the selection */
1004 for (y = sel.nb.y; y <= sel.ne.y; y++) {
1005 linelen = tlinelen(y);
1006
1007 if (sel.type == SEL_RECTANGULAR) {
1008 gp = &term.line[y][sel.nb.x];
1009 lastx = sel.ne.x;
1010 } else {
1011 gp = &term.line[y][sel.nb.y == y ? sel.nb.x : 0];
1012 lastx = (sel.ne.y == y) ? sel.ne.x : term.col-1;
1013 }
1014 last = &term.line[y][MIN(lastx, linelen-1)];
1015 while (last >= gp && last->u == ' ')
1016 --last;
1017
1018 for ( ; gp <= last; ++gp) {
1019 if (gp->mode & ATTR_WDUMMY)
1020 continue;
1021
1022 ptr += utf8encode(gp->u, ptr);
1023 }
1024
1025 /*
1026 * Copy and pasting of line endings is inconsistent
1027 * in the inconsistent terminal and GUI world.
1028 * The best solution seems like to produce '\n' when
1029 * something is copied from st and convert '\n' to
1030 * '\r', when something to be pasted is received by
1031 * st.
1032 * FIXME: Fix the computer world.
1033 */
1034 if ((y < sel.ne.y || lastx >= linelen) && !(last->mode & ATTR_WRAP))
1035 *ptr++ = '\n';
1036 }
1037 *ptr = 0;
1038 return str;
1039 }
1040
1041 void
1042 selcopy(Time t)
1043 {
1044 xsetsel(getsel(), t);
1045 }
1046
1047 void
1048 propnotify(XEvent *e)
1049 {
1050 XPropertyEvent *xpev;
1051 Atom clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
1052
1053 xpev = &e->xproperty;
1054 if (xpev->state == PropertyNewValue &&
1055 (xpev->atom == XA_PRIMARY ||
1056 xpev->atom == clipboard)) {
1057 selnotify(e);
1058 }
1059 }
1060
1061 void
1062 selnotify(XEvent *e)
1063 {
1064 ulong nitems, ofs, rem;
1065 int format;
1066 uchar *data, *last, *repl;
1067 Atom type, incratom, property;
1068
1069 incratom = XInternAtom(xw.dpy, "INCR", 0);
1070
1071 ofs = 0;
1072 if (e->type == SelectionNotify) {
1073 property = e->xselection.property;
1074 } else if(e->type == PropertyNotify) {
1075 property = e->xproperty.atom;
1076 } else {
1077 return;
1078 }
1079 if (property == None)
1080 return;
1081
1082 do {
1083 if (XGetWindowProperty(xw.dpy, xw.win, property, ofs,
1084 BUFSIZ/4, False, AnyPropertyType,
1085 &type, &format, &nitems, &rem,
1086 &data)) {
1087 fprintf(stderr, "Clipboard allocation failed\n");
1088 return;
1089 }
1090
1091 if (e->type == PropertyNotify && nitems == 0 && rem == 0) {
1092 /*
1093 * If there is some PropertyNotify with no data, then
1094 * this is the signal of the selection owner that all
1095 * data has been transferred. We won't need to receive
1096 * PropertyNotify events anymore.
1097 */
1098 MODBIT(xw.attrs.event_mask, 0, PropertyChangeMask);
1099 XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask,
1100 &xw.attrs);
1101 }
1102
1103 if (type == incratom) {
1104 /*
1105 * Activate the PropertyNotify events so we receive
1106 * when the selection owner does send us the next
1107 * chunk of data.
1108 */
1109 MODBIT(xw.attrs.event_mask, 1, PropertyChangeMask);
1110 XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask,
1111 &xw.attrs);
1112
1113 /*
1114 * Deleting the property is the transfer start signal.
1115 */
1116 XDeleteProperty(xw.dpy, xw.win, (int)property);
1117 continue;
1118 }
1119
1120 /*
1121 * As seen in getsel:
1122 * Line endings are inconsistent in the terminal and GUI world
1123 * copy and pasting. When receiving some selection data,
1124 * replace all '\n' with '\r'.
1125 * FIXME: Fix the computer world.
1126 */
1127 repl = data;
1128 last = data + nitems * format / 8;
1129 while ((repl = memchr(repl, '\n', last - repl))) {
1130 *repl++ = '\r';
1131 }
1132
1133 if (IS_SET(MODE_BRCKTPASTE))
1134 ttywrite("\033[200~", 6);
1135 ttysend((char *)data, nitems * format / 8);
1136 if (IS_SET(MODE_BRCKTPASTE))
1137 ttywrite("\033[201~", 6);
1138 XFree(data);
1139 /* number of 32-bit chunks returned */
1140 ofs += nitems * format / 32;
1141 } while (rem > 0);
1142
1143 /*
1144 * Deleting the property again tells the selection owner to send the
1145 * next data chunk in the property.
1146 */
1147 if (e->type == PropertyNotify)
1148 XDeleteProperty(xw.dpy, xw.win, (int)property);
1149 }
1150
1151 void
1152 selpaste(const Arg *dummy)
1153 {
1154 XConvertSelection(xw.dpy, XA_PRIMARY, sel.xtarget, XA_PRIMARY,
1155 xw.win, CurrentTime);
1156 }
1157
1158 void
1159 clipcopy(const Arg *dummy)
1160 {
1161 Atom clipboard;
1162
1163 if (sel.clipboard != NULL)
1164 free(sel.clipboard);
1165
1166 if (sel.primary != NULL) {
1167 sel.clipboard = xstrdup(sel.primary);
1168 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
1169 XSetSelectionOwner(xw.dpy, clipboard, xw.win, CurrentTime);
1170 }
1171 }
1172
1173 void
1174 clippaste(const Arg *dummy)
1175 {
1176 Atom clipboard;
1177
1178 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
1179 XConvertSelection(xw.dpy, clipboard, sel.xtarget, clipboard,
1180 xw.win, CurrentTime);
1181 }
1182
1183 void
1184 selclear(XEvent *e)
1185 {
1186 if (sel.ob.x == -1)
1187 return;
1188 sel.mode = SEL_IDLE;
1189 sel.ob.x = -1;
1190 tsetdirt(sel.nb.y, sel.ne.y);
1191 }
1192
1193 void
1194 selrequest(XEvent *e)
1195 {
1196 XSelectionRequestEvent *xsre;
1197 XSelectionEvent xev;
1198 Atom xa_targets, string, clipboard;
1199 char *seltext;
1200
1201 xsre = (XSelectionRequestEvent *) e;
1202 xev.type = SelectionNotify;
1203 xev.requestor = xsre->requestor;
1204 xev.selection = xsre->selection;
1205 xev.target = xsre->target;
1206 xev.time = xsre->time;
1207 if (xsre->property == None)
1208 xsre->property = xsre->target;
1209
1210 /* reject */
1211 xev.property = None;
1212
1213 xa_targets = XInternAtom(xw.dpy, "TARGETS", 0);
1214 if (xsre->target == xa_targets) {
1215 /* respond with the supported type */
1216 string = sel.xtarget;
1217 XChangeProperty(xsre->display, xsre->requestor, xsre->property,
1218 XA_ATOM, 32, PropModeReplace,
1219 (uchar *) &string, 1);
1220 xev.property = xsre->property;
1221 } else if (xsre->target == sel.xtarget || xsre->target == XA_STRING) {
1222 /*
1223 * xith XA_STRING non ascii characters may be incorrect in the
1224 * requestor. It is not our problem, use utf8.
1225 */
1226 clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
1227 if (xsre->selection == XA_PRIMARY) {
1228 seltext = sel.primary;
1229 } else if (xsre->selection == clipboard) {
1230 seltext = sel.clipboard;
1231 } else {
1232 fprintf(stderr,
1233 "Unhandled clipboard selection 0x%lx\n",
1234 xsre->selection);
1235 return;
1236 }
1237 if (seltext != NULL) {
1238 XChangeProperty(xsre->display, xsre->requestor,
1239 xsre->property, xsre->target,
1240 8, PropModeReplace,
1241 (uchar *)seltext, strlen(seltext));
1242 xev.property = xsre->property;
1243 }
1244 }
1245
1246 /* all done, send a notification to the listener */
1247 if (!XSendEvent(xsre->display, xsre->requestor, 1, 0, (XEvent *) &xev))
1248 fprintf(stderr, "Error sending SelectionNotify event\n");
1249 }
1250
1251 void
1252 xsetsel(char *str, Time t)
1253 {
1254 free(sel.primary);
1255 sel.primary = str;
1256
1257 XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, t);
1258 if (XGetSelectionOwner(xw.dpy, XA_PRIMARY) != xw.win)
1259 selclear(0);
1260 }
1261
1262 void
1263 brelease(XEvent *e)
1264 {
1265 if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forceselmod)) {
1266 mousereport(e);
1267 return;
1268 }
1269
1270 if (e->xbutton.button == Button2) {
1271 selpaste(NULL);
1272 } else if (e->xbutton.button == Button1) {
1273 if (sel.mode == SEL_READY) {
1274 getbuttoninfo(e);
1275 selcopy(e->xbutton.time);
1276 } else
1277 selclear(NULL);
1278 sel.mode = SEL_IDLE;
1279 tsetdirt(sel.nb.y, sel.ne.y);
1280 }
1281 }
1282
1283 void
1284 bmotion(XEvent *e)
1285 {
1286 int oldey, oldex, oldsby, oldsey;
1287
1288 if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forceselmod)) {
1289 mousereport(e);
1290 return;
1291 }
1292
1293 if (!sel.mode)
1294 return;
1295
1296 sel.mode = SEL_READY;
1297 oldey = sel.oe.y;
1298 oldex = sel.oe.x;
1299 oldsby = sel.nb.y;
1300 oldsey = sel.ne.y;
1301 getbuttoninfo(e);
1302
1303 if (oldey != sel.oe.y || oldex != sel.oe.x)
1304 tsetdirt(MIN(sel.nb.y, oldsby), MAX(sel.ne.y, oldsey));
1305 }
1306
1307 void
1308 die(const char *errstr, ...)
1309 {
1310 va_list ap;
1311
1312 va_start(ap, errstr);
1313 vfprintf(stderr, errstr, ap);
1314 va_end(ap);
1315 exit(1);
1316 }
1317
1318 void
1319 execsh(void)
1320 {
1321 char **args, *sh, *prog;
1322 const struct passwd *pw;
1323 char buf[sizeof(long) * 8 + 1];
1324
1325 errno = 0;
1326 if ((pw = getpwuid(getuid())) == NULL) {
1327 if (errno)
1328 die("getpwuid:%s\n", strerror(errno));
1329 else
1330 die("who are you?\n");
1331 }
1332
1333 if ((sh = getenv("SHELL")) == NULL)
1334 sh = (pw->pw_shell[0]) ? pw->pw_shell : shell;
1335
1336 if (opt_cmd)
1337 prog = opt_cmd[0];
1338 else if (utmp)
1339 prog = utmp;
1340 else
1341 prog = sh;
1342 args = (opt_cmd) ? opt_cmd : (char *[]) {prog, NULL};
1343
1344 snprintf(buf, sizeof(buf), "%lu", xw.win);
1345
1346 unsetenv("COLUMNS");
1347 unsetenv("LINES");
1348 unsetenv("TERMCAP");
1349 setenv("LOGNAME", pw->pw_name, 1);
1350 setenv("USER", pw->pw_name, 1);
1351 setenv("SHELL", sh, 1);
1352 setenv("HOME", pw->pw_dir, 1);
1353 setenv("TERM", termname, 1);
1354 setenv("WINDOWID", buf, 1);
1355
1356 signal(SIGCHLD, SIG_DFL);
1357 signal(SIGHUP, SIG_DFL);
1358 signal(SIGINT, SIG_DFL);
1359 signal(SIGQUIT, SIG_DFL);
1360 signal(SIGTERM, SIG_DFL);
1361 signal(SIGALRM, SIG_DFL);
1362
1363 execvp(prog, args);
1364 _exit(1);
1365 }
1366
1367 void
1368 sigchld(int a)
1369 {
1370 int stat;
1371 pid_t p;
1372
1373 if ((p = waitpid(pid, &stat, WNOHANG)) < 0)
1374 die("Waiting for pid %hd failed: %s\n", pid, strerror(errno));
1375
1376 if (pid != p)
1377 return;
1378
1379 if (!WIFEXITED(stat) || WEXITSTATUS(stat))
1380 die("child finished with error '%d'\n", stat);
1381 exit(0);
1382 }
1383
1384
1385 void
1386 stty(void)
1387 {
1388 char cmd[_POSIX_ARG_MAX], **p, *q, *s;
1389 size_t n, siz;
1390
1391 if ((n = strlen(stty_args)) > sizeof(cmd)-1)
1392 die("incorrect stty parameters\n");
1393 memcpy(cmd, stty_args, n);
1394 q = cmd + n;
1395 siz = sizeof(cmd) - n;
1396 for (p = opt_cmd; p && (s = *p); ++p) {
1397 if ((n = strlen(s)) > siz-1)
1398 die("stty parameter length too long\n");
1399 *q++ = ' ';
1400 q = memcpy(q, s, n);
1401 q += n;
1402 siz-= n + 1;
1403 }
1404 *q = '\0';
1405 if (system(cmd) != 0)
1406 perror("Couldn't call stty");
1407 }
1408
1409 void
1410 ttynew(void)
1411 {
1412 int m, s;
1413 struct winsize w = {term.row, term.col, 0, 0};
1414
1415 if (opt_io) {
1416 term.mode |= MODE_PRINT;
1417 iofd = (!strcmp(opt_io, "-")) ?
1418 1 : open(opt_io, O_WRONLY | O_CREAT, 0666);
1419 if (iofd < 0) {
1420 fprintf(stderr, "Error opening %s:%s\n",
1421 opt_io, strerror(errno));
1422 }
1423 }
1424
1425 if (opt_line) {
1426 if ((cmdfd = open(opt_line, O_RDWR)) < 0)
1427 die("open line failed: %s\n", strerror(errno));
1428 close(0);
1429 dup(cmdfd);
1430 stty();
1431 return;
1432 }
1433
1434 /* seems to work fine on linux, openbsd and freebsd */
1435 if (openpty(&m, &s, NULL, NULL, &w) < 0)
1436 die("openpty failed: %s\n", strerror(errno));
1437
1438 switch (pid = fork()) {
1439 case -1:
1440 die("fork failed\n");
1441 break;
1442 case 0:
1443 close(iofd);
1444 setsid(); /* create a new process group */
1445 dup2(s, 0);
1446 dup2(s, 1);
1447 dup2(s, 2);
1448 if (ioctl(s, TIOCSCTTY, NULL) < 0)
1449 die("ioctl TIOCSCTTY failed: %s\n", strerror(errno));
1450 close(s);
1451 close(m);
1452 execsh();
1453 break;
1454 default:
1455 close(s);
1456 cmdfd = m;
1457 signal(SIGCHLD, sigchld);
1458 break;
1459 }
1460 }
1461
1462 void
1463 ttyread(void)
1464 {
1465 static char buf[BUFSIZ];
1466 static int buflen = 0;
1467 char *ptr;
1468 int charsize; /* size of utf8 char in bytes */
1469 Rune unicodep;
1470 int ret;
1471
1472 /* append read bytes to unprocessed bytes */
1473 if ((ret = read(cmdfd, buf+buflen, LEN(buf)-buflen)) < 0)
1474 die("Couldn't read from shell: %s\n", strerror(errno));
1475
1476 /* process every complete utf8 char */
1477 buflen += ret;
1478 ptr = buf;
1479 while ((charsize = utf8decode(ptr, &unicodep, buflen))) {
1480 tputc(unicodep);
1481 ptr += charsize;
1482 buflen -= charsize;
1483 }
1484
1485 /* keep any uncomplete utf8 char for the next call */
1486 memmove(buf, ptr, buflen);
1487 }
1488
1489 void
1490 ttywrite(const char *s, size_t n)
1491 {
1492 fd_set wfd;
1493 struct timespec tv;
1494 ssize_t r;
1495
1496 /*
1497 * Remember that we are using a pty, which might be a modem line.
1498 * Writing too much will clog the line. That's why we are doing this
1499 * dance.
1500 * FIXME: Migrate the world to Plan 9.
1501 */
1502 while (n > 0) {
1503 FD_ZERO(&wfd);
1504 FD_SET(cmdfd, &wfd);
1505 tv.tv_sec = 0;
1506 tv.tv_nsec = 0;
1507
1508 /* Check if we can write. */
1509 if (pselect(cmdfd+1, NULL, &wfd, NULL, &tv, NULL) < 0) {
1510 if (errno == EINTR)
1511 continue;
1512 die("select failed: %s\n", strerror(errno));
1513 }
1514 if(!FD_ISSET(cmdfd, &wfd)) {
1515 /* No, then free some buffer space. */
1516 ttyread();
1517 } else {
1518 /*
1519 * Only write 256 bytes at maximum. This seems to be a
1520 * reasonable value for a serial line. Bigger values
1521 * might clog the I/O.
1522 */
1523 r = write(cmdfd, s, (n < 256)? n : 256);
1524 if (r < 0) {
1525 die("write error on tty: %s\n",
1526 strerror(errno));
1527 }
1528 if (r < n) {
1529 /*
1530 * We weren't able to write out everything.
1531 * This means the buffer is getting full
1532 * again. Empty it.
1533 */
1534 if (n < 256)
1535 ttyread();
1536 n -= r;
1537 s += r;
1538 } else {
1539 /* All bytes have been written. */
1540 break;
1541 }
1542 }
1543 }
1544 }
1545
1546 void
1547 ttysend(char *s, size_t n)
1548 {
1549 int len;
1550 Rune u;
1551
1552 ttywrite(s, n);
1553 if (IS_SET(MODE_ECHO))
1554 while ((len = utf8decode(s, &u, n)) > 0) {
1555 techo(u);
1556 n -= len;
1557 s += len;
1558 }
1559 }
1560
1561 void
1562 ttyresize(void)
1563 {
1564 struct winsize w;
1565
1566 w.ws_row = term.row;
1567 w.ws_col = term.col;
1568 w.ws_xpixel = xw.tw;
1569 w.ws_ypixel = xw.th;
1570 if (ioctl(cmdfd, TIOCSWINSZ, &w) < 0)
1571 fprintf(stderr, "Couldn't set window size: %s\n", strerror(errno));
1572 }
1573
1574 int
1575 tattrset(int attr)
1576 {
1577 int i, j;
1578
1579 for (i = 0; i < term.row-1; i++) {
1580 for (j = 0; j < term.col-1; j++) {
1581 if (term.line[i][j].mode & attr)
1582 return 1;
1583 }
1584 }
1585
1586 return 0;
1587 }
1588
1589 void
1590 tsetdirt(int top, int bot)
1591 {
1592 int i;
1593
1594 LIMIT(top, 0, term.row-1);
1595 LIMIT(bot, 0, term.row-1);
1596
1597 for (i = top; i <= bot; i++)
1598 term.dirty[i] = 1;
1599 }
1600
1601 void
1602 tsetdirtattr(int attr)
1603 {
1604 int i, j;
1605
1606 for (i = 0; i < term.row-1; i++) {
1607 for (j = 0; j < term.col-1; j++) {
1608 if (term.line[i][j].mode & attr) {
1609 tsetdirt(i, i);
1610 break;
1611 }
1612 }
1613 }
1614 }
1615
1616 void
1617 tfulldirt(void)
1618 {
1619 tsetdirt(0, term.row-1);
1620 }
1621
1622 void
1623 tcursor(int mode)
1624 {
1625 static TCursor c[2];
1626 int alt = IS_SET(MODE_ALTSCREEN);
1627
1628 if (mode == CURSOR_SAVE) {
1629 c[alt] = term.c;
1630 } else if (mode == CURSOR_LOAD) {
1631 term.c = c[alt];
1632 tmoveto(c[alt].x, c[alt].y);
1633 }
1634 }
1635
1636 void
1637 treset(void)
1638 {
1639 uint i;
1640
1641 term.c = (TCursor){{
1642 .mode = ATTR_NULL,
1643 .fg = defaultfg,
1644 .bg = defaultbg
1645 }, .x = 0, .y = 0, .state = CURSOR_DEFAULT};
1646
1647 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
1648 for (i = tabspaces; i < term.col; i += tabspaces)
1649 term.tabs[i] = 1;
1650 term.top = 0;
1651 term.bot = term.row - 1;
1652 term.mode = MODE_WRAP;
1653 memset(term.trantbl, CS_USA, sizeof(term.trantbl));
1654 term.charset = 0;
1655
1656 for (i = 0; i < 2; i++) {
1657 tmoveto(0, 0);
1658 tcursor(CURSOR_SAVE);
1659 tclearregion(0, 0, term.col-1, term.row-1);
1660 tswapscreen();
1661 }
1662 }
1663
1664 void
1665 tnew(int col, int row)
1666 {
1667 term = (Term){ .c = { .attr = { .fg = defaultfg, .bg = defaultbg } } };
1668 tresize(col, row);
1669 term.numlock = 1;
1670
1671 treset();
1672 }
1673
1674 void
1675 tswapscreen(void)
1676 {
1677 Line *tmp = term.line;
1678
1679 term.line = term.alt;
1680 term.alt = tmp;
1681 term.mode ^= MODE_ALTSCREEN;
1682 tfulldirt();
1683 }
1684
1685 void
1686 tscrolldown(int orig, int n)
1687 {
1688 int i;
1689 Line temp;
1690
1691 LIMIT(n, 0, term.bot-orig+1);
1692
1693 tsetdirt(orig, term.bot-n);
1694 tclearregion(0, term.bot-n+1, term.col-1, term.bot);
1695
1696 for (i = term.bot; i >= orig+n; i--) {
1697 temp = term.line[i];
1698 term.line[i] = term.line[i-n];
1699 term.line[i-n] = temp;
1700 }
1701
1702 selscroll(orig, n);
1703 }
1704
1705 void
1706 tscrollup(int orig, int n)
1707 {
1708 int i;
1709 Line temp;
1710
1711 LIMIT(n, 0, term.bot-orig+1);
1712
1713 tclearregion(0, orig, term.col-1, orig+n-1);
1714 tsetdirt(orig+n, term.bot);
1715
1716 for (i = orig; i <= term.bot-n; i++) {
1717 temp = term.line[i];
1718 term.line[i] = term.line[i+n];
1719 term.line[i+n] = temp;
1720 }
1721
1722 selscroll(orig, -n);
1723 }
1724
1725 void
1726 selscroll(int orig, int n)
1727 {
1728 if (sel.ob.x == -1)
1729 return;
1730
1731 if (BETWEEN(sel.ob.y, orig, term.bot) || BETWEEN(sel.oe.y, orig, term.bot)) {
1732 if ((sel.ob.y += n) > term.bot || (sel.oe.y += n) < term.top) {
1733 selclear(NULL);
1734 return;
1735 }
1736 if (sel.type == SEL_RECTANGULAR) {
1737 if (sel.ob.y < term.top)
1738 sel.ob.y = term.top;
1739 if (sel.oe.y > term.bot)
1740 sel.oe.y = term.bot;
1741 } else {
1742 if (sel.ob.y < term.top) {
1743 sel.ob.y = term.top;
1744 sel.ob.x = 0;
1745 }
1746 if (sel.oe.y > term.bot) {
1747 sel.oe.y = term.bot;
1748 sel.oe.x = term.col;
1749 }
1750 }
1751 selnormalize();
1752 }
1753 }
1754
1755 void
1756 tnewline(int first_col)
1757 {
1758 int y = term.c.y;
1759
1760 if (y == term.bot) {
1761 tscrollup(term.top, 1);
1762 } else {
1763 y++;
1764 }
1765 tmoveto(first_col ? 0 : term.c.x, y);
1766 }
1767
1768 void
1769 csiparse(void)
1770 {
1771 char *p = csiescseq.buf, *np;
1772 long int v;
1773
1774 csiescseq.narg = 0;
1775 if (*p == '?') {
1776 csiescseq.priv = 1;
1777 p++;
1778 }
1779
1780 csiescseq.buf[csiescseq.len] = '\0';
1781 while (p < csiescseq.buf+csiescseq.len) {
1782 np = NULL;
1783 v = strtol(p, &np, 10);
1784 if (np == p)
1785 v = 0;
1786 if (v == LONG_MAX || v == LONG_MIN)
1787 v = -1;
1788 csiescseq.arg[csiescseq.narg++] = v;
1789 p = np;
1790 if (*p != ';' || csiescseq.narg == ESC_ARG_SIZ)
1791 break;
1792 p++;
1793 }
1794 csiescseq.mode[0] = *p++;
1795 csiescseq.mode[1] = (p < csiescseq.buf+csiescseq.len) ? *p : '\0';
1796 }
1797
1798 /* for absolute user moves, when decom is set */
1799 void
1800 tmoveato(int x, int y)
1801 {
1802 tmoveto(x, y + ((term.c.state & CURSOR_ORIGIN) ? term.top: 0));
1803 }
1804
1805 void
1806 tmoveto(int x, int y)
1807 {
1808 int miny, maxy;
1809
1810 if (term.c.state & CURSOR_ORIGIN) {
1811 miny = term.top;
1812 maxy = term.bot;
1813 } else {
1814 miny = 0;
1815 maxy = term.row - 1;
1816 }
1817 term.c.state &= ~CURSOR_WRAPNEXT;
1818 term.c.x = LIMIT(x, 0, term.col-1);
1819 term.c.y = LIMIT(y, miny, maxy);
1820 }
1821
1822 void
1823 tsetchar(Rune u, Glyph *attr, int x, int y)
1824 {
1825 static char *vt100_0[62] = { /* 0x41 - 0x7e */
1826 "↑", "↓", "→", "←", "█", "▚", "☃", /* A - G */
1827 0, 0, 0, 0, 0, 0, 0, 0, /* H - O */
1828 0, 0, 0, 0, 0, 0, 0, 0, /* P - W */
1829 0, 0, 0, 0, 0, 0, 0, " ", /* X - _ */
1830 "◆", "▒", "␉", "␌", "␍", "␊", "°", "±", /* ` - g */
1831 "␤", "␋", "┘", "┐", "┌", "└", "┼", "⎺", /* h - o */
1832 "⎻", "─", "⎼", "⎽", "├", "┤", "┴", "┬", /* p - w */
1833 "│", "≤", "≥", "π", "≠", "£", "·", /* x - ~ */
1834 };
1835
1836 /*
1837 * The table is proudly stolen from rxvt.
1838 */
1839 if (term.trantbl[term.charset] == CS_GRAPHIC0 &&
1840 BETWEEN(u, 0x41, 0x7e) && vt100_0[u - 0x41])
1841 utf8decode(vt100_0[u - 0x41], &u, UTF_SIZ);
1842
1843 if (term.line[y][x].mode & ATTR_WIDE) {
1844 if (x+1 < term.col) {
1845 term.line[y][x+1].u = ' ';
1846 term.line[y][x+1].mode &= ~ATTR_WDUMMY;
1847 }
1848 } else if (term.line[y][x].mode & ATTR_WDUMMY) {
1849 term.line[y][x-1].u = ' ';
1850 term.line[y][x-1].mode &= ~ATTR_WIDE;
1851 }
1852
1853 term.dirty[y] = 1;
1854 term.line[y][x] = *attr;
1855 term.line[y][x].u = u;
1856 }
1857
1858 void
1859 tclearregion(int x1, int y1, int x2, int y2)
1860 {
1861 int x, y, temp;
1862 Glyph *gp;
1863
1864 if (x1 > x2)
1865 temp = x1, x1 = x2, x2 = temp;
1866 if (y1 > y2)
1867 temp = y1, y1 = y2, y2 = temp;
1868
1869 LIMIT(x1, 0, term.col-1);
1870 LIMIT(x2, 0, term.col-1);
1871 LIMIT(y1, 0, term.row-1);
1872 LIMIT(y2, 0, term.row-1);
1873
1874 for (y = y1; y <= y2; y++) {
1875 term.dirty[y] = 1;
1876 for (x = x1; x <= x2; x++) {
1877 gp = &term.line[y][x];
1878 if (selected(x, y))
1879 selclear(NULL);
1880 gp->fg = term.c.attr.fg;
1881 gp->bg = term.c.attr.bg;
1882 gp->mode = 0;
1883 gp->u = ' ';
1884 }
1885 }
1886 }
1887
1888 void
1889 tdeletechar(int n)
1890 {
1891 int dst, src, size;
1892 Glyph *line;
1893
1894 LIMIT(n, 0, term.col - term.c.x);
1895
1896 dst = term.c.x;
1897 src = term.c.x + n;
1898 size = term.col - src;
1899 line = term.line[term.c.y];
1900
1901 memmove(&line[dst], &line[src], size * sizeof(Glyph));
1902 tclearregion(term.col-n, term.c.y, term.col-1, term.c.y);
1903 }
1904
1905 void
1906 tinsertblank(int n)
1907 {
1908 int dst, src, size;
1909 Glyph *line;
1910
1911 LIMIT(n, 0, term.col - term.c.x);
1912
1913 dst = term.c.x + n;
1914 src = term.c.x;
1915 size = term.col - dst;
1916 line = term.line[term.c.y];
1917
1918 memmove(&line[dst], &line[src], size * sizeof(Glyph));
1919 tclearregion(src, term.c.y, dst - 1, term.c.y);
1920 }
1921
1922 void
1923 tinsertblankline(int n)
1924 {
1925 if (BETWEEN(term.c.y, term.top, term.bot))
1926 tscrolldown(term.c.y, n);
1927 }
1928
1929 void
1930 tdeleteline(int n)
1931 {
1932 if (BETWEEN(term.c.y, term.top, term.bot))
1933 tscrollup(term.c.y, n);
1934 }
1935
1936 int32_t
1937 tdefcolor(int *attr, int *npar, int l)
1938 {
1939 int32_t idx = -1;
1940 uint r, g, b;
1941
1942 switch (attr[*npar + 1]) {
1943 case 2: /* direct color in RGB space */
1944 if (*npar + 4 >= l) {
1945 fprintf(stderr,
1946 "erresc(38): Incorrect number of parameters (%d)\n",
1947 *npar);
1948 break;
1949 }
1950 r = attr[*npar + 2];
1951 g = attr[*npar + 3];
1952 b = attr[*npar + 4];
1953 *npar += 4;
1954 if (!BETWEEN(r, 0, 255) || !BETWEEN(g, 0, 255) || !BETWEEN(b, 0, 255))
1955 fprintf(stderr, "erresc: bad rgb color (%u,%u,%u)\n",
1956 r, g, b);
1957 else
1958 idx = TRUECOLOR(r, g, b);
1959 break;
1960 case 5: /* indexed color */
1961 if (*npar + 2 >= l) {
1962 fprintf(stderr,
1963 "erresc(38): Incorrect number of parameters (%d)\n",
1964 *npar);
1965 break;
1966 }
1967 *npar += 2;
1968 if (!BETWEEN(attr[*npar], 0, 255))
1969 fprintf(stderr, "erresc: bad fgcolor %d\n", attr[*npar]);
1970 else
1971 idx = attr[*npar];
1972 break;
1973 case 0: /* implemented defined (only foreground) */
1974 case 1: /* transparent */
1975 case 3: /* direct color in CMY space */
1976 case 4: /* direct color in CMYK space */
1977 default:
1978 fprintf(stderr,
1979 "erresc(38): gfx attr %d unknown\n", attr[*npar]);
1980 break;
1981 }
1982
1983 return idx;
1984 }
1985
1986 void
1987 tsetattr(int *attr, int l)
1988 {
1989 int i;
1990 int32_t idx;
1991
1992 for (i = 0; i < l; i++) {
1993 switch (attr[i]) {
1994 case 0:
1995 term.c.attr.mode &= ~(
1996 ATTR_BOLD |
1997 ATTR_FAINT |
1998 ATTR_ITALIC |
1999 ATTR_UNDERLINE |
2000 ATTR_BLINK |
2001 ATTR_REVERSE |
2002 ATTR_INVISIBLE |
2003 ATTR_STRUCK );
2004 term.c.attr.fg = defaultfg;
2005 term.c.attr.bg = defaultbg;
2006 break;
2007 case 1:
2008 term.c.attr.mode |= ATTR_BOLD;
2009 break;
2010 case 2:
2011 term.c.attr.mode |= ATTR_FAINT;
2012 break;
2013 case 3:
2014 term.c.attr.mode |= ATTR_ITALIC;
2015 break;
2016 case 4:
2017 term.c.attr.mode |= ATTR_UNDERLINE;
2018 break;
2019 case 5: /* slow blink */
2020 /* FALLTHROUGH */
2021 case 6: /* rapid blink */
2022 term.c.attr.mode |= ATTR_BLINK;
2023 break;
2024 case 7:
2025 term.c.attr.mode |= ATTR_REVERSE;
2026 break;
2027 case 8:
2028 term.c.attr.mode |= ATTR_INVISIBLE;
2029 break;
2030 case 9:
2031 term.c.attr.mode |= ATTR_STRUCK;
2032 break;
2033 case 22:
2034 term.c.attr.mode &= ~(ATTR_BOLD | ATTR_FAINT);
2035 break;
2036 case 23:
2037 term.c.attr.mode &= ~ATTR_ITALIC;
2038 break;
2039 case 24:
2040 term.c.attr.mode &= ~ATTR_UNDERLINE;
2041 break;
2042 case 25:
2043 term.c.attr.mode &= ~ATTR_BLINK;
2044 break;
2045 case 27:
2046 term.c.attr.mode &= ~ATTR_REVERSE;
2047 break;
2048 case 28:
2049 term.c.attr.mode &= ~ATTR_INVISIBLE;
2050 break;
2051 case 29:
2052 term.c.attr.mode &= ~ATTR_STRUCK;
2053 break;
2054 case 38:
2055 if ((idx = tdefcolor(attr, &i, l)) >= 0)
2056 term.c.attr.fg = idx;
2057 break;
2058 case 39:
2059 term.c.attr.fg = defaultfg;
2060 break;
2061 case 48:
2062 if ((idx = tdefcolor(attr, &i, l)) >= 0)
2063 term.c.attr.bg = idx;
2064 break;
2065 case 49:
2066 term.c.attr.bg = defaultbg;
2067 break;
2068 default:
2069 if (BETWEEN(attr[i], 30, 37)) {
2070 term.c.attr.fg = attr[i] - 30;
2071 } else if (BETWEEN(attr[i], 40, 47)) {
2072 term.c.attr.bg = attr[i] - 40;
2073 } else if (BETWEEN(attr[i], 90, 97)) {
2074 term.c.attr.fg = attr[i] - 90 + 8;
2075 } else if (BETWEEN(attr[i], 100, 107)) {
2076 term.c.attr.bg = attr[i] - 100 + 8;
2077 } else {
2078 fprintf(stderr,
2079 "erresc(default): gfx attr %d unknown\n",
2080 attr[i]), csidump();
2081 }
2082 break;
2083 }
2084 }
2085 }
2086
2087 void
2088 tsetscroll(int t, int b)
2089 {
2090 int temp;
2091
2092 LIMIT(t, 0, term.row-1);
2093 LIMIT(b, 0, term.row-1);
2094 if (t > b) {
2095 temp = t;
2096 t = b;
2097 b = temp;
2098 }
2099 term.top = t;
2100 term.bot = b;
2101 }
2102
2103 void
2104 tsetmode(int priv, int set, int *args, int narg)
2105 {
2106 int *lim, mode;
2107 int alt;
2108
2109 for (lim = args + narg; args < lim; ++args) {
2110 if (priv) {
2111 switch (*args) {
2112 case 1: /* DECCKM -- Cursor key */
2113 MODBIT(term.mode, set, MODE_APPCURSOR);
2114 break;
2115 case 5: /* DECSCNM -- Reverse video */
2116 mode = term.mode;
2117 MODBIT(term.mode, set, MODE_REVERSE);
2118 if (mode != term.mode)
2119 redraw();
2120 break;
2121 case 6: /* DECOM -- Origin */
2122 MODBIT(term.c.state, set, CURSOR_ORIGIN);
2123 tmoveato(0, 0);
2124 break;
2125 case 7: /* DECAWM -- Auto wrap */
2126 MODBIT(term.mode, set, MODE_WRAP);
2127 break;
2128 case 0: /* Error (IGNORED) */
2129 case 2: /* DECANM -- ANSI/VT52 (IGNORED) */
2130 case 3: /* DECCOLM -- Column (IGNORED) */
2131 case 4: /* DECSCLM -- Scroll (IGNORED) */
2132 case 8: /* DECARM -- Auto repeat (IGNORED) */
2133 case 18: /* DECPFF -- Printer feed (IGNORED) */
2134 case 19: /* DECPEX -- Printer extent (IGNORED) */
2135 case 42: /* DECNRCM -- National characters (IGNORED) */
2136 case 12: /* att610 -- Start blinking cursor (IGNORED) */
2137 break;
2138 case 25: /* DECTCEM -- Text Cursor Enable Mode */
2139 MODBIT(term.mode, !set, MODE_HIDE);
2140 break;
2141 case 9: /* X10 mouse compatibility mode */
2142 xsetpointermotion(0);
2143 MODBIT(term.mode, 0, MODE_MOUSE);
2144 MODBIT(term.mode, set, MODE_MOUSEX10);
2145 break;
2146 case 1000: /* 1000: report button press */
2147 xsetpointermotion(0);
2148 MODBIT(term.mode, 0, MODE_MOUSE);
2149 MODBIT(term.mode, set, MODE_MOUSEBTN);
2150 break;
2151 case 1002: /* 1002: report motion on button press */
2152 xsetpointermotion(0);
2153 MODBIT(term.mode, 0, MODE_MOUSE);
2154 MODBIT(term.mode, set, MODE_MOUSEMOTION);
2155 break;
2156 case 1003: /* 1003: enable all mouse motions */
2157 xsetpointermotion(set);
2158 MODBIT(term.mode, 0, MODE_MOUSE);
2159 MODBIT(term.mode, set, MODE_MOUSEMANY);
2160 break;
2161 case 1004: /* 1004: send focus events to tty */
2162 MODBIT(term.mode, set, MODE_FOCUS);
2163 break;
2164 case 1006: /* 1006: extended reporting mode */
2165 MODBIT(term.mode, set, MODE_MOUSESGR);
2166 break;
2167 case 1034:
2168 MODBIT(term.mode, set, MODE_8BIT);
2169 break;
2170 case 1049: /* swap screen & set/restore cursor as xterm */
2171 if (!allowaltscreen)
2172 break;
2173 tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
2174 /* FALLTHROUGH */
2175 case 47: /* swap screen */
2176 case 1047:
2177 if (!allowaltscreen)
2178 break;
2179 alt = IS_SET(MODE_ALTSCREEN);
2180 if (alt) {
2181 tclearregion(0, 0, term.col-1,
2182 term.row-1);
2183 }
2184 if (set ^ alt) /* set is always 1 or 0 */
2185 tswapscreen();
2186 if (*args != 1049)
2187 break;
2188 /* FALLTHROUGH */
2189 case 1048:
2190 tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
2191 break;
2192 case 2004: /* 2004: bracketed paste mode */
2193 MODBIT(term.mode, set, MODE_BRCKTPASTE);
2194 break;
2195 /* Not implemented mouse modes. See comments there. */
2196 case 1001: /* mouse highlight mode; can hang the
2197 terminal by design when implemented. */
2198 case 1005: /* UTF-8 mouse mode; will confuse
2199 applications not supporting UTF-8
2200 and luit. */
2201 case 1015: /* urxvt mangled mouse mode; incompatible
2202 and can be mistaken for other control
2203 codes. */
2204 default:
2205 fprintf(stderr,
2206 "erresc: unknown private set/reset mode %d\n",
2207 *args);
2208 break;
2209 }
2210 } else {
2211 switch (*args) {
2212 case 0: /* Error (IGNORED) */
2213 break;
2214 case 2: /* KAM -- keyboard action */
2215 MODBIT(term.mode, set, MODE_KBDLOCK);
2216 break;
2217 case 4: /* IRM -- Insertion-replacement */
2218 MODBIT(term.mode, set, MODE_INSERT);
2219 break;
2220 case 12: /* SRM -- Send/Receive */
2221 MODBIT(term.mode, !set, MODE_ECHO);
2222 break;
2223 case 20: /* LNM -- Linefeed/new line */
2224 MODBIT(term.mode, set, MODE_CRLF);
2225 break;
2226 default:
2227 fprintf(stderr,
2228 "erresc: unknown set/reset mode %d\n",
2229 *args);
2230 break;
2231 }
2232 }
2233 }
2234 }
2235
2236 void
2237 csihandle(void)
2238 {
2239 char buf[40];
2240 int len;
2241
2242 switch (csiescseq.mode[0]) {
2243 default:
2244 unknown:
2245 fprintf(stderr, "erresc: unknown csi ");
2246 csidump();
2247 /* die(""); */
2248 break;
2249 case '@': /* ICH -- Insert <n> blank char */
2250 DEFAULT(csiescseq.arg[0], 1);
2251 tinsertblank(csiescseq.arg[0]);
2252 break;
2253 case 'A': /* CUU -- Cursor <n> Up */
2254 DEFAULT(csiescseq.arg[0], 1);
2255 tmoveto(term.c.x, term.c.y-csiescseq.arg[0]);
2256 break;
2257 case 'B': /* CUD -- Cursor <n> Down */
2258 case 'e': /* VPR --Cursor <n> Down */
2259 DEFAULT(csiescseq.arg[0], 1);
2260 tmoveto(term.c.x, term.c.y+csiescseq.arg[0]);
2261 break;
2262 case 'i': /* MC -- Media Copy */
2263 switch (csiescseq.arg[0]) {
2264 case 0:
2265 tdump();
2266 break;
2267 case 1:
2268 tdumpline(term.c.y);
2269 break;
2270 case 2:
2271 tdumpsel();
2272 break;
2273 case 4:
2274 term.mode &= ~MODE_PRINT;
2275 break;
2276 case 5:
2277 term.mode |= MODE_PRINT;
2278 break;
2279 }
2280 break;
2281 case 'c': /* DA -- Device Attributes */
2282 if (csiescseq.arg[0] == 0)
2283 ttywrite(vtiden, sizeof(vtiden) - 1);
2284 break;
2285 case 'C': /* CUF -- Cursor <n> Forward */
2286 case 'a': /* HPR -- Cursor <n> Forward */
2287 DEFAULT(csiescseq.arg[0], 1);
2288 tmoveto(term.c.x+csiescseq.arg[0], term.c.y);
2289 break;
2290 case 'D': /* CUB -- Cursor <n> Backward */
2291 DEFAULT(csiescseq.arg[0], 1);
2292 tmoveto(term.c.x-csiescseq.arg[0], term.c.y);
2293 break;
2294 case 'E': /* CNL -- Cursor <n> Down and first col */
2295 DEFAULT(csiescseq.arg[0], 1);
2296 tmoveto(0, term.c.y+csiescseq.arg[0]);
2297 break;
2298 case 'F': /* CPL -- Cursor <n> Up and first col */
2299 DEFAULT(csiescseq.arg[0], 1);
2300 tmoveto(0, term.c.y-csiescseq.arg[0]);
2301 break;
2302 case 'g': /* TBC -- Tabulation clear */
2303 switch (csiescseq.arg[0]) {
2304 case 0: /* clear current tab stop */
2305 term.tabs[term.c.x] = 0;
2306 break;
2307 case 3: /* clear all the tabs */
2308 memset(term.tabs, 0, term.col * sizeof(*term.tabs));
2309 break;
2310 default:
2311 goto unknown;
2312 }
2313 break;
2314 case 'G': /* CHA -- Move to <col> */
2315 case '`': /* HPA */
2316 DEFAULT(csiescseq.arg[0], 1);
2317 tmoveto(csiescseq.arg[0]-1, term.c.y);
2318 break;
2319 case 'H': /* CUP -- Move to <row> <col> */
2320 case 'f': /* HVP */
2321 DEFAULT(csiescseq.arg[0], 1);
2322 DEFAULT(csiescseq.arg[1], 1);
2323 tmoveato(csiescseq.arg[1]-1, csiescseq.arg[0]-1);
2324 break;
2325 case 'I': /* CHT -- Cursor Forward Tabulation <n> tab stops */
2326 DEFAULT(csiescseq.arg[0], 1);
2327 tputtab(csiescseq.arg[0]);
2328 break;
2329 case 'J': /* ED -- Clear screen */
2330 selclear(NULL);
2331 switch (csiescseq.arg[0]) {
2332 case 0: /* below */
2333 tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
2334 if (term.c.y < term.row-1) {
2335 tclearregion(0, term.c.y+1, term.col-1,
2336 term.row-1);
2337 }
2338 break;
2339 case 1: /* above */
2340 if (term.c.y > 1)
2341 tclearregion(0, 0, term.col-1, term.c.y-1);
2342 tclearregion(0, term.c.y, term.c.x, term.c.y);
2343 break;
2344 case 2: /* all */
2345 tclearregion(0, 0, term.col-1, term.row-1);
2346 break;
2347 default:
2348 goto unknown;
2349 }
2350 break;
2351 case 'K': /* EL -- Clear line */
2352 switch (csiescseq.arg[0]) {
2353 case 0: /* right */
2354 tclearregion(term.c.x, term.c.y, term.col-1,
2355 term.c.y);
2356 break;
2357 case 1: /* left */
2358 tclearregion(0, term.c.y, term.c.x, term.c.y);
2359 break;
2360 case 2: /* all */
2361 tclearregion(0, term.c.y, term.col-1, term.c.y);
2362 break;
2363 }
2364 break;
2365 case 'S': /* SU -- Scroll <n> line up */
2366 DEFAULT(csiescseq.arg[0], 1);
2367 tscrollup(term.top, csiescseq.arg[0]);
2368 break;
2369 case 'T': /* SD -- Scroll <n> line down */
2370 DEFAULT(csiescseq.arg[0], 1);
2371 tscrolldown(term.top, csiescseq.arg[0]);
2372 break;
2373 case 'L': /* IL -- Insert <n> blank lines */
2374 DEFAULT(csiescseq.arg[0], 1);
2375 tinsertblankline(csiescseq.arg[0]);
2376 break;
2377 case 'l': /* RM -- Reset Mode */
2378 tsetmode(csiescseq.priv, 0, csiescseq.arg, csiescseq.narg);
2379 break;
2380 case 'M': /* DL -- Delete <n> lines */
2381 DEFAULT(csiescseq.arg[0], 1);
2382 tdeleteline(csiescseq.arg[0]);
2383 break;
2384 case 'X': /* ECH -- Erase <n> char */
2385 DEFAULT(csiescseq.arg[0], 1);
2386 tclearregion(term.c.x, term.c.y,
2387 term.c.x + csiescseq.arg[0] - 1, term.c.y);
2388 break;
2389 case 'P': /* DCH -- Delete <n> char */
2390 DEFAULT(csiescseq.arg[0], 1);
2391 tdeletechar(csiescseq.arg[0]);
2392 break;
2393 case 'Z': /* CBT -- Cursor Backward Tabulation <n> tab stops */
2394 DEFAULT(csiescseq.arg[0], 1);
2395 tputtab(-csiescseq.arg[0]);
2396 break;
2397 case 'd': /* VPA -- Move to <row> */
2398 DEFAULT(csiescseq.arg[0], 1);
2399 tmoveato(term.c.x, csiescseq.arg[0]-1);
2400 break;
2401 case 'h': /* SM -- Set terminal mode */
2402 tsetmode(csiescseq.priv, 1, csiescseq.arg, csiescseq.narg);
2403 break;
2404 case 'm': /* SGR -- Terminal attribute (color) */
2405 tsetattr(csiescseq.arg, csiescseq.narg);
2406 break;
2407 case 'n': /* DSR – Device Status Report (cursor position) */
2408 if (csiescseq.arg[0] == 6) {
2409 len = snprintf(buf, sizeof(buf),"\033[%i;%iR",
2410 term.c.y+1, term.c.x+1);
2411 ttywrite(buf, len);
2412 }
2413 break;
2414 case 'r': /* DECSTBM -- Set Scrolling Region */
2415 if (csiescseq.priv) {
2416 goto unknown;
2417 } else {
2418 DEFAULT(csiescseq.arg[0], 1);
2419 DEFAULT(csiescseq.arg[1], term.row);
2420 tsetscroll(csiescseq.arg[0]-1, csiescseq.arg[1]-1);
2421 tmoveato(0, 0);
2422 }
2423 break;
2424 case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
2425 tcursor(CURSOR_SAVE);
2426 break;
2427 case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
2428 tcursor(CURSOR_LOAD);
2429 break;
2430 case ' ':
2431 switch (csiescseq.mode[1]) {
2432 case 'q': /* DECSCUSR -- Set Cursor Style */
2433 DEFAULT(csiescseq.arg[0], 1);
2434 if (!BETWEEN(csiescseq.arg[0], 0, 6)) {
2435 goto unknown;
2436 }
2437 xw.cursor = csiescseq.arg[0];
2438 break;
2439 default:
2440 goto unknown;
2441 }
2442 break;
2443 }
2444 }
2445
2446 void
2447 csidump(void)
2448 {
2449 int i;
2450 uint c;
2451
2452 printf("ESC[");
2453 for (i = 0; i < csiescseq.len; i++) {
2454 c = csiescseq.buf[i] & 0xff;
2455 if (isprint(c)) {
2456 putchar(c);
2457 } else if (c == '\n') {
2458 printf("(\\n)");
2459 } else if (c == '\r') {
2460 printf("(\\r)");
2461 } else if (c == 0x1b) {
2462 printf("(\\e)");
2463 } else {
2464 printf("(%02x)", c);
2465 }
2466 }
2467 putchar('\n');
2468 }
2469
2470 void
2471 csireset(void)
2472 {
2473 memset(&csiescseq, 0, sizeof(csiescseq));
2474 }
2475
2476 void
2477 strhandle(void)
2478 {
2479 char *p = NULL;
2480 int j, narg, par;
2481
2482 term.esc &= ~(ESC_STR_END|ESC_STR);
2483 strparse();
2484 par = (narg = strescseq.narg) ? atoi(strescseq.args[0]) : 0;
2485
2486 switch (strescseq.type) {
2487 case ']': /* OSC -- Operating System Command */
2488 switch (par) {
2489 case 0:
2490 case 1:
2491 case 2:
2492 if (narg > 1)
2493 xsettitle(strescseq.args[1]);
2494 return;
2495 case 4: /* color set */
2496 if (narg < 3)
2497 break;
2498 p = strescseq.args[2];
2499 /* FALLTHROUGH */
2500 case 104: /* color reset, here p = NULL */
2501 j = (narg > 1) ? atoi(strescseq.args[1]) : -1;
2502 if (xsetcolorname(j, p)) {
2503 fprintf(stderr, "erresc: invalid color %s\n", p);
2504 } else {
2505 /*
2506 * TODO if defaultbg color is changed, borders
2507 * are dirty
2508 */
2509 redraw();
2510 }
2511 return;
2512 }
2513 break;
2514 case 'k': /* old title set compatibility */
2515 xsettitle(strescseq.args[0]);
2516 return;
2517 case 'P': /* DCS -- Device Control String */
2518 case '_': /* APC -- Application Program Command */
2519 case '^': /* PM -- Privacy Message */
2520 return;
2521 }
2522
2523 fprintf(stderr, "erresc: unknown str ");
2524 strdump();
2525 }
2526
2527 void
2528 strparse(void)
2529 {
2530 int c;
2531 char *p = strescseq.buf;
2532
2533 strescseq.narg = 0;
2534 strescseq.buf[strescseq.len] = '\0';
2535
2536 if (*p == '\0')
2537 return;
2538
2539 while (strescseq.narg < STR_ARG_SIZ) {
2540 strescseq.args[strescseq.narg++] = p;
2541 while ((c = *p) != ';' && c != '\0')
2542 ++p;
2543 if (c == '\0')
2544 return;
2545 *p++ = '\0';
2546 }
2547 }
2548
2549 void
2550 strdump(void)
2551 {
2552 int i;
2553 uint c;
2554
2555 printf("ESC%c", strescseq.type);
2556 for (i = 0; i < strescseq.len; i++) {
2557 c = strescseq.buf[i] & 0xff;
2558 if (c == '\0') {
2559 return;
2560 } else if (isprint(c)) {
2561 putchar(c);
2562 } else if (c == '\n') {
2563 printf("(\\n)");
2564 } else if (c == '\r') {
2565 printf("(\\r)");
2566 } else if (c == 0x1b) {
2567 printf("(\\e)");
2568 } else {
2569 printf("(%02x)", c);
2570 }
2571 }
2572 printf("ESC\\\n");
2573 }
2574
2575 void
2576 strreset(void)
2577 {
2578 memset(&strescseq, 0, sizeof(strescseq));
2579 }
2580
2581 void
2582 tprinter(char *s, size_t len)
2583 {
2584 if (iofd != -1 && xwrite(iofd, s, len) < 0) {
2585 fprintf(stderr, "Error writing in %s:%s\n",
2586 opt_io, strerror(errno));
2587 close(iofd);
2588 iofd = -1;
2589 }
2590 }
2591
2592 void
2593 toggleprinter(const Arg *arg)
2594 {
2595 term.mode ^= MODE_PRINT;
2596 }
2597
2598 void
2599 printscreen(const Arg *arg)
2600 {
2601 tdump();
2602 }
2603
2604 void
2605 printsel(const Arg *arg)
2606 {
2607 tdumpsel();
2608 }
2609
2610 void
2611 tdumpsel(void)
2612 {
2613 char *ptr;
2614
2615 if ((ptr = getsel())) {
2616 tprinter(ptr, strlen(ptr));
2617 free(ptr);
2618 }
2619 }
2620
2621 void
2622 tdumpline(int n)
2623 {
2624 char buf[UTF_SIZ];
2625 Glyph *bp, *end;
2626
2627 bp = &term.line[n][0];
2628 end = &bp[MIN(tlinelen(n), term.col) - 1];
2629 if (bp != end || bp->u != ' ') {
2630 for ( ;bp <= end; ++bp)
2631 tprinter(buf, utf8encode(bp->u, buf));
2632 }
2633 tprinter("\n", 1);
2634 }
2635
2636 void
2637 tdump(void)
2638 {
2639 int i;
2640
2641 for (i = 0; i < term.row; ++i)
2642 tdumpline(i);
2643 }
2644
2645 void
2646 tputtab(int n)
2647 {
2648 uint x = term.c.x;
2649
2650 if (n > 0) {
2651 while (x < term.col && n--)
2652 for (++x; x < term.col && !term.tabs[x]; ++x)
2653 /* nothing */ ;
2654 } else if (n < 0) {
2655 while (x > 0 && n++)
2656 for (--x; x > 0 && !term.tabs[x]; --x)
2657 /* nothing */ ;
2658 }
2659 term.c.x = LIMIT(x, 0, term.col-1);
2660 }
2661
2662 void
2663 techo(Rune u)
2664 {
2665 if (ISCONTROL(u)) { /* control code */
2666 if (u & 0x80) {
2667 u &= 0x7f;
2668 tputc('^');
2669 tputc('[');
2670 } else if (u != '\n' && u != '\r' && u != '\t') {
2671 u ^= 0x40;
2672 tputc('^');
2673 }
2674 }
2675 tputc(u);
2676 }
2677
2678 void
2679 tdeftran(char ascii)
2680 {
2681 static char cs[] = "0B";
2682 static int vcs[] = {CS_GRAPHIC0, CS_USA};
2683 char *p;
2684
2685 if ((p = strchr(cs, ascii)) == NULL) {
2686 fprintf(stderr, "esc unhandled charset: ESC ( %c\n", ascii);
2687 } else {
2688 term.trantbl[term.icharset] = vcs[p - cs];
2689 }
2690 }
2691
2692 void
2693 tdectest(char c)
2694 {
2695 int x, y;
2696
2697 if (c == '8') { /* DEC screen alignment test. */
2698 for (x = 0; x < term.col; ++x) {
2699 for (y = 0; y < term.row; ++y)
2700 tsetchar('E', &term.c.attr, x, y);
2701 }
2702 }
2703 }
2704
2705 void
2706 tstrsequence(uchar c)
2707 {
2708 switch (c) {
2709 case 0x90: /* DCS -- Device Control String */
2710 c = 'P';
2711 break;
2712 case 0x9f: /* APC -- Application Program Command */
2713 c = '_';
2714 break;
2715 case 0x9e: /* PM -- Privacy Message */
2716 c = '^';
2717 break;
2718 case 0x9d: /* OSC -- Operating System Command */
2719 c = ']';
2720 break;
2721 }
2722 strreset();
2723 strescseq.type = c;
2724 term.esc |= ESC_STR;
2725 }
2726
2727 void
2728 tcontrolcode(uchar ascii)
2729 {
2730 switch (ascii) {
2731 case '\t': /* HT */
2732 tputtab(1);
2733 return;
2734 case '\b': /* BS */
2735 tmoveto(term.c.x-1, term.c.y);
2736 return;
2737 case '\r': /* CR */
2738 tmoveto(0, term.c.y);
2739 return;
2740 case '\f': /* LF */
2741 case '\v': /* VT */
2742 case '\n': /* LF */
2743 /* go to first col if the mode is set */
2744 tnewline(IS_SET(MODE_CRLF));
2745 return;
2746 case '\a': /* BEL */
2747 if (term.esc & ESC_STR_END) {
2748 /* backwards compatibility to xterm */
2749 strhandle();
2750 } else {
2751 if (!(xw.state & WIN_FOCUSED))
2752 xseturgency(1);
2753 if (bellvolume)
2754 XkbBell(xw.dpy, xw.win, bellvolume, (Atom)NULL);
2755 }
2756 break;
2757 case '\033': /* ESC */
2758 csireset();
2759 term.esc &= ~(ESC_CSI|ESC_ALTCHARSET|ESC_TEST);
2760 term.esc |= ESC_START;
2761 return;
2762 case '\016': /* SO (LS1 -- Locking shift 1) */
2763 case '\017': /* SI (LS0 -- Locking shift 0) */
2764 term.charset = 1 - (ascii - '\016');
2765 return;
2766 case '\032': /* SUB */
2767 tsetchar('?', &term.c.attr, term.c.x, term.c.y);
2768 case '\030': /* CAN */
2769 csireset();
2770 break;
2771 case '\005': /* ENQ (IGNORED) */
2772 case '\000': /* NUL (IGNORED) */
2773 case '\021': /* XON (IGNORED) */
2774 case '\023': /* XOFF (IGNORED) */
2775 case 0177: /* DEL (IGNORED) */
2776 return;
2777 case 0x84: /* TODO: IND */
2778 break;
2779 case 0x85: /* NEL -- Next line */
2780 tnewline(1); /* always go to first col */
2781 break;
2782 case 0x88: /* HTS -- Horizontal tab stop */
2783 term.tabs[term.c.x] = 1;
2784 break;
2785 case 0x8d: /* TODO: RI */
2786 case 0x8e: /* TODO: SS2 */
2787 case 0x8f: /* TODO: SS3 */
2788 case 0x98: /* TODO: SOS */
2789 break;
2790 case 0x9a: /* DECID -- Identify Terminal */
2791 ttywrite(vtiden, sizeof(vtiden) - 1);
2792 break;
2793 case 0x9b: /* TODO: CSI */
2794 case 0x9c: /* TODO: ST */
2795 break;
2796 case 0x90: /* DCS -- Device Control String */
2797 case 0x9f: /* APC -- Application Program Command */
2798 case 0x9e: /* PM -- Privacy Message */
2799 case 0x9d: /* OSC -- Operating System Command */
2800 tstrsequence(ascii);
2801 return;
2802 }
2803 /* only CAN, SUB, \a and C1 chars interrupt a sequence */
2804 term.esc &= ~(ESC_STR_END|ESC_STR);
2805 }
2806
2807 /*
2808 * returns 1 when the sequence is finished and it hasn't to read
2809 * more characters for this sequence, otherwise 0
2810 */
2811 int
2812 eschandle(uchar ascii)
2813 {
2814 switch (ascii) {
2815 case '[':
2816 term.esc |= ESC_CSI;
2817 return 0;
2818 case '#':
2819 term.esc |= ESC_TEST;
2820 return 0;
2821 case 'P': /* DCS -- Device Control String */
2822 case '_': /* APC -- Application Program Command */
2823 case '^': /* PM -- Privacy Message */
2824 case ']': /* OSC -- Operating System Command */
2825 case 'k': /* old title set compatibility */
2826 tstrsequence(ascii);
2827 return 0;
2828 case 'n': /* LS2 -- Locking shift 2 */
2829 case 'o': /* LS3 -- Locking shift 3 */
2830 term.charset = 2 + (ascii - 'n');
2831 break;
2832 case '(': /* GZD4 -- set primary charset G0 */
2833 case ')': /* G1D4 -- set secondary charset G1 */
2834 case '*': /* G2D4 -- set tertiary charset G2 */
2835 case '+': /* G3D4 -- set quaternary charset G3 */
2836 term.icharset = ascii - '(';
2837 term.esc |= ESC_ALTCHARSET;
2838 return 0;
2839 case 'D': /* IND -- Linefeed */
2840 if (term.c.y == term.bot) {
2841 tscrollup(term.top, 1);
2842 } else {
2843 tmoveto(term.c.x, term.c.y+1);
2844 }
2845 break;
2846 case 'E': /* NEL -- Next line */
2847 tnewline(1); /* always go to first col */
2848 break;
2849 case 'H': /* HTS -- Horizontal tab stop */
2850 term.tabs[term.c.x] = 1;
2851 break;
2852 case 'M': /* RI -- Reverse index */
2853 if (term.c.y == term.top) {
2854 tscrolldown(term.top, 1);
2855 } else {
2856 tmoveto(term.c.x, term.c.y-1);
2857 }
2858 break;
2859 case 'Z': /* DECID -- Identify Terminal */
2860 ttywrite(vtiden, sizeof(vtiden) - 1);
2861 break;
2862 case 'c': /* RIS -- Reset to inital state */
2863 treset();
2864 xresettitle();
2865 xloadcols();
2866 break;
2867 case '=': /* DECPAM -- Application keypad */
2868 term.mode |= MODE_APPKEYPAD;
2869 break;
2870 case '>': /* DECPNM -- Normal keypad */
2871 term.mode &= ~MODE_APPKEYPAD;
2872 break;
2873 case '7': /* DECSC -- Save Cursor */
2874 tcursor(CURSOR_SAVE);
2875 break;
2876 case '8': /* DECRC -- Restore Cursor */
2877 tcursor(CURSOR_LOAD);
2878 break;
2879 case '\\': /* ST -- String Terminator */
2880 if (term.esc & ESC_STR_END)
2881 strhandle();
2882 break;
2883 default:
2884 fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n",
2885 (uchar) ascii, isprint(ascii)? ascii:'.');
2886 break;
2887 }
2888 return 1;
2889 }
2890
2891 void
2892 tputc(Rune u)
2893 {
2894 char c[UTF_SIZ];
2895 int control;
2896 int width, len;
2897 Glyph *gp;
2898
2899 len = utf8encode(u, c);
2900 if ((width = wcwidth(u)) == -1) {
2901 memcpy(c, "\357\277\275", 4); /* UTF_INVALID */
2902 width = 1;
2903 }
2904
2905 if (IS_SET(MODE_PRINT))
2906 tprinter(c, len);
2907 control = ISCONTROL(u);
2908
2909 /*
2910 * STR sequence must be checked before anything else
2911 * because it uses all following characters until it
2912 * receives a ESC, a SUB, a ST or any other C1 control
2913 * character.
2914 */
2915 if (term.esc & ESC_STR) {
2916 if (u == '\a' || u == 030 || u == 032 || u == 033 ||
2917 ISCONTROLC1(u)) {
2918 term.esc &= ~(ESC_START|ESC_STR);
2919 term.esc |= ESC_STR_END;
2920 } else if (strescseq.len + len < sizeof(strescseq.buf) - 1) {
2921 memmove(&strescseq.buf[strescseq.len], c, len);
2922 strescseq.len += len;
2923 return;
2924 } else {
2925 /*
2926 * Here is a bug in terminals. If the user never sends
2927 * some code to stop the str or esc command, then st
2928 * will stop responding. But this is better than
2929 * silently failing with unknown characters. At least
2930 * then users will report back.
2931 *
2932 * In the case users ever get fixed, here is the code:
2933 */
2934 /*
2935 * term.esc = 0;
2936 * strhandle();
2937 */
2938 return;
2939 }
2940 }
2941
2942 /*
2943 * Actions of control codes must be performed as soon they arrive
2944 * because they can be embedded inside a control sequence, and
2945 * they must not cause conflicts with sequences.
2946 */
2947 if (control) {
2948 tcontrolcode(u);
2949 /*
2950 * control codes are not shown ever
2951 */
2952 return;
2953 } else if (term.esc & ESC_START) {
2954 if (term.esc & ESC_CSI) {
2955 csiescseq.buf[csiescseq.len++] = u;
2956 if (BETWEEN(u, 0x40, 0x7E)
2957 || csiescseq.len >= \
2958 sizeof(csiescseq.buf)-1) {
2959 term.esc = 0;
2960 csiparse();
2961 csihandle();
2962 }
2963 return;
2964 } else if (term.esc & ESC_ALTCHARSET) {
2965 tdeftran(u);
2966 } else if (term.esc & ESC_TEST) {
2967 tdectest(u);
2968 } else {
2969 if (!eschandle(u))
2970 return;
2971 /* sequence already finished */
2972 }
2973 term.esc = 0;
2974 /*
2975 * All characters which form part of a sequence are not
2976 * printed
2977 */
2978 return;
2979 }
2980 if (sel.ob.x != -1 && BETWEEN(term.c.y, sel.ob.y, sel.oe.y))
2981 selclear(NULL);
2982
2983 gp = &term.line[term.c.y][term.c.x];
2984 if (IS_SET(MODE_WRAP) && (term.c.state & CURSOR_WRAPNEXT)) {
2985 gp->mode |= ATTR_WRAP;
2986 tnewline(1);
2987 gp = &term.line[term.c.y][term.c.x];
2988 }
2989
2990 if (IS_SET(MODE_INSERT) && term.c.x+width < term.col)
2991 memmove(gp+width, gp, (term.col - term.c.x - width) * sizeof(Glyph));
2992
2993 if (term.c.x+width > term.col) {
2994 tnewline(1);
2995 gp = &term.line[term.c.y][term.c.x];
2996 }
2997
2998 tsetchar(u, &term.c.attr, term.c.x, term.c.y);
2999
3000 if (width == 2) {
3001 gp->mode |= ATTR_WIDE;
3002 if (term.c.x+1 < term.col) {
3003 gp[1].u = '\0';
3004 gp[1].mode = ATTR_WDUMMY;
3005 }
3006 }
3007 if (term.c.x+width < term.col) {
3008 tmoveto(term.c.x+width, term.c.y);
3009 } else {
3010 term.c.state |= CURSOR_WRAPNEXT;
3011 }
3012 }
3013
3014 void
3015 tresize(int col, int row)
3016 {
3017 int i;
3018 int minrow = MIN(row, term.row);
3019 int mincol = MIN(col, term.col);
3020 int *bp;
3021 TCursor c;
3022
3023 if (col < 1 || row < 1) {
3024 fprintf(stderr,
3025 "tresize: error resizing to %dx%d\n", col, row);
3026 return;
3027 }
3028
3029 /*
3030 * slide screen to keep cursor where we expect it -
3031 * tscrollup would work here, but we can optimize to
3032 * memmove because we're freeing the earlier lines
3033 */
3034 for (i = 0; i <= term.c.y - row; i++) {
3035 free(term.line[i]);
3036 free(term.alt[i]);
3037 }
3038 /* ensure that both src and dst are not NULL */
3039 if (i > 0) {
3040 memmove(term.line, term.line + i, row * sizeof(Line));
3041 memmove(term.alt, term.alt + i, row * sizeof(Line));
3042 }
3043 for (i += row; i < term.row; i++) {
3044 free(term.line[i]);
3045 free(term.alt[i]);
3046 }
3047
3048 /* resize to new width */
3049 term.specbuf = xrealloc(term.specbuf, col * sizeof(XftGlyphFontSpec));
3050
3051 /* resize to new height */
3052 term.line = xrealloc(term.line, row * sizeof(Line));
3053 term.alt = xrealloc(term.alt, row * sizeof(Line));
3054 term.dirty = xrealloc(term.dirty, row * sizeof(*term.dirty));
3055 term.tabs = xrealloc(term.tabs, col * sizeof(*term.tabs));
3056
3057 /* resize each row to new width, zero-pad if needed */
3058 for (i = 0; i < minrow; i++) {
3059 term.line[i] = xrealloc(term.line[i], col * sizeof(Glyph));
3060 term.alt[i] = xrealloc(term.alt[i], col * sizeof(Glyph));
3061 }
3062
3063 /* allocate any new rows */
3064 for (/* i == minrow */; i < row; i++) {
3065 term.line[i] = xmalloc(col * sizeof(Glyph));
3066 term.alt[i] = xmalloc(col * sizeof(Glyph));
3067 }
3068 if (col > term.col) {
3069 bp = term.tabs + term.col;
3070
3071 memset(bp, 0, sizeof(*term.tabs) * (col - term.col));
3072 while (--bp > term.tabs && !*bp)
3073 /* nothing */ ;
3074 for (bp += tabspaces; bp < term.tabs + col; bp += tabspaces)
3075 *bp = 1;
3076 }
3077 /* update terminal size */
3078 term.col = col;
3079 term.row = row;
3080 /* reset scrolling region */
3081 tsetscroll(0, row-1);
3082 /* make use of the LIMIT in tmoveto */
3083 tmoveto(term.c.x, term.c.y);
3084 /* Clearing both screens (it makes dirty all lines) */
3085 c = term.c;
3086 for (i = 0; i < 2; i++) {
3087 if (mincol < col && 0 < minrow) {
3088 tclearregion(mincol, 0, col - 1, minrow - 1);
3089 }
3090 if (0 < col && minrow < row) {
3091 tclearregion(0, minrow, col - 1, row - 1);
3092 }
3093 tswapscreen();
3094 tcursor(CURSOR_LOAD);
3095 }
3096 term.c = c;
3097 }
3098
3099 void
3100 xresize(int col, int row)
3101 {
3102 xw.tw = MAX(1, col * xw.cw);
3103 xw.th = MAX(1, row * xw.ch);
3104
3105 XFreePixmap(xw.dpy, xw.buf);
3106 xw.buf = XCreatePixmap(xw.dpy, xw.win, xw.w, xw.h,
3107 DefaultDepth(xw.dpy, xw.scr));
3108 XftDrawChange(xw.draw, xw.buf);
3109 xclear(0, 0, xw.w, xw.h);
3110 }
3111
3112 ushort
3113 sixd_to_16bit(int x)
3114 {
3115 return x == 0 ? 0 : 0x3737 + 0x2828 * x;
3116 }
3117
3118 int
3119 xloadcolor(int i, const char *name, Color *ncolor)
3120 {
3121 XRenderColor color = { .alpha = 0xffff };
3122
3123 if (!name) {
3124 if (BETWEEN(i, 16, 255)) { /* 256 color */
3125 if (i < 6*6*6+16) { /* same colors as xterm */
3126 color.red = sixd_to_16bit( ((i-16)/36)%6 );
3127 color.green = sixd_to_16bit( ((i-16)/6) %6 );
3128 color.blue = sixd_to_16bit( ((i-16)/1) %6 );
3129 } else { /* greyscale */
3130 color.red = 0x0808 + 0x0a0a * (i - (6*6*6+16));
3131 color.green = color.blue = color.red;
3132 }
3133 return XftColorAllocValue(xw.dpy, xw.vis,
3134 xw.cmap, &color, ncolor);
3135 } else
3136 name = colorname[i];
3137 }
3138
3139 return XftColorAllocName(xw.dpy, xw.vis, xw.cmap, name, ncolor);
3140 }
3141
3142 void
3143 xloadcols(void)
3144 {
3145 int i;
3146 static int loaded;
3147 Color *cp;
3148
3149 if (loaded) {
3150 for (cp = dc.col; cp < &dc.col[LEN(dc.col)]; ++cp)
3151 XftColorFree(xw.dpy, xw.vis, xw.cmap, cp);
3152 }
3153
3154 for (i = 0; i < LEN(dc.col); i++)
3155 if (!xloadcolor(i, NULL, &dc.col[i])) {
3156 if (colorname[i])
3157 die("Could not allocate color '%s'\n", colorname[i]);
3158 else
3159 die("Could not allocate color %d\n", i);
3160 }
3161 loaded = 1;
3162 }
3163
3164 int
3165 xsetcolorname(int x, const char *name)
3166 {
3167 Color ncolor;
3168
3169 if (!BETWEEN(x, 0, LEN(dc.col)))
3170 return 1;
3171
3172
3173 if (!xloadcolor(x, name, &ncolor))
3174 return 1;
3175
3176 XftColorFree(xw.dpy, xw.vis, xw.cmap, &dc.col[x]);
3177 dc.col[x] = ncolor;
3178
3179 return 0;
3180 }
3181
3182 void
3183 xtermclear(int col1, int row1, int col2, int row2)
3184 {
3185 XftDrawRect(xw.draw,
3186 &dc.col[IS_SET(MODE_REVERSE) ? defaultfg : defaultbg],
3187 borderpx + col1 * xw.cw,
3188 borderpx + row1 * xw.ch,
3189 (col2-col1+1) * xw.cw,
3190 (row2-row1+1) * xw.ch);
3191 }
3192
3193 /*
3194 * Absolute coordinates.
3195 */
3196 void
3197 xclear(int x1, int y1, int x2, int y2)
3198 {
3199 XftDrawRect(xw.draw,
3200 &dc.col[IS_SET(MODE_REVERSE)? defaultfg : defaultbg],
3201 x1, y1, x2-x1, y2-y1);
3202 }
3203
3204 void
3205 xhints(void)
3206 {
3207 XClassHint class = {opt_class ? opt_class : termname, termname};
3208 XWMHints wm = {.flags = InputHint, .input = 1};
3209 XSizeHints *sizeh = NULL;
3210
3211 sizeh = XAllocSizeHints();
3212
3213 sizeh->flags = PSize | PResizeInc | PBaseSize;
3214 sizeh->height = xw.h;
3215 sizeh->width = xw.w;
3216 sizeh->height_inc = xw.ch;
3217 sizeh->width_inc = xw.cw;
3218 sizeh->base_height = 2 * borderpx;
3219 sizeh->base_width = 2 * borderpx;
3220 if (xw.isfixed) {
3221 sizeh->flags |= PMaxSize | PMinSize;
3222 sizeh->min_width = sizeh->max_width = xw.w;
3223 sizeh->min_height = sizeh->max_height = xw.h;
3224 }
3225 if (xw.gm & (XValue|YValue)) {
3226 sizeh->flags |= USPosition | PWinGravity;
3227 sizeh->x = xw.l;
3228 sizeh->y = xw.t;
3229 sizeh->win_gravity = xgeommasktogravity(xw.gm);
3230 }
3231
3232 XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm,
3233 &class);
3234 XFree(sizeh);
3235 }
3236
3237 int
3238 xgeommasktogravity(int mask)
3239 {
3240 switch (mask & (XNegative|YNegative)) {
3241 case 0:
3242 return NorthWestGravity;
3243 case XNegative:
3244 return NorthEastGravity;
3245 case YNegative:
3246 return SouthWestGravity;
3247 }
3248
3249 return SouthEastGravity;
3250 }
3251
3252 int
3253 xloadfont(Font *f, FcPattern *pattern)
3254 {
3255 FcPattern *match;
3256 FcResult result;
3257
3258 match = FcFontMatch(NULL, pattern, &result);
3259 if (!match)
3260 return 1;
3261
3262 if (!(f->match = XftFontOpenPattern(xw.dpy, match))) {
3263 FcPatternDestroy(match);
3264 return 1;
3265 }
3266
3267 f->set = NULL;
3268 f->pattern = FcPatternDuplicate(pattern);
3269
3270 f->ascent = f->match->ascent;
3271 f->descent = f->match->descent;
3272 f->lbearing = 0;
3273 f->rbearing = f->match->max_advance_width;
3274
3275 f->height = f->ascent + f->descent;
3276 f->width = f->lbearing + f->rbearing;
3277
3278 return 0;
3279 }
3280
3281 void
3282 xloadfonts(char *fontstr, double fontsize)
3283 {
3284 FcPattern *pattern;
3285 double fontval;
3286 float ceilf(float);
3287
3288 if (fontstr[0] == '-') {
3289 pattern = XftXlfdParse(fontstr, False, False);
3290 } else {
3291 pattern = FcNameParse((FcChar8 *)fontstr);
3292 }
3293
3294 if (!pattern)
3295 die("st: can't open font %s\n", fontstr);
3296
3297 if (fontsize > 1) {
3298 FcPatternDel(pattern, FC_PIXEL_SIZE);
3299 FcPatternDel(pattern, FC_SIZE);
3300 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, (double)fontsize);
3301 usedfontsize = fontsize;
3302 } else {
3303 if (FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &fontval) ==
3304 FcResultMatch) {
3305 usedfontsize = fontval;
3306 } else if (FcPatternGetDouble(pattern, FC_SIZE, 0, &fontval) ==
3307 FcResultMatch) {
3308 usedfontsize = -1;
3309 } else {
3310 /*
3311 * Default font size is 12, if none given. This is to
3312 * have a known usedfontsize value.
3313 */
3314 FcPatternAddDouble(pattern, FC_PIXEL_SIZE, 12);
3315 usedfontsize = 12;
3316 }
3317 defaultfontsize = usedfontsize;
3318 }
3319
3320 FcConfigSubstitute(0, pattern, FcMatchPattern);
3321 FcDefaultSubstitute(pattern);
3322
3323 if (xloadfont(&dc.font, pattern))
3324 die("st: can't open font %s\n", fontstr);
3325
3326 if (usedfontsize < 0) {
3327 FcPatternGetDouble(dc.font.match->pattern,
3328 FC_PIXEL_SIZE, 0, &fontval);
3329 usedfontsize = fontval;
3330 if (fontsize == 0)
3331 defaultfontsize = fontval;
3332 }
3333
3334 /* Setting character width and height. */
3335 xw.cw = ceilf(dc.font.width * cwscale);
3336 xw.ch = ceilf(dc.font.height * chscale);
3337
3338 FcPatternDel(pattern, FC_SLANT);
3339 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC);
3340 if (xloadfont(&dc.ifont, pattern))
3341 die("st: can't open font %s\n", fontstr);
3342
3343 FcPatternDel(pattern, FC_WEIGHT);
3344 FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD);
3345 if (xloadfont(&dc.ibfont, pattern))
3346 die("st: can't open font %s\n", fontstr);
3347
3348 FcPatternDel(pattern, FC_SLANT);
3349 FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ROMAN);
3350 if (xloadfont(&dc.bfont, pattern))
3351 die("st: can't open font %s\n", fontstr);
3352
3353 FcPatternDestroy(pattern);
3354 }
3355
3356 void
3357 xunloadfont(Font *f)
3358 {
3359 XftFontClose(xw.dpy, f->match);
3360 FcPatternDestroy(f->pattern);
3361 if (f->set)
3362 FcFontSetDestroy(f->set);
3363 }
3364
3365 void
3366 xunloadfonts(void)
3367 {
3368 /* Free the loaded fonts in the font cache. */
3369 while (frclen > 0)
3370 XftFontClose(xw.dpy, frc[--frclen].font);
3371
3372 xunloadfont(&dc.font);
3373 xunloadfont(&dc.bfont);
3374 xunloadfont(&dc.ifont);
3375 xunloadfont(&dc.ibfont);
3376 }
3377
3378 void
3379 xzoom(const Arg *arg)
3380 {
3381 Arg larg;
3382
3383 larg.f = usedfontsize + arg->f;
3384 xzoomabs(&larg);
3385 }
3386
3387 void
3388 xzoomabs(const Arg *arg)
3389 {
3390 xunloadfonts();
3391 xloadfonts(usedfont, arg->f);
3392 cresize(0, 0);
3393 redraw();
3394 xhints();
3395 }
3396
3397 void
3398 xzoomreset(const Arg *arg)
3399 {
3400 Arg larg;
3401
3402 if (defaultfontsize > 0) {
3403 larg.f = defaultfontsize;
3404 xzoomabs(&larg);
3405 }
3406 }
3407
3408 void
3409 xinit(void)
3410 {
3411 XGCValues gcvalues;
3412 Cursor cursor;
3413 Window parent;
3414 pid_t thispid = getpid();
3415 XColor xmousefg, xmousebg;
3416
3417 if (!(xw.dpy = XOpenDisplay(NULL)))
3418 die("Can't open display\n");
3419 xw.scr = XDefaultScreen(xw.dpy);
3420 xw.vis = XDefaultVisual(xw.dpy, xw.scr);
3421
3422 /* font */
3423 if (!FcInit())
3424 die("Could not init fontconfig.\n");
3425
3426 usedfont = (opt_font == NULL)? font : opt_font;
3427 xloadfonts(usedfont, 0);
3428
3429 /* colors */
3430 xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
3431 xloadcols();
3432
3433 /* adjust fixed window geometry */
3434 xw.w = 2 * borderpx + term.col * xw.cw;
3435 xw.h = 2 * borderpx + term.row * xw.ch;
3436 if (xw.gm & XNegative)
3437 xw.l += DisplayWidth(xw.dpy, xw.scr) - xw.w - 2;
3438 if (xw.gm & YNegative)
3439 xw.t += DisplayWidth(xw.dpy, xw.scr) - xw.h - 2;
3440
3441 /* Events */
3442 xw.attrs.background_pixel = dc.col[defaultbg].pixel;
3443 xw.attrs.border_pixel = dc.col[defaultbg].pixel;
3444 xw.attrs.bit_gravity = NorthWestGravity;
3445 xw.attrs.event_mask = FocusChangeMask | KeyPressMask
3446 | ExposureMask | VisibilityChangeMask | StructureNotifyMask
3447 | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
3448 xw.attrs.colormap = xw.cmap;
3449
3450 if (!(opt_embed && (parent = strtol(opt_embed, NULL, 0))))
3451 parent = XRootWindow(xw.dpy, xw.scr);
3452 xw.win = XCreateWindow(xw.dpy, parent, xw.l, xw.t,
3453 xw.w, xw.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
3454 xw.vis, CWBackPixel | CWBorderPixel | CWBitGravity
3455 | CWEventMask | CWColormap, &xw.attrs);
3456
3457 memset(&gcvalues, 0, sizeof(gcvalues));
3458 gcvalues.graphics_exposures = False;
3459 dc.gc = XCreateGC(xw.dpy, parent, GCGraphicsExposures,
3460 &gcvalues);
3461 xw.buf = XCreatePixmap(xw.dpy, xw.win, xw.w, xw.h,
3462 DefaultDepth(xw.dpy, xw.scr));
3463 XSetForeground(xw.dpy, dc.gc, dc.col[defaultbg].pixel);
3464 XFillRectangle(xw.dpy, xw.buf, dc.gc, 0, 0, xw.w, xw.h);
3465
3466 /* Xft rendering context */
3467 xw.draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
3468
3469 /* input methods */
3470 if ((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
3471 XSetLocaleModifiers("@im=local");
3472 if ((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
3473 XSetLocaleModifiers("@im=");
3474 if ((xw.xim = XOpenIM(xw.dpy,
3475 NULL, NULL, NULL)) == NULL) {
3476 die("XOpenIM failed. Could not open input"
3477 " device.\n");
3478 }
3479 }
3480 }
3481 xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
3482 | XIMStatusNothing, XNClientWindow, xw.win,
3483 XNFocusWindow, xw.win, NULL);
3484 if (xw.xic == NULL)
3485 die("XCreateIC failed. Could not obtain input method.\n");
3486
3487 /* white cursor, black outline */
3488 cursor = XCreateFontCursor(xw.dpy, mouseshape);
3489 XDefineCursor(xw.dpy, xw.win, cursor);
3490
3491 if (XParseColor(xw.dpy, xw.cmap, colorname[mousefg], &xmousefg) == 0) {
3492 xmousefg.red = 0xffff;
3493 xmousefg.green = 0xffff;
3494 xmousefg.blue = 0xffff;
3495 }
3496
3497 if (XParseColor(xw.dpy, xw.cmap, colorname[mousebg], &xmousebg) == 0) {
3498 xmousebg.red = 0x0000;
3499 xmousebg.green = 0x0000;
3500 xmousebg.blue = 0x0000;
3501 }
3502
3503 XRecolorCursor(xw.dpy, cursor, &xmousefg, &xmousebg);
3504
3505 xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
3506 xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
3507 xw.netwmname = XInternAtom(xw.dpy, "_NET_WM_NAME", False);
3508 XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
3509
3510 xw.netwmpid = XInternAtom(xw.dpy, "_NET_WM_PID", False);
3511 XChangeProperty(xw.dpy, xw.win, xw.netwmpid, XA_CARDINAL, 32,
3512 PropModeReplace, (uchar *)&thispid, 1);
3513
3514 xresettitle();
3515 XMapWindow(xw.dpy, xw.win);
3516 xhints();
3517 XSync(xw.dpy, False);
3518 }
3519
3520 int
3521 xmakeglyphfontspecs(XftGlyphFontSpec *specs, const Glyph *glyphs, int len, int x, int y)
3522 {
3523 float winx = borderpx + x * xw.cw, winy = borderpx + y * xw.ch, xp, yp;
3524 ushort mode, prevmode = USHRT_MAX;
3525 Font *font = &dc.font;
3526 int frcflags = FRC_NORMAL;
3527 float runewidth = xw.cw;
3528 Rune rune;
3529 FT_UInt glyphidx;
3530 FcResult fcres;
3531 FcPattern *fcpattern, *fontpattern;
3532 FcFontSet *fcsets[] = { NULL };
3533 FcCharSet *fccharset;
3534 int i, f, numspecs = 0;
3535
3536 for (i = 0, xp = winx, yp = winy + font->ascent; i < len; ++i) {
3537 /* Fetch rune and mode for current glyph. */
3538 rune = glyphs[i].u;
3539 mode = glyphs[i].mode;
3540
3541 /* Skip dummy wide-character spacing. */
3542 if (mode == ATTR_WDUMMY)
3543 continue;
3544
3545 /* Determine font for glyph if different from previous glyph. */
3546 if (prevmode != mode) {
3547 prevmode = mode;
3548 font = &dc.font;
3549 frcflags = FRC_NORMAL;
3550 runewidth = xw.cw * ((mode & ATTR_WIDE) ? 2.0f : 1.0f);
3551 if ((mode & ATTR_ITALIC) && (mode & ATTR_BOLD)) {
3552 font = &dc.ibfont;
3553 frcflags = FRC_ITALICBOLD;
3554 } else if (mode & ATTR_ITALIC) {
3555 font = &dc.ifont;
3556 frcflags = FRC_ITALIC;
3557 } else if (mode & ATTR_BOLD) {
3558 font = &dc.bfont;
3559 frcflags = FRC_BOLD;
3560 }
3561 yp = winy + font->ascent;
3562 }
3563
3564 /* Lookup character index with default font. */
3565 glyphidx = XftCharIndex(xw.dpy, font->match, rune);
3566 if (glyphidx) {
3567 specs[numspecs].font = font->match;
3568 specs[numspecs].glyph = glyphidx;
3569 specs[numspecs].x = (short)xp;
3570 specs[numspecs].y = (short)yp;
3571 xp += runewidth;
3572 numspecs++;
3573 continue;
3574 }
3575
3576 /* Fallback on font cache, search the font cache for match. */
3577 for (f = 0; f < frclen; f++) {
3578 glyphidx = XftCharIndex(xw.dpy, frc[f].font, rune);
3579 /* Everything correct. */
3580 if (glyphidx && frc[f].flags == frcflags)
3581 break;
3582 /* We got a default font for a not found glyph. */
3583 if (!glyphidx && frc[f].flags == frcflags
3584 && frc[f].unicodep == rune) {
3585 break;
3586 }
3587 }
3588
3589 /* Nothing was found. Use fontconfig to find matching font. */
3590 if (f >= frclen) {
3591 if (!font->set)
3592 font->set = FcFontSort(0, font->pattern,
3593 1, 0, &fcres);
3594 fcsets[0] = font->set;
3595
3596 /*
3597 * Nothing was found in the cache. Now use
3598 * some dozen of Fontconfig calls to get the
3599 * font for one single character.
3600 *
3601 * Xft and fontconfig are design failures.
3602 */
3603 fcpattern = FcPatternDuplicate(font->pattern);
3604 fccharset = FcCharSetCreate();
3605
3606 FcCharSetAddChar(fccharset, rune);
3607 FcPatternAddCharSet(fcpattern, FC_CHARSET,
3608 fccharset);
3609 FcPatternAddBool(fcpattern, FC_SCALABLE, 1);
3610
3611 FcConfigSubstitute(0, fcpattern,
3612 FcMatchPattern);
3613 FcDefaultSubstitute(fcpattern);
3614
3615 fontpattern = FcFontSetMatch(0, fcsets, 1,
3616 fcpattern, &fcres);
3617
3618 /*
3619 * Overwrite or create the new cache entry.
3620 */
3621 if (frclen >= LEN(frc)) {
3622 frclen = LEN(frc) - 1;
3623 XftFontClose(xw.dpy, frc[frclen].font);
3624 frc[frclen].unicodep = 0;
3625 }
3626
3627 frc[frclen].font = XftFontOpenPattern(xw.dpy,
3628 fontpattern);
3629 frc[frclen].flags = frcflags;
3630 frc[frclen].unicodep = rune;
3631
3632 glyphidx = XftCharIndex(xw.dpy, frc[frclen].font, rune);
3633
3634 f = frclen;
3635 frclen++;
3636
3637 FcPatternDestroy(fcpattern);
3638 FcCharSetDestroy(fccharset);
3639 }
3640
3641 specs[numspecs].font = frc[f].font;
3642 specs[numspecs].glyph = glyphidx;
3643 specs[numspecs].x = (short)xp;
3644 specs[numspecs].y = (short)(winy + frc[f].font->ascent);
3645 xp += runewidth;
3646 numspecs++;
3647 }
3648
3649 return numspecs;
3650 }
3651
3652 void
3653 xdrawglyphfontspecs(const XftGlyphFontSpec *specs, Glyph base, int len, int x, int y)
3654 {
3655 int charlen = len * ((base.mode & ATTR_WIDE) ? 2 : 1);
3656 int winx = borderpx + x * xw.cw, winy = borderpx + y * xw.ch,
3657 width = charlen * xw.cw;
3658 Color *fg, *bg, *temp, revfg, revbg, truefg, truebg;
3659 XRenderColor colfg, colbg;
3660 XRectangle r;
3661
3662 /* Determine foreground and background colors based on mode. */
3663 if (base.fg == defaultfg) {
3664 if (base.mode & ATTR_ITALIC)
3665 base.fg = defaultitalic;
3666 else if ((base.mode & ATTR_ITALIC) && (base.mode & ATTR_BOLD))
3667 base.fg = defaultitalic;
3668 else if (base.mode & ATTR_UNDERLINE)
3669 base.fg = defaultunderline;
3670 }
3671
3672 if (IS_TRUECOL(base.fg)) {
3673 colfg.alpha = 0xffff;
3674 colfg.red = TRUERED(base.fg);
3675 colfg.green = TRUEGREEN(base.fg);
3676 colfg.blue = TRUEBLUE(base.fg);
3677 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &truefg);
3678 fg = &truefg;
3679 } else {
3680 fg = &dc.col[base.fg];
3681 }
3682
3683 if (IS_TRUECOL(base.bg)) {
3684 colbg.alpha = 0xffff;
3685 colbg.green = TRUEGREEN(base.bg);
3686 colbg.red = TRUERED(base.bg);
3687 colbg.blue = TRUEBLUE(base.bg);
3688 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &truebg);
3689 bg = &truebg;
3690 } else {
3691 bg = &dc.col[base.bg];
3692 }
3693
3694 /* Change basic system colors [0-7] to bright system colors [8-15] */
3695 if ((base.mode & ATTR_BOLD_FAINT) == ATTR_BOLD && BETWEEN(base.fg, 0, 7))
3696 fg = &dc.col[base.fg + 8];
3697
3698 if (IS_SET(MODE_REVERSE)) {
3699 if (fg == &dc.col[defaultfg]) {
3700 fg = &dc.col[defaultbg];
3701 } else {
3702 colfg.red = ~fg->color.red;
3703 colfg.green = ~fg->color.green;
3704 colfg.blue = ~fg->color.blue;
3705 colfg.alpha = fg->color.alpha;
3706 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg,
3707 &revfg);
3708 fg = &revfg;
3709 }
3710
3711 if (bg == &dc.col[defaultbg]) {
3712 bg = &dc.col[defaultfg];
3713 } else {
3714 colbg.red = ~bg->color.red;
3715 colbg.green = ~bg->color.green;
3716 colbg.blue = ~bg->color.blue;
3717 colbg.alpha = bg->color.alpha;
3718 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg,
3719 &revbg);
3720 bg = &revbg;
3721 }
3722 }
3723
3724 if (base.mode & ATTR_REVERSE) {
3725 temp = fg;
3726 fg = bg;
3727 bg = temp;
3728 }
3729
3730 if ((base.mode & ATTR_BOLD_FAINT) == ATTR_FAINT) {
3731 colfg.red = fg->color.red / 2;
3732 colfg.green = fg->color.green / 2;
3733 colfg.blue = fg->color.blue / 2;
3734 XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
3735 fg = &revfg;
3736 }
3737
3738 if (base.mode & ATTR_BLINK && term.mode & MODE_BLINK)
3739 fg = bg;
3740
3741 if (base.mode & ATTR_INVISIBLE)
3742 fg = bg;
3743
3744 /* Intelligent cleaning up of the borders. */
3745 if (x == 0) {
3746 xclear(0, (y == 0)? 0 : winy, borderpx,
3747 winy + xw.ch + ((y >= term.row-1)? xw.h : 0));
3748 }
3749 if (x + charlen >= term.col) {
3750 xclear(winx + width, (y == 0)? 0 : winy, xw.w,
3751 ((y >= term.row-1)? xw.h : (winy + xw.ch)));
3752 }
3753 if (y == 0)
3754 xclear(winx, 0, winx + width, borderpx);
3755 if (y == term.row-1)
3756 xclear(winx, winy + xw.ch, winx + width, xw.h);
3757
3758 /* Clean up the region we want to draw to. */
3759 XftDrawRect(xw.draw, bg, winx, winy, width, xw.ch);
3760
3761 /* Set the clip region because Xft is sometimes dirty. */
3762 r.x = 0;
3763 r.y = 0;
3764 r.height = xw.ch;
3765 r.width = width;
3766 XftDrawSetClipRectangles(xw.draw, winx, winy, &r, 1);
3767
3768 /* Render the glyphs. */
3769 XftDrawGlyphFontSpec(xw.draw, fg, specs, len);
3770
3771 /* Render underline and strikethrough. */
3772 if (base.mode & ATTR_UNDERLINE) {
3773 XftDrawRect(xw.draw, fg, winx, winy + dc.font.ascent + 1,
3774 width, 1);
3775 }
3776
3777 if (base.mode & ATTR_STRUCK) {
3778 XftDrawRect(xw.draw, fg, winx, winy + 2 * dc.font.ascent / 3,
3779 width, 1);
3780 }
3781
3782 /* Reset clip to none. */
3783 XftDrawSetClip(xw.draw, 0);
3784 }
3785
3786 void
3787 xdrawglyph(Glyph g, int x, int y)
3788 {
3789 int numspecs;
3790 XftGlyphFontSpec spec;
3791 numspecs = xmakeglyphfontspecs(&spec, &g, 1, x, y);
3792 xdrawglyphfontspecs(&spec, g, numspecs, x, y);
3793 }
3794
3795 void
3796 xdrawcursor(void)
3797 {
3798 static int oldx = 0, oldy = 0;
3799 int curx;
3800 Glyph g = {' ', ATTR_NULL, defaultbg, defaultcs};
3801
3802 LIMIT(oldx, 0, term.col-1);
3803 LIMIT(oldy, 0, term.row-1);
3804
3805 curx = term.c.x;
3806
3807 /* adjust position if in dummy */
3808 if (term.line[oldy][oldx].mode & ATTR_WDUMMY)
3809 oldx--;
3810 if (term.line[term.c.y][curx].mode & ATTR_WDUMMY)
3811 curx--;
3812
3813 g.u = term.line[term.c.y][term.c.x].u;
3814
3815 /* remove the old cursor */
3816 xdrawglyph(term.line[oldy][oldx], oldx, oldy);
3817
3818 if (IS_SET(MODE_HIDE))
3819 return;
3820
3821 /* draw the new one */
3822 if (xw.state & WIN_FOCUSED) {
3823 switch (xw.cursor) {
3824 case 0: /* Blinking Block */
3825 case 1: /* Blinking Block (Default) */
3826 case 2: /* Steady Block */
3827 if (IS_SET(MODE_REVERSE)) {
3828 g.mode |= ATTR_REVERSE;
3829 g.fg = defaultcs;
3830 g.bg = defaultfg;
3831 }
3832
3833 g.mode |= term.line[term.c.y][curx].mode & ATTR_WIDE;
3834 xdrawglyph(g, term.c.x, term.c.y);
3835 break;
3836 case 3: /* Blinking Underline */
3837 case 4: /* Steady Underline */
3838 XftDrawRect(xw.draw, &dc.col[defaultcs],
3839 borderpx + curx * xw.cw,
3840 borderpx + (term.c.y + 1) * xw.ch - cursorthickness,
3841 xw.cw, cursorthickness);
3842 break;
3843 case 5: /* Blinking bar */
3844 case 6: /* Steady bar */
3845 XftDrawRect(xw.draw, &dc.col[defaultcs],
3846 borderpx + curx * xw.cw,
3847 borderpx + term.c.y * xw.ch,
3848 cursorthickness, xw.ch);
3849 break;
3850 }
3851 } else {
3852 XftDrawRect(xw.draw, &dc.col[defaultcs],
3853 borderpx + curx * xw.cw,
3854 borderpx + term.c.y * xw.ch,
3855 xw.cw - 1, 1);
3856 XftDrawRect(xw.draw, &dc.col[defaultcs],
3857 borderpx + curx * xw.cw,
3858 borderpx + term.c.y * xw.ch,
3859 1, xw.ch - 1);
3860 XftDrawRect(xw.draw, &dc.col[defaultcs],
3861 borderpx + (curx + 1) * xw.cw - 1,
3862 borderpx + term.c.y * xw.ch,
3863 1, xw.ch - 1);
3864 XftDrawRect(xw.draw, &dc.col[defaultcs],
3865 borderpx + curx * xw.cw,
3866 borderpx + (term.c.y + 1) * xw.ch - 1,
3867 xw.cw, 1);
3868 }
3869 oldx = curx, oldy = term.c.y;
3870 }
3871
3872
3873 void
3874 xsettitle(char *p)
3875 {
3876 XTextProperty prop;
3877
3878 Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle,
3879 &prop);
3880 XSetWMName(xw.dpy, xw.win, &prop);
3881 XSetTextProperty(xw.dpy, xw.win, &prop, xw.netwmname);
3882 XFree(prop.value);
3883 }
3884
3885 void
3886 xresettitle(void)
3887 {
3888 xsettitle(opt_title ? opt_title : "st");
3889 }
3890
3891 void
3892 redraw(void)
3893 {
3894 tfulldirt();
3895 draw();
3896 }
3897
3898 void
3899 draw(void)
3900 {
3901 drawregion(0, 0, term.col, term.row);
3902 XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, 0, 0, xw.w,
3903 xw.h, 0, 0);
3904 XSetForeground(xw.dpy, dc.gc,
3905 dc.col[IS_SET(MODE_REVERSE)?
3906 defaultfg : defaultbg].pixel);
3907 }
3908
3909 void
3910 drawregion(int x1, int y1, int x2, int y2)
3911 {
3912 int i, x, y, ox, numspecs;
3913 Glyph base, new;
3914 XftGlyphFontSpec* specs;
3915 int ena_sel = sel.ob.x != -1 && sel.alt == IS_SET(MODE_ALTSCREEN);
3916
3917 if (!(xw.state & WIN_VISIBLE))
3918 return;
3919
3920 for (y = y1; y < y2; y++) {
3921 if (!term.dirty[y])
3922 continue;
3923
3924 xtermclear(0, y, term.col, y);
3925 term.dirty[y] = 0;
3926
3927 specs = term.specbuf;
3928 numspecs = xmakeglyphfontspecs(specs, &term.line[y][x1], x2 - x1, x1, y);
3929
3930 i = ox = 0;
3931 for (x = x1; x < x2 && i < numspecs; x++) {
3932 new = term.line[y][x];
3933 if (new.mode == ATTR_WDUMMY)
3934 continue;
3935 if (ena_sel && selected(x, y))
3936 new.mode ^= ATTR_REVERSE;
3937 if (i > 0 && ATTRCMP(base, new)) {
3938 xdrawglyphfontspecs(specs, base, i, ox, y);
3939 specs += i;
3940 numspecs -= i;
3941 i = 0;
3942 }
3943 if (i == 0) {
3944 ox = x;
3945 base = new;
3946 }
3947 i++;
3948 }
3949 if (i > 0)
3950 xdrawglyphfontspecs(specs, base, i, ox, y);
3951 }
3952 xdrawcursor();
3953 }
3954
3955 void
3956 expose(XEvent *ev)
3957 {
3958 redraw();
3959 }
3960
3961 void
3962 visibility(XEvent *ev)
3963 {
3964 XVisibilityEvent *e = &ev->xvisibility;
3965
3966 MODBIT(xw.state, e->state != VisibilityFullyObscured, WIN_VISIBLE);
3967 }
3968
3969 void
3970 unmap(XEvent *ev)
3971 {
3972 xw.state &= ~WIN_VISIBLE;
3973 }
3974
3975 void
3976 xsetpointermotion(int set)
3977 {
3978 MODBIT(xw.attrs.event_mask, set, PointerMotionMask);
3979 XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask, &xw.attrs);
3980 }
3981
3982 void
3983 xseturgency(int add)
3984 {
3985 XWMHints *h = XGetWMHints(xw.dpy, xw.win);
3986
3987 MODBIT(h->flags, add, XUrgencyHint);
3988 XSetWMHints(xw.dpy, xw.win, h);
3989 XFree(h);
3990 }
3991
3992 void
3993 focus(XEvent *ev)
3994 {
3995 XFocusChangeEvent *e = &ev->xfocus;
3996
3997 if (e->mode == NotifyGrab)
3998 return;
3999
4000 if (ev->type == FocusIn) {
4001 XSetICFocus(xw.xic);
4002 xw.state |= WIN_FOCUSED;
4003 xseturgency(0);
4004 if (IS_SET(MODE_FOCUS))
4005 ttywrite("\033[I", 3);
4006 } else {
4007 XUnsetICFocus(xw.xic);
4008 xw.state &= ~WIN_FOCUSED;
4009 if (IS_SET(MODE_FOCUS))
4010 ttywrite("\033[O", 3);
4011 }
4012 }
4013
4014 int
4015 match(uint mask, uint state)
4016 {
4017 return mask == XK_ANY_MOD || mask == (state & ~ignoremod);
4018 }
4019
4020 void
4021 numlock(const Arg *dummy)
4022 {
4023 term.numlock ^= 1;
4024 }
4025
4026 char*
4027 kmap(KeySym k, uint state)
4028 {
4029 Key *kp;
4030 int i;
4031
4032 /* Check for mapped keys out of X11 function keys. */
4033 for (i = 0; i < LEN(mappedkeys); i++) {
4034 if (mappedkeys[i] == k)
4035 break;
4036 }
4037 if (i == LEN(mappedkeys)) {
4038 if ((k & 0xFFFF) < 0xFD00)
4039 return NULL;
4040 }
4041
4042 for (kp = key; kp < key + LEN(key); kp++) {
4043 if (kp->k != k)
4044 continue;
4045
4046 if (!match(kp->mask, state))
4047 continue;
4048
4049 if (IS_SET(MODE_APPKEYPAD) ? kp->appkey < 0 : kp->appkey > 0)
4050 continue;
4051 if (term.numlock && kp->appkey == 2)
4052 continue;
4053
4054 if (IS_SET(MODE_APPCURSOR) ? kp->appcursor < 0 : kp->appcursor > 0)
4055 continue;
4056
4057 if (IS_SET(MODE_CRLF) ? kp->crlf < 0 : kp->crlf > 0)
4058 continue;
4059
4060 return kp->s;
4061 }
4062
4063 return NULL;
4064 }
4065
4066 void
4067 kpress(XEvent *ev)
4068 {
4069 XKeyEvent *e = &ev->xkey;
4070 KeySym ksym;
4071 char buf[32], *customkey;
4072 int len;
4073 Rune c;
4074 Status status;
4075 Shortcut *bp;
4076
4077 if (IS_SET(MODE_KBDLOCK))
4078 return;
4079
4080 len = XmbLookupString(xw.xic, e, buf, sizeof buf, &ksym, &status);
4081 /* 1. shortcuts */
4082 for (bp = shortcuts; bp < shortcuts + LEN(shortcuts); bp++) {
4083 if (ksym == bp->keysym && match(bp->mod, e->state)) {
4084 bp->func(&(bp->arg));
4085 return;
4086 }
4087 }
4088
4089 /* 2. custom keys from config.h */
4090 if ((customkey = kmap(ksym, e->state))) {
4091 ttysend(customkey, strlen(customkey));
4092 return;
4093 }
4094
4095 /* 3. composed string from input method */
4096 if (len == 0)
4097 return;
4098 if (len == 1 && e->state & Mod1Mask) {
4099 if (IS_SET(MODE_8BIT)) {
4100 if (*buf < 0177) {
4101 c = *buf | 0x80;
4102 len = utf8encode(c, buf);
4103 }
4104 } else {
4105 buf[1] = buf[0];
4106 buf[0] = '\033';
4107 len = 2;
4108 }
4109 }
4110 ttysend(buf, len);
4111 }
4112
4113
4114 void
4115 cmessage(XEvent *e)
4116 {
4117 /*
4118 * See xembed specs
4119 * http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html
4120 */
4121 if (e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
4122 if (e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
4123 xw.state |= WIN_FOCUSED;
4124 xseturgency(0);
4125 } else if (e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
4126 xw.state &= ~WIN_FOCUSED;
4127 }
4128 } else if (e->xclient.data.l[0] == xw.wmdeletewin) {
4129 /* Send SIGHUP to shell */
4130 kill(pid, SIGHUP);
4131 exit(0);
4132 }
4133 }
4134
4135 void
4136 cresize(int width, int height)
4137 {
4138 int col, row;
4139
4140 if (width != 0)
4141 xw.w = width;
4142 if (height != 0)
4143 xw.h = height;
4144
4145 col = (xw.w - 2 * borderpx) / xw.cw;
4146 row = (xw.h - 2 * borderpx) / xw.ch;
4147
4148 tresize(col, row);
4149 xresize(col, row);
4150 ttyresize();
4151 }
4152
4153 void
4154 resize(XEvent *e)
4155 {
4156 if (e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
4157 return;
4158
4159 cresize(e->xconfigure.width, e->xconfigure.height);
4160 }
4161
4162 void
4163 run(void)
4164 {
4165 XEvent ev;
4166 int w = xw.w, h = xw.h;
4167 fd_set rfd;
4168 int xfd = XConnectionNumber(xw.dpy), xev, blinkset = 0, dodraw = 0;
4169 struct timespec drawtimeout, *tv = NULL, now, last, lastblink;
4170 long deltatime;
4171
4172 /* Waiting for window mapping */
4173 do {
4174 XNextEvent(xw.dpy, &ev);
4175 /*
4176 * This XFilterEvent call is required because of XOpenIM. It
4177 * does filter out the key event and some client message for
4178 * the input method too.
4179 */
4180 if (XFilterEvent(&ev, None))
4181 continue;
4182 if (ev.type == ConfigureNotify) {
4183 w = ev.xconfigure.width;
4184 h = ev.xconfigure.height;
4185 }
4186 } while (ev.type != MapNotify);
4187
4188 ttynew();
4189 cresize(w, h);
4190
4191 clock_gettime(CLOCK_MONOTONIC, &last);
4192 lastblink = last;
4193
4194 for (xev = actionfps;;) {
4195 FD_ZERO(&rfd);
4196 FD_SET(cmdfd, &rfd);
4197 FD_SET(xfd, &rfd);
4198
4199 if (pselect(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, tv, NULL) < 0) {
4200 if (errno == EINTR)
4201 continue;
4202 die("select failed: %s\n", strerror(errno));
4203 }
4204 if (FD_ISSET(cmdfd, &rfd)) {
4205 ttyread();
4206 if (blinktimeout) {
4207 blinkset = tattrset(ATTR_BLINK);
4208 if (!blinkset)
4209 MODBIT(term.mode, 0, MODE_BLINK);
4210 }
4211 }
4212
4213 if (FD_ISSET(xfd, &rfd))
4214 xev = actionfps;
4215
4216 clock_gettime(CLOCK_MONOTONIC, &now);
4217 drawtimeout.tv_sec = 0;
4218 drawtimeout.tv_nsec = (1000 * 1E6)/ xfps;
4219 tv = &drawtimeout;
4220
4221 dodraw = 0;
4222 if (blinktimeout && TIMEDIFF(now, lastblink) > blinktimeout) {
4223 tsetdirtattr(ATTR_BLINK);
4224 term.mode ^= MODE_BLINK;
4225 lastblink = now;
4226 dodraw = 1;
4227 }
4228 deltatime = TIMEDIFF(now, last);
4229 if (deltatime > 1000 / (xev ? xfps : actionfps)) {
4230 dodraw = 1;
4231 last = now;
4232 }
4233
4234 if (dodraw) {
4235 while (XPending(xw.dpy)) {
4236 XNextEvent(xw.dpy, &ev);
4237 if (XFilterEvent(&ev, None))
4238 continue;
4239 if (handler[ev.type])
4240 (handler[ev.type])(&ev);
4241 }
4242
4243 draw();
4244 XFlush(xw.dpy);
4245
4246 if (xev && !FD_ISSET(xfd, &rfd))
4247 xev--;
4248 if (!FD_ISSET(cmdfd, &rfd) && !FD_ISSET(xfd, &rfd)) {
4249 if (blinkset) {
4250 if (TIMEDIFF(now, lastblink) \
4251 > blinktimeout) {
4252 drawtimeout.tv_nsec = 1000;
4253 } else {
4254 drawtimeout.tv_nsec = (1E6 * \
4255 (blinktimeout - \
4256 TIMEDIFF(now,
4257 lastblink)));
4258 }
4259 drawtimeout.tv_sec = \
4260 drawtimeout.tv_nsec / 1E9;
4261 drawtimeout.tv_nsec %= (long)1E9;
4262 } else {
4263 tv = NULL;
4264 }
4265 }
4266 }
4267 }
4268 }
4269
4270 void
4271 usage(void)
4272 {
4273 die("%s " VERSION " (c) 2010-2015 st engineers\n"
4274 "usage: st [-a] [-v] [-c class] [-f font] [-g geometry] [-o file]\n"
4275 " [-i] [-t title] [-T title] [-w windowid] [-e command ...]"
4276 " [command ...]\n"
4277 " st [-a] [-v] [-c class] [-f font] [-g geometry] [-o file]\n"
4278 " [-i] [-t title] [-T title] [-w windowid] [-l line]"
4279 " [stty_args ...]\n",
4280 argv0);
4281 }
4282
4283 int
4284 main(int argc, char *argv[])
4285 {
4286 uint cols = 80, rows = 24;
4287
4288 xw.l = xw.t = 0;
4289 xw.isfixed = False;
4290 xw.cursor = 0;
4291
4292 ARGBEGIN {
4293 case 'a':
4294 allowaltscreen = 0;
4295 break;
4296 case 'c':
4297 opt_class = EARGF(usage());
4298 break;
4299 case 'e':
4300 if (argc > 0)
4301 --argc, ++argv;
4302 goto run;
4303 case 'f':
4304 opt_font = EARGF(usage());
4305 break;
4306 case 'g':
4307 xw.gm = XParseGeometry(EARGF(usage()),
4308 &xw.l, &xw.t, &cols, &rows);
4309 break;
4310 case 'i':
4311 xw.isfixed = 1;
4312 break;
4313 case 'o':
4314 opt_io = EARGF(usage());
4315 break;
4316 case 'l':
4317 opt_line = EARGF(usage());
4318 break;
4319 case 't':
4320 case 'T':
4321 opt_title = EARGF(usage());
4322 break;
4323 case 'w':
4324 opt_embed = EARGF(usage());
4325 break;
4326 case 'v':
4327 default:
4328 usage();
4329 } ARGEND;
4330
4331 run:
4332 if (argc > 0) {
4333 /* eat all remaining arguments */
4334 opt_cmd = argv;
4335 if (!opt_title && !opt_line)
4336 opt_title = basename(xstrdup(argv[0]));
4337 }
4338 setlocale(LC_CTYPE, "");
4339 XSetLocaleModifiers("");
4340 tnew(MAX(cols, 1), MAX(rows, 1));
4341 xinit();
4342 selinit();
4343 run();
4344
4345 return 0;
4346 }
4347