'maxdrawtimeout' option
[k8sterm.git] / src / sterm.c
bloba37f50ba6dc55dac87d86ca81cf607ddd3cf8059
1 /* See LICENSE for licence details. */
2 #define VERSION "0.3.1.beta3"
4 #ifdef _XOPEN_SOURCE
5 # undef _XOPEN_SOURCE
6 #endif
7 #define _XOPEN_SOURCE 600
9 #include <alloca.h>
10 #include <ctype.h>
11 #include <errno.h>
12 #include <fcntl.h>
13 #include <iconv.h>
14 #include <limits.h>
15 #include <locale.h>
16 #include <pty.h>
17 #include <stdarg.h>
18 #include <stdio.h>
19 #include <stdlib.h>
20 #include <string.h>
21 #include <strings.h>
22 #include <signal.h>
23 #include <sys/ioctl.h>
24 #include <sys/select.h>
25 #include <sys/stat.h>
26 #include <sys/time.h>
27 #include <sys/types.h>
28 #include <sys/wait.h>
29 #include <time.h>
30 #include <unistd.h>
31 #include <X11/Xatom.h>
32 #include <X11/Xlib.h>
33 #include <X11/Xutil.h>
34 #include <X11/cursorfont.h>
35 #include <X11/keysym.h>
37 //#include "dbglog.h"
40 // uncomment the following to use XCreateGlyphCursor() instead of XCreatePixmapCursor()
41 //#define BLANKPTR_USE_GLYPH_CURSOR
44 //#define PASTE_SELECTION_DEBUG
46 //#define DUMP_KEYSYMS
48 //#define KEYPAD_DUMP
50 //#define DUMP_PROG_OUTPUT
51 //#define DUMP_PROG_INPUT
53 //#define DUMP_IO_READ
54 //#define DUMP_IO_WRITE
56 #if defined(DUMP_IO_READ) || defined(DUMP_IO_WRITE)
57 # define DUMP_IO
58 #endif
60 #ifdef KEYPAD_DUMP
61 # define DUMP_KEYPAD_SWITCH(strflag,strstate) do { fprintf(stderr, "KEYPAD %s (%s)\n", (strstate), (strflag)); } while (0)
62 #else
63 # define DUMP_KEYPAD_SWITCH(strflag,strstate) ((void)(sizeof(strflag)+sizeof(strstate)))
64 #endif
67 ////////////////////////////////////////////////////////////////////////////////
68 #define USAGE \
69 "sterm " VERSION " (c) 2010-2012 st engineers and Ketmar // Vampire Avalon\n" \
70 "usage: sterm [-t title] [-c class] [-w windowid] [-T termname] [-C config_file] [-l langiconv] [-S] [-v] [-R stcmd] [-e command...]\n"
73 ////////////////////////////////////////////////////////////////////////////////
74 #define FONT "-*-fixed-medium-r-normal-*-18-*-*-*-*-*-*-*"
75 #define FONTBOLD "-*-fixed-bold-r-normal-*-18-*-*-*-*-*-*-*"
76 #define FONTTAB "-*-fixed-medium-r-normal-*-14-*-*-*-*-*-*-*"
79 /* Default shell to use if SHELL is not set in the env */
80 #define SHELL "/bin/sh"
83 /* Terminal colors (16 first used in escape sequence) */
84 static const char *defcolornames[] = {
85 #if 1
86 /* 8 normal colors */
87 "black",
88 "red3",
89 "green3",
90 "yellow3",
91 "blue2",
92 "magenta3",
93 "cyan3",
94 "gray90",
95 /* 8 bright colors */
96 "gray50",
97 "red",
98 "green",
99 "yellow",
100 "#5c5cff",
101 "magenta",
102 "cyan",
103 "white",
104 #else
105 /* 8 normal colors */
106 "#000000",
107 "#b21818",
108 "#18b218",
109 "#b26818",
110 "#1818b2",
111 "#b218b2",
112 "#18b2b2",
113 "#b2b2b2",
114 /* 8 bright colors */
115 "#686868",
116 "#ff5454",
117 "#54ff54",
118 "#ffff54",
119 "#5454ff",
120 "#ff54ff",
121 "#54ffff",
122 "#ffffff",
123 #endif
127 /* more colors can be added after 255 to use with DefaultXX */
128 static const char *defextcolornames[] = {
129 "#cccccc", /* 256 */
130 "#333333", /* 257 */
131 /* root terminal fg and bg */
132 "#809a70", /* 258 */
133 "#002000", /* 259 */
134 /* bold and underline */
135 "#00afaf", /* 260 */
136 "#00af00", /* 261 */
140 /* Default colors (colorname index) foreground, background, cursor, unfocused cursor */
141 #define DEFAULT_FG (7)
142 #define DEFAULT_BG (0)
143 #define DEFAULT_CS (256)
144 #define DEFAULT_UCS (257)
146 #define TNAME "xterm"
148 /* double-click timeout (in milliseconds) between clicks for selection */
149 #define DOUBLECLICK_TIMEOUT (300)
150 #define TRIPLECLICK_TIMEOUT (2*DOUBLECLICK_TIMEOUT)
151 //#define SELECT_TIMEOUT 20 /* 20 ms */
152 #define DRAW_TIMEOUT 18 /* 18 ms */
154 #define TAB (8)
157 ////////////////////////////////////////////////////////////////////////////////
158 #define MAX_COLOR (511)
160 /* XEMBED messages */
161 #define XEMBED_FOCUS_IN (4)
162 #define XEMBED_FOCUS_OUT (5)
165 /* Arbitrary sizes */
166 #define ESC_TITLE_SIZ (256)
167 #define ESC_BUF_SIZ (256)
168 #define ESC_ARG_SIZ (16)
169 #define DRAW_BUF_SIZ (2048)
170 #define UTF_SIZ (4)
171 #define OBUFSIZ (256)
172 #define WBUFSIZ (256)
175 /* masks for key translation */
176 #define XK_NO_MOD (UINT_MAX)
177 #define XK_ANY_MOD (0)
180 /* misc utility macros */
181 //#define TIMEDIFF(t1, t2) ((t1.tv_sec-t2.tv_sec)*1000+(t1.tv_usec-t2.tv_usec)/1000)
182 #define SERRNO strerror(errno)
183 #define MIN(a, b) ((a) < (b) ? (a) : (b))
184 #define MAX(a, b) ((a) < (b) ? (b) : (a))
185 #define LEN(a) (sizeof(a)/sizeof(a[0]))
186 #define DEFAULT(a, b) (a) = ((a) ? (a) : (b))
187 #define BETWEEN(x, a, b) ((a) <= (x) && (x) <= (b))
188 #define LIMIT(x, a, b) ((x) = (x) < (a) ? (a) : (x) > (b) ? (b) : (x))
189 #define ATTRCMP(a, b) ((a).attr != (b).attr || (a).fg != (b).fg || (a).bg != (b).bg)
190 #define IS_SET(flag) (term->mode&(flag))
191 #define X2COL(x) ((x)/xw.cw)
192 #define Y2ROW(y) ((y-(opt_tabposition==1 ? xw.tabheight : 0))/xw.ch-(term!=NULL ? term->topline : 0))
193 #define IS_GFX(mode) ((mode)&ATTR_GFX)
196 ////////////////////////////////////////////////////////////////////////////////
197 enum {
198 BELL_AUDIO = 0x01,
199 BELL_URGENT = 0x02
202 enum {
203 CMDMODE_NONE,
204 CMDMODE_INPUT,
205 CMDMODE_MESSAGE
208 enum glyph_attribute {
209 ATTR_NULL = 0x00,
210 ATTR_REVERSE = 0x01,
211 ATTR_UNDERLINE = 0x02,
212 ATTR_BOLD = 0x04,
213 ATTR_GFX = 0x08,
214 ATTR_DEFFG = 0x10,
215 ATTR_DEFBG = 0x20,
218 enum cursor_movement {
219 CURSOR_UP,
220 CURSOR_DOWN,
221 CURSOR_LEFT,
222 CURSOR_RIGHT,
223 CURSOR_SAVE,
224 CURSOR_LOAD
227 enum cursor_state {
228 CURSOR_DEFAULT = 0x00,
229 CURSOR_HIDE = 0x01,
230 CURSOR_WRAPNEXT = 0x02
233 enum glyph_state {
234 GLYPH_SET = 0x01, /* for selection only */
235 GLYPH_DIRTY = 0x02,
236 GLYPH_WRAP = 0x10, /* can be set for the last line glyph */
240 enum term_mode {
241 MODE_WRAP = 0x01,
242 MODE_INSERT = 0x02,
243 MODE_APPKEYPAD = 0x04,
244 MODE_ALTSCREEN = 0x08,
245 MODE_CRLF = 0x10,
246 MODE_MOUSEBTN = 0x20,
247 MODE_MOUSEMOTION = 0x40,
248 MODE_MOUSE = 0x20|0x40,
249 MODE_REVERSE = 0x80,
250 MODE_BRACPASTE = 0x100,
251 MODE_FOCUSEVT = 0x200,
252 MODE_DISPCTRL = 0x400, //TODO: not implemented yet
253 MODE_GFX0 = 0x1000,
254 MODE_GFX1 = 0x2000,
257 enum escape_state {
258 ESC_START = 0x01,
259 ESC_CSI = 0x02,
260 ESC_OSC = 0x04,
261 ESC_TITLE = 0x08,
262 ESC_ALTCHARSET = 0x10,
263 ESC_HASH = 0x20,
264 ESC_PERCENT = 0x40,
265 ESC_ALTG1 = 0x80,
268 enum window_state {
269 WIN_VISIBLE = 0x01,
270 WIN_REDRAW = 0x02,
271 WIN_FOCUSED = 0x04,
274 /* bit macro */
275 #undef B0
276 enum { B0=1, B1=2, B2=4, B3=8, B4=16, B5=32, B6=64, B7=128 };
279 ////////////////////////////////////////////////////////////////////////////////
280 typedef unsigned char uchar;
281 typedef unsigned int uint;
282 typedef unsigned long ulong;
283 typedef unsigned short ushort;
286 typedef struct __attribute__((packed)) {
287 char c[UTF_SIZ]; /* character code */
288 uchar attr; /* attribute flags */
289 ushort fg; /* foreground */
290 ushort bg; /* background */
291 uchar state; /* state flags */
292 } Glyph;
295 typedef Glyph *Line;
297 typedef struct {
298 Glyph attr; /* current char attributes */
299 int x;
300 int y;
301 char state;
302 } TCursor;
305 /* CSI Escape sequence structs */
306 /* ESC '[' [[ [<priv>] <arg> [;]] <mode>] */
307 typedef struct {
308 char buf[ESC_BUF_SIZ]; /* raw string */
309 int len; /* raw string length */
310 char priv;
311 int arg[ESC_ARG_SIZ];
312 int narg; /* nb of args */
313 char mode;
314 } CSIEscape;
317 /* Purely graphic info */
318 typedef struct {
319 Display *dpy;
320 Colormap cmap;
321 Window win;
322 Cursor cursor;
323 Cursor blankPtr;
324 Atom xembed;
325 XIM xim;
326 XIC xic;
327 int scr;
328 int w; /* window width */
329 int h; /* window height */
330 int bufw; /* pixmap width */
331 int bufh; /* pixmap height */
332 int ch; /* char height */
333 int cw; /* char width */
334 char state; /* focus, redraw, visible */
336 int tch; /* tab text char height */
337 Pixmap pictab;
338 int tabheight;
339 //struct timeval lastdraw;
340 } XWindow;
343 /* TODO: use better name for vars... */
344 typedef struct {
345 int mode;
346 int bx, by;
347 int ex, ey;
348 struct { int x, y; } b, e;
349 char *clip;
350 Atom xtarget;
351 int tclick1;
352 int tclick2;
353 } Selection;
356 /* Drawing Context */
357 typedef struct {
358 ulong *ncol; // normal colors
359 ulong *bcol; // b/w colors
360 ulong *gcol; // green colors
361 ulong *clrs[3];
362 GC gc;
363 struct {
364 int ascent;
365 int descent;
366 short lbearing;
367 short rbearing;
368 XFontSet set;
369 Font fid;
370 } font[3];
371 } DC;
374 typedef void (*CmdLineExecFn) (int cancelled);
377 #define CMDLINE_SIZE (256)
379 /* Internal representation of the screen */
380 typedef struct Term {
381 int cmdfd;
382 int dead;
383 int exitcode;
384 int needConv; /* 0: utf-8 locale */
385 int belltype;
386 int blackandwhite;
388 int curblink;
389 int curbhidden;
390 int lastBlinkTime;
391 int curblinkinactive;
393 int row; /* nb row */
394 int col; /* nb col */
395 int topline; /* top line for drawing (0: no history; 1: show one history line; etc) */
396 int linecount; /* full, with history */
397 int maxhistory;/* max history lines; 0: none; <0: infinite */
398 Line *line; /* screen */
399 Line *alt; /* alternate screen */
400 char *dirty; /* dirtyness of lines */
401 TCursor c; /* cursor */
402 int top; /* top scroll limit */
403 int bot; /* bottom scroll limit */
404 int mode; /* terminal mode flags */
405 int mousemode; /* mouse mode: 1000, 1005, 1006, 1015 */
406 int esc; /* escape state flags */
407 int charset; /* 0 or 1 */
409 TCursor csaved; /* saved cursor info */
410 // old cursor position
411 int oldcx;
412 int oldcy;
414 char title[ESC_TITLE_SIZ+1];
415 int titlelen;
417 int mouseob;
418 int mouseox;
419 int mouseoy;
421 char obuf[OBUFSIZ];
422 #ifdef DUMP_PROG_OUTPUT
423 int xobuflen;
424 #endif
425 int obuflen;
427 char ubuf[UTF_SIZ];
428 int ubufpos;
430 char drawbuf[DRAW_BUF_SIZ];
432 char wrbuf[WBUFSIZ];
433 int wrbufsize;
434 int wrbufused;
435 int wrbufpos;
437 CSIEscape escseq;
438 Selection sel;
439 pid_t pid;
440 int lastDrawTime;
442 char *execcmd;
444 Pixmap picbuf;
445 int picbufw;
446 int picbufh;
448 ushort deffg;
449 ushort defbg;
451 int wantRedraw;
453 int lastActiveTime;
455 int cmdMode;
456 char cmdline[UTF_SIZ*CMDLINE_SIZE];
457 int cmdreslen; // byte length of 'reserved' (read-only) part
458 int cmdofs;
459 char cmdc[UTF_SIZ+1];
460 int cmdcl;
461 int cmdtabpos;
462 const char *cmdprevc;
463 CmdLineExecFn cmdexecfn;
464 } Term;
467 ////////////////////////////////////////////////////////////////////////////////
468 /* Globals */
469 static ushort *unimap = NULL; // 0 or 65535 items; 127: special; high bit set: use alt(gfx) mode; 0: empty
471 static char **opt_cmd = NULL;
472 static char *opt_title = NULL;
473 static char *opt_embed = NULL;
474 static char *opt_class = NULL;
475 static char *opt_term = NULL;
476 static char *opt_fontnorm = NULL;
477 static char *opt_fontbold = NULL;
478 static char *opt_fonttab = NULL;
479 static char *opt_shell = NULL;
480 static char *opt_colornames[512];
481 static int opt_term_locked = 0;
482 static int opt_doubleclick_timeout = DOUBLECLICK_TIMEOUT;
483 static int opt_tripleclick_timeout = TRIPLECLICK_TIMEOUT;
484 static int opt_tabsize = TAB;
485 static int defaultFG = DEFAULT_FG;
486 static int defaultBG = DEFAULT_BG;
487 static int defaultCursorFG = 0;
488 static int defaultCursorBG = DEFAULT_CS;
489 static int defaultCursorInactiveFG = 0;
490 static int defaultCursorInactiveBG = DEFAULT_UCS;
491 static int defaultBoldFG = -1;
492 static int defaultUnderlineFG = -1;
493 static int normalTabFG = 258;
494 static int normalTabBG = 257;
495 static int activeTabFG = 258;
496 static int activeTabBG = 0;
497 static int opt_maxhistory = 512;
498 static int opt_ptrblank = 2000; // delay; 0: never
499 static int opt_tabcount = 6;
500 static int opt_tabposition = 0;
501 static int opt_drawtimeout = DRAW_TIMEOUT;
502 static int opt_disabletabs = 0;
503 static int opt_audiblebell = 1;
504 static int opt_urgentbell = 1;
505 static int opt_cursorBlink = 0;
506 static int opt_cursorBlinkInactive = 0;
507 static int opt_drawunderline = 1;
508 static int opt_ignoreclose = 0;
509 static int opt_maxdrawtimeout = 3000;
510 static int ptrBlanked = 0;
511 static int ptrLastMove = 0;
512 static int globalBW = 0;
514 static Term **term_array = NULL;
515 static int term_count = 0;
516 static int term_array_size = 0;
517 static Term *term; // current terminal
518 static int termidx; // current terminal index; DON'T RELAY ON IT!
519 static int updateTabBar;
520 static int lastDrawTime = 0;
521 static char *lastSelStr = NULL;
522 //static int lastSelLength = 0;
524 static int exitcode = 0;
525 static int closeRequestComes = 0;
527 static DC dc;
528 static XWindow xw;
530 static Atom XA_VT_SELECTION;
531 static Atom XA_CLIPBOARD;
532 static Atom XA_UTF8;
533 static Atom XA_TARGETS;
534 static Atom XA_NETWM_NAME;
535 static Atom XA_WM_DELETE_WINDOW;
538 ////////////////////////////////////////////////////////////////////////////////
539 typedef struct {
540 KeySym src;
541 KeySym dst;
542 } KeyTransDef;
545 static KeyTransDef *keytrans = NULL;
546 static int keytrans_size = 0;
547 static int keytrans_used = 0;
550 typedef struct {
551 KeySym key;
552 uint mask;
553 int kp;
554 char *str;
555 } KeyInfoDef;
558 static KeyInfoDef *keybinds = NULL;
559 static int keybinds_size = 0;
560 static int keybinds_used = 0;
562 static KeyInfoDef *keymap = NULL;
563 static int keymap_size = 0;
564 static int keymap_used = 0;
567 ////////////////////////////////////////////////////////////////////////////////
568 static void executeCommands (const char *str);
569 static const char *findCommandCompletion (const char *str, int slen, const char *prev);
571 static void ttyresize (void);
572 static void tputc (const char *c); // `c` is utf-8
573 static void ttywrite (const char *s, size_t n);
574 static void tsetdirt (int top, int bot);
575 static void tfulldirt (void);
577 static void xseturgency (int add);
578 static void xfixsel (void);
579 static void xblankPointer (void);
580 static void xunblankPointer (void);
582 static void draw (int forced);
584 static void tcmdput (const char *s, int len);
587 static inline void ttywritestr (const char *s) { if (s != NULL && s[0]) ttywrite(s, strlen(s)); }
590 static inline ulong getColor (int idx) {
591 if (globalBW && (term == NULL || !term->blackandwhite)) return dc.clrs[globalBW][idx];
592 if (term != NULL) return dc.clrs[term->blackandwhite%3][idx];
593 return dc.clrs[0][idx];
595 if (globalBW) return dc.bcol[idx];
596 if (term != NULL) {
597 return (term->blackandwhite ? dc.bcol[idx] : dc.ncol[idx]);
599 return dc.ncol[idx];
604 ////////////////////////////////////////////////////////////////////////////////
606 static void trimstr (char *s) {
607 char *e;
609 while (*s && isspace(*s)) ++s;
610 for (e = s+strlen(s); e > s; --e) if (!isspace(e[-1])) break;
611 if (e <= s) *s = 0; else *e = 0;
615 // parse the argument list
616 // return error message or NULL
617 // format:
618 // '*': skip
619 // 's': string (char *)
620 // 'i': integer (int *)
621 // 'b': boolean (int *)
622 // '|': optional arguments follows
623 // '.': stop parsing, ignore rest
624 // 'R': stop parsing, set rest ptr (char *)
625 // string modifiers (also for 'R'):
626 // '!' -- don't allow empty strings
627 // '-' -- trim spaces
628 // int modifiers:
629 // {lo,hi}
630 // {,hi}
631 // {lo}
632 // WARNING! `line` will be modified!
633 // WARNING! string pointers will point INSIDE `line`, so don't discard it!
634 // UGLY! REWRITE!
635 const char *iniParseArguments (char *line, const char *fmt, ...) {
636 va_list ap;
637 int inOptional = 0;
639 if (line == NULL) return "alas";
640 trimstr(line);
641 va_start(ap, fmt);
642 while (*fmt) {
643 char spec = *fmt++, *args;
645 if (spec == '|') { inOptional = 1; continue; }
646 if (spec == '.') { va_end(ap); return NULL; }
648 while (*line && isspace(*line)) ++line;
649 if (*line == '#') *line = 0;
651 if (spec == 'R') {
652 char **p = va_arg(ap, char **);
653 int noempty = 0;
655 while (*fmt) {
656 if (*fmt == '!') { ++fmt; noempty = 1; }
657 else if (*fmt == '-') { ++fmt; trimstr(line); }
658 else break;
660 va_end(ap);
661 if (noempty && !line[0]) return "invalid empty arg";
662 if (p != NULL) *p = line;
663 return NULL;
666 if (!line[0]) {
667 // end of line, stop right here
668 va_end(ap);
669 if (!inOptional) return "out of args";
670 return NULL;
673 args = line;
675 char *dest = args, qch = '#';
676 int n;
678 if (line[0] == '"' || line[0] == '\'') qch = *line++;
680 while (*line && *line != qch) {
681 if (qch == '#' && isspace(*line)) break;
683 if (*line == '\\') {
684 if (!line[1]) { va_end(ap); return "invalid escape"; }
685 switch (*(++line)) {
686 case 'n': *dest++ = '\n'; ++line; break;
687 case 'r': *dest++ = '\r'; ++line; break;
688 case 't': *dest++ = '\t'; ++line; break;
689 case 'a': *dest++ = '\a'; ++line; break;
690 case 'e': *dest++ = '\x1b'; ++line; break; // esc
691 case 's': *dest++ = ' '; ++line; break;
692 case 'x': // hex
693 ++line;
694 if (!isxdigit(*line)) { va_end(ap); return "invalid hex escape"; }
695 n = toupper(*line)-'0'; if (n > 9) n -= 7;
696 ++line;
697 if (isxdigit(*line)) {
698 int b = toupper(*line)-'0'; if (b > 9) b -= 7;
700 n = (n*16)+b;
701 ++line;
703 *dest++ = n;
704 break;
705 case '0': // octal
706 n = 0;
707 for (int f = 0; f < 4; ++f) {
708 if (*line < '0' || *line > '7') break;
709 n = (n*8)+(line[0]-'0');
710 if (n > 255) { va_end(ap); return "invalid oct escape"; }
711 ++line;
713 if (n == 0) { va_end(ap); return "invalid oct escape"; }
714 *dest++ = n;
715 break;
716 case '1'...'9': // decimal
717 n = 0;
718 for (int f = 0; f < 3; ++f) {
719 if (*line < '0' || *line > '9') break;
720 n = (n*8)+(line[0]-'0');
721 if (n > 255) { va_end(ap); return "invalid dec escape"; }
722 ++line;
724 if (n == 0) { va_end(ap); return "invalid oct escape"; }
725 *dest++ = n;
726 break;
727 default:
728 *dest++ = *line++;
729 break;
731 } else {
732 *dest++ = *line++;
735 if (qch != '#') {
736 if (*line != qch) return "unfinished string";
737 if (*line) ++line;
738 } else if (*line && *line != '#') ++line;
739 *dest = 0;
741 // now process and convert argument
742 switch (spec) {
743 case '*': /* skip */
744 break;
745 case 's': { /* string */
746 int noempty = 0, trim = 0;
747 char **p;
749 for (;;) {
750 if (*fmt == '!') { noempty = 1; ++fmt; }
751 else if (*fmt == '-') { trim = 1; ++fmt; }
752 else break;
755 if (trim) trimstr(args);
757 if (noempty && !args[0]) { va_end(ap); return "invalid empty string"; }
758 p = va_arg(ap, char **);
759 if (p != NULL) *p = args;
760 } break;
761 case 'i': /* int */
762 if (!args[0]) {
763 va_end(ap);
764 return "invalid integer";
765 } else {
766 int *p = va_arg(ap, int *);
767 long int n;
768 char *eptr;
770 trimstr(args);
771 n = strtol(args, &eptr, 0);
772 if (*eptr) { va_end(ap); return "invalid integer"; }
774 if (*fmt == '{') {
775 // check min/max
776 int minmax[2], haveminmax[2];
778 haveminmax[0] = haveminmax[1] = 0;
779 minmax[0] = minmax[1] = 0;
780 ++fmt;
781 for (int f = 0; f < 2; ++f) {
782 if (isdigit(*fmt) || *fmt == '-' || *fmt == '+') {
783 int neg = 0;
784 haveminmax[f] = 1;
785 if (*fmt == '-') neg = 1;
786 if (!isdigit(*fmt)) {
787 ++fmt;
788 if (!isdigit(*fmt)) { va_end(ap); return "invalid integer bounds"; }
790 while (isdigit(*fmt)) {
791 minmax[f] = minmax[f]*10+(fmt[0]-'0');
792 ++fmt;
794 if (neg) minmax[f] = -minmax[f];
795 //fprintf(stderr, "got: %d\n", minmax[f]);
797 if (*fmt == ',') {
798 if (f == 1) { va_end(ap); return "invalid integer bounds: extra comma"; }
799 // do nothing, we are happy
800 ++fmt;
801 } else if (*fmt == '}') {
802 // ok, done
803 break;
804 } else { va_end(ap); return "invalid integer bounds"; }
806 if (*fmt != '}') { va_end(ap); return "invalid integer bounds"; }
807 ++fmt;
809 //fprintf(stderr, "b: (%d,%d) (%d,%d)\n", haveminmax[0], minmax[0], haveminmax[1], minmax[1]);
810 if ((haveminmax[0] && n < minmax[0]) || (haveminmax[1] && n > minmax[1])) { va_end(ap); return "integer out of bounds"; }
813 if (p) *p = n;
815 break;
816 case 'b': { /* bool */
817 int *p = va_arg(ap, int *);
819 trimstr(args);
820 if (!args[0]) { va_end(ap); return "invalid boolean"; }
821 if (strcasecmp(args, "true") == 0 || strcasecmp(args, "on") == 0 ||
822 strcasecmp(args, "tan") == 0 || strcasecmp(args, "1") == 0) {
823 if (p) *p = 1;
824 } else if (strcasecmp(args, "false") == 0 || strcasecmp(args, "off") == 0 ||
825 strcasecmp(args, "ona") == 0 || strcasecmp(args, "0") == 0) {
827 if (p) *p = 0;
828 } else {
829 va_end(ap);
830 return "invalid boolean";
832 } break;
833 default:
834 va_end(ap);
835 return "invalid format specifier";
838 va_end(ap);
839 while (*line && isspace(*line)) ++line;
840 if (!line[0] || line[0] == '#') return NULL;
841 return "extra args";
845 ////////////////////////////////////////////////////////////////////////////////
846 // UTF-8
847 static int utf8decode (const char *s, ulong *u) {
848 uchar c;
849 int n, rtn;
851 rtn = 1;
852 c = *s;
853 if (~c & B7) { /* 0xxxxxxx */
854 *u = c;
855 return rtn;
856 } else if ((c & (B7|B6|B5)) == (B7|B6)) { /* 110xxxxx */
857 *u = c&(B4|B3|B2|B1|B0);
858 n = 1;
859 } else if ((c & (B7|B6|B5|B4)) == (B7|B6|B5)) { /* 1110xxxx */
860 *u = c&(B3|B2|B1|B0);
861 n = 2;
862 } else if ((c & (B7|B6|B5|B4|B3)) == (B7|B6|B5|B4)) { /* 11110xxx */
863 *u = c & (B2|B1|B0);
864 n = 3;
865 } else {
866 goto invalid;
868 ++s;
869 for (int f = n; f > 0; --f, ++rtn, ++s) {
870 c = *s;
871 if ((c & (B7|B6)) != B7) goto invalid; /* 10xxxxxx */
872 *u <<= 6;
873 *u |= c & (B5|B4|B3|B2|B1|B0);
875 if ((n == 1 && *u < 0x80) ||
876 (n == 2 && *u < 0x800) ||
877 (n == 3 && *u < 0x10000) ||
878 (*u >= 0xD800 && *u <= 0xDFFF)) {
879 goto invalid;
881 return rtn;
882 invalid:
883 *u = 0xFFFD;
884 return rtn;
888 static int utf8encode (ulong u, char *s) {
889 uchar *sp;
890 ulong uc;
891 int n;
893 sp = (uchar *)s;
894 uc = u&0x1fffff;
895 if (uc < 0x80) {
896 *sp = uc; /* 0xxxxxxx */
897 return 1;
898 } else if (uc < 0x800) {
899 *sp = (uc >> 6) | (B7|B6); /* 110xxxxx */
900 n = 1;
901 } else if (uc < 0x10000) {
902 *sp = (uc >> 12) | (B7|B6|B5); /* 1110xxxx */
903 n = 2;
904 } else if (uc <= 0x10FFFF) {
905 *sp = (uc >> 18) | (B7|B6|B5|B4); /* 11110xxx */
906 n = 3;
907 } else {
908 goto invalid;
910 ++sp;
911 for (int f = n; f > 0; --f, ++sp) *sp = ((uc >> 6*(f-1)) & (B5|B4|B3|B2|B1|B0)) | B7; /* 10xxxxxx */
912 return n+1;
913 invalid:
914 /* U+FFFD */
915 *s++ = '\xEF';
916 *s++ = '\xBF';
917 *s = '\xBD';
918 return 3;
922 /* use this if your buffer is less than UTF_SIZ, it returns 1 if you can decode
923 UTF-8 otherwise return 0 */
924 static int isfullutf8 (const char *s, int b) {
925 uchar *c1, *c2, *c3;
927 c1 = (uchar *) s;
928 c2 = (uchar *) ++s;
929 c3 = (uchar *) ++s;
930 if (b < 1) return 0;
931 if ((*c1&(B7|B6|B5)) == (B7|B6) && b == 1) return 0;
932 if ((*c1&(B7|B6|B5|B4)) == (B7|B6|B5) && (b == 1 || (b == 2 && (*c2&(B7|B6)) == B7))) return 0;
933 if ((*c1&(B7|B6|B5|B4|B3)) == (B7|B6|B5|B4) && (b == 1 || (b == 2 && (*c2&(B7|B6)) == B7) || (b == 3 && (*c2&(B7|B6)) == B7 && (*c3&(B7|B6)) == B7))) return 0;
934 return 1;
938 static int utf8size (const char *s) {
939 uchar c = *s;
941 if (~c&B7) return 1;
942 if ((c&(B7|B6|B5)) == (B7|B6)) return 2;
943 if ((c&(B7|B6|B5|B4)) == (B7|B6|B5)) return 3;
944 return 4;
948 static int utf8strlen (const char *s) {
949 int len = 0;
951 while (*s) {
952 if (((unsigned char)(s[0])&0xc0) == 0xc0 || ((unsigned char)(s[0])&0x80) == 0) ++len;
953 ++s;
955 return len;
959 static void utf8choplast (char *s) {
960 int lastpos = 0;
962 for (char *t = s; *t; ++t) {
963 if (((unsigned char)(t[0])&0xc0) == 0xc0 || ((unsigned char)(t[0])&0x80) == 0) lastpos = (int)(t-s);
965 s[lastpos] = 0;
969 ////////////////////////////////////////////////////////////////////////////////
970 // utilities
971 static char *SPrintfVA (const char *fmt, va_list vaorig) {
972 char *buf = NULL;
973 int olen, len = 128;
975 buf = malloc(len);
976 if (buf == NULL) { fprintf(stderr, "\nFATAL: out of memory!\n"); abort(); }
977 for (;;) {
978 char *nb;
979 va_list va;
981 va_copy(va, vaorig);
982 olen = vsnprintf(buf, len, fmt, va);
983 va_end(va);
984 if (olen >= 0 && olen < len) return buf;
985 if (olen < 0) olen = len*2-1;
986 nb = realloc(buf, olen+1);
987 if (nb == NULL) { fprintf(stderr, "\nFATAL: out of memory!\n"); abort(); }
988 buf = nb;
989 len = olen+1;
994 static __attribute__((format(printf,1,2))) char *SPrintf (const char *fmt, ...) {
995 char *buf = NULL;
996 va_list va;
998 va_start(va, fmt);
999 buf = SPrintfVA(fmt, va);
1000 va_end(va);
1001 return buf;
1005 static __attribute__((noreturn)) __attribute__((format(printf,1,2))) void die (const char *errstr, ...) {
1006 va_list ap;
1008 fprintf(stderr, "FATAL: ");
1009 va_start(ap, errstr);
1010 vfprintf(stderr, errstr, ap);
1011 va_end(ap);
1012 fprintf(stderr, "\n");
1013 exit(EXIT_FAILURE);
1017 ////////////////////////////////////////////////////////////////////////////////
1018 // getticks
1019 static struct timespec mclk_sttime; // starting time of monotonic clock
1022 static void mclock_init (void) {
1023 clock_gettime(CLOCK_MONOTONIC /*CLOCK_MONOTONIC_RAW*/, &mclk_sttime);
1027 static uint mclock_ticks (void) {
1028 struct timespec tp;
1030 clock_gettime(CLOCK_MONOTONIC /*CLOCK_MONOTONIC_RAW*/, &tp);
1031 tp.tv_sec -= mclk_sttime.tv_sec;
1032 return tp.tv_sec*1000+(tp.tv_nsec/1000000);
1036 ////////////////////////////////////////////////////////////////////////////////
1037 // locale conversions
1038 static iconv_t icFromLoc;
1039 static iconv_t icToLoc;
1040 static int needConversion = 0;
1041 static const char *cliLocale = NULL;
1044 static void initLCConversion (void) {
1045 const char *lct = setlocale(LC_CTYPE, NULL);
1046 char *cstr;
1048 needConversion = 0;
1049 if (cliLocale == NULL) {
1050 if (strrchr(lct, '.') != NULL) lct = strrchr(lct, '.')+1;
1051 } else {
1052 lct = cliLocale;
1054 if (strcasecmp(lct, "utf8") == 0 || strcasecmp(lct, "utf-8") == 0) return;
1055 //fprintf(stderr, "locale: [%s]\n", lct);
1056 icFromLoc = iconv_open("UTF-8", lct);
1057 if (icFromLoc == (iconv_t)-1) die("can't initialize locale conversion");
1058 cstr = SPrintf("%s//TRANSLIT", lct);
1059 icToLoc = iconv_open(cstr, "UTF-8");
1060 free(cstr);
1061 if (icToLoc == (iconv_t)-1) die("can't initialize locale conversion");
1062 needConversion = 1;
1066 static int loc2utf (char *dest, const char *src, int len) {
1067 if (needConversion) {
1068 char *ibuf, *obuf;
1069 size_t il, ol, ool;
1071 ibuf = (char *)src;
1072 obuf = dest;
1073 il = len;
1074 ool = ol = il*4;
1075 il = iconv(icFromLoc, &ibuf, &il, &obuf, &ol);
1076 if (il == (size_t)-1) return 0;
1077 return ool-ol;
1078 } else {
1079 if (len > 0) memmove(dest, src, len);
1080 return len;
1085 static int utf2loc (char *dest, const char *src, int len) {
1086 if (needConversion) {
1087 char *ibuf, *obuf;
1088 size_t il, ol, ool;
1090 ibuf = (char *)src;
1091 obuf = dest;
1092 il = len;
1093 ool = ol = il*4;
1094 il = iconv(icToLoc, &ibuf, &il, &obuf, &ol);
1095 if (il == (size_t)-1) return 0;
1096 return ool-ol;
1097 } else {
1098 if (len > 0) memmove(dest, src, len);
1099 return len;
1104 ////////////////////////////////////////////////////////////////////////////////
1105 static void fixWindowTitle (const Term *t) {
1106 const char *title = (t != NULL) ? t->title : NULL;
1108 if (title == NULL || !title[0]) {
1109 title = opt_title;
1110 if (title == NULL) title = "";
1112 XStoreName(xw.dpy, xw.win, title);
1113 XChangeProperty(xw.dpy, xw.win, XA_NETWM_NAME, XA_UTF8, 8, PropModeReplace, (const unsigned char *)title, strlen(title));
1117 // find latest active terminal (but not current %-)
1118 static int findTermToSwitch (void) {
1119 int maxlat = -1, idx = -1;
1121 for (int f = 0; f < term_count; ++f) {
1122 if (term != term_array[f] && term_array[f]->lastActiveTime > maxlat) {
1123 maxlat = term_array[f]->lastActiveTime;
1124 idx = f;
1127 if (idx < 0) {
1128 if (termidx == 0) idx = 0; else idx = termidx+1;
1129 if (idx > term_count) idx = term_count-1;
1131 return idx;
1135 static void switchToTerm (int idx, int redraw) {
1136 if (idx >= 0 && idx < term_count && term_array[idx] != NULL && term_array[idx] != term) {
1137 int tt = mclock_ticks();;
1139 if (term != NULL) term->lastActiveTime = tt;
1140 termidx = idx;
1141 term = term_array[termidx];
1142 term->curbhidden = 0;
1143 term->lastBlinkTime = tt;
1144 xseturgency(0);
1145 tfulldirt();
1146 fixWindowTitle(term);
1147 updateTabBar = 1;
1148 if (redraw) draw(1);
1149 //FIXME: optimize memory allocations
1150 if (term->sel.clip != NULL && term->sel.bx >= 0) {
1151 if (lastSelStr != NULL) free(lastSelStr);
1152 lastSelStr = strdup(term->sel.clip);
1153 //fprintf(stderr, "newsel: [%s]\n", lastSelStr);
1155 xfixsel();
1156 //fprintf(stderr, "term #%d\n", termidx);
1157 //fprintf(stderr, "needConv: %d\n", term->needConv);
1162 static Term *termalloc (void) {
1163 Term *t;
1165 if (term_count >= term_array_size) {
1166 int newsz = (term_count==0) ? 1 : term_array_size+64;
1167 Term **n = realloc(term_array, sizeof(Term *)*newsz);
1169 if (n == NULL && term_count == 0) die("out of memory!");
1170 term_array = n;
1171 term_array_size = newsz;
1173 if ((t = calloc(1, sizeof(Term))) == NULL) return NULL;
1174 t->wrbufsize = WBUFSIZ;
1175 t->deffg = defaultFG;
1176 t->defbg = defaultBG;
1177 t->dead = 1;
1178 t->needConv = (needConversion ? 1 : 0);
1179 t->belltype = (opt_audiblebell?BELL_AUDIO:0)|(opt_urgentbell?BELL_URGENT:0);
1180 t->curblink = opt_cursorBlink;
1181 t->curblinkinactive = opt_cursorBlinkInactive;
1182 term_array[term_count++] = t;
1183 return t;
1187 // newer delete last terminal!
1188 static void termfree (int idx) {
1189 if (idx >= 0 && idx < term_count && term_array[idx] != NULL) {
1190 Term *t = term_array[idx];
1192 if (t->pid != 0) {
1193 kill(t->pid, SIGKILL);
1194 return;
1196 if (t->cmdfd >= 0) {
1197 close(t->cmdfd);
1198 t->cmdfd = -1;
1200 exitcode = t->exitcode;
1201 if (idx == termidx) {
1202 if (term_count > 1) {
1203 t->dead = 1;
1204 //switchToTerm((idx > 0) ? idx-1 : 1, 0);
1205 switchToTerm(findTermToSwitch(), 0);
1206 return;
1208 term = NULL;
1210 for (int y = 0; y < t->row; ++y) free(t->alt[y]);
1211 for (int y = 0; y < t->linecount; ++y) {
1212 //fprintf(stderr, "y=%d\n", y);
1213 free(t->line[y]);
1215 free(t->dirty);
1216 free(t->alt);
1217 free(t->line);
1218 if (t->execcmd != NULL) free(t->execcmd);
1219 // condense array
1220 if (termidx > idx) {
1221 // not current, and current at the right
1222 --termidx;
1224 for (int f = idx+1; f < term_count; ++f) term_array[f-1] = term_array[f];
1225 --term_count;
1226 XFreePixmap(xw.dpy, t->picbuf);
1227 free(t);
1232 static void termcleanup (void) {
1233 int f = 0, needredraw = 0;
1235 while (f < term_count) {
1236 if (term_array[f]->dead) {
1237 termfree(f);
1238 needredraw = 1;
1239 } else {
1240 ++f;
1243 if (needredraw) {
1244 updateTabBar = 1;
1245 draw(1);
1250 //FIXME: is it safe to assume that signal interrupted main program?
1251 static void sigchld (int a) {
1252 //if (waitpid(term->pid, &stat, 0) < 0) die("waiting for pid %hd failed: %s", term->pid, SERRNO);
1253 for (;;) {
1254 int stat = 0;
1255 pid_t res = waitpid(-1, &stat, WNOHANG);
1257 if (res == (pid_t)-1 || res == 0) break;
1259 for (int f = 0; f < term_count; ++f) {
1260 if (term_array[f]->pid == res) {
1261 // this terminal should die
1262 //if (term_count == 1) exit(0);
1263 //close(term_array[f]->cmdfd);
1264 //term_array[f]->cmdfd = -1;
1265 term_array[f]->dead = 1;
1266 term_array[f]->pid = 0;
1267 term_array[f]->exitcode = (WIFEXITED(stat)) ? WEXITSTATUS(stat) : 127;
1268 //fprintf(stderr, "exitcode=%d\n", term_array[f]->exitcode);
1269 updateTabBar = 1;
1270 break;
1274 signal(SIGCHLD, sigchld);
1278 ////////////////////////////////////////////////////////////////////////////////
1279 static void keytrans_reset (void) {
1280 if (keytrans) free(keytrans);
1281 keytrans = NULL;
1282 keytrans_size = 0;
1283 keytrans_used = 0;
1287 static void keytrans_add (const char *src, const char *dst) {
1288 KeySym kssrc = XStringToKeysym(src);
1289 KeySym ksdst = XStringToKeysym(dst);
1291 if (kssrc == NoSymbol) die("invalid keysym: '%s'", src);
1292 if (ksdst == NoSymbol) die("invalid keysym: '%s'", dst);
1293 if (kssrc == ksdst) return; // idiot
1295 for (int f = 0; f < keytrans_used; ++f) {
1296 if (keytrans[f].src == kssrc) {
1297 // replace
1298 keytrans[f].dst = ksdst;
1299 return;
1303 if (keytrans_used >= keytrans_size) {
1304 int newsize = keytrans_size+64;
1305 KeyTransDef *n = realloc(keytrans, sizeof(KeyTransDef)*newsize);
1307 if (n == NULL) die("out of memory");
1308 keytrans_size = newsize;
1309 keytrans = n;
1311 keytrans[keytrans_used].src = kssrc;
1312 keytrans[keytrans_used].dst = ksdst;
1313 ++keytrans_used;
1317 ////////////////////////////////////////////////////////////////////////////////
1318 static void parsekeyname (const char *str, KeySym *ks, uint *mask, int *kp) {
1319 char *s = alloca(strlen(str)+1);
1321 if (s == NULL) die("out of memory");
1322 strcpy(s, str);
1323 *kp = 0;
1324 *ks = NoSymbol;
1325 *mask = XK_NO_MOD;
1327 while (*s) {
1328 char *e, oc;
1329 uint mm = 0;
1330 int mod = 1;
1332 while (*s && isspace(*s)) ++s;
1333 for (e = s; *e && !isspace(*e) && *e != '+'; ++e) ;
1334 oc = *e; *e = 0;
1336 if (strcasecmp(s, "alt") == 0) mm = Mod1Mask;
1337 else if (strcasecmp(s, "win") == 0) mm = Mod4Mask;
1338 else if (strcasecmp(s, "ctrl") == 0) mm = ControlMask;
1339 else if (strcasecmp(s, "shift") == 0) mm = ShiftMask;
1340 else if (strcasecmp(s, "any") == 0) mm = XK_NO_MOD; //!
1341 else if (strcasecmp(s, "kpad") == 0) *kp = 1;
1342 else {
1343 mod = 0;
1344 if ((*ks = XStringToKeysym(s)) == NoSymbol) break;
1345 //fprintf(stderr, "[%s]\n", s);
1348 *e = oc;
1349 s = e;
1350 while (*s && isspace(*s)) ++s;
1351 if (mod) {
1352 if (*s != '+') { *ks = NoSymbol; break; }
1353 ++s;
1354 if (mm != 0) {
1355 if (mm == XK_NO_MOD) *mask = XK_ANY_MOD;
1356 else if (*mask == XK_NO_MOD) *mask = mm;
1357 else if (*mask != XK_ANY_MOD) *mask |= mm;
1359 } else {
1360 if (*s) { *ks = NoSymbol; break; }
1363 if (*ks == NoSymbol) die("invalid key name: '%s'", str);
1364 //fprintf(stderr, "mask=0x%08x, kp=%d\n", *mask, *kp);
1368 ////////////////////////////////////////////////////////////////////////////////
1369 static void keybinds_reset (void) {
1370 if (keybinds) free(keybinds);
1371 keybinds = NULL;
1372 keybinds_size = 0;
1373 keybinds_used = 0;
1377 static void keybind_add (const char *key, const char *act) {
1378 KeySym ks;
1379 uint mask;
1380 int kp;
1382 parsekeyname(key, &ks, &mask, &kp);
1384 for (int f = 0; f < keybinds_used; ++f) {
1385 if (keybinds[f].key == ks && keybinds[f].mask == mask) {
1386 // replace or remove
1387 free(keybinds[f].str);
1388 if (act == NULL || !act[0]) {
1389 // remove
1390 for (int c = f+1; c < keybinds_used; ++c) keybinds[c-1] = keybinds[c];
1391 } else {
1392 // replace
1393 if ((keybinds[f].str = strdup(act)) == NULL) die("out of memory");
1395 return;
1399 if (keybinds_used >= keybinds_size) {
1400 int newsize = keybinds_size+64;
1401 KeyInfoDef *n = realloc(keybinds, sizeof(KeyInfoDef)*newsize);
1403 if (n == NULL) die("out of memory");
1404 keybinds_size = newsize;
1405 keybinds = n;
1407 keybinds[keybinds_used].key = ks;
1408 keybinds[keybinds_used].mask = mask;
1409 keybinds[keybinds_used].kp = 0;
1410 if ((keybinds[keybinds_used].str = strdup(act)) == NULL) die("out of memory");
1411 ++keybinds_used;
1415 ////////////////////////////////////////////////////////////////////////////////
1416 static void keymap_reset (void) {
1417 if (keymap) free(keymap);
1418 keymap = NULL;
1419 keymap_size = 0;
1420 keymap_used = 0;
1424 static void keymap_add (const char *key, const char *act) {
1425 KeySym ks;
1426 uint mask;
1427 int kp;
1429 parsekeyname(key, &ks, &mask, &kp);
1431 for (int f = 0; f < keymap_used; ++f) {
1432 if (keymap[f].key == ks && keymap[f].mask == mask && keymap[f].kp == kp) {
1433 // replace or remove
1434 free(keymap[f].str);
1435 if (act == NULL) {
1436 // remove
1437 for (int c = f+1; c < keymap_used; ++c) keymap[c-1] = keymap[c];
1438 } else {
1439 // replace
1440 if ((keymap[f].str = strdup(act)) == NULL) die("out of memory");
1442 return;
1446 if (keymap_used >= keymap_size) {
1447 int newsize = keymap_size+128;
1448 KeyInfoDef *n = realloc(keymap, sizeof(KeyInfoDef)*newsize);
1450 if (n == NULL) die("out of memory");
1451 keymap_size = newsize;
1452 keymap = n;
1454 keymap[keymap_used].key = ks;
1455 keymap[keymap_used].mask = mask;
1456 keymap[keymap_used].kp = kp;
1457 if ((keymap[keymap_used].str = strdup(act)) == NULL) die("out of memory");
1458 ++keymap_used;
1462 ////////////////////////////////////////////////////////////////////////////////
1463 // selection
1464 static inline void setWantRedraw (void) {
1465 if (term != NULL) {
1466 term->wantRedraw = 1;
1467 term->lastDrawTime = mclock_ticks(); //FIXME: avoid excess redraw?
1472 static void inline markDirty (int lineno, int flag) {
1473 if (term != NULL && lineno >= 0 && lineno < term->row) {
1474 term->dirty[lineno] |= flag;
1475 term->wantRedraw = 1;
1476 term->lastDrawTime = mclock_ticks(); //FIXME: avoid excess redraw?
1481 static void selinit (void) {
1482 term->sel.tclick1 = term->sel.tclick2 = mclock_ticks();
1483 term->sel.mode = 0;
1484 term->sel.bx = -1;
1485 term->sel.clip = NULL;
1486 term->sel.xtarget = XA_UTF8;
1487 //if (term->sel.xtarget == None) term->sel.xtarget = XA_STRING;
1491 static void selhide (void) {
1492 if (term->sel.bx != -1) {
1493 term->sel.mode = 0;
1494 term->sel.bx = -1;
1495 tfulldirt();
1500 static inline int selected (int x, int y) {
1501 if (term->sel.bx == -1) return 0;
1503 if (y >= term->row) y = 0-(y-term->row+1);
1504 if (term->sel.ey == y && term->sel.by == y) {
1505 int bx = MIN(term->sel.bx, term->sel.ex);
1506 int ex = MAX(term->sel.bx, term->sel.ex);
1508 return BETWEEN(x, bx, ex);
1511 return
1512 ((term->sel.b.y < y && y < term->sel.e.y) || (y == term->sel.e.y && x <= term->sel.e.x)) ||
1513 (y == term->sel.b.y && x >= term->sel.b.x && (x <= term->sel.e.x || term->sel.b.y != term->sel.e.y));
1517 static void getbuttoninfo (XEvent *e, int *b, int *x, int *y) {
1518 if (b != NULL) *b = e->xbutton.button;
1519 if (x != NULL) *x = X2COL(e->xbutton.x);
1520 if (y != NULL) *y = Y2ROW(e->xbutton.y);
1521 term->sel.b.x = (term->sel.by < term->sel.ey ? term->sel.bx : term->sel.ex);
1522 term->sel.b.y = MIN(term->sel.by, term->sel.ey);
1523 term->sel.e.x = (term->sel.by < term->sel.ey ? term->sel.ex : term->sel.bx);
1524 term->sel.e.y = MAX(term->sel.by, term->sel.ey);
1528 static void mousereport (XEvent *e) {
1529 int x = X2COL(e->xbutton.x);
1530 int y = Y2ROW(e->xbutton.y);
1531 int button = e->xbutton.button;
1532 int state = e->xbutton.state;
1533 //char buf[] = { '\033', '[', 'M', 0, 32+x+1, 32+y+1 };
1534 char buf[32], *p;
1535 char lastCh = 'M';
1536 int ss;
1538 if (term == NULL) return;
1539 if (x < 0 || x >= term->col || y < 0 || y >= term->row) return;
1541 #if 0
1542 case 1000: /* X11 xterm mouse reporting */
1543 case 1005: /* utf-8 mouse encoding */
1544 case 1006: /* sgr mouse encoding */
1545 case 1015: /* urxvt mouse encoding */
1546 #endif
1547 //sprintf(buf, "\x1b[M%c%c%c", 0, 32+x+1, 32+y+1);
1548 p = buf+sprintf(buf, "\x1b[M");
1549 /* from urxvt */
1550 if (e->xbutton.type == MotionNotify) {
1551 if (!IS_SET(MODE_MOUSEMOTION) || (x == term->mouseox && y == term->mouseoy)) return;
1552 button = term->mouseob+32;
1553 term->mouseox = x;
1554 term->mouseoy = y;
1555 } else if (e->xbutton.type == ButtonRelease || button == AnyButton) {
1556 if (term->mousemode != 1006) {
1557 button = 3; // 'release' flag
1558 } else {
1559 lastCh = 'm';
1560 button -= Button1;
1561 if (button >= 3) button += 64-3;
1563 } else {
1564 button -= Button1;
1565 if (button >= 3) button += 64-3;
1566 if (e->xbutton.type == ButtonPress) {
1567 term->mouseob = button;
1568 term->mouseox = x;
1569 term->mouseoy = y;
1572 ss = (state & ShiftMask ? 4 : 0)+(state & Mod4Mask ? 8 : 0)+(state & ControlMask ? 16 : 0);
1573 switch (term->mousemode) {
1574 case 1006: /* sgr */
1575 buf[2] = '<';
1576 p += sprintf(p, "%d;", button+ss);
1577 break;
1578 case 1015: /* urxvt */
1579 --p; // remove 'M'
1580 p += sprintf(p, "%d;", 32+button+ss);
1581 break;
1582 default:
1583 *p++ = 32+button+ss;
1584 break;
1586 // coords
1587 switch (term->mousemode) {
1588 case 1005: /* utf-8 */
1589 p += utf8encode(x+1, p);
1590 p += utf8encode(y+1, p);
1591 break;
1592 case 1006: /* sgr */
1593 p += sprintf(p, "%d;%d%c", x+1, y+1, lastCh);
1594 break;
1595 case 1015: /* urxvt */
1596 p += sprintf(p, "%d;%dM", x+1, y+1);
1597 break;
1598 default:
1599 p += sprintf(p, "%c%c", 32+x+1, 32+y+1);
1600 break;
1602 *p = 0;
1605 fprintf(stderr, "(%d)<", term->mousemode);
1606 for (const unsigned char *s = (const unsigned char *)buf; *s; ++s) {
1607 if (s[0] < 32) fprintf(stderr, "{%d}", s[0]); else fputc(s[0], stderr);
1609 fputs(">\n", stderr);
1612 ttywritestr(buf);
1616 static void xfixsel (void) {
1617 if (lastSelStr != NULL) {
1618 XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, CurrentTime);
1619 XSetSelectionOwner(xw.dpy, XA_CLIPBOARD, xw.win, CurrentTime);
1620 } else {
1621 if (XGetSelectionOwner(xw.dpy, XA_PRIMARY) == xw.win) XSetSelectionOwner(xw.dpy, XA_PRIMARY, None, CurrentTime);
1622 if (XGetSelectionOwner(xw.dpy, XA_CLIPBOARD) == xw.win) XSetSelectionOwner(xw.dpy, XA_CLIPBOARD, None, CurrentTime);
1624 XFlush(xw.dpy);
1628 static void xsetsel (char *str) {
1629 /* register the selection for both the clipboard and the primary */
1630 if (term == NULL) return;
1631 if (term->sel.clip != NULL) free(term->sel.clip);
1632 term->sel.clip = str;
1633 if (lastSelStr != NULL) free(lastSelStr);
1634 lastSelStr = (str != NULL ? strdup(str) : NULL);
1635 xfixsel();
1636 //fprintf(stderr, "[%s]\n", str);
1640 static void selclear (XEvent *e) {
1641 if (lastSelStr != NULL) free(lastSelStr);
1642 lastSelStr = NULL;
1643 if (term != NULL) {
1644 if (term->sel.clip != NULL) free(term->sel.clip);
1645 term->sel.clip = NULL;
1646 term->sel.mode = 0;
1647 if (term->sel.bx != 0) {
1648 term->sel.bx = -1;
1649 tfulldirt();
1650 draw(1);
1656 static Line selgetlinebyy (int y) {
1657 Line l;
1659 if (y >= term->row) return NULL;
1660 if (y < 0) {
1661 if (y < -(term->maxhistory)) return NULL;
1662 l = term->line[term->row+(-y)-1];
1663 } else {
1664 l = term->line[y];
1666 return l;
1670 static void selcopy (void) {
1671 char *str, *ptr;
1672 int x, y, bufsize, is_selected = 0;
1674 if (term == NULL || term->sel.bx == -1) {
1675 str = NULL;
1676 } else {
1677 int sy = MIN(term->sel.e.y, term->sel.b.y);
1678 int ey = MAX(term->sel.e.y, term->sel.b.y);
1681 fprintf(stderr, "bx=%d; ex=%d; by=%d; ey=%d\n", term->sel.bx, term->sel.by, term->sel.ex, term->sel.ey);
1682 fprintf(stderr, " b.x=%d; e.x=%d; b.y=%d; e.y=%d\n", term->sel.b.x, term->sel.b.y, term->sel.e.x, term->sel.e.y);
1683 fprintf(stderr, " sy=%d; ey=%d\n", sy, ey);
1685 if (ey >= term->row) { selclear(NULL); return; }
1686 bufsize = (term->col+1)*(ey-sy+1)*UTF_SIZ;
1687 ptr = str = malloc(bufsize);
1688 /* append every set & selected glyph to the selection */
1689 for (y = sy; y <= ey; ++y) {
1690 Line l = selgetlinebyy(y);
1691 char *pstart = ptr;
1693 if (l == NULL) continue;
1694 for (x = 0; x < term->col; ++x) {
1695 if ((is_selected = selected(x, y)) != 0) {
1696 int size = utf8size(l[x].c);
1698 //if (size == 1) fprintf(stderr, "x=%d; y=%d; size=%d; c=%d\n", x, y, size, l[x].c[0]);
1699 if (size == 1) {
1700 unsigned char c = (unsigned char)l[x].c[0];
1702 *ptr = (c < 32 || c >= 127) ? ' ' : c;
1703 } else {
1704 memcpy(ptr, l[x].c, size);
1706 ptr += size;
1709 //fprintf(stderr, "y=%d; linebytes=%d\n", y, (int)(ptr-pstart));
1710 // trim trailing spaces
1711 while (ptr > pstart && ptr[-1] == ' ') --ptr;
1712 // \n at the end of every unwrapped selected line except for the last one
1713 if (is_selected && y < ey && selected(term->col-1, y) && !(l[term->col-1].state&GLYPH_WRAP)) *ptr++ = '\n';
1715 *ptr = 0;
1717 xsetsel(str);
1718 if (!str || !str[0]) selclear(NULL);
1722 static void selnotify (XEvent *e) {
1723 ulong nitems, ofs, rem;
1724 int format;
1725 uchar *data;
1726 Atom type;
1727 XSelectionEvent *se = (XSelectionEvent *)e;
1728 int isutf8;
1729 int wasbrk = 0;
1730 char *ucbuf = NULL;
1731 int ucbufsize = 0;
1733 if (term == NULL || term->cmdMode == CMDMODE_MESSAGE) return;
1734 #ifdef PASTE_SELECTION_DEBUG
1736 char *name;
1738 fprintf(stderr, "selnotify!\n");
1740 name = se->selection != None ? XGetAtomName(se->display, se->selection) : NULL;
1741 fprintf(stderr, " selection: [%s]\n", name);
1742 if (name != NULL) XFree(name);
1744 name = se->target != None ? XGetAtomName(se->display, se->target) : NULL;
1745 fprintf(stderr, " target: [%s]\n", name);
1746 if (name != NULL) XFree(name);
1748 name = se->property != None ? XGetAtomName(se->display, se->property) : NULL;
1749 fprintf(stderr, " property: [%s]\n", name);
1750 if (name != NULL) XFree(name);
1752 #endif
1754 if (se->property != XA_VT_SELECTION) return;
1756 #ifdef PASTE_SELECTION_DEBUG
1758 fprintf(stderr, "selection:\n");
1759 fprintf(stderr, " primary: %d\n", se->selection == XA_PRIMARY);
1760 fprintf(stderr, " secondary: %d\n", se->selection == XA_SECONDARY);
1761 fprintf(stderr, " clipboard: %d\n", se->selection == XA_CLIPBOARD);
1762 fprintf(stderr, " vtsel: %d\n", se->selection == XA_VT_SELECTION);
1763 fprintf(stderr, "target:\n");
1764 fprintf(stderr, " primary: %d\n", se->target == XA_PRIMARY);
1765 fprintf(stderr, " secondary: %d\n", se->target == XA_SECONDARY);
1766 fprintf(stderr, " clipboard: %d\n", se->target == XA_CLIPBOARD);
1767 fprintf(stderr, " vtsel: %d\n", se->target == XA_VT_SELECTION);
1769 #endif
1770 if (se->target == XA_UTF8) {
1771 isutf8 = 1;
1772 } else if (se->target == XA_STRING) {
1773 isutf8 = 0;
1774 } else if (se->target == XA_TARGETS) {
1775 Atom rqtype = None, *targ;
1777 if (XGetWindowProperty(xw.dpy, xw.win, se->property, 0, 65536, False, XA_ATOM, &type, &format, &nitems, &rem, &data)) {
1778 //fprintf(stderr, "no targets\n");
1779 rqtype = XA_STRING;
1780 } else {
1781 for (targ = (Atom *)data; nitems > 0; --nitems, ++targ) {
1782 #ifdef PASTE_SELECTION_DEBUG
1783 fprintf(stderr, " TGT: [%s]\n", XGetAtomName(se->display, *targ));
1784 #endif
1785 if (*targ == XA_UTF8) rqtype = XA_UTF8;
1786 else if (*targ == XA_STRING && rqtype == None) rqtype = XA_STRING;
1788 XFree(data);
1790 if (rqtype != None) XConvertSelection(xw.dpy, se->selection, rqtype, XA_VT_SELECTION, xw.win, CurrentTime);
1791 return;
1792 } else {
1793 return;
1796 ofs = 0;
1797 do {
1798 int blen;
1799 char *str;
1801 if (XGetWindowProperty(xw.dpy, xw.win, se->property, ofs, BUFSIZ/4, False, AnyPropertyType, &type, &format, &nitems, &rem, &data)) {
1802 fprintf(stderr, "Clipboard allocation failed\n");
1803 break;
1805 //fprintf(stderr, "nitems=%d; format=%d; rem=%d\n", (int)nitems, format, (int)rem);
1806 blen = nitems*format/8;
1808 if (!isutf8) {
1809 int newsz = blen*4+64;
1811 if (ucbufsize < newsz) {
1812 char *n = realloc(ucbuf, newsz);
1814 if (n == NULL) { XFree(data); break; }
1815 ucbuf = n;
1816 ucbufsize = newsz;
1819 blen = loc2utf(ucbuf, (const char *)data, blen);
1820 str = ucbuf;
1821 } else {
1822 str = (char *)data;
1825 if (term->cmdMode != CMDMODE_NONE) {
1826 tcmdput(str, blen);
1827 } else {
1828 if (nitems*format/8 > 0 && !wasbrk && IS_SET(MODE_BRACPASTE)) {
1829 wasbrk = 1;
1830 ttywritestr("\x1b[200~");
1832 ttywrite(str, blen);
1834 XFree(data);
1835 /* number of 32-bit chunks returned */
1836 ofs += nitems*format/32;
1837 } while (rem > 0);
1839 if (wasbrk) ttywritestr("\x1b[201~");
1840 if (ucbuf != NULL) free(ucbuf);
1844 static void selpaste (Atom which) {
1845 if (term == NULL) return;
1846 if (XGetSelectionOwner(xw.dpy, which) == None) return;
1847 //XConvertSelection(xw.dpy, which, term->sel.xtarget, XA_VT_SELECTION, xw.win, CurrentTime);
1848 XConvertSelection(xw.dpy, which, XA_TARGETS, XA_VT_SELECTION, xw.win, CurrentTime);
1850 if (which == XA_PRIMARY) selpaste(XA_SECONDARY);
1851 else if (which == XA_SECONDARY) selpaste(XA_CLIPBOARD);
1856 static void selrequest (XEvent *e) {
1857 XSelectionRequestEvent *xsre;
1858 XSelectionEvent xev;
1860 if (lastSelStr == NULL) return;
1861 xsre = (XSelectionRequestEvent *)e;
1862 xev.type = SelectionNotify;
1863 xev.requestor = xsre->requestor;
1864 xev.selection = xsre->selection;
1865 xev.target = xsre->target;
1866 xev.time = xsre->time;
1867 /* reject */
1868 xev.property = None;
1869 if (xsre->target == XA_TARGETS) {
1870 /* respond with the supported type */
1871 Atom tlist[3] = {XA_UTF8, XA_STRING, XA_TARGETS};
1873 XChangeProperty(xsre->display, xsre->requestor, xsre->property, XA_ATOM, 32, PropModeReplace, (uchar *)tlist, 3);
1874 xev.property = xsre->property;
1875 } else if (xsre->target == XA_UTF8 && lastSelStr != NULL) {
1876 XChangeProperty(xsre->display, xsre->requestor, xsre->property, XA_UTF8, 8, PropModeReplace, (uchar *)lastSelStr, strlen(lastSelStr));
1877 xev.property = xsre->property;
1878 } else if (xsre->target == XA_STRING && lastSelStr != NULL) {
1879 char *s = malloc(strlen(lastSelStr)*4+8);
1881 if (s != NULL) {
1882 int len = utf2loc(s, lastSelStr, strlen(lastSelStr));
1884 XChangeProperty(xsre->display, xsre->requestor, xsre->property, XA_STRING, 8, PropModeReplace, (uchar *)s, len);
1885 xev.property = xsre->property;
1886 free(s);
1889 /* all done, send a notification to the listener */
1890 if (!XSendEvent(xsre->display, xsre->requestor, True, 0, (XEvent *)&xev)) fprintf(stderr, "Error sending SelectionNotify event\n");
1894 static void bpress (XEvent *e) {
1895 if (term == NULL) return;
1897 switch (opt_tabposition) {
1898 case 0: // bottom
1899 if (e->xbutton.y >= xw.h-xw.tabheight) return;
1900 break;
1901 case 1: // top
1902 if (e->xbutton.y < xw.tabheight) return;
1903 break;
1906 if ((e->xbutton.state&ShiftMask) != 0) {
1907 if (e->xbutton.button == Button1) {
1908 if (term->sel.bx != -1) tsetdirt(term->sel.b.y, term->sel.e.y);
1909 term->sel.mode = 1;
1910 term->sel.ex = term->sel.bx = X2COL(e->xbutton.x);
1911 term->sel.ey = term->sel.by = Y2ROW(e->xbutton.y);
1912 //fprintf(stderr, "x=%d; y=%d\n", term->sel.bx, term->sel.by);
1913 draw(1);
1914 return;
1917 if (e->xbutton.button == Button3) {
1918 term->sel.bx = -1;
1919 selcopy();
1920 draw(1);
1923 return;
1925 if (IS_SET(MODE_MOUSE)) mousereport(e);
1929 static void brelease (XEvent *e) {
1930 if (term == NULL) return;
1932 switch (opt_tabposition) {
1933 case 0: // bottom
1934 if (e->xbutton.y >= xw.h-xw.tabheight) return;
1935 break;
1936 case 1: // top
1937 if (e->xbutton.y < xw.tabheight) return;
1938 break;
1941 if ((e->xbutton.state&ShiftMask) == 0 && !term->sel.mode) {
1942 if (IS_SET(MODE_MOUSE)) mousereport(e);
1943 return;
1946 if (e->xbutton.button == Button2) {
1947 selpaste(XA_PRIMARY);
1948 } else if (e->xbutton.button == Button1) {
1949 term->sel.mode = 0;
1950 getbuttoninfo(e, NULL, &term->sel.ex, &term->sel.ey); // this sets sel.b and sel.e
1952 if (term->sel.bx == term->sel.ex && term->sel.by == term->sel.ey) {
1953 // single line, single char selection
1954 int now;
1956 markDirty(term->sel.ey, 2);
1957 term->sel.bx = -1;
1958 now = mclock_ticks();
1959 if (now-term->sel.tclick2 <= opt_tripleclick_timeout) {
1960 /* triple click on the line */
1961 term->sel.b.x = term->sel.bx = 0;
1962 term->sel.e.x = term->sel.ex = term->col;
1963 term->sel.b.y = term->sel.e.y = term->sel.ey;
1964 } else if (now-term->sel.tclick1 <= opt_doubleclick_timeout) {
1965 /* double click to select word */
1966 Line l = selgetlinebyy(term->sel.ey);
1968 if (l != NULL) {
1969 //FIXME: write better word selection code
1970 term->sel.bx = term->sel.ex;
1971 if (IS_GFX(l[term->sel.bx].attr)) {
1972 while (term->sel.bx > 0 && IS_GFX(l[term->sel.bx-1].attr)) --term->sel.bx;
1973 term->sel.b.x = term->sel.bx;
1974 while (term->sel.ex < term->col-1 && IS_GFX(l[term->sel.ex+1].attr)) ++term->sel.ex;
1975 } else {
1976 while (term->sel.bx > 0 && !IS_GFX(l[term->sel.bx-1].attr) && l[term->sel.bx-1].c[0] != ' ') --term->sel.bx;
1977 term->sel.b.x = term->sel.bx;
1978 while (term->sel.ex < term->col-1 && !IS_GFX(l[term->sel.ex+1].attr) && l[term->sel.ex+1].c[0] != ' ') ++term->sel.ex;
1980 term->sel.e.x = term->sel.ex;
1981 term->sel.b.y = term->sel.e.y = term->sel.ey;
1985 selcopy();
1986 draw(1);
1987 } else {
1988 // multiline or multichar selection
1989 selcopy();
1992 term->sel.tclick2 = term->sel.tclick1;
1993 term->sel.tclick1 = mclock_ticks();
1994 //draw(1);
1998 static void bmotion (XEvent *e) {
1999 if (term == NULL) return;
2001 switch (opt_tabposition) {
2002 case 0: // bottom
2003 if (e->xbutton.y >= xw.h-xw.tabheight) return;
2004 break;
2005 case 1: // top
2006 if (e->xbutton.y < xw.tabheight) return;
2007 break;
2010 if (term->sel.mode) {
2011 int oldey = term->sel.ey, oldex = term->sel.ex;
2013 getbuttoninfo(e, NULL, &term->sel.ex, &term->sel.ey); // this sets sel.b and sel.e
2014 if (oldey != term->sel.ey || oldex != term->sel.ex) {
2015 int starty = MIN(oldey, term->sel.ey);
2016 int endy = MAX(oldey, term->sel.ey);
2018 tsetdirt(starty, endy);
2019 draw(1);
2021 return;
2023 //if (IS_SET(MODE_MOUSE) && e->xbutton.button != 0) mousereport(e);
2027 ////////////////////////////////////////////////////////////////////////////////
2028 // tty init
2030 static void dump (char c) {
2031 static int col;
2033 fprintf(stderr, " %02x '%c' ", c, isprint(c)?c:'.');
2034 if (++col % 10 == 0) fprintf(stderr, "\n");
2039 static __attribute__((noreturn)) void execsh (const char *str) {
2040 char **args;
2042 if (str == NULL) {
2043 char *envshell = getenv("SHELL");
2045 DEFAULT(envshell, opt_shell);
2046 setenv("TERM", opt_term, 1);
2047 args = opt_cmd ? opt_cmd : (char *[]){envshell, "-i", NULL};
2048 } else {
2049 int argc = 0;
2051 args = calloc(32768, sizeof(char *));
2052 if (args == NULL) exit(EXIT_FAILURE);
2053 while (*str) {
2054 const char *b;
2056 while (*str && isspace(*str)) ++str;
2057 if (!str[0]) break;
2059 b = str;
2060 while (*str && !isspace(*str)) {
2061 if (*str++ == '\\') {
2062 if (*str) ++str;
2066 args[argc] = calloc(str-b+1, 1);
2067 memcpy(args[argc], b, str-b);
2070 FILE *fo = fopen("z.log", "a");
2071 fprintf(fo, "%d: [%s]\n", argc, args[argc]);
2072 fclose(fo);
2075 ++argc;
2077 if (argc < 1) exit(EXIT_FAILURE);
2079 execvp(args[0], args);
2080 exit(EXIT_FAILURE);
2084 static int ttynew (Term *term) {
2085 int m, s;
2086 struct winsize w = {term->row, term->col, 0, 0};
2087 static int signalset = 0;
2089 if (openpty(&m, &s, NULL, NULL, &w) < 0) die("openpty failed: %s", SERRNO);
2090 term->cmdfd = m;
2091 ttyresize();
2092 term->cmdfd = -1;
2093 switch (term->pid = fork()) {
2094 case -1: /* error */
2095 fprintf(stderr, "fork failed");
2096 return -1;
2097 case 0: /* child */
2098 setsid(); /* create a new process group */
2099 dup2(s, STDIN_FILENO);
2100 dup2(s, STDOUT_FILENO);
2101 dup2(s, STDERR_FILENO);
2102 if (ioctl(s, TIOCSCTTY, NULL) < 0) die("ioctl TIOCSCTTY failed: %s", SERRNO);
2103 close(s);
2104 close(m);
2105 execsh(term->execcmd);
2106 break;
2107 default: /* master */
2108 close(s);
2109 term->cmdfd = m;
2110 term->dead = 0;
2111 ttyresize();
2112 if (!signalset) { signalset = 1; signal(SIGCHLD, sigchld); }
2113 break;
2115 return 0;
2119 ////////////////////////////////////////////////////////////////////////////////
2120 // tty r/w
2121 static int ttycanread (void) {
2122 for (;;) {
2123 fd_set rfd;
2124 struct timeval timeout = {0};
2126 if (term->dead || term->cmdfd < 0) return 0;
2127 FD_ZERO(&rfd);
2128 FD_SET(term->cmdfd, &rfd);
2129 if (select(term->cmdfd+1, &rfd, NULL, NULL, &timeout) < 0) {
2130 if (errno == EINTR) continue;
2131 die("select failed: %s", SERRNO);
2133 if (FD_ISSET(term->cmdfd, &rfd)) return 1;
2134 break;
2136 return 0;
2140 static int ttycanwrite (void) {
2141 for (;;) {
2142 fd_set wfd;
2143 struct timeval timeout = {0};
2145 if (term->dead || term->cmdfd < 0) return 0;
2146 FD_ZERO(&wfd);
2147 FD_SET(term->cmdfd, &wfd);
2148 if (select(term->cmdfd+1, NULL, &wfd, NULL, &timeout) < 0) {
2149 if (errno == EINTR) continue;
2150 die("select failed: %s", SERRNO);
2152 if (FD_ISSET(term->cmdfd, &wfd)) return 1;
2153 break;
2155 return 0;
2159 #ifdef DUMP_IO
2160 static void wrstr (const char *s, int len) {
2161 if (s == NULL) return;
2162 while (len-- > 0) {
2163 unsigned char c = (unsigned char)(*s++);
2165 if (c < 32) fprintf(stderr, "{%u}", c); else fwrite(&c, 1, 1, stderr);
2168 #endif
2171 static void ttyread (void) {
2172 char *ptr;
2173 int left;
2175 /* append read bytes to unprocessed bytes */
2176 if (term == NULL || term->dead || term->cmdfd < 0) return;
2177 #ifdef DUMP_PROG_OUTPUT
2178 term->xobuflen = term->obuflen;
2179 #endif
2180 left = OBUFSIZ-term->obuflen;
2181 //dlogf("0: ttyread before: free=%d, used=%d", left, term->obuflen);
2182 while (left > 0 && ttycanread()) {
2183 int ret;
2185 //if ((ret = read(term->cmdfd, term->obuf+term->obuflen, 1)) < 0) die("Couldn't read from shell: %s", SERRNO);
2186 if ((ret = read(term->cmdfd, term->obuf+term->obuflen, left)) < 0) {
2187 //fprintf(stderr, "Warning: couldn't read from tty #%d: %s\n", termidx, SERRNO);
2188 break;
2190 term->obuflen += ret;
2191 left -= ret;
2193 //dlogf("1: ttyread after: free=%d, used=%d", left, term->obuflen);
2194 /* process every complete utf8 char */
2195 #ifdef DUMP_PROG_OUTPUT
2197 FILE *fo = fopen("zlogo.log", "ab");
2198 if (fo) {
2199 fwrite(term->obuf+term->xobuflen, term->obuflen-term->xobuflen, 1, fo);
2200 fclose(fo);
2203 #endif
2204 ptr = term->obuf;
2205 if (term->needConv) {
2206 // need conversion from locale to utf-8
2207 //fprintf(stderr, "buf: %d bytes\n", term->obuflen);
2208 while (term->obuflen > 0) {
2209 char obuf[UTF_SIZ+1];
2210 int len;
2212 len = loc2utf(obuf, ptr, 1);
2213 #ifdef DUMP_IO_READ
2215 fprintf(stderr, "rdc: [");
2216 wrstr(ptr, 1);
2217 fprintf(stderr, "] --> [");
2218 wrstr(obuf, len);
2219 fprintf(stderr, "]\n");
2220 fflush(stderr);
2222 #endif
2223 if (len > 0) {
2224 obuf[len] = 0;
2225 tputc(obuf);
2227 ++ptr;
2228 --term->obuflen;
2230 term->obuflen = 0;
2231 } else {
2232 // don't do any conversion
2233 while (term->obuflen >= UTF_SIZ || isfullutf8(ptr, term->obuflen)) {
2234 ulong utf8c;
2235 char s[UTF_SIZ+1];
2236 int charsize = utf8decode(ptr, &utf8c); /* returns size of utf8 char in bytes */
2237 int len;
2239 len = utf8encode(utf8c, s);
2240 #ifdef DUMP_IO_READ
2242 fprintf(stderr, "rdx: [");
2243 wrstr(s, len);
2244 fprintf(stderr, "]\n");
2245 fflush(stderr);
2247 #endif
2248 if (len > 0) {
2249 s[len] = 0;
2250 tputc(s);
2252 ptr += charsize;
2253 term->obuflen -= charsize;
2255 //dlogf("2: ttyread afterproc: used=%d", term->obuflen);
2257 /* keep any uncomplete utf8 char for the next call */
2258 if (term->obuflen > 0) memmove(term->obuf, ptr, term->obuflen);
2262 static void ttyflushwrbuf (void) {
2263 if (term == NULL || term->dead || term->cmdfd < 0) return;
2264 if (term->wrbufpos >= term->wrbufused) {
2265 term->wrbufpos = term->wrbufused = 0;
2266 return;
2268 //dlogf("0: ttyflushwrbuf before: towrite=%d", term->wrbufused-term->wrbufpos);
2269 while (term->wrbufpos < term->wrbufused && ttycanwrite()) {
2270 int ret;
2272 if ((ret = write(term->cmdfd, term->wrbuf+term->wrbufpos, term->wrbufused-term->wrbufpos)) == -1) {
2273 //fprintf(stderr, "Warning: write error on tty #%d: %s\n", termidx, SERRNO);
2275 term->wrbufpos += ret;
2277 if (term->wrbufpos > 0) {
2278 int left = term->wrbufused-term->wrbufpos;
2280 if (left < 1) {
2281 // write buffer is empty
2282 term->wrbufpos = term->wrbufused = 0;
2283 } else {
2284 memmove(term->wrbuf, term->wrbuf+term->wrbufpos, left);
2285 term->wrbufpos = 0;
2286 term->wrbufused = left;
2289 //dlogf("1: ttyflushwrbuf after: towrite=%d", term->wrbufused-term->wrbufpos);
2293 // convert char to locale and write it
2294 static void ttywriterawchar (const char *s, int len) {
2295 char loc[16];
2296 int clen;
2298 if (s == NULL || len < 1) return;
2299 if (term->needConv) {
2300 if ((clen = utf2loc(loc, s, len)) < 1) return;
2301 } else {
2302 if ((clen = utf8size(s)) < 1) return;
2303 memmove(loc, s, clen);
2305 #ifdef DUMP_IO_WRITE
2307 fprintf(stderr, "wrc: [");
2308 wrstr(s, len);
2309 fprintf(stderr, "] --> [");
2310 wrstr(loc, clen);
2311 fprintf(stderr, "]\n");
2312 fflush(stderr);
2314 #endif
2316 while (term->wrbufused+clen >= term->wrbufsize) {
2317 //FIXME: make write buffer dynamic?
2318 // force write at least one char
2319 //dlogf("ttywrite: forced write");
2320 if (write(term->cmdfd, term->wrbuf+term->wrbufpos, 1) == -1) {
2321 //fprintf(stderr, "Warning: write error on tty #%d: %s\n", termidx, SERRNO);
2322 } else {
2323 ++term->wrbufpos;
2325 ttyflushwrbuf(); // make room for char
2327 memcpy(term->wrbuf+term->wrbufused, loc, clen);
2328 term->wrbufused += clen;
2332 static void ttywrite (const char *s, size_t n) {
2333 if (term == NULL || term->dead || term->cmdfd < 0) return;
2334 #ifdef DUMP_PROG_INPUT
2335 if (s != NULL && n > 0) {
2336 FILE *fo = fopen("zlogw.log", "ab");
2337 if (fo) {
2338 fwrite(s, n, 1, fo);
2339 fclose(fo);
2342 #endif
2343 //ttyflushwrbuf();
2344 if (s != NULL && n > 0) {
2345 while (n > 0) {
2346 unsigned char c = (unsigned char)(s[0]);
2348 if (term->ubufpos > 0 && isfullutf8(term->ubuf, term->ubufpos)) {
2349 // have complete char
2350 ttywriterawchar(term->ubuf, term->ubufpos);
2351 term->ubufpos = 0;
2352 continue;
2355 if (term->ubufpos == 0) {
2356 // new char
2357 if (c < 128) {
2358 ttywriterawchar(s, 1);
2359 } else if ((c&0xc0) == 0xc0) {
2360 // new utf-8 char
2361 term->ubuf[term->ubufpos++] = *s;
2362 } else {
2363 // ignore unsynced utf-8
2365 ++s;
2366 --n;
2367 continue;
2369 // char continues
2370 if (c < 128 || term->ubufpos >= UTF_SIZ || (c&0xc0) == 0xc0) {
2371 // discard previous utf-8, it's bad
2372 term->ubufpos = 0;
2373 continue;
2375 // collect
2376 term->ubuf[term->ubufpos++] = *s;
2377 ++s;
2378 --n;
2379 if (isfullutf8(term->ubuf, term->ubufpos)) {
2380 // have complete char
2381 ttywriterawchar(term->ubuf, term->ubufpos);
2382 term->ubufpos = 0;
2386 ttyflushwrbuf();
2390 ////////////////////////////////////////////////////////////////////////////////
2391 // tty resize ioctl
2392 static void ttyresize (void) {
2393 struct winsize w;
2395 if (term != NULL && term->cmdfd >= 0) {
2396 w.ws_row = term->row;
2397 w.ws_col = term->col;
2398 w.ws_xpixel = w.ws_ypixel = 0;
2399 if (ioctl(term->cmdfd, TIOCSWINSZ, &w) < 0) fprintf(stderr, "Warning: couldn't set window size: %s\n", SERRNO);
2400 setWantRedraw();
2405 ////////////////////////////////////////////////////////////////////////////////
2406 // tty utilities
2407 static void csidump (void) {
2408 printf("ESC");
2409 for (int f = 1; f < term->escseq.len; ++f) {
2410 uint c = (term->escseq.buf[f]&0xff);
2412 if (isprint(c)) putchar(c);
2413 else if (c == '\n') printf("(\\n)");
2414 else if (c == '\r') printf("(\\r)");
2415 else if (c == 0x1b) printf("(\\e)");
2416 else printf("(%02x)", c);
2418 putchar('\n');
2422 static void tsetdirt (int top, int bot) {
2423 LIMIT(top, 0, term->row-1);
2424 LIMIT(bot, 0, term->row-1);
2425 for (int y = top; y <= bot; ++y) markDirty(y, 2);
2429 static void tfulldirt (void) {
2430 tsetdirt(0, term->row-1);
2434 static void tmoveto (int x, int y) {
2435 LIMIT(x, 0, term->col-1);
2436 LIMIT(y, 0, term->row-1);
2437 term->c.state &= ~CURSOR_WRAPNEXT;
2438 if (term->c.x != x || term->c.y != y) {
2439 term->c.x = x;
2440 term->c.y = y;
2441 setWantRedraw();
2446 static void tclearregion (int x1, int y1, int x2, int y2) {
2447 int temp;
2449 //fprintf(stderr, "tclearregion: (%d,%d)-(%d,%d)\n", x1, y1, x2, y2);
2450 if (x1 > x2) { temp = x1; x1 = x2; x2 = temp; }
2451 if (y1 > y2) { temp = y1; y1 = y2; y2 = temp; }
2452 LIMIT(x1, 0, term->col-1);
2453 LIMIT(x2, 0, term->col-1);
2454 LIMIT(y1, 0, term->row-1);
2455 LIMIT(y2, 0, term->row-1);
2456 //fprintf(stderr, " tclearregion: (%d,%d)-(%d,%d)\n", x1, y1, x2, y2);
2457 for (int y = y1; y <= y2; ++y) {
2458 Line l = term->line[y];
2460 markDirty(y, (x1 <= 0 && x2 >= term->col-1) ? 2 : 1);
2461 for (int x = x1; x <= x2; ++x) {
2462 l[x].fg = term->c.attr.fg;
2463 l[x].bg = term->c.attr.bg;
2464 l[x].state = GLYPH_DIRTY;
2465 l[x].attr = ATTR_NULL|(term->c.attr.attr&(ATTR_DEFFG|ATTR_DEFBG));
2466 l[x].c[0] = ' ';
2467 if (term->sel.bx != -1 && selected(x, y)) selhide();
2469 l[term->col-1].state &= ~GLYPH_WRAP;
2474 static void tcursor (int mode) {
2475 if (mode == CURSOR_SAVE) {
2476 term->csaved = term->c;
2477 } else if (mode == CURSOR_LOAD) {
2478 term->c = term->csaved;
2479 tmoveto(term->c.x, term->c.y);
2480 setWantRedraw();
2485 static void treset (void) {
2486 Glyph g;
2488 term->c = (TCursor){{
2489 .attr = ATTR_NULL|ATTR_DEFFG|ATTR_DEFBG,
2490 .fg = 0,
2491 .bg = 0
2492 }, .x = 0, .y = 0, .state = CURSOR_DEFAULT};
2493 term->c.attr.fg = term->deffg;
2494 term->c.attr.bg = term->defbg;
2496 g.state = GLYPH_DIRTY;
2497 g.attr = term->c.attr.attr;
2498 g.fg = term->c.attr.fg;
2499 g.bg = term->c.attr.bg;
2500 g.c[0] = ' ';
2501 g.c[1] = 0;
2503 term->top = 0;
2504 term->bot = term->row-1;
2505 term->mode = MODE_WRAP/* | MODE_MOUSEBTN*/;
2506 term->mousemode = 1000;
2507 term->charset = MODE_GFX0;
2508 //tclearregion(0, 0, term->col-1, term->row-1);
2509 for (int y = 0; y < term->row; ++y) {
2510 markDirty(y, 2);
2511 for (int x = 0; x < term->col; ++x) term->alt[y][x] = term->line[y][x] = g;
2513 for (int y = term->row; y < term->linecount; ++y) {
2514 for (int x = 0; x < term->col; ++x) term->line[y][x] = g;
2516 tcursor(CURSOR_SAVE);
2517 term->topline = 0;
2518 tfulldirt();
2522 static int tinitialize (int col, int row) {
2523 //memset(term, 0, sizeof(Term));
2524 //term->needConv = needConversion ? 1 : 0;
2525 term->wrbufsize = WBUFSIZ;
2526 term->deffg = term->deffg;
2527 term->defbg = term->defbg;
2528 term->row = row;
2529 term->col = col;
2530 term->dirty = calloc(term->row, sizeof(*term->dirty));
2531 term->maxhistory = opt_maxhistory;
2532 term->linecount = term->maxhistory+term->row;
2533 term->line = calloc(term->linecount, sizeof(Line));
2534 term->alt = calloc(term->row, sizeof(Line));
2535 for (int y = 0; y < term->linecount; ++y) term->line[y] = calloc(term->col, sizeof(Glyph));
2536 for (int y = 0; y < term->row; ++y) term->alt[y] = calloc(term->col, sizeof(Glyph));
2537 /* setup screen */
2538 treset();
2539 return 1;
2543 static void tadjustmaxhistory (int maxh) {
2544 if (term != NULL) {
2545 LIMIT(maxh, 0, 65535);
2546 if (term->maxhistory < maxh) {
2547 Line *nl;
2548 int newlc = term->linecount+(maxh-term->maxhistory);
2550 // add history lines
2551 if ((nl = realloc(term->line, sizeof(Line)*newlc)) != NULL) {
2552 Glyph g;
2554 term->topline = 0;
2555 term->line = nl;
2556 g.state = GLYPH_DIRTY;
2557 g.attr = ATTR_NULL|ATTR_DEFFG|ATTR_DEFBG;
2558 g.fg = term->deffg;
2559 g.bg = term->defbg;
2560 g.c[0] = ' ';
2561 g.c[1] = 0;
2562 for (int y = term->linecount; y < newlc; ++y) {
2563 term->line[y] = calloc(term->col, sizeof(Glyph));
2564 for (int x = 0; x < term->col; ++x) term->line[y][x] = g;
2566 term->maxhistory = maxh;
2567 term->linecount = newlc;
2569 } else if (term->maxhistory > maxh) {
2570 Line *nl;
2572 term->topline = 0;
2573 // remove history lines
2574 while (term->linecount > term->row+maxh) free(term->line[--term->linecount]);
2575 if ((nl = realloc(term->line, sizeof(Line)*term->linecount)) != NULL) term->line = nl;
2576 term->maxhistory = maxh;
2582 static void tswapscreen (void) {
2583 selhide();
2584 for (int f = 0; f < term->row; ++f) {
2585 Line t = term->line[f];
2587 term->line[f] = term->alt[f];
2588 term->alt[f] = t;
2590 term->mode ^= MODE_ALTSCREEN;
2591 tfulldirt();
2595 //FIXME: works bad with history
2596 //FIXME: ugly code
2597 static void selscroll (int orig, int n, int tohistory) {
2598 int docopy = 0;
2600 if (term->sel.bx == -1) return;
2602 tfulldirt(); // just in case
2603 if (!tohistory) {
2604 if (BETWEEN(term->sel.by, orig, term->bot) || BETWEEN(term->sel.ey, orig, term->bot)) {
2605 if ((term->sel.by += n) > term->bot || (term->sel.ey += n) < term->top) {
2606 selclear(NULL);
2607 return;
2609 if (term->sel.by < term->top) {
2610 term->sel.by = term->top;
2611 term->sel.bx = 0;
2612 docopy = 1;
2614 if (term->sel.ey > term->bot) {
2615 term->sel.ey = term->bot;
2616 term->sel.ex = term->col;
2617 docopy = 1;
2619 term->sel.b.x = term->sel.bx;
2620 term->sel.b.y = term->sel.by;
2621 term->sel.e.x = term->sel.ex;
2622 term->sel.e.y = term->sel.ey;
2624 } else {
2625 // tohistory!=0; always scrolls full screen up (n == -1)
2626 //fprintf(stderr, "selscroll to history\n");
2627 term->sel.by += n;
2628 term->sel.ey += n;
2629 //fprintf(stderr, " by=%d; ey=%d; maxhistory=%d\n", term->sel.by, term->sel.ey, term->maxhistory);
2630 if (term->sel.ey < 0 && -(term->sel.ey) > term->maxhistory) {
2631 // out of screen completely
2632 selclear(NULL);
2633 return;
2635 if (term->sel.by < 0 && -(term->sel.by) > term->maxhistory) {
2636 term->sel.by = -term->maxhistory;
2637 term->sel.bx = 0;
2638 docopy = 1;
2640 term->sel.b.x = term->sel.bx;
2641 term->sel.b.y = term->sel.by;
2642 term->sel.e.x = term->sel.ex;
2643 term->sel.e.y = term->sel.ey;
2646 if (docopy) selcopy();
2650 static void tscrolldown (int orig, int n) {
2651 Line temp;
2653 LIMIT(n, 0, term->bot-orig+1);
2654 if (n < 1) return;
2655 selscroll(orig, n, 0);
2656 //fprintf(stderr, "tscrolldown(%d, %d)\n", orig, n);
2657 tclearregion(0, term->bot-n+1, term->col-1, term->bot);
2658 for (int f = term->bot; f >= orig+n; --f) {
2659 temp = term->line[f];
2660 term->line[f] = term->line[f-n];
2661 term->line[f-n] = temp;
2662 markDirty(f, 2);
2663 markDirty(f-n, 2);
2668 static void tscrollup (int orig, int n, int tohistory) {
2669 Line temp;
2671 if (term == NULL) return;
2672 LIMIT(n, 0, term->bot-orig+1);
2673 if (n < 1) return;
2674 //fprintf(stderr, "tscrollup(%d, %d)\n", orig, n);
2675 if (tohistory && !IS_SET(MODE_ALTSCREEN) && term->maxhistory > 0) {
2676 Line l = term->line[term->linecount-1];
2678 for (int f = term->linecount-1; f > term->row; --f) term->line[f] = term->line[f-1];
2679 term->line[term->row] = l;
2680 for (int x = 0; x < term->col; ++x) l[x] = term->line[0][x];
2681 } else {
2682 tohistory = 0;
2685 selscroll(orig, -n, tohistory);
2686 //tclearregion(0, orig, term->col-1, orig+n-1);
2687 for (int f = orig; f <= term->bot-n; ++f) {
2688 temp = term->line[f];
2689 term->line[f] = term->line[f+n];
2690 term->line[f+n] = temp;
2691 markDirty(f, 2);
2692 markDirty(f+n, 2);
2694 tclearregion(0, term->bot-n+1, term->col-1, term->bot);
2698 static inline void tsetcharwrap (int y, int wrap) {
2699 if (y >= 0 && y < term->row) {
2700 if (wrap) term->line[y][term->col-1].state |= GLYPH_WRAP;
2701 else term->line[y][term->col-1].state &= ~GLYPH_WRAP;
2706 static void tnewline (int first_col) {
2707 int y = term->c.y;
2709 tsetcharwrap(y, (first_col == 2)); // 2: wrapping
2710 if (y == term->bot) tscrollup(term->top, 1, 1); else ++y;
2711 tmoveto(first_col ? 0 : term->c.x, y);
2715 static void csiparse (void) {
2716 const char *p = term->escseq.buf;
2718 term->escseq.narg = 0;
2719 if (*p == '?') { term->escseq.priv = 1; ++p; }
2720 while (p < term->escseq.buf+term->escseq.len) {
2721 int n = term->escseq.arg[term->escseq.narg];
2723 for (; *p && isdigit(*p); ++p) n = n*10+(p[0]-'0');
2724 term->escseq.arg[term->escseq.narg] = n;
2726 if (*p == ';' && term->escseq.narg+1 < ESC_ARG_SIZ) {
2727 ++term->escseq.narg;
2728 ++p;
2729 } else {
2730 term->escseq.mode = *p;
2731 ++term->escseq.narg;
2732 break;
2738 static void tsetchar (const char *c) {
2739 char ub[UTF_SIZ+1];
2740 int rev = 0, gfx = 0;
2741 int x = term->c.x, y = term->c.y;
2743 if (x < 0 || x >= term->col || y < 0 || y >= term->row) return;
2745 if (!term->needConv && unimap != NULL) {
2746 ulong cc;
2748 utf8decode(c, &cc);
2749 if (cc <= 65535) {
2750 ushort uc = unimap[cc];
2752 if (uc) {
2753 if (uc == 127) {
2754 // inversed space
2755 rev = 1;
2756 ub[0] = ' ';
2757 //ub[1] = 0;
2758 } else {
2759 if (uc&0x8000) {
2760 ub[0] = (uc&0x7f);
2761 gfx = 1;
2762 } else {
2763 //ub[0] = uc&0x7f;
2764 utf8encode(uc, ub);
2767 c = ub;
2771 markDirty(y, 1);
2773 term->line[y][x] = term->c.attr;
2774 if (rev) term->line[y][x].attr ^= ATTR_REVERSE;
2775 if (gfx || (term->mode&term->charset)) {
2776 term->line[y][x].attr |= ATTR_GFX;
2777 } else {
2778 term->line[y][x].attr &= ~ATTR_GFX;
2781 term->line[y][x].state = (GLYPH_SET | GLYPH_DIRTY);
2782 memmove(term->line[y][x].c, c, UTF_SIZ);
2784 if (IS_GFX(term->line[y][x].attr)) {
2785 unsigned char c = (unsigned char)(term->line[y][x].c[0]);
2787 if (c > 95 && c < 128) term->line[y][x].c[0] -= 95;
2788 else if (c > 127) term->line[y][x].c[0] = ' ';
2790 if (term->sel.bx != -1 && selected(x, y)) selhide();
2791 //dlogf("tsetchar(%d,%d): [%c] (%d); dirty=%d\n", x, y, c[0], term->wantRedraw, term->dirty[y]);
2795 static void tdeletechar (int n) {
2796 int src = term->c.x+n;
2797 int dst = term->c.x;
2798 int size = term->col-src;
2800 markDirty(term->c.y, 2);
2801 if (src >= term->col) {
2802 tclearregion(term->c.x, term->c.y, term->col-1, term->c.y);
2803 } else {
2804 memmove(&term->line[term->c.y][dst], &term->line[term->c.y][src], size*sizeof(Glyph));
2805 tclearregion(term->col-n, term->c.y, term->col-1, term->c.y);
2810 static void tinsertblank (int n) {
2811 int src = term->c.x;
2812 int dst = src+n;
2813 int size = term->col-dst;
2815 markDirty(term->c.y, 2);
2816 if (dst >= term->col) {
2817 tclearregion(term->c.x, term->c.y, term->col-1, term->c.y);
2818 } else {
2819 memmove(&term->line[term->c.y][dst], &term->line[term->c.y][src], size*sizeof(Glyph));
2820 tclearregion(src, term->c.y, dst-1, term->c.y);
2825 static void tinsertblankline (int n) {
2826 if (term->c.y < term->top || term->c.y > term->bot) return;
2827 tscrolldown(term->c.y, n);
2831 static void tdeleteline (int n) {
2832 if (term->c.y < term->top || term->c.y > term->bot) return;
2833 tscrollup(term->c.y, n, 0);
2837 static void tsetattr (int *attr, int l) {
2838 for (int f = 0; f < l; ++f) {
2839 switch (attr[f]) {
2840 case 0:
2841 term->c.attr.attr &= ~(ATTR_REVERSE | ATTR_UNDERLINE | ATTR_BOLD);
2842 term->c.attr.attr |= ATTR_DEFFG | ATTR_DEFBG;
2843 term->c.attr.fg = term->deffg;
2844 term->c.attr.bg = term->defbg;
2845 break;
2846 case 1:
2847 term->c.attr.attr |= ATTR_BOLD;
2848 break;
2849 case 4:
2850 term->c.attr.attr |= ATTR_UNDERLINE;
2851 break;
2852 case 7:
2853 term->c.attr.attr |= ATTR_REVERSE;
2854 break;
2855 case 22:
2856 term->c.attr.attr &= ~ATTR_BOLD;
2857 break;
2858 case 24:
2859 term->c.attr.attr &= ~ATTR_UNDERLINE;
2860 break;
2861 case 27:
2862 term->c.attr.attr &= ~ATTR_REVERSE;
2863 break;
2864 case 38:
2865 if (f+2 < l && attr[f+1] == 5) {
2866 f += 2;
2867 if (BETWEEN(attr[f], 0, 255)) {
2868 term->c.attr.fg = attr[f];
2869 term->c.attr.attr &= ~ATTR_DEFFG;
2870 } else {
2871 fprintf(stderr, "erresc: bad fgcolor %d\n", attr[f]);
2873 } else {
2874 //fprintf(stderr, "erresc: gfx attr %d unknown\n", attr[f]);
2875 term->c.attr.fg = term->deffg;
2876 term->c.attr.attr |= ATTR_DEFFG;
2878 break;
2879 case 39:
2880 term->c.attr.fg = term->deffg;
2881 term->c.attr.attr |= ATTR_DEFFG;
2882 break;
2883 case 48:
2884 if (f+2 < l && attr[f+1] == 5) {
2885 f += 2;
2886 if (BETWEEN(attr[f], 0, 255)) {
2887 term->c.attr.bg = attr[f];
2888 term->c.attr.attr &= ~ATTR_DEFBG;
2889 } else {
2890 fprintf(stderr, "erresc: bad bgcolor %d\n", attr[f]);
2892 } else {
2893 fprintf(stderr, "erresc: gfx attr %d unknown\n", attr[f]);
2895 break;
2896 case 49:
2897 term->c.attr.bg = term->defbg;
2898 term->c.attr.attr |= ATTR_DEFBG;
2899 break;
2900 default:
2901 if (BETWEEN(attr[f], 30, 37)) { term->c.attr.fg = attr[f]-30; term->c.attr.attr &= ~ATTR_DEFFG; }
2902 else if (BETWEEN(attr[f], 40, 47)) { term->c.attr.bg = attr[f]-40; term->c.attr.attr &= ~ATTR_DEFBG; }
2903 else if (BETWEEN(attr[f], 90, 97)) { term->c.attr.fg = attr[f]-90+8; term->c.attr.attr &= ~ATTR_DEFFG; }
2904 else if (BETWEEN(attr[f], 100, 107)) { term->c.attr.bg = attr[f]-100+8; term->c.attr.attr &= ~ATTR_DEFBG; }
2905 else { fprintf(stderr, "erresc: gfx attr %d unknown\n", attr[f]); csidump(); }
2906 break;
2912 static void tsetscroll (int t, int b) {
2913 int temp;
2915 LIMIT(t, 0, term->row-1);
2916 LIMIT(b, 0, term->row-1);
2917 if (t > b) {
2918 temp = t;
2919 t = b;
2920 b = temp;
2922 term->top = t;
2923 term->bot = b;
2927 ////////////////////////////////////////////////////////////////////////////////
2928 // esc processing
2929 static void csihandle (void) {
2930 switch (term->escseq.mode) {
2931 case '@': /* ICH -- Insert <n> blank char */
2932 DEFAULT(term->escseq.arg[0], 1);
2933 tinsertblank(term->escseq.arg[0]);
2934 break;
2935 case 'A': /* CUU -- Cursor <n> Up */
2936 case 'e':
2937 DEFAULT(term->escseq.arg[0], 1);
2938 tmoveto(term->c.x, term->c.y-term->escseq.arg[0]);
2939 break;
2940 case 'B': /* CUD -- Cursor <n> Down */
2941 DEFAULT(term->escseq.arg[0], 1);
2942 tmoveto(term->c.x, term->c.y+term->escseq.arg[0]);
2943 break;
2944 case 'C': /* CUF -- Cursor <n> Forward */
2945 case 'a':
2946 DEFAULT(term->escseq.arg[0], 1);
2947 tmoveto(term->c.x+term->escseq.arg[0], term->c.y);
2948 break;
2949 case 'D': /* CUB -- Cursor <n> Backward */
2950 DEFAULT(term->escseq.arg[0], 1);
2951 tmoveto(term->c.x-term->escseq.arg[0], term->c.y);
2952 break;
2953 case 'E': /* CNL -- Cursor <n> Down and first col */
2954 DEFAULT(term->escseq.arg[0], 1);
2955 tmoveto(0, term->c.y+term->escseq.arg[0]);
2956 break;
2957 case 'F': /* CPL -- Cursor <n> Up and first col */
2958 DEFAULT(term->escseq.arg[0], 1);
2959 tmoveto(0, term->c.y-term->escseq.arg[0]);
2960 break;
2961 case 'G': /* CHA -- Move to <col> */
2962 case '`': /* XXX: HPA -- same? */
2963 DEFAULT(term->escseq.arg[0], 1);
2964 tmoveto(term->escseq.arg[0]-1, term->c.y);
2965 break;
2966 case 'H': /* CUP -- Move to <row> <col> */
2967 case 'f': /* XXX: HVP -- same? */
2968 DEFAULT(term->escseq.arg[0], 1);
2969 DEFAULT(term->escseq.arg[1], 1);
2970 tmoveto(term->escseq.arg[1]-1, term->escseq.arg[0]-1);
2971 break;
2972 /* XXX: (CSI n I) CHT -- Cursor Forward Tabulation <n> tab stops */
2973 case 'J': /* ED -- Clear screen */
2974 term->sel.bx = -1;
2975 switch (term->escseq.arg[0]) {
2976 case 0: /* below */
2977 tclearregion(term->c.x, term->c.y, term->col-1, term->c.y);
2978 if (term->c.y < term->row-1) tclearregion(0, term->c.y+1, term->col-1, term->row-1);
2979 break;
2980 case 1: /* above */
2981 if (term->c.y > 1) tclearregion(0, 0, term->col-1, term->c.y-1);
2982 tclearregion(0, term->c.y, term->c.x, term->c.y);
2983 break;
2984 case 2: /* all */
2985 tclearregion(0, 0, term->col-1, term->row-1);
2986 break;
2987 default:
2988 goto unknown;
2990 break;
2991 case 'K': /* EL -- Clear line */
2992 switch (term->escseq.arg[0]) {
2993 case 0: /* right */
2994 tclearregion(term->c.x, term->c.y, term->col-1, term->c.y);
2995 break;
2996 case 1: /* left */
2997 tclearregion(0, term->c.y, term->c.x, term->c.y);
2998 break;
2999 case 2: /* all */
3000 tclearregion(0, term->c.y, term->col-1, term->c.y);
3001 break;
3003 break;
3004 case 'S': /* SU -- Scroll <n> line up */
3005 DEFAULT(term->escseq.arg[0], 1);
3006 tscrollup(term->top, term->escseq.arg[0], 0);
3007 break;
3008 case 'T': /* SD -- Scroll <n> line down */
3009 DEFAULT(term->escseq.arg[0], 1);
3010 tscrolldown(term->top, term->escseq.arg[0]);
3011 break;
3012 case 'L': /* IL -- Insert <n> blank lines */
3013 DEFAULT(term->escseq.arg[0], 1);
3014 tinsertblankline(term->escseq.arg[0]);
3015 break;
3016 case 'l': /* RM -- Reset Mode */
3017 if (term->escseq.priv) {
3018 switch (term->escseq.arg[0]) {
3019 case 1: // 1001 for xterm compatibility
3020 DUMP_KEYPAD_SWITCH("1", "OFF");
3021 term->mode &= ~MODE_APPKEYPAD;
3022 break;
3023 case 5: /* DECSCNM -- Remove reverse video */
3024 if (IS_SET(MODE_REVERSE)) {
3025 term->mode &= ~MODE_REVERSE;
3026 tfulldirt();
3028 break;
3029 case 7: /* autowrap off */
3030 term->mode &= ~MODE_WRAP;
3031 break;
3032 case 12: /* att610 -- Stop blinking cursor (IGNORED) */
3033 break;
3034 case 20: /* non-standard code? */
3035 term->mode &= ~MODE_CRLF;
3036 break;
3037 case 25: /* hide cursor */
3038 if ((term->c.state&CURSOR_HIDE) == 0) {
3039 term->c.state |= CURSOR_HIDE;
3040 term->wantRedraw = 1;
3042 break;
3043 case 1000: /* disable X11 xterm mouse reporting */
3044 term->mode &= ~MODE_MOUSEBTN;
3045 break;
3046 case 1002:
3047 term->mode &= ~MODE_MOUSEMOTION;
3048 break;
3049 case 1004:
3050 term->mode &= ~MODE_FOCUSEVT;
3051 break;
3052 case 1005: /* utf-8 mouse encoding */
3053 case 1006: /* sgr mouse encoding */
3054 case 1015: /* urxvt mouse encoding */
3055 term->mousemode = 1000;
3056 break;
3057 case 1049: /* = 1047 and 1048 */
3058 case 47:
3059 case 1047:
3060 if (IS_SET(MODE_ALTSCREEN)) {
3061 tclearregion(0, 0, term->col-1, term->row-1);
3062 tswapscreen();
3064 if (term->escseq.arg[0] != 1049) break;
3065 case 1048:
3066 tcursor(CURSOR_LOAD);
3067 break;
3068 case 2004: /* reset bracketed paste mode */
3069 term->mode &= ~MODE_BRACPASTE;
3070 break;
3071 default:
3072 goto unknown;
3074 } else {
3075 switch (term->escseq.arg[0]) {
3076 case 3:
3077 term->mode &= ~MODE_DISPCTRL;
3078 break;
3079 case 4:
3080 term->mode &= ~MODE_INSERT;
3081 break;
3082 default:
3083 goto unknown;
3086 break;
3087 case 'M': /* DL -- Delete <n> lines */
3088 DEFAULT(term->escseq.arg[0], 1);
3089 tdeleteline(term->escseq.arg[0]);
3090 break;
3091 case 'X': /* ECH -- Erase <n> char */
3092 DEFAULT(term->escseq.arg[0], 1);
3093 tclearregion(term->c.x, term->c.y, term->c.x + term->escseq.arg[0], term->c.y);
3094 break;
3095 case 'P': /* DCH -- Delete <n> char */
3096 DEFAULT(term->escseq.arg[0], 1);
3097 tdeletechar(term->escseq.arg[0]);
3098 break;
3099 /* XXX: (CSI n Z) CBT -- Cursor Backward Tabulation <n> tab stops */
3100 case 'd': /* VPA -- Move to <row> */
3101 DEFAULT(term->escseq.arg[0], 1);
3102 tmoveto(term->c.x, term->escseq.arg[0]-1);
3103 break;
3104 case 'h': /* SM -- Set terminal mode */
3105 if (term->escseq.priv) {
3106 switch (term->escseq.arg[0]) {
3107 case 1:
3108 DUMP_KEYPAD_SWITCH("1", "ON");
3109 term->mode |= MODE_APPKEYPAD;
3110 break;
3111 case 5: /* DECSCNM -- Reverve video */
3112 if (!IS_SET(MODE_REVERSE)) {
3113 term->mode |= MODE_REVERSE;
3114 tfulldirt();
3116 break;
3117 case 7:
3118 term->mode |= MODE_WRAP;
3119 break;
3120 case 20:
3121 term->mode |= MODE_CRLF;
3122 break;
3123 case 12: /* att610 -- Start blinking cursor (IGNORED) */
3124 /* fallthrough for xterm cvvis = CSI [ ? 12 ; 25 h */
3125 if (term->escseq.narg > 1 && term->escseq.arg[1] != 25) break;
3126 case 25:
3127 if ((term->c.state&CURSOR_HIDE) != 0) {
3128 term->c.state &= ~CURSOR_HIDE;
3129 term->wantRedraw = 1;
3131 break;
3132 case 1000: /* 1000,1002: enable xterm mouse report */
3133 term->mode |= MODE_MOUSEBTN;
3134 break;
3135 case 1002:
3136 term->mode |= MODE_MOUSEMOTION;
3137 break;
3138 case 1004:
3139 term->mode |= MODE_FOCUSEVT;
3140 break;
3141 case 1005: /* utf-8 mouse encoding */
3142 case 1006: /* sgr mouse encoding */
3143 case 1015: /* urxvt mouse encoding */
3144 term->mousemode = term->escseq.arg[0];
3145 break;
3146 case 1049: /* = 1047 and 1048 */
3147 case 47:
3148 case 1047:
3149 if (IS_SET(MODE_ALTSCREEN)) tclearregion(0, 0, term->col-1, term->row-1); else tswapscreen();
3150 if (term->escseq.arg[0] != 1049) break;
3151 case 1048:
3152 tcursor(CURSOR_SAVE);
3153 break;
3154 case 2004: /* set bracketed paste mode */
3155 term->mode |= MODE_BRACPASTE;
3156 break;
3157 default: goto unknown;
3159 } else {
3160 switch (term->escseq.arg[0]) {
3161 case 3:
3162 term->mode |= MODE_DISPCTRL;
3163 break;
3164 case 4:
3165 term->mode |= MODE_INSERT;
3166 break;
3167 default:
3168 goto unknown;
3171 break;
3172 case 'm': /* SGR -- Terminal attribute (color) */
3173 tsetattr(term->escseq.arg, term->escseq.narg);
3174 break;
3175 case 'n':
3176 if (!term->escseq.priv) {
3177 switch (term->escseq.arg[0]) {
3178 case 6: { /* cursor position report */
3179 char buf[32];
3181 sprintf(buf, "\x1b[%d;%dR", term->c.x+1, term->c.y+1);
3182 ttywritestr(buf);
3183 } break;
3186 break;
3187 case 'r': /* DECSTBM -- Set Scrolling Region */
3188 if (term->escseq.priv && term->escseq.arg[0] == 1001) {
3189 // xterm compatibility
3190 DUMP_KEYPAD_SWITCH("1001", "OFF");
3191 term->mode &= ~MODE_APPKEYPAD;
3192 } else if (term->escseq.priv) {
3193 goto unknown;
3194 } else {
3195 DEFAULT(term->escseq.arg[0], 1);
3196 DEFAULT(term->escseq.arg[1], term->row);
3197 tsetscroll(term->escseq.arg[0]-1, term->escseq.arg[1]-1);
3198 tmoveto(0, 0);
3200 break;
3201 case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
3202 if (term->escseq.priv && term->escseq.arg[0] == 1001) {
3203 // xterm compatibility
3204 DUMP_KEYPAD_SWITCH("1001", "ON");
3205 term->mode |= MODE_APPKEYPAD;
3206 } else {
3207 tcursor(CURSOR_SAVE);
3209 break;
3210 case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
3211 tcursor(CURSOR_LOAD);
3212 break;
3213 default:
3214 unknown:
3215 fprintf(stderr, "erresc: unknown csi ");
3216 csidump();
3217 break;
3222 static void csireset (void) {
3223 memset(&term->escseq, 0, sizeof(term->escseq));
3227 static void tputtab (void) {
3228 int space = opt_tabsize-term->c.x%opt_tabsize;
3230 if (space > 0) tmoveto(term->c.x+space, term->c.y);
3234 ////////////////////////////////////////////////////////////////////////////////
3235 // put char to output buffer or process command
3237 // return 1 if this was control character
3238 // return -1 if this should break esape sequence
3239 static int tputc_ctrl (char ascii) {
3240 int res = 1;
3242 if (term->esc&ESC_TITLE) return 0;
3244 switch (ascii) {
3245 case '\t': tputtab(); break;
3246 case '\b': tmoveto(term->c.x-1, term->c.y); break;
3247 case '\r': tmoveto(0, term->c.y); break;
3248 case '\f': case '\n': case '\v': tnewline(IS_SET(MODE_CRLF)?1:0); break; /* go to first col if the mode is set */
3249 case '\a':
3250 if (!(xw.state & WIN_FOCUSED) && (term->belltype&BELL_URGENT)) xseturgency(1);
3251 if (term->belltype&BELL_AUDIO) XBell(xw.dpy, 100);
3252 break;
3253 case 14: term->charset = MODE_GFX1; break;
3254 case 15: term->charset = MODE_GFX0; break;
3255 case 0x18: case 0x1a: res = -1; break; // do nothing, interrupt current escape sequence
3256 case 127: break; // ignore it
3257 case '\033': csireset(); term->esc = ESC_START; break;
3258 //case 0x9b: csireset(); term->esc = ESC_START | ESC_CSI; break;
3259 default: res = 0; break;
3261 return res;
3265 static void tputc (const char *c) {
3266 char ascii = *c;
3267 int ctl = tputc_ctrl(ascii);
3269 if (ctl > 0) return; // control char; should not break escape sequence
3270 if (ctl < 0) {
3271 // control char; should break escape sequence
3272 term->esc = 0;
3273 return;
3275 //dlogf("tputc: [%c]\n", c[0]);
3276 if (term->esc & ESC_START) {
3277 if (term->esc & ESC_CSI) {
3278 term->escseq.buf[term->escseq.len++] = ascii;
3279 if (BETWEEN(ascii, 0x40, 0x7E) || term->escseq.len >= ESC_BUF_SIZ) {
3280 term->esc = 0;
3281 csiparse();
3282 csihandle();
3284 } else if (term->esc & ESC_OSC) {
3285 /* TODO: handle other OSC */
3286 if (ascii == ';') {
3287 term->title[0] = 0;
3288 term->titlelen = 0;
3289 term->esc = ESC_START | ESC_TITLE;
3290 //updateTabBar = 1;
3292 } else if (term->esc & ESC_TITLE) {
3293 int len = utf8size(c);
3295 if (ascii == '\a' || term->titlelen+len >= ESC_TITLE_SIZ) {
3296 term->esc = 0;
3297 term->title[term->titlelen] = '\0';
3298 fixWindowTitle(term);
3299 updateTabBar = 1;
3300 } else if (len > 0) {
3301 memcpy(term->title+term->titlelen, c, len);
3302 term->titlelen += len;
3303 term->title[term->titlelen] = '\0';
3305 } else if (term->esc & ESC_ALTCHARSET) {
3306 term->esc = 0;
3307 switch (ascii) {
3308 case '0': /* Line drawing crap */
3309 term->mode |= MODE_GFX0;
3310 break;
3311 case 'B': /* Back to regular text */
3312 term->mode &= ~MODE_GFX0;
3313 break;
3314 default:
3315 fprintf(stderr, "esc unhandled charset: ESC ( %c\n", ascii);
3316 term->mode &= ~MODE_GFX0;
3317 break;
3319 } else if (term->esc & ESC_ALTG1) {
3320 term->esc = 0;
3321 switch (ascii) {
3322 case '0': /* Line drawing crap */
3323 term->mode |= MODE_GFX1;
3324 break;
3325 case 'B': /* Back to regular text */
3326 term->mode &= ~MODE_GFX1;
3327 break;
3328 default:
3329 fprintf(stderr, "esc unhandled charset: ESC ) %c\n", ascii);
3330 term->mode &= ~MODE_GFX1;
3331 break;
3333 } else if (term->esc & ESC_HASH) {
3334 term->esc = 0;
3335 switch (ascii) {
3336 case '8': /* DECALN -- DEC screen alignment test -- fill screen with E's */
3337 //tfillscreenwithE();
3338 break;
3340 } else if (term->esc & ESC_PERCENT) {
3341 term->esc = 0;
3342 } else {
3343 switch (ascii) {
3344 case '[': term->esc |= ESC_CSI; break;
3345 case ']': term->esc |= ESC_OSC; break;
3346 case '(': term->esc |= ESC_ALTCHARSET; break;
3347 case ')': term->esc |= ESC_ALTG1; break;
3348 case '#': term->esc |= ESC_HASH; break;
3349 case '%': term->esc |= ESC_PERCENT; break;
3350 case 'D': /* IND -- Linefeed */
3351 term->esc = 0;
3352 if (term->c.y == term->bot) tscrollup(term->top, 1, 1); else tmoveto(term->c.x, term->c.y+1);
3353 break;
3354 case 'E': /* NEL -- Next line */
3355 term->esc = 0;
3356 tnewline(1); /* always go to first col */
3357 break;
3358 case 'M': /* RI -- Reverse linefeed */
3359 term->esc = 0;
3360 if (term->c.y == term->top) tscrolldown(term->top, 1); else tmoveto(term->c.x, term->c.y-1);
3361 break;
3362 case 'c': /* RIS -- Reset to inital state */
3363 term->esc = 0;
3364 treset();
3365 break;
3366 case '=': /* DECPAM -- Application keypad */
3367 DUMP_KEYPAD_SWITCH("=", "ON");
3368 term->esc = 0;
3369 term->mode |= MODE_APPKEYPAD;
3370 break;
3371 case '>': /* DECPNM -- Normal keypad */
3372 DUMP_KEYPAD_SWITCH(">", "OFF");
3373 term->esc = 0;
3374 term->mode &= ~MODE_APPKEYPAD;
3375 break;
3376 case '7': /* DECSC -- Save Cursor */
3377 /* Save current state (cursor coordinates, attributes, character sets pointed at by G0, G1) */
3378 //TODO?
3379 term->esc = 0;
3380 tcursor(CURSOR_SAVE);
3381 break;
3382 case '8': /* DECRC -- Restore Cursor */
3383 //TODO?
3384 term->esc = 0;
3385 tcursor(CURSOR_LOAD);
3386 break;
3387 case 'Z': /* DEC private identification */
3388 term->esc = 0;
3389 ttywritestr("\x1b[?1;2c");
3390 break;
3391 default:
3392 term->esc = 0;
3393 fprintf(stderr, "erresc: unknown sequence ESC 0x%02X ('%c')\n", (uchar)ascii, isprint(ascii)?ascii:'.');
3394 break;
3397 } else {
3398 //if (term->sel.bx != -1 && BETWEEN(term->c.y, term->sel.by, term->sel.ey)) term->sel.bx = -1;
3399 do {
3400 if (term->needConv && IS_GFX(term->c.attr.attr)) {
3401 ulong cc;
3403 utf8decode(c, &cc);
3404 if (cc < 32 || cc >= 127) break; //FIXME: nothing at all?
3405 } else {
3406 if ((unsigned char)ascii < 32 || ascii == 127) break; // seems that this chars are empty too
3408 if (term->c.state&CURSOR_WRAPNEXT) {
3409 if (IS_SET(MODE_WRAP)) {
3410 // always go to first col
3411 tnewline(2);
3412 } else {
3413 tsetcharwrap(term->c.y, 0);
3414 break; // wrap is off, don't want more chars
3417 tsetchar(c);
3418 if (term->c.x+1 < term->col) tmoveto(term->c.x+1, term->c.y); else term->c.state |= CURSOR_WRAPNEXT;
3419 } while (0);
3424 static void tunshowhistory (void) {
3425 if (term != NULL && term->topline != 0) {
3426 term->topline = 0;
3427 term->wantRedraw = 1;
3428 term->lastDrawTime = 0;
3433 static void tsendfocusevent (int focused) {
3434 if (term != NULL && IS_SET(MODE_FOCUSEVT)) {
3435 ttywritestr("\x1b[");
3436 ttywrite(focused?"I":"O", 1);
3441 static void tcmdlinedirty (void) {
3442 if (term != NULL) {
3443 markDirty(term->row-term->topline-1, 2);
3444 term->wantRedraw = 1;
3449 static void tcmdlinefixofs (void) {
3450 int ofs, len;
3452 len = utf8strlen(term->cmdline);
3453 ofs = len-(term->col-1);
3454 if (ofs < 0) ofs = 0;
3455 for (term->cmdofs = 0; ofs > 0; --ofs) term->cmdofs += utf8size(term->cmdline+term->cmdofs);
3456 tcmdlinedirty();
3460 static void tcmdlinehide (void) {
3461 term->cmdMode = CMDMODE_NONE;
3462 term->cmdprevc = NULL;
3463 tcmdlinedirty();
3467 // utf-8
3468 static void tcmdlinemsg (const char *msg) {
3469 if (msg != NULL) {
3470 int ofs = 0;
3472 term->cmdMode = CMDMODE_MESSAGE;
3473 term->cmdofs = 0;
3474 term->cmdtabpos = -1;
3475 term->cmdprevc = NULL;
3477 while (*msg) {
3478 int len = utf8size(msg);
3480 if (len < 1 || ofs+len >= sizeof(term->cmdline)-1) break;
3481 memcpy(term->cmdline+ofs, msg, len);
3482 ofs += len;
3483 msg += len;
3486 term->cmdline[ofs] = 0;
3487 tcmdlinedirty();
3492 static void tcmdlineinitex (const char *msg) {
3493 term->cmdMode = CMDMODE_INPUT;
3494 term->cmdofs = 0;
3495 term->cmdline[0] = 0;
3496 term->cmdc[0] = 0;
3497 term->cmdcl = 0;
3498 term->cmdtabpos = -1;
3499 term->cmdprevc = NULL;
3500 term->cmdreslen = 0;
3501 term->cmdexecfn = NULL;
3502 if (msg != NULL && msg[0]) {
3503 strcpy(term->cmdline, msg);
3504 term->cmdreslen = strlen(term->cmdline);
3506 tcmdlinefixofs();
3510 static void tcmdlineinit (void) {
3511 tcmdlineinitex(NULL);
3515 static void tcmdlinechoplast (void) {
3516 if (term->cmdcl != 0) {
3517 term->cmdcl = 0;
3518 } else {
3519 if (strlen(term->cmdline) > term->cmdreslen) utf8choplast(term->cmdline);
3521 tcmdlinefixofs();
3525 // utf-8
3526 static void tcmdaddchar (const char *s) {
3527 int len = utf8size(s);
3529 if (len > 0) {
3530 int slen = strlen(term->cmdline);
3532 if (slen+len < sizeof(term->cmdline)) {
3533 memcpy(term->cmdline+slen, s, len);
3534 term->cmdline[slen+len] = 0;
3535 tcmdlinefixofs();
3541 static void tcmdput (const char *s, int len) {
3542 while (len-- > 0) {
3543 int ok;
3545 term->cmdc[term->cmdcl++] = *s++;
3546 term->cmdc[term->cmdcl] = 0;
3548 if ((ok = isfullutf8(term->cmdc, term->cmdcl)) != 0 || term->cmdcl == UTF_SIZ) {
3549 if (ok) tcmdaddchar(term->cmdc);
3550 term->cmdcl = 0;
3556 ////////////////////////////////////////////////////////////////////////////////
3557 // tty resising
3558 static int tresize (int col, int row) {
3559 int mincol = MIN(col, term->col);
3560 int slide = term->c.y-row+1;
3561 Glyph g;
3563 if (col < 1 || row < 1) return 0;
3565 selhide();
3567 g.state = GLYPH_DIRTY;
3568 g.attr = ATTR_NULL|ATTR_DEFFG|ATTR_DEFBG;
3569 g.fg = term->deffg;
3570 g.bg = term->defbg;
3571 g.c[0] = ' ';
3572 g.c[1] = 0;
3574 if (slide > 0) {
3575 tsetscroll(0, term->row-1);
3576 for (; slide > 0; --slide) tscrollup(0, 1, 1); // to fill history
3579 if (row < term->row) {
3580 /* free unneeded rows */
3581 for (int f = row; f < term->row; ++f) free(term->alt[f]);
3582 for (int f = term->linecount-(term->row-row); f < term->linecount; ++f) free(term->line[f]);
3583 term->linecount -= (term->row-row);
3584 /* resize to new height */
3585 term->alt = realloc(term->alt, row*sizeof(Line));
3586 term->line = realloc(term->line, term->linecount*sizeof(Line));
3587 } else if (row > term->row) {
3588 /* resize to new height */
3589 term->alt = realloc(term->alt, row*sizeof(Line));
3590 term->line = realloc(term->line, (row+term->maxhistory)*sizeof(Line));
3591 /* add more lines */
3592 for (int f = term->row; f < row; ++f) {
3593 term->alt[f] = calloc(col, sizeof(Glyph));
3594 for (int x = 0; x < col; ++x) term->alt[f][x] = g;
3596 for (int f = 0; f < row-term->row; ++f) {
3597 int y = term->linecount++;
3599 term->line[y] = calloc(col, sizeof(Glyph));
3600 for (int x = 0; x < col; ++x) term->line[y][x] = g;
3604 if (row != term->row) {
3605 term->dirty = realloc(term->dirty, row*sizeof(*term->dirty));
3608 /* resize each row to new width, zero-pad if needed */
3609 for (int f = 0; f < term->linecount; ++f) {
3610 term->line[f] = realloc(term->line[f], col*sizeof(Glyph));
3611 for (int x = mincol; x < col; ++x) term->line[f][x] = g;
3612 if (f < row) {
3613 markDirty(f, 2);
3614 term->alt[f] = realloc(term->alt[f], col*sizeof(Glyph));
3615 for (int x = mincol; x < col; ++x) term->alt[f][x] = g;
3618 /* update terminal size */
3619 term->topline = 0;
3620 term->col = col;
3621 term->row = row;
3622 /* make use of the LIMIT in tmoveto */
3623 tmoveto(term->c.x, term->c.y);
3624 /* reset scrolling region */
3625 tsetscroll(0, row-1);
3626 tfulldirt();
3627 return (slide > 0);
3631 static void xresize (int col, int row) {
3632 Pixmap newbuf;
3633 int oldw, oldh;
3635 if (term == NULL) return;
3636 oldw = term->picbufw;
3637 oldh = term->picbufh;
3638 term->picbufw = MAX(1, col*xw.cw);
3639 term->picbufh = MAX(1, row*xw.ch);
3640 newbuf = XCreatePixmap(xw.dpy, xw.win, term->picbufw, term->picbufh, XDefaultDepth(xw.dpy, xw.scr));
3641 XCopyArea(xw.dpy, term->picbuf, newbuf, dc.gc, 0, 0, term->picbufw, term->picbufh, 0, 0);
3642 XFreePixmap(xw.dpy, term->picbuf);
3643 XSetForeground(xw.dpy, dc.gc, getColor(term->defbg));
3644 if (term->picbufw > oldw) {
3645 XFillRectangle(xw.dpy, newbuf, dc.gc, oldw, 0, term->picbufw-oldw, MIN(term->picbufh, oldh));
3646 } else if (term->picbufw < oldw && xw.w > term->picbufw) {
3647 XClearArea(xw.dpy, xw.win, term->picbufw, 0, xw.w-term->picbufh, MIN(term->picbufh, oldh), False);
3649 if (term->picbufh > oldh) {
3650 XFillRectangle(xw.dpy, newbuf, dc.gc, 0, oldh, term->picbufw, term->picbufh-oldh);
3651 } else if (term->picbufh < oldh && xw.h > term->picbufh) {
3652 XClearArea(xw.dpy, xw.win, 0, term->picbufh, xw.w, xw.h-term->picbufh, False);
3654 term->picbuf = newbuf;
3655 tfulldirt();
3656 updateTabBar = 1;
3660 ////////////////////////////////////////////////////////////////////////////////
3661 // x11 drawing and utils
3663 static void xcreatebw (void) {
3664 if ((dc.bcol = calloc(MAX_COLOR+1, sizeof(dc.bcol[0]))) == NULL) die("out of memory");
3666 for (int f = 0; f <= MAX_COLOR; ++f) {
3667 XColor nclr;
3669 nclr = dc.ncol[f].pixel;
3670 XQueryColor(xw.dpy, xw.cmap, &nclr);
3671 fprintf(stderr, "%d: r=%u; g=%u; b=%u\n", f, nclr.red, nclr.green, nclr.blue);
3677 static void xallocbwclr (int idx, XColor *color) {
3678 double lumi;
3680 XQueryColor(xw.dpy, xw.cmap, color);
3681 //fprintf(stderr, "%d: r=%u; g=%u; b=%u\n", idx, color->red, color->green, color->blue);
3683 lumi = 0.3*((double)color->red/65535.0)+0.59*((double)color->green/65535.0)+0.11*((double)color->blue/65535.0);
3684 color->red = color->green = color->blue = (int)(lumi*65535.0);
3685 if (!XAllocColor(xw.dpy, xw.cmap, color)) {
3686 fprintf(stderr, "WARNING: could not allocate b/w color #%d\n", idx);
3687 return;
3689 dc.bcol[idx] = color->pixel;
3690 color->red = color->blue = 0;
3691 if (!XAllocColor(xw.dpy, xw.cmap, color)) {
3692 fprintf(stderr, "WARNING: could not allocate b/w color #%d\n", idx);
3693 return;
3695 dc.gcol[idx] = color->pixel;
3699 static void xallocnamedclr (int idx, const char *cname) {
3700 XColor color;
3702 if (!XAllocNamedColor(xw.dpy, xw.cmap, cname, &color, &color)) {
3703 fprintf(stderr, "WARNING: could not allocate color #%d: '%s'\n", idx, cname);
3704 return;
3706 dc.ncol[idx] = color.pixel;
3707 xallocbwclr(idx, &color);
3711 static void xloadcols (void) {
3712 int f, r, g, b;
3713 XColor color;
3714 ulong white = WhitePixel(xw.dpy, xw.scr);
3716 if ((dc.clrs[0] = dc.ncol = calloc(MAX_COLOR+1, sizeof(dc.ncol[0]))) == NULL) die("out of memory");
3717 if ((dc.clrs[1] = dc.bcol = calloc(MAX_COLOR+1, sizeof(dc.bcol[0]))) == NULL) die("out of memory");
3718 if ((dc.clrs[2] = dc.gcol = calloc(MAX_COLOR+1, sizeof(dc.gcol[0]))) == NULL) die("out of memory");
3720 for (f = 0; f <= MAX_COLOR; ++f) dc.ncol[f] = dc.bcol[f] = white;
3721 /* load colors [0-15] */
3722 for (f = 0; f <= 15; ++f) {
3723 const char *cname = opt_colornames[f]!=NULL?opt_colornames[f]:defcolornames[f];
3725 xallocnamedclr(f, cname);
3727 /* load colors [256-...] */
3728 for (f = 256; f <= MAX_COLOR; ++f) {
3729 const char *cname = opt_colornames[f];
3731 if (cname == NULL) {
3732 if (LEN(defextcolornames) <= f-256) continue;
3733 cname = defextcolornames[f-256];
3735 if (cname == NULL) continue;
3736 xallocnamedclr(f, cname);
3738 /* load colors [16-255] ; same colors as xterm */
3739 for (f = 16, r = 0; r < 6; ++r) {
3740 for (g = 0; g < 6; ++g) {
3741 for (b = 0; b < 6; ++b) {
3742 if (opt_colornames[f] != NULL) {
3743 xallocnamedclr(f, opt_colornames[f]);
3744 } else {
3745 color.red = r == 0 ? 0 : 0x3737+0x2828*r;
3746 color.green = g == 0 ? 0 : 0x3737+0x2828*g;
3747 color.blue = b == 0 ? 0 : 0x3737+0x2828*b;
3748 if (!XAllocColor(xw.dpy, xw.cmap, &color)) {
3749 fprintf(stderr, "WARNING: could not allocate color #%d\n", f);
3750 } else {
3751 dc.ncol[f] = color.pixel;
3752 xallocbwclr(f, &color);
3755 ++f;
3759 for (r = 0; r < 24; ++r, ++f) {
3760 if (opt_colornames[f] != NULL) {
3761 xallocnamedclr(f, opt_colornames[f]);
3762 } else {
3763 color.red = color.green = color.blue = 0x0808+0x0a0a*r;
3764 if (!XAllocColor(xw.dpy, xw.cmap, &color)) {
3765 fprintf(stderr, "WARNING: could not allocate color #%d\n", f);
3766 } else {
3767 dc.ncol[f] = color.pixel;
3768 xallocbwclr(f, &color);
3773 for (int f = 0; f < LEN(opt_colornames); ++f) if (opt_colornames[f]) free(opt_colornames[f]);
3777 static void xclear (int x1, int y1, int x2, int y2) {
3778 XSetForeground(xw.dpy, dc.gc, getColor(IS_SET(MODE_REVERSE) ? term->deffg : term->defbg));
3779 XFillRectangle(xw.dpy, term->picbuf, dc.gc, x1*xw.cw, y1*xw.ch, (x2-x1+1)*xw.cw, (y2-y1+1)*xw.ch);
3783 static void xhints (void) {
3784 XClassHint class = {opt_class, opt_title};
3785 XWMHints wm = {.flags = InputHint, .input = 1};
3786 XSizeHints size = {
3787 .flags = PSize | PResizeInc | PBaseSize,
3788 .height = xw.h,
3789 .width = xw.w,
3790 .height_inc = xw.ch,
3791 .width_inc = xw.cw,
3792 .base_height = xw.h/*xw.tabheight*/,
3793 .base_width = xw.w,
3795 //XSetWMNormalHints(xw.dpy, xw.win, &size);
3796 XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, &size, &wm, &class);
3797 XSetWMProtocols(xw.dpy, xw.win, &XA_WM_DELETE_WINDOW, 1);
3801 static XFontSet xinitfont (const char *fontstr) {
3802 XFontSet set;
3803 char *def, **missing;
3804 int n;
3806 missing = NULL;
3807 set = XCreateFontSet(xw.dpy, fontstr, &missing, &n, &def);
3808 if (missing) {
3809 while (n--) fprintf(stderr, "sterm: missing fontset: %s\n", missing[n]);
3810 XFreeStringList(missing);
3812 return set;
3816 static void xgetfontinfo (XFontSet set, int *ascent, int *descent, short *lbearing, short *rbearing, Font *fid) {
3817 XFontStruct **xfonts;
3818 char **font_names;
3819 int n;
3821 *ascent = *descent = *lbearing = *rbearing = 0;
3822 n = XFontsOfFontSet(set, &xfonts, &font_names);
3823 for (int f = 0; f < n; ++f) {
3824 if (f == 0) *fid = (*xfonts)->fid;
3825 *ascent = MAX(*ascent, (*xfonts)->ascent);
3826 *descent = MAX(*descent, (*xfonts)->descent);
3827 *lbearing = MAX(*lbearing, (*xfonts)->min_bounds.lbearing);
3828 *rbearing = MAX(*rbearing, (*xfonts)->max_bounds.rbearing);
3829 ++xfonts;
3834 static void initfonts (const char *fontstr, const char *bfontstr, const char *tabfont) {
3835 if ((dc.font[0].set = xinitfont(fontstr)) == NULL) {
3836 if ((dc.font[0].set = xinitfont(FONT)) == NULL) die("can't load font %s", fontstr);
3838 xgetfontinfo(dc.font[0].set, &dc.font[0].ascent, &dc.font[0].descent, &dc.font[0].lbearing, &dc.font[0].rbearing, &dc.font[0].fid);
3840 if ((dc.font[1].set = xinitfont(bfontstr)) == NULL) {
3841 if ((dc.font[1].set = xinitfont(FONTBOLD)) == NULL) die("can't load font %s", bfontstr);
3843 xgetfontinfo(dc.font[1].set, &dc.font[1].ascent, &dc.font[1].descent, &dc.font[1].lbearing, &dc.font[1].rbearing, &dc.font[1].fid);
3845 if ((dc.font[2].set = xinitfont(tabfont)) == NULL) {
3846 if ((dc.font[2].set = xinitfont(FONTTAB)) == NULL) die("can't load font %s", tabfont);
3848 xgetfontinfo(dc.font[2].set, &dc.font[2].ascent, &dc.font[2].descent, &dc.font[2].lbearing, &dc.font[2].rbearing, &dc.font[2].fid);
3852 static void xinit (void) {
3853 XSetWindowAttributes attrs;
3854 Window parent;
3855 XColor blackcolor = { 0, 0, 0, 0, 0, 0 };
3857 if (!(xw.dpy = XOpenDisplay(NULL))) die("can't open display");
3859 XA_VT_SELECTION = XInternAtom(xw.dpy, "_STERM_SELECTION_", 0);
3860 XA_CLIPBOARD = XInternAtom(xw.dpy, "CLIPBOARD", 0);
3861 XA_UTF8 = XInternAtom(xw.dpy, "UTF8_STRING", 0);
3862 XA_NETWM_NAME = XInternAtom(xw.dpy, "_NET_WM_NAME", 0);
3863 XA_TARGETS = XInternAtom(xw.dpy, "TARGETS", 0);
3864 XA_WM_DELETE_WINDOW = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", 0);
3865 xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
3867 xw.scr = XDefaultScreen(xw.dpy);
3868 /* font */
3869 initfonts(opt_fontnorm, opt_fontbold, opt_fonttab);
3870 /* XXX: Assuming same size for bold font */
3871 xw.cw = dc.font[0].rbearing-dc.font[0].lbearing;
3872 xw.ch = dc.font[0].ascent+dc.font[0].descent;
3873 xw.tch = dc.font[2].ascent+dc.font[2].descent;
3874 xw.tabheight = opt_disabletabs ? 0 : xw.tch+2;
3875 //fprintf(stderr, "tabh: %d\n", xw.tabheight);
3876 //xw.tabheight = 0;
3877 /* colors */
3878 xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
3879 xloadcols();
3880 /* window - default size */
3881 term->picbufh = term->row*xw.ch;
3882 term->picbufw = term->col*xw.cw;
3884 xw.h = term->picbufh+xw.tabheight;
3885 xw.w = term->picbufw;
3887 attrs.background_pixel = getColor(defaultBG);
3888 attrs.border_pixel = getColor(defaultBG);
3889 attrs.bit_gravity = NorthWestGravity;
3890 attrs.event_mask = FocusChangeMask | KeyPressMask
3891 | ExposureMask | VisibilityChangeMask | StructureNotifyMask
3892 | /*ButtonMotionMask*/ PointerMotionMask | ButtonPressMask | ButtonReleaseMask
3893 | EnterWindowMask | LeaveWindowMask;
3894 attrs.colormap = xw.cmap;
3895 //fprintf(stderr, "oe: [%s]\n", opt_embed);
3896 parent = opt_embed ? strtol(opt_embed, NULL, 0) : XRootWindow(xw.dpy, xw.scr);
3897 xw.win = XCreateWindow(xw.dpy, parent, 0, 0,
3898 xw.w, xw.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
3899 XDefaultVisual(xw.dpy, xw.scr),
3900 CWBackPixel | CWBorderPixel | CWBitGravity | CWEventMask
3901 | CWColormap,
3902 &attrs);
3903 xhints();
3904 term->picbuf = XCreatePixmap(xw.dpy, xw.win, term->picbufw, term->picbufh, XDefaultDepth(xw.dpy, xw.scr));
3905 xw.pictab = XCreatePixmap(xw.dpy, xw.win, xw.w, xw.tabheight>0?xw.tabheight:1, XDefaultDepth(xw.dpy, xw.scr));
3906 /* input methods */
3907 if ((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) die("XOpenIM() failed");
3908 xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing | XIMStatusNothing, XNClientWindow, xw.win, XNFocusWindow, xw.win, NULL);
3909 /* gc */
3910 dc.gc = XCreateGC(xw.dpy, xw.win, 0, NULL);
3911 /* white cursor, black outline */
3912 xw.cursor = XCreateFontCursor(xw.dpy, XC_xterm);
3913 XDefineCursor(xw.dpy, xw.win, xw.cursor);
3914 XRecolorCursor(xw.dpy, xw.cursor,
3915 &(XColor){.red = 0xffff, .green = 0xffff, .blue = 0xffff},
3916 &(XColor){.red = 0x0000, .green = 0x0000, .blue = 0x0000});
3917 fixWindowTitle(term);
3918 //XStoreName(xw.dpy, xw.win, opt_title);
3920 XSetForeground(xw.dpy, dc.gc, 0);
3921 XFillRectangle(xw.dpy, term->picbuf, dc.gc, 0, 0, term->picbufw, term->picbufh);
3922 if (xw.tabheight > 0) XFillRectangle(xw.dpy, xw.pictab, dc.gc, 0, 0, xw.w, xw.tabheight);
3924 XMapWindow(xw.dpy, xw.win);
3926 #if BLANKPTR_USE_GLYPH_CURSOR
3927 xw.blankPtr = XCreateGlyphCursor(xw.dpy, dc.font[0].fid, dc.font[0].fid, ' ', ' ', &blackcolor, &blackcolor);
3928 #else
3929 static const char cmbmp[1] = {0};
3930 Pixmap pm;
3932 pm = XCreateBitmapFromData(xw.dpy, xw.win, cmbmp, 1, 1);
3933 xw.blankPtr = XCreatePixmapCursor(xw.dpy, pm, pm, &blackcolor, &blackcolor, 0, 0);
3934 XFreePixmap(xw.dpy, pm);
3935 #endif
3937 XSync(xw.dpy, 0);
3941 static void xblankPointer (void) {
3942 if (!ptrBlanked && xw.blankPtr != None) {
3943 ptrBlanked = 1;
3944 XDefineCursor(xw.dpy, xw.win, xw.blankPtr);
3945 XFlush(xw.dpy);
3950 static void xunblankPointer (void) {
3951 if (ptrBlanked && xw.cursor != None) {
3952 ptrBlanked = 0;
3953 XDefineCursor(xw.dpy, xw.win, xw.cursor);
3954 XFlush(xw.dpy);
3955 ptrLastMove = mclock_ticks();
3960 static void xdraws (const char *s, const Glyph *base, int x, int y, int charlen, int bytelen) {
3961 int fg = base->fg, bg = base->bg, temp;
3962 int winx = x*xw.cw, winy = y*xw.ch+dc.font[0].ascent, width = charlen*xw.cw;
3963 XFontSet fontset = dc.font[0].set;
3964 int defF = base->attr&ATTR_DEFFG, defB = base->attr&ATTR_DEFBG;
3966 /* only switch default fg/bg if term is in RV mode */
3967 if (IS_SET(MODE_REVERSE)) {
3968 if (defF) fg = term->defbg;
3969 if (defB) bg = term->deffg;
3971 if (base->attr&ATTR_REVERSE) defF = defB = 0;
3972 if (base->attr&ATTR_BOLD) {
3973 if (defF && defB && defaultBoldFG >= 0) fg = defaultBoldFG;
3974 else if (fg < 8) fg += 8;
3975 fontset = dc.font[1].set;
3977 if ((base->attr&ATTR_UNDERLINE) && defaultUnderlineFG >= 0) {
3978 if (defF && defB) fg = defaultUnderlineFG;
3981 if (base->attr&ATTR_REVERSE) { temp = fg; fg = bg; bg = temp; }
3983 XSetBackground(xw.dpy, dc.gc, getColor(bg));
3984 XSetForeground(xw.dpy, dc.gc, getColor(fg));
3988 FILE *fo = fopen("zlog.log", "ab");
3989 fprintf(fo, "xdraws: x=%d; y=%d; charlen=%d; bytelen=%d\n", x, y, charlen, bytelen);
3990 fclose(fo);
3994 if (IS_GFX(base->attr)) {
3995 XmbDrawImageString(xw.dpy, term->picbuf, fontset, dc.gc, winx, winy, s, bytelen);
3996 } else if (!needConversion) {
3997 XmbDrawImageString(xw.dpy, term->picbuf, fontset, dc.gc, winx, winy, s, bytelen);
3998 } else {
3999 if (bytelen > 0) {
4000 //k8: dunno why, but Xutf8DrawImageString() ignores ascii (at least for terminus)
4001 const char *pos = s;
4002 int xpos = winx;
4004 while (pos < s+bytelen) {
4005 const char *e;
4006 int clen;
4008 if ((unsigned char)(pos[0]) < 128) {
4009 for (e = pos+1; e < s+bytelen && (unsigned char)(*e) < 128; ++e) ;
4010 clen = e-pos;
4011 XmbDrawImageString(xw.dpy, term->picbuf, fontset, dc.gc, xpos, winy, pos, e-pos);
4014 FILE *fo = fopen("zlog.log", "ab");
4015 fprintf(fo, " norm: clen=%d (%d); [", clen, (int)(e-pos));
4016 fwrite(pos, 1, e-pos, fo);
4017 fprintf(fo, "]\n");
4018 fclose(fo);
4021 } else {
4022 for (clen = 0, e = pos; e < s+bytelen && (unsigned char)(*e) >= 128; ++e) {
4023 if (((unsigned char)(e[0])&0xc0) == 0xc0) ++clen;
4025 Xutf8DrawImageString(xw.dpy, term->picbuf, fontset, dc.gc, xpos, winy, pos, e-pos);
4028 FILE *fo = fopen("zlog.log", "ab");
4029 fprintf(fo, " utf8: clen=%d (%d); [", clen, (int)(e-pos));
4030 fwrite(pos, 1, e-pos, fo);
4031 fprintf(fo, "]\n");
4032 fclose(fo);
4036 xpos += xw.cw*clen;
4037 pos = e;
4042 if (opt_drawunderline && (base->attr&ATTR_UNDERLINE)) {
4043 XDrawLine(xw.dpy, term->picbuf, dc.gc, winx, winy+1, winx+width-1, winy+1);
4048 /* copy buffer pixmap to screen pixmap */
4049 static void xcopy (int x, int y, int cols, int rows) {
4050 int src_x = x*xw.cw, src_y = y*xw.ch, src_w = cols*xw.cw, src_h = rows*xw.ch;
4051 int dst_x = src_x, dst_y = src_y;
4053 if (opt_tabposition == 1) { dst_y += xw.tabheight; }
4054 XCopyArea(xw.dpy, term->picbuf, xw.win, dc.gc, src_x, src_y, src_w, src_h, dst_x, dst_y);
4058 static void xdrawcursor (void) {
4059 Glyph g;
4060 int sl, scrx, scry, cmy;
4062 if (term == NULL) return;
4064 LIMIT(term->oldcx, 0, term->col-1);
4065 LIMIT(term->oldcy, 0, term->row-1);
4067 cmy = term->row-term->topline-1;
4069 if (!(xw.state&WIN_FOCUSED) && !term->curblinkinactive) term->curbhidden = 0;
4071 if (term->cmdMode == CMDMODE_NONE || term->oldcy != cmy) {
4072 scrx = term->oldcx;
4073 scry = term->oldcy+term->topline;
4074 if (scry >= 0 && scry < term->row) {
4075 if (term->curbhidden < 0 ||
4076 term->oldcy != term->c.y || term->oldcx != term->c.x ||
4077 (term->c.state&CURSOR_HIDE) ||
4078 !(xw.state&WIN_FOCUSED)) {
4079 /* remove the old cursor */
4080 sl = utf8size(term->line[term->oldcy][scrx].c);
4081 g = term->line[term->oldcy][scrx];
4082 if (selected(scrx, term->c.y)) g.attr ^= ATTR_REVERSE;
4083 xdraws(g.c, &g, scrx, scry, 1, sl);
4084 //xclear(scrx, term->oldcy, scrx, term->oldcy);
4085 xcopy(scrx, scry, 1, 1);
4087 if (term->curbhidden) term->curbhidden = 1;
4091 if (term->cmdMode != CMDMODE_NONE && term->oldcy == cmy) return;
4092 if ((term->c.state&CURSOR_HIDE) != 0) return;
4093 if (term->curbhidden) return;
4094 /* draw the new one */
4095 scrx = term->c.x;
4096 scry = term->c.y+term->topline;
4097 if (scry >= 0 && scry < term->row) {
4098 int nodraw = 0;
4100 if (!(xw.state&WIN_FOCUSED)) {
4101 if (defaultCursorInactiveBG < 0) {
4102 XSetForeground(xw.dpy, dc.gc, getColor(defaultCursorBG));
4103 XDrawRectangle(xw.dpy, term->picbuf, dc.gc, scrx*xw.cw, scry*xw.ch, xw.cw-1, xw.ch-1);
4104 nodraw = 1;
4105 } else {
4106 g.bg = defaultCursorInactiveBG;
4107 g.fg = defaultCursorInactiveFG;
4109 } else {
4110 g.fg = defaultCursorFG;
4111 g.bg = defaultCursorBG;
4113 if (!nodraw) {
4114 memcpy(g.c, term->line[term->c.y][scrx].c, UTF_SIZ);
4115 g.state = 0;
4116 g.attr = ATTR_NULL;
4117 if (IS_SET(MODE_REVERSE)) g.attr |= ATTR_REVERSE;
4118 sl = utf8size(g.c);
4119 xdraws(g.c, &g, scrx, scry, 1, sl);
4121 term->oldcx = scrx;
4122 term->oldcy = term->c.y;
4123 xcopy(scrx, scry, 1, 1);
4128 static void xdrawTabBar (void) {
4129 if (xw.tabheight > 0 && updateTabBar) {
4130 if (updateTabBar > 0) {
4131 static int tableft = 0;
4132 int tabstart;
4133 int tabw = xw.w/opt_tabcount;
4134 XFontSet fontset = dc.font[2].set;
4136 XSetForeground(xw.dpy, dc.gc, getColor(normalTabBG));
4137 XFillRectangle(xw.dpy, xw.pictab, dc.gc, 0, 0, xw.w, xw.tabheight);
4139 if (termidx < tableft) tableft = termidx;
4140 else if (termidx > tableft+opt_tabcount-1) tableft = termidx-opt_tabcount+1;
4141 if (tableft < 0) tableft = 0;
4143 tabstart = tableft;
4144 for (int f = tabstart; f < tabstart+opt_tabcount; ++f) {
4145 int x = (f-tabstart)*tabw;
4146 const char *title;
4147 char *tit;
4149 if (f >= term_count) {
4150 XSetForeground(xw.dpy, dc.gc, getColor(normalTabBG));
4151 XFillRectangle(xw.dpy, xw.pictab, dc.gc, x, 0, xw.w, xw.tabheight);
4153 XSetForeground(xw.dpy, dc.gc, getColor(normalTabFG));
4154 XDrawLine(xw.dpy, xw.pictab, dc.gc, x/*+tabw-1*/, 0, x/*+tabw-1*/, xw.tabheight);
4155 break;
4157 title = term_array[f]->title;
4158 if (!title[0]) title = opt_title;
4159 tit = SPrintf("[%d]%s", f, title);
4160 title = tit;
4162 XSetForeground(xw.dpy, dc.gc, getColor(f == termidx ? activeTabBG : normalTabBG));
4163 XFillRectangle(xw.dpy, xw.pictab, dc.gc, x, 0, tabw, xw.tabheight);
4165 XSetBackground(xw.dpy, dc.gc, getColor(f == termidx ? activeTabBG : normalTabBG));
4166 XSetForeground(xw.dpy, dc.gc, getColor(f == termidx ? activeTabFG : normalTabFG));
4168 if (needConversion) {
4169 int xx = x+2;
4171 while (*title && xx < x+tabw) {
4172 const char *e = title;
4173 XRectangle r;
4175 memset(&r, 0, sizeof(r));
4177 if ((unsigned char)(*e) > 127) {
4178 while (*e && (unsigned char)(*e) > 127) ++e;
4179 Xutf8DrawImageString(xw.dpy, xw.pictab, fontset, dc.gc, xx, dc.font[2].ascent+2, title, e-title);
4180 Xutf8TextExtents(fontset, title, e-title, &r, NULL);
4181 } else {
4182 while (*e && (unsigned char)(*e) <= 127) ++e;
4183 XmbDrawImageString(xw.dpy, xw.pictab, fontset, dc.gc, xx, dc.font[2].ascent+2, title, e-title);
4184 XmbTextExtents(fontset, title, e-title, &r, NULL);
4186 title = e;
4187 xx += r.width-r.x;
4190 XmbDrawImageString(xw.dpy, xw.pictab, fontset, dc.gc, x+2, dc.font[2].ascent+2, title, strlen(title));
4191 } else {
4192 Xutf8DrawImageString(xw.dpy, xw.pictab, fontset, dc.gc, x+2, dc.font[2].ascent+2, title, strlen(title));
4194 free(tit);
4196 XSetForeground(xw.dpy, dc.gc, getColor(f == termidx ? activeTabBG : normalTabBG));
4197 XFillRectangle(xw.dpy, xw.pictab, dc.gc, x+tabw-2, 0, 2, xw.tabheight);
4199 if (f > tabstart) {
4200 XSetForeground(xw.dpy, dc.gc, getColor(normalTabFG));
4201 XDrawLine(xw.dpy, xw.pictab, dc.gc, x/*+tabw-1*/, 0, x/*+tabw-1*/, xw.tabheight);
4205 XSetForeground(xw.dpy, dc.gc, getColor(normalTabFG));
4206 //XDrawRectangle(xw.dpy, xw.pictab, dc.gc, -1, 0, xw.w+1, xw.tabheight+1);
4207 if (opt_tabposition == 0) {
4208 XDrawLine(xw.dpy, xw.pictab, dc.gc, 0, 0, xw.w, 0);
4209 } else {
4210 XDrawLine(xw.dpy, xw.pictab, dc.gc, 0, xw.tabheight-1, xw.w, xw.tabheight-1);
4214 if (opt_tabposition == 0) {
4215 XCopyArea(xw.dpy, xw.pictab, xw.win, dc.gc, 0, 0, xw.w, xw.tabheight, 0, xw.h-xw.tabheight);
4216 } else {
4217 XCopyArea(xw.dpy, xw.pictab, xw.win, dc.gc, 0, 0, xw.w, xw.tabheight, 0, 0);
4220 updateTabBar = 0;
4224 static void drawcmdline (int scry) {
4225 Glyph base;
4226 int cpos = term->cmdofs, bc = 0, x, sx;
4227 int back = (term->cmdMode == CMDMODE_INPUT ? 21 : 124);
4229 base.attr = ATTR_NULL;
4230 base.fg = 255;
4231 base.bg = back;
4232 base.state = 0;
4233 for (sx = x = 0; x < term->col && term->cmdline[cpos]; ++x) {
4234 int l = utf8size(term->cmdline+cpos);
4236 if (bc+l > DRAW_BUF_SIZ) {
4237 xdraws(term->drawbuf, &base, sx, scry, x-sx, bc);
4238 bc = 0;
4239 sx = x;
4241 memcpy(term->drawbuf+bc, term->cmdline+cpos, l);
4242 cpos += l;
4243 bc += l;
4245 if (bc > 0) xdraws(term->drawbuf, &base, sx, scry, x-sx, bc);
4247 if (x < term->col && term->cmdMode == CMDMODE_INPUT) {
4248 base.fg = back;
4249 base.bg = 255;
4250 xdraws(" ", &base, x, scry, 1, 1);
4251 ++x;
4254 if (x < term->col) {
4255 base.fg = 255;
4256 base.bg = back;
4257 memset(term->drawbuf, ' ', DRAW_BUF_SIZ);
4258 while (x < term->col) {
4259 sx = x;
4260 x += DRAW_BUF_SIZ;
4261 if (x > term->col) x = term->col;
4262 xdraws(term->drawbuf, &base, sx, scry, x-sx, x-sx);
4266 xcopy(0, scry, term->col, 1);
4270 static void drawline (int x1, int x2, int scry, int lineno, int dontcopy) {
4271 //fprintf(stderr, "%d: drawline: x1=%d; x2=%d; scry=%d; row:%d; lineno=%d\n", mclock_ticks(), x1, x2, scry, term->row, lineno);
4272 if (scry < 0 || scry >= term->row) return;
4273 if (scry == term->row-1 && term->cmdMode != CMDMODE_NONE) { drawcmdline(scry); return; }
4274 if (lineno < 0 || lineno >= term->linecount) {
4275 xclear(0, scry, term->col-1, scry);
4276 xcopy(0, scry, term->col, 1);
4277 } else {
4278 int ic, ib, ox, sl;
4279 int stx, ex;
4280 Glyph base, new;
4281 Line l = term->line[lineno];
4283 if (lineno < term->row && term->topline == 0) {
4284 if (!term->dirty[lineno]) return;
4285 if (!dontcopy) {
4286 // fix 'dirty' flag for line
4287 if (term->dirty[lineno]&0x02) {
4288 // mark full line as dirty
4289 stx = 0;
4290 ex = term->col;
4291 term->dirty[lineno] = 0;
4292 } else {
4293 term->dirty[lineno] = 0;
4294 if (x1 > 0) for (int x = 0; x < x1; ++x) if (l[x].state&GLYPH_DIRTY) { term->dirty[lineno] = 1; break; }
4295 if (!term->dirty[lineno] && x2 < term->col) for (int x = x2; x < term->col; ++x) if (l[x].state&GLYPH_DIRTY) { term->dirty[lineno] = 1; break; }
4297 // find dirty region
4298 for (stx = x1; stx < x2; ++stx) if (l[stx].state&GLYPH_DIRTY) break;
4299 for (ex = x2; ex > stx; --ex) if (l[ex-1].state&GLYPH_DIRTY) break;
4300 if (stx >= x2 || ex <= stx) return; // nothing to do
4302 } else {
4303 // 'dontcopy' means that the whole screen is dirty
4304 stx = 0;
4305 ex = term->col;
4306 term->dirty[lineno] = 0;
4308 } else {
4309 //if (lineno < term->row) term->dirty[lineno] = 0;
4310 stx = 0;
4311 ex = term->col;
4314 base = l[stx];
4315 if (term->sel.bx != -1 && selected(stx, lineno)) base.attr ^= ATTR_REVERSE;
4316 ic = ib = 0;
4317 ox = stx;
4318 //xclear(stx, scry, ex-1, scry); //k8: actually, we don't need this for good monospace fonts, so...
4319 for (int x = stx; x < ex; ++x) {
4320 new = l[x];
4321 l[x].state &= ~GLYPH_DIRTY; //!
4322 if (term->sel.bx != -1 && selected(x, lineno)) new.attr ^= ATTR_REVERSE;
4323 if (ib > 0 && (ATTRCMP(base, new) || ib >= DRAW_BUF_SIZ-UTF_SIZ)) {
4324 // flush draw buffer
4325 xdraws(term->drawbuf, &base, ox, scry, ic, ib);
4326 ic = ib = 0;
4328 if (ib == 0) { ox = x; base = new; }
4329 sl = utf8size(new.c);
4330 memcpy(term->drawbuf+ib, new.c, sl);
4331 ib += sl;
4332 ++ic;
4334 if (ib > 0) xdraws(term->drawbuf, &base, ox, scry, ic, ib);
4335 //xcopy(0, scry, term->col, 1);
4336 //if (term->c.y == lineno && term->c.x >= stx && term->c.x < ex) xdrawcursor();
4337 if (!dontcopy) xcopy(stx, scry, ex-stx, 1);
4342 static void drawregion (int x1, int y1, int x2, int y2, int forced) {
4343 int fulldirty = 0;
4345 if (!forced && (xw.state&WIN_VISIBLE) == 0) {
4346 //dlogf("invisible");
4347 lastDrawTime = term->lastDrawTime = 1;
4348 term->wantRedraw = 1;
4349 return;
4352 if (y1 == 0 && y2 == term->row) {
4353 fulldirty = 1;
4354 for (int y = 0; y < y2; ++y) if (!(term->dirty[y]&0x02)) { fulldirty = 0; break; }
4357 if (term->topline < term->row) {
4358 for (int y = y1; y < y2; ++y) drawline(x1, x2, y+term->topline, y, fulldirty);
4360 if (term->topline > 0) {
4361 int scry = MIN(term->topline, term->row), y = term->row;
4363 fulldirty = 1;
4364 if (term->topline >= term->row) y += term->topline-term->row;
4365 while (--scry >= 0) {
4366 drawline(0, term->col, scry, y, 0);
4367 ++y;
4370 if (fulldirty) xcopy(0, 0, term->col, term->row);
4371 xdrawcursor();
4372 xdrawTabBar();
4373 //XFlush(xw.dpy);
4374 lastDrawTime = term->lastDrawTime = mclock_ticks();
4375 term->wantRedraw = 0;
4379 static void draw (int forced) {
4380 if (term != NULL) {
4381 //fprintf(stderr, "draw(%d) (%d)\n", forced, mclock_ticks());
4382 drawregion(0, 0, term->col, term->row, forced);
4387 static void expose (XEvent *ev) {
4388 XExposeEvent *e = &ev->xexpose;
4390 if (xw.state&WIN_REDRAW) {
4391 if (!e->count && term != NULL) {
4392 xw.state &= ~WIN_REDRAW;
4393 xcopy(0, 0, term->col, term->row);
4395 } else if (term != NULL) {
4396 //XCopyArea(xw.dpy, term->picbuf, xw.win, dc.gc, e->x, e->y, e->width, e->height, e->x, e->y+(opt_tabposition==1?xw.height:0)));
4397 xcopy(0, 0, term->col, term->row);
4399 updateTabBar = -1;
4400 xdrawTabBar();
4401 //XFlush(xw.dpy);
4405 static void visibility (XEvent *ev) {
4406 XVisibilityEvent *e = &ev->xvisibility;
4408 if (e->state == VisibilityFullyObscured) xw.state &= ~WIN_VISIBLE;
4409 else if ((xw.state&WIN_VISIBLE) == 0) xw.state |= WIN_VISIBLE | WIN_REDRAW; /* need a full redraw for next Expose, not just a buf copy */
4413 static void unmap (XEvent *ev) {
4414 xw.state &= ~WIN_VISIBLE;
4418 static void xseturgency (int add) {
4419 XWMHints *h = XGetWMHints(xw.dpy, xw.win);
4421 h->flags = add ? (h->flags | XUrgencyHint) : (h->flags & ~XUrgencyHint);
4422 XSetWMHints(xw.dpy, xw.win, h);
4423 XFree(h);
4427 static void focus (XEvent *ev) {
4428 if (ev->type == FocusIn) {
4429 xw.state |= WIN_FOCUSED;
4430 xseturgency(0);
4431 tsendfocusevent(1);
4432 } else {
4433 xw.state &= ~WIN_FOCUSED;
4434 tsendfocusevent(0);
4436 //draw(1);
4437 updateTabBar = -1;
4438 xdrawTabBar();
4439 xdrawcursor();
4440 //xcopy(0, 0, term->col, term->row);
4444 ////////////////////////////////////////////////////////////////////////////////
4445 // keyboard mapping
4446 static const char *kmap (KeySym k, uint state) {
4447 const char *res = NULL;
4449 state &= ~Mod2Mask; // numlock
4450 for (int f = 0; f < keymap_used; ++f) {
4451 uint mask = keymap[f].mask;
4453 if (keymap[f].key == k && ((mask == XK_NO_MOD && !state) || state == mask)) {
4454 //fprintf(stderr, "kp: %d\n", IS_SET(MODE_APPKEYPAD));
4455 if (!IS_SET(MODE_APPKEYPAD)) {
4456 if (!keymap[f].kp) {
4457 //fprintf(stderr, "nokp! %d %s\n", keymap[f].kp, keymap[f].str+1);
4458 return keymap[f].str; // non-keypad hit
4460 continue;
4462 //fprintf(stderr, "kp! %d %s\n", keymap[f].kp, keymap[f].str+1);
4463 if (keymap[f].kp) return keymap[f].str; // keypad hit
4464 res = keymap[f].str; // kp mode, but non-kp mapping found
4467 return res;
4471 static const char *kbind (KeySym k, uint state) {
4472 state &= ~Mod2Mask; // numlock
4473 for (int f = 0; f < keybinds_used; ++f) {
4474 uint mask = keybinds[f].mask;
4476 if (keybinds[f].key == k && ((mask == XK_NO_MOD && !state) || state == mask)) return keybinds[f].str;
4478 return NULL;
4482 static KeySym do_keytrans (KeySym ks) {
4483 for (int f = 0; f < keytrans_used; ++f) if (keytrans[f].src == ks) return keytrans[f].dst;
4484 return ks;
4488 static void cmdline_closequeryexec (int cancelled) {
4489 if (!cancelled) {
4490 char *rep = term->cmdline+term->cmdreslen;
4492 trimstr(rep);
4493 if (!rep[0] || strchr("yt", tolower(rep[0])) != NULL) {
4494 closeRequestComes = 2;
4495 return;
4498 closeRequestComes = 0;
4502 static void kpress (XEvent *ev) {
4503 XKeyEvent *e = &ev->xkey;
4504 KeySym ksym = NoSymbol;
4505 const char *kstr;
4506 int len;
4507 Status status;
4508 char buf[32];
4510 if (term == NULL) return;
4512 if (!ptrBlanked && opt_ptrblank > 0) xblankPointer();
4514 //if (len < 1) len = XmbLookupString(xw.xic, e, buf, sizeof(buf), &ksym, &status);
4515 if ((len = Xutf8LookupString(xw.xic, e, buf, sizeof(buf), &ksym, &status)) > 0) buf[len] = 0;
4516 // leave only known mods
4517 e->state &= (Mod1Mask | Mod4Mask | ControlMask | ShiftMask);
4518 #ifdef DUMP_KEYSYMS
4520 const char *ksname = XKeysymToString(ksym);
4522 fprintf(stderr, "utf(%d):[%s] (%s) 0x%08x\n", len, len>=0?buf:"<shit>", ksname, (unsigned int)e->state);
4524 #endif
4525 if ((kstr = kbind(ksym, e->state)) != NULL) {
4526 // keybind found
4527 executeCommands(kstr);
4528 return;
4531 if (term->cmdMode != CMDMODE_NONE) {
4532 int mode = term->cmdMode;
4534 switch (do_keytrans(ksym)) {
4535 case XK_Return:
4536 tcmdlinehide();
4537 if (term->cmdexecfn) term->cmdexecfn(0);
4538 else if (mode == CMDMODE_INPUT) executeCommands(term->cmdline);
4539 break;
4540 case XK_BackSpace:
4541 if (mode == CMDMODE_INPUT) {
4542 tcmdlinechoplast();
4543 term->cmdtabpos = -1;
4544 term->cmdprevc = NULL;
4545 } else {
4546 tcmdlinehide();
4547 if (term->cmdexecfn) term->cmdexecfn(1);
4549 break;
4550 case XK_Escape:
4551 tcmdlinehide();
4552 if (term->cmdexecfn) term->cmdexecfn(1);
4553 break;
4554 case XK_Tab:
4555 if (mode == CMDMODE_INPUT && term->cmdline[0] && term->cmdcl == 0 && term->cmdexecfn == NULL) {
4556 const char *cpl;
4558 if (term->cmdtabpos < 0) {
4559 term->cmdtabpos = 0;
4560 while (term->cmdline[term->cmdtabpos] && isalnum(term->cmdline[term->cmdtabpos])) ++term->cmdtabpos;
4561 if (term->cmdline[term->cmdtabpos]) {
4562 term->cmdtabpos = -1;
4563 break;
4565 term->cmdprevc = NULL;
4567 cpl = findCommandCompletion(term->cmdline, term->cmdtabpos, term->cmdprevc);
4568 if (cpl == NULL && term->cmdprevc != NULL) cpl = findCommandCompletion(term->cmdline, term->cmdtabpos, NULL);
4569 term->cmdprevc = cpl;
4570 if (cpl != NULL) strcpy(term->cmdline, cpl);
4571 tcmdlinefixofs();
4572 } else if (mode != CMDMODE_INPUT) {
4573 tcmdlinehide();
4574 if (term->cmdexecfn) term->cmdexecfn(1);
4576 break;
4577 default:
4578 if (mode == CMDMODE_INPUT) {
4579 if (len > 0 && (unsigned char)buf[0] >= 32) {
4580 tcmdput(buf, len);
4581 term->cmdtabpos = -1;
4582 term->cmdprevc = NULL;
4585 break;
4587 return;
4590 if ((kstr = kmap(do_keytrans(ksym), e->state)) != NULL) {
4591 if (kstr[0]) {
4592 tunshowhistory();
4593 ttywritestr(kstr);
4595 } else {
4596 int meta = (e->state&Mod1Mask);
4598 int shift = (e->state&ShiftMask);
4599 int ctrl = (e->state&ControlMask);
4601 switch (ksym) {
4602 case XK_Return:
4603 tunshowhistory();
4604 if (meta) {
4605 ttywritestr("\x1b\x0a");
4606 } else {
4607 if (IS_SET(MODE_CRLF)) ttywritestr("\r\n"); else ttywritestr("\r");
4609 break;
4610 default:
4611 if (len > 0) {
4612 tunshowhistory();
4613 if (meta && len == 1) ttywritestr("\x1b");
4614 ttywrite(buf, len);
4616 break;
4622 ////////////////////////////////////////////////////////////////////////////////
4623 // xembed?
4624 static void cmessage (XEvent *e) {
4625 /* See xembed specs http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html */
4626 if (e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
4627 if (e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
4628 xw.state |= WIN_FOCUSED;
4629 xseturgency(0);
4630 tsendfocusevent(1);
4631 } else if (e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
4632 xw.state &= ~WIN_FOCUSED;
4633 tsendfocusevent(0);
4635 xdrawcursor();
4636 xdrawTabBar();
4637 xcopy(0, 0, term->col, term->row);
4638 return;
4641 if (e->xclient.data.l[0] == XA_WM_DELETE_WINDOW) {
4642 closeRequestComes = 1;
4643 return;
4648 ////////////////////////////////////////////////////////////////////////////////
4649 static void resize (XEvent *e) {
4650 int col, row;
4651 Term *ot = term;
4653 //if (e->xconfigure.width == 65535 || e->xconfigure.width == -1) e->xconfigure.width = xw.w;
4654 if (e->xconfigure.height == 65535 || e->xconfigure.height == -1) e->xconfigure.height = xw.h;
4655 //if ((short int)e->xconfigure.height < xw.ch) return;
4657 if (e->xconfigure.width == xw.w && e->xconfigure.height == xw.h) return;
4658 xw.w = e->xconfigure.width;
4659 xw.h = e->xconfigure.height;
4660 col = xw.w/xw.cw;
4661 row = (xw.h-xw.tabheight)/xw.ch;
4662 //fprintf(stderr, "neww=%d; newh=%d; ch=%d; th=%d; col=%d; row=%d; ocol=%d; orow=%d\n", xw.w, xw.h, xw.ch, xw.tabheight, col, row, term->col, term->row);
4663 if (col == term->col && row == term->row) return;
4664 for (int f = 0; f < term_count; ++f) {
4665 term = term_array[f];
4666 if (tresize(col, row) && ot == term) draw(1);
4667 ttyresize();
4668 xresize(col, row);
4670 term = ot;
4671 XFreePixmap(xw.dpy, xw.pictab);
4672 xw.pictab = XCreatePixmap(xw.dpy, xw.win, xw.w, xw.tabheight>0?xw.tabheight:1, XDefaultDepth(xw.dpy, xw.scr));
4673 updateTabBar = 1;
4677 static inline int last_draw_too_old (void) {
4678 int tt = mclock_ticks();
4680 if (term != NULL) {
4681 if (term->dead || !term->wantRedraw) return 0;
4682 return (tt-term->lastDrawTime >= opt_drawtimeout);
4684 return (tt-lastDrawTime >= opt_maxdrawtimeout);
4688 ////////////////////////////////////////////////////////////////////////////////
4689 // main loop
4690 static void (*handler[LASTEvent])(XEvent *) = {
4691 [KeyPress] = kpress,
4692 [ClientMessage] = cmessage,
4693 [ConfigureNotify] = resize,
4694 [VisibilityNotify] = visibility,
4695 [UnmapNotify] = unmap,
4696 [Expose] = expose,
4697 [FocusIn] = focus,
4698 [FocusOut] = focus,
4699 [MotionNotify] = bmotion,
4700 [ButtonPress] = bpress,
4701 [ButtonRelease] = brelease,
4702 [SelectionNotify] = selnotify,
4703 [SelectionRequest] = selrequest,
4704 [SelectionClear] = selclear,
4708 static void run (void) {
4709 //int stuff_to_print = 0;
4710 int xfd = XConnectionNumber(xw.dpy);
4712 ptrLastMove = mclock_ticks();
4713 while (term_count > 0) {
4714 XEvent ev;
4715 fd_set rfd, wfd;
4716 struct timeval timeout;
4717 int maxfd = xfd;
4718 Term *ot;
4719 int dodraw;
4721 FD_ZERO(&rfd);
4722 FD_ZERO(&wfd);
4723 FD_SET(xfd, &rfd);
4724 //FD_SET(term->cmdfd, &rfd);
4725 // have something to write?
4726 for (int f = 0; f < term_count; ++f) {
4727 Term *t = term_array[f];
4729 if (!t->dead && term->cmdfd >= 0 && t->pid != 0) {
4730 if (t->cmdfd > maxfd) maxfd = t->cmdfd;
4731 FD_SET(t->cmdfd, &rfd);
4732 if (t->wrbufpos < t->wrbufused) FD_SET(t->cmdfd, &wfd);
4736 timeout.tv_sec = 0;
4737 timeout.tv_usec = (opt_drawtimeout+2)*1000;
4738 if (select(maxfd+1, &rfd, &wfd, NULL, &timeout) < 0) {
4739 if (errno == EINTR) continue;
4740 die("select failed: %s", SERRNO);
4743 ot = term;
4744 for (int f = 0; f < term_count; ++f) {
4745 Term *t = term_array[f];
4747 if (!t->dead && term->cmdfd >= 0 && term->pid != 0) {
4748 term = t;
4749 if (FD_ISSET(t->cmdfd, &wfd)) ttyflushwrbuf();
4750 if (FD_ISSET(t->cmdfd, &rfd)) ttyread(); //t->wantRedraw = 1;
4751 term = ot;
4755 termcleanup();
4756 if (term_count == 0) exit(exitcode);
4758 dodraw = 0;
4759 if (term != NULL && term->curblink > 0) {
4760 int tt = mclock_ticks();
4762 if (tt-term->lastBlinkTime >= term->curblink) {
4763 term->lastBlinkTime = tt;
4764 if ((xw.state&WIN_FOCUSED) || term->curblinkinactive) {
4765 term->curbhidden = (term->curbhidden ? 0 : -1);
4766 dodraw = 1;
4767 } else {
4768 term->curbhidden = 0;
4772 if (updateTabBar) xdrawTabBar();
4773 if (dodraw || last_draw_too_old()) draw(0);
4775 if (XPending(xw.dpy)) {
4776 while (XPending(xw.dpy)) {
4777 XNextEvent(xw.dpy, &ev);
4778 switch (ev.type) {
4779 //case VisibilityNotify:
4780 //case UnmapNotify:
4781 //case FocusIn:
4782 //case FocusOut:
4783 case MotionNotify:
4784 case ButtonPress:
4785 case ButtonRelease:
4786 xunblankPointer();
4787 ptrLastMove = mclock_ticks();
4788 break;
4789 default: ;
4791 if (XFilterEvent(&ev, xw.win)) continue;
4792 if (handler[ev.type]) (handler[ev.type])(&ev);
4796 if (term != NULL) {
4797 switch (closeRequestComes) {
4798 case 1: // just comes
4799 if (opt_ignoreclose == 0) {
4800 tcmdlinehide();
4801 tcmdlineinitex("Do you really want to close sterm [Y/n]? ");
4802 term->cmdexecfn = cmdline_closequeryexec;
4803 } else if (opt_ignoreclose < 0) {
4804 //FIXME: kill all clients?
4805 return;
4807 closeRequestComes = 0;
4808 break;
4809 case 2: // ok, die now
4810 //FIXME: kill all clients?
4811 return;
4815 if (!ptrBlanked && opt_ptrblank > 0 && mclock_ticks()-ptrLastMove >= opt_ptrblank) {
4816 xblankPointer();
4822 ////////////////////////////////////////////////////////////////////////////////
4823 typedef const char * (*IniHandlerFn) (const char *optname, const char *fmt, char *argstr, void *udata);
4826 typedef struct {
4827 const char *name;
4828 const char *fmt;
4829 void *udata;
4830 IniHandlerFn fn;
4831 } IniCommand;
4833 static const char *inifnGenericOneArg (const char *optname, const char *fmt, char *argstr, void *udata) {
4834 return iniParseArguments(argstr, fmt, udata);
4838 static const char *inifnGenericOneStr (const char *optname, const char *fmt, char *argstr, void *udata) {
4839 char *s = NULL;
4840 const char *err = iniParseArguments(argstr, fmt, &s);
4842 if (err != NULL) return err;
4843 if ((s = strdup(s)) == NULL) return "out of memory";
4844 if (udata) {
4845 char **ustr = (char **)udata;
4847 if (*ustr) free(*ustr);
4848 *ustr = s;
4850 return NULL;
4854 static const IniCommand iniCommands[] = {
4855 {"term", "s!-", &opt_term, inifnGenericOneStr},
4856 {"class", "s!-", &opt_class, inifnGenericOneStr},
4857 {"title", "s!-", &opt_title, inifnGenericOneStr},
4858 {"fontnorm", "s!-", &opt_fontnorm, inifnGenericOneStr},
4859 {"fontbold", "s!-", &opt_fontbold, inifnGenericOneStr},
4860 {"fonttab", "s!-", &opt_fonttab, inifnGenericOneStr},
4861 {"shell", "s!-", &opt_shell, inifnGenericOneStr},
4862 {"doubleclicktimeout", "i{0,10000}", &opt_doubleclick_timeout, inifnGenericOneArg},
4863 {"tripleclicktimeout", "i{0,10000}", &opt_tripleclick_timeout, inifnGenericOneArg},
4864 {"tabsize", "i{1,256}", &opt_tabsize, inifnGenericOneArg},
4865 {"defaultfg", "i{0,511}", &defaultFG, inifnGenericOneArg},
4866 {"defaultbg", "i{0,511}", &defaultBG, inifnGenericOneArg},
4867 {"defaultcursorfg", "i{0,511}", &defaultCursorFG, inifnGenericOneArg},
4868 {"defaultcursorbg", "i{0,511}", &defaultCursorBG, inifnGenericOneArg},
4869 {"defaultinactivecursorfg", "i{0,511}", &defaultCursorInactiveFG, inifnGenericOneArg},
4870 {"defaultinactivecursorbg", "i{-1,511}", &defaultCursorInactiveBG, inifnGenericOneArg},
4871 {"defaultboldfg", "i{-1,511}", &defaultBoldFG, inifnGenericOneArg},
4872 {"defaultunderlinefg", "i{-1,511}", &defaultUnderlineFG, inifnGenericOneArg},
4873 {"normaltabfg", "i{0,511}", &normalTabFG, inifnGenericOneArg},
4874 {"normaltabbg", "i{0,511}", &normalTabBG, inifnGenericOneArg},
4875 {"activetabfg", "i{0,511}", &activeTabFG, inifnGenericOneArg},
4876 {"activetabbg", "i{0,511}", &activeTabBG, inifnGenericOneArg},
4877 {"maxhistory", "i{0,65535}", &opt_maxhistory, inifnGenericOneArg},
4878 {"ptrblank", "i{0,65535}", &opt_ptrblank, inifnGenericOneArg},
4879 {"tabcount", "i{1,128}", &opt_tabcount, inifnGenericOneArg},
4880 {"tabposition", "i{0,1}", &opt_tabposition, inifnGenericOneArg},
4881 {"drawtimeout", "i{5,30000}", &opt_drawtimeout, inifnGenericOneArg},
4882 {"audiblebell", "b", &opt_audiblebell, inifnGenericOneArg},
4883 {"urgentbell", "b", &opt_urgentbell, inifnGenericOneArg},
4884 {"cursorblink", "i{0,10000}", &opt_cursorBlink, inifnGenericOneArg},
4885 {"cursorblinkinactive", "b", &opt_cursorBlinkInactive, inifnGenericOneArg},
4886 {"drawunderline", "b", &opt_drawunderline, inifnGenericOneArg},
4887 {"ignoreclose", "i{-1,1}", &opt_ignoreclose, inifnGenericOneArg},
4888 {"maxdrawtimeout", "i{100,60000}", &opt_maxdrawtimeout, inifnGenericOneArg},
4889 {NULL, NULL, NULL, NULL}
4893 #define MISC_CMD_NONE ((const char *)-1)
4896 // NULL: command processed; MISC_CMD_NONE: unknown command; !NULL: error
4897 static const char *processMiscCmds (const char *optname, char *argstr) {
4898 const char *err = NULL;
4900 if (strcasecmp(optname, "unimap") == 0) {
4901 int uni, ch;
4902 char *alt = NULL;
4904 if (iniParseArguments(argstr, "R!-", &argstr) == NULL) {
4905 if (strcasecmp(argstr, "reset") == 0 || strcasecmp(argstr, "clear") == 0) {
4906 if (unimap) free(unimap);
4907 unimap = NULL;
4908 return NULL;
4911 //unimap 0x2592 0x61 alt
4912 if ((err = iniParseArguments(argstr, "i{0,65535}i{0,255}|s!-", &uni, &ch, &alt)) != NULL) return err;
4913 if (alt != NULL && strcasecmp(alt, "alt") != 0) return "invalid unimap";
4914 if (unimap == NULL) {
4915 if ((unimap = calloc(65536, sizeof(unimap[0]))) == NULL) return "out of memory";
4917 if (alt != NULL && ch == 0) alt = NULL;
4918 if (alt != NULL && ch < 96) return "invalid unimap";
4919 unimap[uni] = ch;
4920 if (alt != NULL) unimap[uni] |= 0x8000;
4921 return NULL;
4924 if (strcasecmp(optname, "keytrans") == 0) {
4925 char *src = NULL, *dst = NULL;
4927 if (iniParseArguments(argstr, "R!-", &argstr) == NULL) {
4928 if (strcasecmp(argstr, "reset") == 0 || strcasecmp(argstr, "clear") == 0) {
4929 keytrans_reset();
4930 return NULL;
4933 if ((err = iniParseArguments(argstr, "s!-s!-", &src, &dst)) != NULL) return err;
4934 keytrans_add(src, dst);
4935 return NULL;
4938 if (strcasecmp(optname, "keybind") == 0) {
4939 char *key = NULL, *act = NULL;
4940 if (iniParseArguments(argstr, "R!-", &argstr) == NULL) {
4941 if (strcasecmp(argstr, "reset") == 0 || strcasecmp(argstr, "clear") == 0) {
4942 keybinds_reset();
4943 return NULL;
4946 if ((err = iniParseArguments(argstr, "s!-R!", &key, &act)) != NULL) return err;
4947 keybind_add(key, act);
4948 return NULL;
4951 if (strcasecmp(optname, "keymap") == 0) {
4952 char *key = NULL, *str = NULL;
4954 if (iniParseArguments(argstr, "R!-", &argstr) == NULL) {
4955 if (strcasecmp(argstr, "reset") == 0 || strcasecmp(argstr, "clear") == 0) {
4956 keymap_reset();
4957 return NULL;
4960 if ((err = iniParseArguments(argstr, "s!-s!-", &key, &str)) != NULL) return err;
4961 keymap_add(key, str);
4962 return NULL;
4965 return MISC_CMD_NONE;
4969 #define INI_LINE_SIZE (32768)
4971 // <0: file not found
4972 // >0: file loading error
4973 // 0: ok
4974 static int loadConfig (const char *fname) {
4975 int inifelse = 0; // 0: not; 1: doing true; 2: doing false; -1: waiting else/endif; -2: waiting endif
4976 FILE *fi = fopen(fname, "r");
4977 const char *err = NULL;
4978 char *line;
4979 int lineno = 0;
4981 if (fi == NULL) return -1;
4982 if ((line = malloc(INI_LINE_SIZE)) == NULL) { err = "out of memory"; goto quit; }
4984 while (fgets(line, INI_LINE_SIZE-1, fi) != NULL) {
4985 char *optname, *argstr, *d;
4986 int goodoption = 0;
4988 ++lineno;
4989 line[INI_LINE_SIZE-1] = 0;
4990 // get option name
4991 for (optname = line; *optname && isspace(*optname); ++optname) ;
4992 if (!optname[0] || optname[0] == '#') continue; // comment
4993 if (!isalnum(optname[0])) { err = "invalid option name"; goto quit; }
4994 d = argstr = optname;
4995 while (*argstr) {
4996 if (!argstr[0] || isspace(argstr[0])) break;
4997 if (!isalnum(argstr[0]) && argstr[0] != '_' && argstr[0] != '.') { err = "invalid option name"; goto quit; }
4998 if (argstr[0] != '_') *d++ = tolower(*argstr);
4999 ++argstr;
5001 if (*argstr) ++argstr;
5002 *d = 0;
5003 if (!isalnum(optname[0])) { err = "invalid option name"; goto quit; }
5005 if (strcasecmp(optname, "ifterm") == 0) {
5006 char *val;
5008 if (inifelse != 0) { err = "nested ifs are not allowed"; goto quit; }
5009 inifelse = -1;
5010 if ((err = iniParseArguments(argstr, "s", &val)) != NULL) goto quit;
5011 if (strcasecmp(opt_term, val) == 0) inifelse = 1;
5012 continue;
5014 if (strcasecmp(optname, "else") == 0) {
5015 switch (inifelse) {
5016 case -1: inifelse = 2; break;
5017 case 2: case -2: case 0: err = "else without if"; goto quit;
5018 case 1: inifelse = -2; break;
5020 continue;
5022 if (strcasecmp(optname, "endif") == 0) {
5023 switch (inifelse) {
5024 case -1: case -2: case 1: case 2: inifelse = 0; break;
5025 case 0: err = "endif without if"; goto quit;
5027 continue;
5030 if (inifelse < 0) {
5031 //trimstr(argstr);
5032 //fprintf(stderr, "skip: [%s]\n", argstr);
5033 continue;
5035 if (opt_term_locked && strcasecmp(optname, "term") == 0) continue; // termname given in command line
5036 // ok, we have option name in `optname` and arguments in `argstr`
5037 if (strncmp(optname, "color.", 6) == 0) {
5038 int n = 0;
5039 char *s = NULL;
5041 optname += 6;
5042 if (!optname[0]) { err = "invalid color option"; goto quit; }
5043 while (*optname) {
5044 if (!isdigit(*optname)) { err = "invalid color option"; goto quit; }
5045 n = (n*10)+(optname[0]-'0');
5046 ++optname;
5048 if (n < 0 || n > 511) { err = "invalid color index"; goto quit; }
5050 if ((err = iniParseArguments(argstr, "s!-", &s)) != NULL) goto quit;
5051 if ((s = strdup(s)) == NULL) { err = "out of memory"; goto quit; }
5052 if (opt_colornames[n] != NULL) free(opt_colornames[n]);
5053 opt_colornames[n] = s;
5054 continue;
5057 if ((err = processMiscCmds(optname, argstr)) != MISC_CMD_NONE) {
5058 if (err != NULL) goto quit;
5059 continue;
5060 } else {
5061 err = NULL;
5064 for (int f = 0; iniCommands[f].name != NULL; ++f) {
5065 if (strcmp(iniCommands[f].name, optname) == 0) {
5066 if ((err = iniCommands[f].fn(optname, iniCommands[f].fmt, argstr, iniCommands[f].udata)) != NULL) goto quit;
5067 goodoption = 1;
5068 break;
5071 if (!goodoption) {
5072 fprintf(stderr, "ini error at line %d: unknown option '%s'!\n", lineno, optname);
5075 quit:
5076 if (line != NULL) free(line);
5077 fclose(fi);
5078 if (err == NULL && inifelse != 0) err = "if without endif";
5079 if (err != NULL) die("ini error at line %d: %s", lineno, err);
5080 return 0;
5084 static void initDefaultOptions (void) {
5085 opt_title = strdup("sterm");
5086 opt_class = strdup("sterm");
5087 opt_term = strdup(TNAME);
5088 opt_fontnorm = strdup(FONT);
5089 opt_fontbold = strdup(FONTBOLD);
5090 opt_fonttab = strdup(FONTTAB);
5091 opt_shell = strdup(SHELL);
5093 memset(opt_colornames, 0, sizeof(opt_colornames));
5094 for (int f = 0; f < LEN(defcolornames); ++f) opt_colornames[f] = strdup(defcolornames[f]);
5095 for (int f = 0; f < LEN(defextcolornames); ++f) opt_colornames[f+256] = strdup(defextcolornames[f]);
5097 keytrans_add("KP_Home", "Home");
5098 keytrans_add("KP_Left", "Left");
5099 keytrans_add("KP_Up", "Up");
5100 keytrans_add("KP_Right", "Right");
5101 keytrans_add("KP_Down", "Down");
5102 keytrans_add("KP_Prior", "Prior");
5103 keytrans_add("KP_Next", "Next");
5104 keytrans_add("KP_End", "End");
5105 keytrans_add("KP_Begin", "Begin");
5106 keytrans_add("KP_Insert", "Insert");
5107 keytrans_add("KP_Delete", "Delete");
5109 keybind_add("shift+Insert", "PastePrimary");
5110 keybind_add("alt+Insert", "PasteCliboard");
5111 keybind_add("ctrl+alt+t", "NewTab");
5112 keybind_add("ctrl+alt+Left", "SwitchToTab prev");
5113 keybind_add("ctrl+alt+Right", "SwitchToTab next");
5115 keymap_add("BackSpace", "\177");
5116 keymap_add("Insert", "\x1b[2~");
5117 keymap_add("Delete", "\x1b[3~");
5118 keymap_add("Home", "\x1b[1~");
5119 keymap_add("End", "\x1b[4~");
5120 keymap_add("Prior", "\x1b[5~");
5121 keymap_add("Next", "\x1b[6~");
5122 keymap_add("F1", "\x1bOP");
5123 keymap_add("F2", "\x1bOQ");
5124 keymap_add("F3", "\x1bOR");
5125 keymap_add("F4", "\x1bOS");
5126 keymap_add("F5", "\x1b[15~");
5127 keymap_add("F6", "\x1b[17~");
5128 keymap_add("F7", "\x1b[18~");
5129 keymap_add("F8", "\x1b[19~");
5130 keymap_add("F9", "\x1b[20~");
5131 keymap_add("F10", "\x1b[21~");
5132 keymap_add("Up", "\x1bOA");
5133 keymap_add("Down", "\x1bOB");
5134 keymap_add("Right", "\x1bOC");
5135 keymap_add("Left", "\x1bOD");
5139 ////////////////////////////////////////////////////////////////////////////////
5140 static Term *oldTerm;
5141 static int oldTermIdx;
5142 static Term *newTerm;
5143 static int newTermIdx;
5144 static int newTermSwitch;
5147 typedef void (*CmdHandlerFn) (const char *cmdname, char *argstr);
5149 typedef struct {
5150 const char *name;
5151 CmdHandlerFn fn;
5152 } Command;
5155 static void cmdPastePrimary (const char *cmdname, char *argstr) {
5156 selpaste(XA_PRIMARY);
5160 static void cmdPasteSecondary (const char *cmdname, char *argstr) {
5161 selpaste(XA_SECONDARY);
5165 static void cmdPasteClipboard (const char *cmdname, char *argstr) {
5166 selpaste(XA_CLIPBOARD);
5170 static void cmdExec (const char *cmdname, char *argstr) {
5171 if (term != NULL) {
5172 if (term->execcmd != NULL) free(term->execcmd);
5173 term->execcmd = (argstr[0] ? strdup(argstr) : NULL);
5178 static int parseTabArgs (char *argstr, int *noswitch, int nowrap, int idx) {
5179 for (;;) {
5180 char *arg;
5182 while (*argstr && isspace(*argstr)) ++argstr;
5183 if (!argstr[0]) break;
5184 if (iniParseArguments(argstr, "s-R-", &arg, &argstr) != NULL) break;
5186 if (strcasecmp(arg, "noswitch") == 0) *noswitch = 1;
5187 else if (strcasecmp(arg, "switch") == 0) *noswitch = 0;
5188 else if (strcasecmp(arg, "nowrap") == 0) nowrap = 1;
5189 else if (strcasecmp(arg, "wrap") == 0) nowrap = 0;
5190 else if (strcasecmp(arg, "first") == 0) idx = 0;
5191 else if (strcasecmp(arg, "last") == 0) idx = term_count-1;
5192 else if (strcasecmp(arg, "prev") == 0) idx = -1;
5193 else if (strcasecmp(arg, "next") == 0) idx = -2;
5194 else {
5195 long int n = -1;
5196 char *eptr;
5198 n = strtol(arg, &eptr, 0);
5199 if (!eptr[0] && n >= 0 && n < term_count) idx = n;
5202 switch (idx) {
5203 case -1: // prev
5204 if ((idx = termidx-1) < 0) idx = nowrap ? 0 : term_count-1;
5205 break;
5206 case -2: // next
5207 if ((idx = termidx+1) >= term_count) idx = nowrap ? term_count-1 : 0;
5208 break;
5210 return idx;
5214 static void flushNewTerm (void) {
5215 if (newTerm != NULL) {
5216 if (newTermSwitch && term != NULL) term->lastActiveTime = mclock_ticks();
5217 term = newTerm;
5218 termidx = newTermIdx;
5219 tinitialize(term_array[0]->col, term_array[0]->row);
5221 term->picbufh = term->row*xw.ch;
5222 term->picbufw = term->col*xw.cw;
5223 term->picbuf = XCreatePixmap(xw.dpy, xw.win, term->picbufw, term->picbufh, XDefaultDepth(xw.dpy, xw.scr));
5224 XFillRectangle(xw.dpy, term->picbuf, dc.gc, 0, 0, term->picbufw, term->picbufh);
5226 if (ttynew(term) != 0) {
5227 term = oldTerm;
5228 termidx = oldTermIdx;
5229 termfree(newTermIdx);
5230 } else {
5231 selinit();
5232 ttyresize();
5233 if (newTermSwitch) {
5234 term = NULL;
5235 termidx = 0;
5236 switchToTerm(newTermIdx, 1);
5237 oldTerm = term;
5238 oldTermIdx = termidx;
5239 } else {
5240 term = oldTerm;
5241 termidx = oldTermIdx;
5244 newTerm = NULL;
5249 static void cmdNewTab (const char *cmdname, char *argstr) {
5250 int noswitch = 0, idx;
5252 if (opt_disabletabs) return;
5253 flushNewTerm();
5254 if ((newTerm = termalloc()) == NULL) return;
5255 /*idx =*/ parseTabArgs(argstr, &noswitch, 0, termidx);
5256 idx = term_count-1;
5257 if (!noswitch) {
5258 if (term != NULL) term->lastActiveTime = mclock_ticks();
5259 oldTermIdx = idx;
5261 newTermIdx = termidx = idx;
5262 term = newTerm;
5263 newTermSwitch = !noswitch;
5267 static void cmdCloseTab (const char *cmdname, char *argstr) {
5268 flushNewTerm();
5269 if (term != NULL && !term->dead) kill(term->pid, SIGTERM);
5273 static void cmdKillTab (const char *cmdname, char *argstr) {
5274 flushNewTerm();
5275 if (!term->dead) kill(term->pid, SIGKILL);
5279 static void cmdSwitchToTab (const char *cmdname, char *argstr) {
5280 int noswitch = 0, idx;
5282 flushNewTerm();
5283 idx = parseTabArgs(argstr, &noswitch, 0, -666);
5284 if (idx >= 0) {
5285 switchToTerm(idx, 1);
5286 oldTerm = term;
5287 oldTermIdx = termidx;
5292 static void cmdMoveTabTo (const char *cmdname, char *argstr) {
5293 int noswitch = 0, idx;
5295 flushNewTerm();
5296 idx = parseTabArgs(argstr, &noswitch, 0, termidx);
5297 if (idx != termidx && idx >= 0 && idx < term_count) {
5298 Term *t = term_array[termidx];
5300 // remove current term
5301 for (int f = termidx+1; f < term_count; ++f) term_array[f-1] = term_array[f];
5302 // insert term
5303 for (int f = term_count-2; f >= idx; --f) term_array[f+1] = term_array[f];
5304 term_array[idx] = t;
5305 termidx = idx;
5306 oldTerm = t;
5307 oldTermIdx = idx;
5308 updateTabBar = 1;
5313 static void cmdDefaultFG (const char *cmdname, char *argstr) {
5314 char *s = NULL;
5315 int c;
5317 if (iniParseArguments(argstr, "i{0,511}|s-", &c, &s) == NULL) {
5318 if (s != NULL && tolower(s[0]) == 'g') defaultFG = c; else term->deffg = c;
5323 static void cmdDefaultBG (const char *cmdname, char *argstr) {
5324 char *s = NULL;
5325 int c;
5327 if (iniParseArguments(argstr, "i{0,511}|s-", &c) == NULL) {
5328 if (s != NULL && tolower(s[0]) == 'g') defaultBG = c; else term->defbg = c;
5333 static void scrollHistory (int delta) {
5334 if (term->maxhistory < 1) return; // no history
5335 term->topline += delta;
5336 if (term->topline > term->maxhistory) term->topline = term->maxhistory;
5337 if (term->topline < 0) term->topline = 0;
5338 tfulldirt();
5339 draw(1);
5343 static void cmdScrollHistoryLineUp (const char *cmdname, char *argstr) {
5344 scrollHistory(1);
5348 static void cmdScrollHistoryPageUp (const char *cmdname, char *argstr) {
5349 scrollHistory(term->row);
5353 static void cmdScrollHistoryLineDown (const char *cmdname, char *argstr) {
5354 scrollHistory(-1);
5358 static void cmdScrollHistoryPageDown (const char *cmdname, char *argstr) {
5359 scrollHistory(-term->row);
5363 static void cmdScrollHistoryTop (const char *cmdname, char *argstr) {
5364 scrollHistory(term->linecount);
5368 static void cmdScrollHistoryBottom (const char *cmdname, char *argstr) {
5369 scrollHistory(-term->linecount);
5373 static void cmdUTF8Locale (const char *cmdname, char *argstr) {
5374 int b;
5376 if (iniParseArguments(argstr, "b", &b) == NULL) {
5377 if (!needConversion) b = 1;
5378 if (term != NULL) term->needConv = !b;
5379 //fprintf(stderr, "needConv: %d (%d)\n", term->needConv, needConversion);
5384 static void cmdCommandMode (const char *cmdname, char *argstr) {
5385 if (term != NULL) {
5386 if (term->cmdMode == CMDMODE_NONE) tcmdlineinit(); else tcmdlinehide();
5391 // [show|hide]
5392 static void cmdCursor (const char *cmdname, char *argstr) {
5393 if (term != NULL) {
5394 char *s;
5396 if (iniParseArguments(argstr, "s!-", &s) != NULL) {
5397 tcmdlinemsg((term->c.state&CURSOR_HIDE) ? "cursor is hidden" : "cursor is visible");
5398 } else {
5399 if (strcasecmp(s, "show") == 0) term->c.state &= ~CURSOR_HIDE;
5400 else if (strcasecmp(s, "hide") == 0) term->c.state |= CURSOR_HIDE;
5401 term->wantRedraw = 1;
5407 static void cmdResetAttrs (const char *cmdname, char *argstr) {
5408 if (term != NULL) {
5409 term->c.attr.attr &= ~(ATTR_REVERSE | ATTR_UNDERLINE | ATTR_BOLD);
5410 term->c.attr.attr |= ATTR_DEFFG | ATTR_DEFBG;
5411 term->c.attr.fg = term->deffg;
5412 term->c.attr.bg = term->defbg;
5417 static void cmdResetCharset (const char *cmdname, char *argstr) {
5418 if (term != NULL) {
5419 term->mode &= ~(MODE_GFX0|MODE_GFX1);
5420 term->charset = MODE_GFX0;
5425 // [norm|alt]
5426 static void cmdScreen (const char *cmdname, char *argstr) {
5427 if (term != NULL) {
5428 char *s;
5430 if (iniParseArguments(argstr, "s!-", &s) != NULL) {
5431 tcmdlinemsg(IS_SET(MODE_ALTSCREEN) ? "screen: alt" : "screen: norm");
5432 } else {
5433 if (strcasecmp(s, "norm") == 0) {
5434 if (IS_SET(MODE_ALTSCREEN)) tswapscreen();
5435 } else if (strcasecmp(s, "alt") == 0) {
5436 if (!IS_SET(MODE_ALTSCREEN)) tswapscreen();
5443 // [on|off]
5444 static void cmdMouseReports (const char *cmdname, char *argstr) {
5445 if (term != NULL) {
5446 int b;
5448 if (iniParseArguments(argstr, "b", &b) != NULL) {
5449 tcmdlinemsg(IS_SET(MODE_MOUSE) ? "mouse reports are on" : "mouse reports are off");
5450 } else {
5451 if (b) term->mode |= MODE_MOUSEBTN; else term->mode &= ~MODE_MOUSEBTN;
5457 static int cmd_parseIntArg (const char *fmt, char *argstr, int *b, int *global, int *toggle) {
5458 while (argstr[0]) {
5459 char *s = NULL;
5461 if (iniParseArguments(argstr, "R-", &argstr) != NULL) break;
5462 if (!argstr[0]) break;
5464 if (iniParseArguments(argstr, "s!-R-", &s, &argstr) != NULL) break;
5465 if (global && tolower(s[0]) == 'g') {
5466 *global = 1;
5467 } else if (toggle && tolower(s[0]) == 't') {
5468 *toggle = 1;
5469 } else {
5470 if (!b || iniParseArguments(s, fmt, b) != NULL) return -1;
5473 return 0;
5477 static void cmdAudibleBell (const char *cmdname, char *argstr) {
5478 int b = -1, toggle = 0, global = 0;
5480 if (term == NULL) return;
5481 if (cmd_parseIntArg("b", argstr, &b, &global, &toggle) != 0) return;
5483 if (b == -1) {
5484 tcmdlinemsg((global ? opt_audiblebell : (term->belltype&BELL_AUDIO)) ? "AudibleBell: 1" : "AudibleBell: 0");
5485 } else {
5486 if (toggle) {
5487 if (global) opt_audiblebell = !opt_audiblebell; else term->belltype ^= BELL_AUDIO;
5488 } else {
5489 if (global) opt_audiblebell = b; else term->belltype = (term->belltype&~BELL_AUDIO)|(b!=0?BELL_AUDIO:0);
5495 static void cmdUrgentBell (const char *cmdname, char *argstr) {
5496 int b = -1, toggle = 0, global = 0;
5498 if (term == NULL) return;
5499 if (cmd_parseIntArg("b", argstr, &b, &global, &toggle) != 0) return;
5501 if (b == -1) {
5502 tcmdlinemsg((global ? opt_urgentbell : (term->belltype&BELL_URGENT)) ? "UrgentBell: 1" : "UrgentBell: 0");
5503 } else {
5504 if (toggle) {
5505 if (global) opt_urgentbell = !opt_urgentbell; else term->belltype ^= BELL_URGENT;
5506 } else {
5507 if (global) opt_urgentbell = b; else term->belltype = (term->belltype&~BELL_URGENT)|(b!=0?BELL_URGENT:0);
5513 static void cmdMonochrome (const char *cmdname, char *argstr) {
5514 int b = -1, global = 0;
5516 if (term == NULL) return;
5517 if (cmd_parseIntArg("i{0,3}", argstr, &b, &global, NULL) != 0) return;
5519 if (b == -1) {
5520 char buf[32];
5522 b = (global ? globalBW : term->blackandwhite);
5523 sprintf(buf, "Monochrome: %d", b);
5524 tcmdlinemsg(buf);
5525 } else {
5526 if (global) {
5527 if (b == 3) tcmdlinemsg("Monochrome-global can't be '3'!");
5528 else globalBW = b;
5529 } else {
5530 term->blackandwhite = b;
5533 tfulldirt();
5534 updateTabBar = 1;
5538 static void cmdCursorBlink (const char *cmdname, char *argstr) {
5539 int b = -1, global = 0;
5541 if (term == NULL) return;
5542 if (cmd_parseIntArg("i{0,10000}", argstr, &b, &global, NULL) != 0) return;
5544 if (b == -1) {
5545 char buf[32];
5547 b = (global ? opt_cursorBlink : term->curblink);
5548 sprintf(buf, "CursorBlink: %d", b);
5549 tcmdlinemsg(buf);
5550 } else {
5551 if (global) {
5552 opt_cursorBlink = b;
5553 } else {
5554 term->curblink = b;
5555 term->curbhidden = 0;
5558 tfulldirt();
5559 updateTabBar = 1;
5563 static void cmdCursorBlinkInactive (const char *cmdname, char *argstr) {
5564 int b = -1, global = 0, toggle = 0, *iptr;
5566 if (term == NULL) return;
5567 if (cmd_parseIntArg("b", argstr, &b, &global, &toggle) != 0) return;
5569 iptr = (global ? &opt_cursorBlinkInactive : &term->curblinkinactive);
5570 if (b != -1) {
5571 if (toggle) *iptr = !(*iptr); else *iptr = b;
5572 draw(0);
5577 static void cmdIgnoreClose (const char *cmdname, char *argstr) {
5578 int b = -666;
5580 if (term == NULL) return;
5581 if (cmd_parseIntArg("i{-1,1}", argstr, &b, NULL, NULL) != 0) return;
5583 if (b == -666) {
5584 char buf[32];
5586 sprintf(buf, "IgnoreClose: %d", opt_ignoreclose);
5587 tcmdlinemsg(buf);
5588 } else {
5589 opt_ignoreclose = b;
5594 static void cmdMaxHistory (const char *cmdname, char *argstr) {
5595 int b = -1, global = 0;
5597 if (term == NULL) return;
5598 if (cmd_parseIntArg("i{0,65535}", argstr, &b, &global, NULL) != 0) return;
5600 if (b == -1) {
5601 char buf[32];
5603 sprintf(buf, "MaxHistory: %d", (global?opt_maxhistory:term->maxhistory));
5604 tcmdlinemsg(buf);
5605 } else {
5606 if (!global) tadjustmaxhistory(b); else opt_maxhistory = b;
5611 static void cmdMaxDrawTimeout (const char *cmdname, char *argstr) {
5612 int b = -1;
5614 if (term == NULL) return;
5615 if (cmd_parseIntArg("i{100,60000}", argstr, &b, NULL, NULL) != 0) return;
5617 if (b == -1) {
5618 char buf[32];
5620 sprintf(buf, "cmdMaxDrawTimeout: %d", opt_maxdrawtimeout);
5621 tcmdlinemsg(buf);
5622 } else {
5623 opt_maxdrawtimeout = b;
5628 static const Command commandList[] = {
5629 {"PastePrimary", cmdPastePrimary},
5630 {"PasteSecondary", cmdPasteSecondary},
5631 {"PasteClipboard", cmdPasteClipboard},
5632 {"exec", cmdExec},
5633 {"NewTab", cmdNewTab}, // 'noswitch' 'next' 'prev' 'first' 'last'
5634 {"CloseTab", cmdCloseTab},
5635 {"KillTab", cmdKillTab},
5636 {"SwitchToTab", cmdSwitchToTab}, // 'next' 'prev' 'first' 'last' 'nowrap' 'wrap'
5637 {"MoveTabTo", cmdMoveTabTo}, // 'next' 'prev' 'first' 'last' 'nowrap' 'wrap'
5638 {"defaultfg", cmdDefaultFG},
5639 {"defaultbg", cmdDefaultBG},
5640 {"ScrollHistoryLineUp", cmdScrollHistoryLineUp},
5641 {"ScrollHistoryPageUp", cmdScrollHistoryPageUp},
5642 {"ScrollHistoryLineDown", cmdScrollHistoryLineDown},
5643 {"ScrollHistoryPageDown", cmdScrollHistoryPageDown},
5644 {"ScrollHistoryTop", cmdScrollHistoryTop},
5645 {"ScrollHistoryBottom", cmdScrollHistoryBottom},
5646 {"UTF8Locale", cmdUTF8Locale}, // 'on', 'off'
5647 {"AudibleBell", cmdAudibleBell},
5648 {"UrgentBell", cmdUrgentBell},
5649 {"CommandMode", cmdCommandMode},
5650 {"Cursor", cmdCursor},
5651 {"ResetAttrs", cmdResetAttrs},
5652 {"ResetCharset", cmdResetCharset},
5653 {"Screen", cmdScreen},
5654 {"MouseReports", cmdMouseReports},
5655 {"Monochrome", cmdMonochrome},
5656 {"Mono", cmdMonochrome},
5657 {"CursorBlink", cmdCursorBlink},
5658 {"CursorBlinkInactive", cmdCursorBlinkInactive},
5659 {"IgnoreClose", cmdIgnoreClose},
5660 {"MaxHistory", cmdMaxHistory},
5661 {"MaxDrawTimeout", cmdMaxDrawTimeout},
5663 {"term", cmdTermName},
5664 {"title", cmdWinTitle},
5665 {"tabsize", cmdTabSize},
5666 {"defaultcursorfg", cmdDefaultCursorFG},
5667 {"defaultcursorbg", cmdDefaultCursorBG},
5668 {"defaultinactivecursorfg", cmdDefaultInactiveCursorFG},
5669 {"defaultinactivecursorbg", cmdDefaultInactiveCursorBG},
5670 {"defaultboldfg", cmdDefaultBoldFG},
5671 {"defaultunderlinefg", cmdDefaultUnderlineFG},
5673 {NULL, NULL}
5677 static const char *findCommandCompletion (const char *str, int slen, const char *prev) {
5678 const char *res = NULL;
5679 int phit = 0;
5681 if (slen < 1) return NULL;
5682 for (int f = 0; commandList[f].name != NULL; ++f) {
5683 if (strlen(commandList[f].name) >= slen && strncasecmp(commandList[f].name, str, slen) == 0) {
5684 if (prev == NULL || phit) return commandList[f].name;
5685 if (strcasecmp(commandList[f].name, prev) == 0) phit = 1;
5686 if (res == NULL) res = commandList[f].name;
5689 return res;
5693 // !0: NewTab command
5694 static int executeCommand (const char *str, int slen) {
5695 const char *e;
5696 char *cmdname;
5697 int cmdfound = 0;
5699 if (str == NULL) return 0;
5700 if (slen < 0) slen = strlen(str);
5702 for (int f = 0; f < slen; ++f) if (!str[f]) { slen = f; break; }
5704 while (slen > 0 && isspace(*str)) { ++str; --slen; }
5705 if (slen < 1 || !str[0]) return 0;
5707 for (e = str; slen > 0 && !isspace(*e); ++e, --slen) ;
5709 if (e-str > 127) return 0;
5710 cmdname = alloca(e-str+8);
5711 if (cmdname == NULL) return 0;
5712 memcpy(cmdname, str, e-str);
5713 cmdname[e-str] = 0;
5714 if (opt_disabletabs && strcasecmp(cmdname, "NewTab") == 0) return 1;
5716 while (slen > 0 && isspace(*e)) { ++e; --slen; }
5717 //FIXME: ugly copypaste!
5719 for (int f = 0; commandList[f].name != NULL; ++f) {
5720 if (strcasecmp(commandList[f].name, cmdname) == 0) {
5721 char *left = calloc(slen+2, 1);
5723 if (left != NULL) {
5724 if (slen > 0) memcpy(left, e, slen);
5725 //fprintf(stderr, "command: [%s]; args: [%s]\n", cmdname, left);
5726 commandList[f].fn(cmdname, left);
5727 free(left);
5729 cmdfound = 1;
5730 break;
5734 if (!cmdfound) {
5735 char *left = calloc(slen+2, 1);
5737 if (left != NULL) {
5738 if (slen > 0) memcpy(left, e, slen);
5739 processMiscCmds(cmdname, left);
5740 free(left);
5744 return 0;
5749 static const char *cmdpSkipStr (const char *str) {
5750 while (*str && isspace(*str)) ++str;
5751 if (str[0] && str[0] != ';') {
5752 char qch = ' ';
5754 while (*str) {
5755 if (*str == ';' && qch == ' ') break;
5756 if (qch != ' ' && *str == qch) { qch = ' '; ++str; continue; }
5757 if (*str == '"' || *str == '\'') {
5758 if (qch == ' ') qch = *str;
5759 ++str;
5760 continue;
5762 if (*str++ == '\\' && *str) ++str;
5765 return str;
5770 static void executeCommands (const char *str) {
5771 oldTerm = term;
5772 oldTermIdx = termidx;
5773 newTerm = NULL;
5774 newTermSwitch = 0;
5775 if (str == NULL) return;
5776 while (*str) {
5777 const char *ce;
5778 char qch;
5780 while (*str && isspace(*str)) ++str;
5781 if (!*str) break;
5782 if (*str == ';') { ++str; continue; }
5784 ce = str;
5785 qch = ' ';
5786 while (*ce) {
5787 if (*ce == ';' && qch == ' ') break;
5788 if (qch != ' ' && *ce == qch) { qch = ' '; ++ce; continue; }
5789 if (*ce == '"' || *ce == '\'') {
5790 if (qch == ' ') qch = *ce;
5791 ++ce;
5792 continue;
5794 if (*ce++ == '\\' && *ce) ++ce;
5797 if (executeCommand(str, ce-str)) break;
5798 if (*ce) str = ce+1; else break;
5800 flushNewTerm();
5801 switchToTerm(oldTermIdx, 1);
5805 ////////////////////////////////////////////////////////////////////////////////
5806 int main (int argc, char *argv[]) {
5807 char *configfile = NULL;
5808 char *runcmd = NULL;
5810 //dbgLogInit();
5812 for (int f = 1; f < argc; f++) {
5813 if (strcmp(argv[f], "-name") == 0) { ++f; continue; }
5814 if (strcmp(argv[f], "-into") == 0) { ++f; continue; }
5815 if (strcmp(argv[f], "-embed") == 0) { ++f; continue; }
5816 switch (argv[f][0] != '-' || argv[f][2] ? -1 : argv[f][1]) {
5817 case 'e': f = argc+1; break;
5818 case 't':
5819 case 'c':
5820 case 'w':
5821 case 'b':
5822 case 'R':
5823 ++f;
5824 break;
5825 case 'T':
5826 if (++f < argc) {
5827 free(opt_term);
5828 opt_term = strdup(argv[f]);
5829 opt_term_locked = 1;
5831 break;
5832 case 'C':
5833 if (++f < argc) {
5834 if (configfile != NULL) free(configfile);
5835 configfile = strdup(argv[f]);
5837 break;
5838 case 'l':
5839 if (++f < argc) cliLocale = argv[f];
5840 break;
5841 case 'S': // single-tab mode
5842 opt_disabletabs = 1;
5843 break;
5844 case 'v':
5845 case 'h':
5846 default:
5847 fprintf(stderr, "%s", USAGE);
5848 exit(EXIT_FAILURE);
5852 initDefaultOptions();
5853 if (configfile == NULL) {
5854 const char *home = getenv("HOME");
5856 if (home != NULL) {
5857 configfile = SPrintf("%s/.sterm.rc", home);
5858 if (loadConfig(configfile) == 0) goto cfgdone;
5859 free(configfile); configfile = NULL;
5861 configfile = SPrintf("%s/.config/sterm.rc", home);
5862 if (loadConfig(configfile) == 0) goto cfgdone;
5863 free(configfile); configfile = NULL;
5866 configfile = SPrintf("/etc/sterm.rc");
5867 if (loadConfig(configfile) == 0) goto cfgdone;
5868 free(configfile); configfile = NULL;
5870 configfile = SPrintf("/etc/sterm/sterm.rc");
5871 if (loadConfig(configfile) == 0) goto cfgdone;
5872 free(configfile); configfile = NULL;
5874 configfile = SPrintf("./.sterm.rc");
5875 if (loadConfig(configfile) == 0) goto cfgdone;
5876 free(configfile); configfile = NULL;
5877 // no config
5878 } else {
5879 if (loadConfig(configfile) < 0) die("config file '%s' not found!", configfile);
5881 cfgdone:
5882 if (configfile != NULL) free(configfile); configfile = NULL;
5884 for (int f = 1; f < argc; f++) {
5885 if (strcmp(argv[f], "-name") == 0) { ++f; continue; }
5886 if (strcmp(argv[f], "-into") == 0 || strcmp(argv[f], "-embed") == 0) {
5887 if (opt_embed) free(opt_embed);
5888 opt_embed = strdup(argv[f]);
5889 continue;
5891 switch (argv[f][0] != '-' || argv[f][2] ? -1 : argv[f][1]) {
5892 case 't':
5893 if (++f < argc) {
5894 free(opt_title);
5895 opt_title = strdup(argv[f]);
5897 break;
5898 case 'c':
5899 if (++f < argc) {
5900 free(opt_class);
5901 opt_class = strdup(argv[f]);
5903 break;
5904 case 'w':
5905 if (++f < argc) {
5906 if (opt_embed) free(opt_embed);
5907 opt_embed = strdup(argv[f]);
5909 break;
5910 case 'R':
5911 if (++f < argc) runcmd = argv[f];
5912 break;
5913 case 'e':
5914 /* eat every remaining arguments */
5915 if (++f < argc) opt_cmd = &argv[f];
5916 f = argc+1;
5917 case 'T':
5918 case 'C':
5919 case 'l':
5920 ++f;
5921 break;
5922 case 'S':
5923 break;
5924 case 'v':
5925 case 'h':
5926 default:
5927 fprintf(stderr, "%s", USAGE);
5928 exit(EXIT_FAILURE);
5932 setenv("TERM", opt_term, 1);
5933 mclock_init();
5934 setlocale(LC_ALL, "");
5935 initLCConversion();
5936 updateTabBar = 1;
5937 termidx = 0;
5938 term = termalloc();
5939 if (term->execcmd != NULL) { free(term->execcmd); term->execcmd = NULL; }
5940 tinitialize(80, 25);
5941 if (ttynew(term) != 0) die("can't run process");
5942 opt_cmd = NULL;
5943 xinit();
5944 selinit();
5945 if (runcmd != NULL) executeCommands(runcmd);
5946 run();
5947 return 0;