Xinqi Bao's Git

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