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