st.c 81 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746
  1. /* See LICENSE for licence 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 <stdbool.h>
  10. #include <stdio.h>
  11. #include <stdlib.h>
  12. #include <string.h>
  13. #include <signal.h>
  14. #include <sys/ioctl.h>
  15. #include <sys/select.h>
  16. #include <sys/stat.h>
  17. #include <sys/time.h>
  18. #include <sys/types.h>
  19. #include <sys/wait.h>
  20. #include <time.h>
  21. #include <unistd.h>
  22. #include <libgen.h>
  23. #include <X11/Xatom.h>
  24. #include <X11/Xlib.h>
  25. #include <X11/Xutil.h>
  26. #include <X11/cursorfont.h>
  27. #include <X11/keysym.h>
  28. #include <X11/Xft/Xft.h>
  29. #include <fontconfig/fontconfig.h>
  30. #include "arg.h"
  31. char *argv0;
  32. #define Glyph Glyph_
  33. #define Font Font_
  34. #define Draw XftDraw *
  35. #define Colour XftColor
  36. #define Colourmap Colormap
  37. #define Rectangle XRectangle
  38. #if defined(__linux)
  39. #include <pty.h>
  40. #elif defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
  41. #include <util.h>
  42. #elif defined(__FreeBSD__) || defined(__DragonFly__)
  43. #include <libutil.h>
  44. #endif
  45. /* XEMBED messages */
  46. #define XEMBED_FOCUS_IN 4
  47. #define XEMBED_FOCUS_OUT 5
  48. /* Arbitrary sizes */
  49. #define UTF_SIZ 4
  50. #define ESC_BUF_SIZ (128*UTF_SIZ)
  51. #define ESC_ARG_SIZ 16
  52. #define STR_BUF_SIZ ESC_BUF_SIZ
  53. #define STR_ARG_SIZ ESC_ARG_SIZ
  54. #define DRAW_BUF_SIZ 20*1024
  55. #define XK_ANY_MOD UINT_MAX
  56. #define XK_NO_MOD 0
  57. #define XK_SWITCH_MOD (1<<13)
  58. #define REDRAW_TIMEOUT (80*1000) /* 80 ms */
  59. /* macros */
  60. #define SERRNO strerror(errno)
  61. #define MIN(a, b) ((a) < (b) ? (a) : (b))
  62. #define MAX(a, b) ((a) < (b) ? (b) : (a))
  63. #define LEN(a) (sizeof(a) / sizeof(a[0]))
  64. #define DEFAULT(a, b) (a) = (a) ? (a) : (b)
  65. #define BETWEEN(x, a, b) ((a) <= (x) && (x) <= (b))
  66. #define LIMIT(x, a, b) (x) = (x) < (a) ? (a) : (x) > (b) ? (b) : (x)
  67. #define ATTRCMP(a, b) ((a).mode != (b).mode || (a).fg != (b).fg || (a).bg != (b).bg)
  68. #define IS_SET(flag) ((term.mode & (flag)) != 0)
  69. #define TIMEDIFF(t1, t2) ((t1.tv_sec-t2.tv_sec)*1000 + (t1.tv_usec-t2.tv_usec)/1000)
  70. #define CEIL(x) (((x) != (int) (x)) ? (x) + 1 : (x))
  71. #define TRUECOLOR(r,g,b) (1 << 24 | (r) << 16 | (g) << 8 | (b))
  72. #define IS_TRUECOL(x) (1 << 24 & (x))
  73. #define TRUERED(x) (((x) & 0xff0000) >> 8)
  74. #define TRUEGREEN(x) (((x) & 0xff00))
  75. #define TRUEBLUE(x) (((x) & 0xff) << 8)
  76. #define VT102ID "\033[?6c"
  77. enum glyph_attribute {
  78. ATTR_NULL = 0,
  79. ATTR_REVERSE = 1,
  80. ATTR_UNDERLINE = 2,
  81. ATTR_BOLD = 4,
  82. ATTR_GFX = 8,
  83. ATTR_ITALIC = 16,
  84. ATTR_BLINK = 32,
  85. ATTR_WRAP = 64,
  86. };
  87. enum cursor_movement {
  88. CURSOR_SAVE,
  89. CURSOR_LOAD
  90. };
  91. enum cursor_state {
  92. CURSOR_DEFAULT = 0,
  93. CURSOR_WRAPNEXT = 1,
  94. CURSOR_ORIGIN = 2
  95. };
  96. enum term_mode {
  97. MODE_WRAP = 1,
  98. MODE_INSERT = 2,
  99. MODE_APPKEYPAD = 4,
  100. MODE_ALTSCREEN = 8,
  101. MODE_CRLF = 16,
  102. MODE_MOUSEBTN = 32,
  103. MODE_MOUSEMOTION = 64,
  104. MODE_REVERSE = 128,
  105. MODE_KBDLOCK = 256,
  106. MODE_HIDE = 512,
  107. MODE_ECHO = 1024,
  108. MODE_APPCURSOR = 2048,
  109. MODE_MOUSESGR = 4096,
  110. MODE_8BIT = 8192,
  111. MODE_BLINK = 16384,
  112. MODE_FBLINK = 32768,
  113. MODE_FOCUS = 65536,
  114. MODE_MOUSEX10 = 131072,
  115. MODE_MOUSEMANY = 262144,
  116. MODE_MOUSE = MODE_MOUSEBTN|MODE_MOUSEMOTION|MODE_MOUSEX10\
  117. |MODE_MOUSEMANY,
  118. };
  119. enum escape_state {
  120. ESC_START = 1,
  121. ESC_CSI = 2,
  122. ESC_STR = 4, /* DSC, OSC, PM, APC */
  123. ESC_ALTCHARSET = 8,
  124. ESC_STR_END = 16, /* a final string was encountered */
  125. ESC_TEST = 32, /* Enter in test mode */
  126. };
  127. enum window_state {
  128. WIN_VISIBLE = 1,
  129. WIN_REDRAW = 2,
  130. WIN_FOCUSED = 4
  131. };
  132. enum selection_type {
  133. SEL_REGULAR = 1,
  134. SEL_RECTANGULAR = 2
  135. };
  136. enum selection_snap {
  137. SNAP_WORD = 1,
  138. SNAP_LINE = 2
  139. };
  140. typedef unsigned char uchar;
  141. typedef unsigned int uint;
  142. typedef unsigned long ulong;
  143. typedef unsigned short ushort;
  144. typedef struct {
  145. char c[UTF_SIZ]; /* character code */
  146. uchar mode; /* attribute flags */
  147. ulong fg; /* foreground */
  148. ulong bg; /* background */
  149. } Glyph;
  150. typedef Glyph *Line;
  151. typedef struct {
  152. Glyph attr; /* current char attributes */
  153. int x;
  154. int y;
  155. char state;
  156. } TCursor;
  157. /* CSI Escape sequence structs */
  158. /* ESC '[' [[ [<priv>] <arg> [;]] <mode>] */
  159. typedef struct {
  160. char buf[ESC_BUF_SIZ]; /* raw string */
  161. int len; /* raw string length */
  162. char priv;
  163. int arg[ESC_ARG_SIZ];
  164. int narg; /* nb of args */
  165. char mode;
  166. } CSIEscape;
  167. /* STR Escape sequence structs */
  168. /* ESC type [[ [<priv>] <arg> [;]] <mode>] ESC '\' */
  169. typedef struct {
  170. char type; /* ESC type ... */
  171. char buf[STR_BUF_SIZ]; /* raw string */
  172. int len; /* raw string length */
  173. char *args[STR_ARG_SIZ];
  174. int narg; /* nb of args */
  175. } STREscape;
  176. /* Internal representation of the screen */
  177. typedef struct {
  178. int row; /* nb row */
  179. int col; /* nb col */
  180. Line *line; /* screen */
  181. Line *alt; /* alternate screen */
  182. bool *dirty; /* dirtyness of lines */
  183. TCursor c; /* cursor */
  184. int top; /* top scroll limit */
  185. int bot; /* bottom scroll limit */
  186. int mode; /* terminal mode flags */
  187. int esc; /* escape state flags */
  188. bool numlock; /* lock numbers in keyboard */
  189. bool *tabs;
  190. } Term;
  191. /* Purely graphic info */
  192. typedef struct {
  193. Display *dpy;
  194. Colourmap cmap;
  195. Window win;
  196. Drawable buf;
  197. Atom xembed, wmdeletewin;
  198. XIM xim;
  199. XIC xic;
  200. Draw draw;
  201. Visual *vis;
  202. XSetWindowAttributes attrs;
  203. int scr;
  204. bool isfixed; /* is fixed geometry? */
  205. int fx, fy, fw, fh; /* fixed geometry */
  206. int tw, th; /* tty width and height */
  207. int w, h; /* window width and height */
  208. int ch; /* char height */
  209. int cw; /* char width */
  210. char state; /* focus, redraw, visible */
  211. } XWindow;
  212. typedef struct {
  213. int b;
  214. uint mask;
  215. char s[ESC_BUF_SIZ];
  216. } Mousekey;
  217. typedef struct {
  218. KeySym k;
  219. uint mask;
  220. char s[ESC_BUF_SIZ];
  221. /* three valued logic variables: 0 indifferent, 1 on, -1 off */
  222. signed char appkey; /* application keypad */
  223. signed char appcursor; /* application cursor */
  224. signed char crlf; /* crlf mode */
  225. } Key;
  226. typedef struct {
  227. int mode;
  228. int type;
  229. int snap;
  230. /*
  231. * Selection variables:
  232. * nb – normalized coordinates of the beginning of the selection
  233. * ne – normalized coordinates of the end of the selection
  234. * ob – original coordinates of the beginning of the selection
  235. * oe – original coordinates of the end of the selection
  236. */
  237. struct {
  238. int x, y;
  239. } nb, ne, ob, oe;
  240. char *clip;
  241. Atom xtarget;
  242. bool alt;
  243. struct timeval tclick1;
  244. struct timeval tclick2;
  245. } Selection;
  246. typedef union {
  247. int i;
  248. unsigned int ui;
  249. float f;
  250. const void *v;
  251. } Arg;
  252. typedef struct {
  253. unsigned int mod;
  254. KeySym keysym;
  255. void (*func)(const Arg *);
  256. const Arg arg;
  257. } Shortcut;
  258. /* function definitions used in config.h */
  259. static void clippaste(const Arg *);
  260. static void numlock(const Arg *);
  261. static void selpaste(const Arg *);
  262. static void xzoom(const Arg *);
  263. /* Config.h for applying patches and the configuration. */
  264. #include "config.h"
  265. /* Font structure */
  266. typedef struct {
  267. int height;
  268. int width;
  269. int ascent;
  270. int descent;
  271. short lbearing;
  272. short rbearing;
  273. XftFont *match;
  274. FcFontSet *set;
  275. FcPattern *pattern;
  276. } Font;
  277. /* Drawing Context */
  278. typedef struct {
  279. Colour col[LEN(colorname) < 256 ? 256 : LEN(colorname)];
  280. Font font, bfont, ifont, ibfont;
  281. GC gc;
  282. } DC;
  283. static void die(const char *, ...);
  284. static void draw(void);
  285. static void redraw(int);
  286. static void drawregion(int, int, int, int);
  287. static void execsh(void);
  288. static void sigchld(int);
  289. static void run(void);
  290. static void csidump(void);
  291. static void csihandle(void);
  292. static void csiparse(void);
  293. static void csireset(void);
  294. static void strdump(void);
  295. static void strhandle(void);
  296. static void strparse(void);
  297. static void strreset(void);
  298. static int tattrset(int);
  299. static void tclearregion(int, int, int, int);
  300. static void tcursor(int);
  301. static void tdeletechar(int);
  302. static void tdeleteline(int);
  303. static void tinsertblank(int);
  304. static void tinsertblankline(int);
  305. static void tmoveto(int, int);
  306. static void tmoveato(int x, int y);
  307. static void tnew(int, int);
  308. static void tnewline(int);
  309. static void tputtab(bool);
  310. static void tputc(char *, int);
  311. static void treset(void);
  312. static int tresize(int, int);
  313. static void tscrollup(int, int);
  314. static void tscrolldown(int, int);
  315. static void tsetattr(int*, int);
  316. static void tsetchar(char *, Glyph *, int, int);
  317. static void tsetscroll(int, int);
  318. static void tswapscreen(void);
  319. static void tsetdirt(int, int);
  320. static void tsetdirtattr(int);
  321. static void tsetmode(bool, bool, int *, int);
  322. static void tfulldirt(void);
  323. static void techo(char *, int);
  324. static ulong tdefcolor(int *, int *, int);
  325. static inline bool match(uint, uint);
  326. static void ttynew(void);
  327. static void ttyread(void);
  328. static void ttyresize(void);
  329. static void ttywrite(const char *, size_t);
  330. static void xdraws(char *, Glyph, int, int, int, int);
  331. static void xhints(void);
  332. static void xclear(int, int, int, int);
  333. static void xdrawcursor(void);
  334. static void xinit(void);
  335. static void xloadcols(void);
  336. static int xsetcolorname(int, const char *);
  337. static int xloadfont(Font *, FcPattern *);
  338. static void xloadfonts(char *, int);
  339. static int xloadfontset(Font *);
  340. static void xsettitle(char *);
  341. static void xresettitle(void);
  342. static void xsetpointermotion(int);
  343. static void xseturgency(int);
  344. static void xsetsel(char*);
  345. static void xtermclear(int, int, int, int);
  346. static void xunloadfont(Font *f);
  347. static void xunloadfonts(void);
  348. static void xresize(int, int);
  349. static void expose(XEvent *);
  350. static void visibility(XEvent *);
  351. static void unmap(XEvent *);
  352. static char *kmap(KeySym, uint);
  353. static void kpress(XEvent *);
  354. static void cmessage(XEvent *);
  355. static void cresize(int, int);
  356. static void resize(XEvent *);
  357. static void focus(XEvent *);
  358. static void brelease(XEvent *);
  359. static void bpress(XEvent *);
  360. static void bmotion(XEvent *);
  361. static void selnotify(XEvent *);
  362. static void selclear(XEvent *);
  363. static void selrequest(XEvent *);
  364. static void selinit(void);
  365. static void selsort(void);
  366. static inline bool selected(int, int);
  367. static void selcopy(void);
  368. static void selscroll(int, int);
  369. static void selsnap(int, int *, int *, int);
  370. static int utf8decode(char *, long *);
  371. static int utf8encode(long *, char *);
  372. static int utf8size(char *);
  373. static int isfullutf8(char *, int);
  374. static ssize_t xwrite(int, char *, size_t);
  375. static void *xmalloc(size_t);
  376. static void *xrealloc(void *, size_t);
  377. static void *xcalloc(size_t, size_t);
  378. static void (*handler[LASTEvent])(XEvent *) = {
  379. [KeyPress] = kpress,
  380. [ClientMessage] = cmessage,
  381. [ConfigureNotify] = resize,
  382. [VisibilityNotify] = visibility,
  383. [UnmapNotify] = unmap,
  384. [Expose] = expose,
  385. [FocusIn] = focus,
  386. [FocusOut] = focus,
  387. [MotionNotify] = bmotion,
  388. [ButtonPress] = bpress,
  389. [ButtonRelease] = brelease,
  390. [SelectionClear] = selclear,
  391. [SelectionNotify] = selnotify,
  392. [SelectionRequest] = selrequest,
  393. };
  394. /* Globals */
  395. static DC dc;
  396. static XWindow xw;
  397. static Term term;
  398. static CSIEscape csiescseq;
  399. static STREscape strescseq;
  400. static int cmdfd;
  401. static pid_t pid;
  402. static Selection sel;
  403. static int iofd = -1;
  404. static char **opt_cmd = NULL;
  405. static char *opt_io = NULL;
  406. static char *opt_title = NULL;
  407. static char *opt_embed = NULL;
  408. static char *opt_class = NULL;
  409. static char *opt_font = NULL;
  410. static int oldbutton = 3; /* button event on startup: 3 = release */
  411. static char *usedfont = NULL;
  412. static int usedfontsize = 0;
  413. /* Font Ring Cache */
  414. enum {
  415. FRC_NORMAL,
  416. FRC_ITALIC,
  417. FRC_BOLD,
  418. FRC_ITALICBOLD
  419. };
  420. typedef struct {
  421. XftFont *font;
  422. int flags;
  423. } Fontcache;
  424. /* Fontcache is an array now. A new font will be appended to the array. */
  425. static Fontcache frc[16];
  426. static int frclen = 0;
  427. ssize_t
  428. xwrite(int fd, char *s, size_t len) {
  429. size_t aux = len;
  430. while(len > 0) {
  431. ssize_t r = write(fd, s, len);
  432. if(r < 0)
  433. return r;
  434. len -= r;
  435. s += r;
  436. }
  437. return aux;
  438. }
  439. void *
  440. xmalloc(size_t len) {
  441. void *p = malloc(len);
  442. if(!p)
  443. die("Out of memory\n");
  444. return p;
  445. }
  446. void *
  447. xrealloc(void *p, size_t len) {
  448. if((p = realloc(p, len)) == NULL)
  449. die("Out of memory\n");
  450. return p;
  451. }
  452. void *
  453. xcalloc(size_t nmemb, size_t size) {
  454. void *p = calloc(nmemb, size);
  455. if(!p)
  456. die("Out of memory\n");
  457. return p;
  458. }
  459. int
  460. utf8decode(char *s, long *u) {
  461. uchar c;
  462. int i, n, rtn;
  463. rtn = 1;
  464. c = *s;
  465. if(~c & 0x80) { /* 0xxxxxxx */
  466. *u = c;
  467. return rtn;
  468. } else if((c & 0xE0) == 0xC0) { /* 110xxxxx */
  469. *u = c & 0x1F;
  470. n = 1;
  471. } else if((c & 0xF0) == 0xE0) { /* 1110xxxx */
  472. *u = c & 0x0F;
  473. n = 2;
  474. } else if((c & 0xF8) == 0xF0) { /* 11110xxx */
  475. *u = c & 0x07;
  476. n = 3;
  477. } else {
  478. goto invalid;
  479. }
  480. for(i = n, ++s; i > 0; --i, ++rtn, ++s) {
  481. c = *s;
  482. if((c & 0xC0) != 0x80) /* 10xxxxxx */
  483. goto invalid;
  484. *u <<= 6;
  485. *u |= c & 0x3F;
  486. }
  487. if((n == 1 && *u < 0x80) ||
  488. (n == 2 && *u < 0x800) ||
  489. (n == 3 && *u < 0x10000) ||
  490. (*u >= 0xD800 && *u <= 0xDFFF)) {
  491. goto invalid;
  492. }
  493. return rtn;
  494. invalid:
  495. *u = 0xFFFD;
  496. return rtn;
  497. }
  498. int
  499. utf8encode(long *u, char *s) {
  500. uchar *sp;
  501. ulong uc;
  502. int i, n;
  503. sp = (uchar *)s;
  504. uc = *u;
  505. if(uc < 0x80) {
  506. *sp = uc; /* 0xxxxxxx */
  507. return 1;
  508. } else if(*u < 0x800) {
  509. *sp = (uc >> 6) | 0xC0; /* 110xxxxx */
  510. n = 1;
  511. } else if(uc < 0x10000) {
  512. *sp = (uc >> 12) | 0xE0; /* 1110xxxx */
  513. n = 2;
  514. } else if(uc <= 0x10FFFF) {
  515. *sp = (uc >> 18) | 0xF0; /* 11110xxx */
  516. n = 3;
  517. } else {
  518. goto invalid;
  519. }
  520. for(i=n,++sp; i>0; --i,++sp)
  521. *sp = ((uc >> 6*(i-1)) & 0x3F) | 0x80; /* 10xxxxxx */
  522. return n+1;
  523. invalid:
  524. /* U+FFFD */
  525. *s++ = '\xEF';
  526. *s++ = '\xBF';
  527. *s = '\xBD';
  528. return 3;
  529. }
  530. /* use this if your buffer is less than UTF_SIZ, it returns 1 if you can decode
  531. UTF-8 otherwise return 0 */
  532. int
  533. isfullutf8(char *s, int b) {
  534. uchar *c1, *c2, *c3;
  535. c1 = (uchar *)s;
  536. c2 = (uchar *)++s;
  537. c3 = (uchar *)++s;
  538. if(b < 1) {
  539. return 0;
  540. } else if((*c1 & 0xE0) == 0xC0 && b == 1) {
  541. return 0;
  542. } else if((*c1 & 0xF0) == 0xE0 &&
  543. ((b == 1) ||
  544. ((b == 2) && (*c2 & 0xC0) == 0x80))) {
  545. return 0;
  546. } else if((*c1 & 0xF8) == 0xF0 &&
  547. ((b == 1) ||
  548. ((b == 2) && (*c2 & 0xC0) == 0x80) ||
  549. ((b == 3) && (*c2 & 0xC0) == 0x80 && (*c3 & 0xC0) == 0x80))) {
  550. return 0;
  551. } else {
  552. return 1;
  553. }
  554. }
  555. int
  556. utf8size(char *s) {
  557. uchar c = *s;
  558. if(~c & 0x80) {
  559. return 1;
  560. } else if((c & 0xE0) == 0xC0) {
  561. return 2;
  562. } else if((c & 0xF0) == 0xE0) {
  563. return 3;
  564. } else {
  565. return 4;
  566. }
  567. }
  568. static void
  569. selinit(void) {
  570. memset(&sel.tclick1, 0, sizeof(sel.tclick1));
  571. memset(&sel.tclick2, 0, sizeof(sel.tclick2));
  572. sel.mode = 0;
  573. sel.ob.x = -1;
  574. sel.clip = NULL;
  575. sel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
  576. if(sel.xtarget == None)
  577. sel.xtarget = XA_STRING;
  578. }
  579. static int
  580. x2col(int x) {
  581. x -= borderpx;
  582. x /= xw.cw;
  583. return LIMIT(x, 0, term.col-1);
  584. }
  585. static int
  586. y2row(int y) {
  587. y -= borderpx;
  588. y /= xw.ch;
  589. return LIMIT(y, 0, term.row-1);
  590. }
  591. static void
  592. selsort(void) {
  593. if(sel.ob.y == sel.oe.y) {
  594. sel.nb.x = MIN(sel.ob.x, sel.oe.x);
  595. sel.ne.x = MAX(sel.ob.x, sel.oe.x);
  596. } else {
  597. sel.nb.x = sel.ob.y < sel.oe.y ? sel.ob.x : sel.oe.x;
  598. sel.ne.x = sel.ob.y < sel.oe.y ? sel.oe.x : sel.ob.x;
  599. }
  600. sel.nb.y = MIN(sel.ob.y, sel.oe.y);
  601. sel.ne.y = MAX(sel.ob.y, sel.oe.y);
  602. }
  603. static inline bool
  604. selected(int x, int y) {
  605. if(sel.ne.y == y && sel.nb.y == y)
  606. return BETWEEN(x, sel.nb.x, sel.ne.x);
  607. if(sel.type == SEL_RECTANGULAR) {
  608. return ((sel.nb.y <= y && y <= sel.ne.y)
  609. && (sel.nb.x <= x && x <= sel.ne.x));
  610. }
  611. return ((sel.nb.y < y && y < sel.ne.y)
  612. || (y == sel.ne.y && x <= sel.ne.x))
  613. || (y == sel.nb.y && x >= sel.nb.x
  614. && (x <= sel.ne.x || sel.nb.y != sel.ne.y));
  615. }
  616. void
  617. selsnap(int mode, int *x, int *y, int direction) {
  618. int i;
  619. switch(mode) {
  620. case SNAP_WORD:
  621. /*
  622. * Snap around if the word wraps around at the end or
  623. * beginning of a line.
  624. */
  625. for(;;) {
  626. if(direction < 0 && *x <= 0) {
  627. if(*y > 0 && term.line[*y - 1][term.col-1].mode
  628. & ATTR_WRAP) {
  629. *y -= 1;
  630. *x = term.col-1;
  631. } else {
  632. break;
  633. }
  634. }
  635. if(direction > 0 && *x >= term.col-1) {
  636. if(*y < term.row-1 && term.line[*y][*x].mode
  637. & ATTR_WRAP) {
  638. *y += 1;
  639. *x = 0;
  640. } else {
  641. break;
  642. }
  643. }
  644. if(strchr(worddelimiters,
  645. term.line[*y][*x + direction].c[0])) {
  646. break;
  647. }
  648. *x += direction;
  649. }
  650. break;
  651. case SNAP_LINE:
  652. /*
  653. * Snap around if the the previous line or the current one
  654. * has set ATTR_WRAP at its end. Then the whole next or
  655. * previous line will be selected.
  656. */
  657. *x = (direction < 0) ? 0 : term.col - 1;
  658. if(direction < 0 && *y > 0) {
  659. for(; *y > 0; *y += direction) {
  660. if(!(term.line[*y-1][term.col-1].mode
  661. & ATTR_WRAP)) {
  662. break;
  663. }
  664. }
  665. } else if(direction > 0 && *y < term.row-1) {
  666. for(; *y < term.row; *y += direction) {
  667. if(!(term.line[*y][term.col-1].mode
  668. & ATTR_WRAP)) {
  669. break;
  670. }
  671. }
  672. }
  673. break;
  674. default:
  675. /*
  676. * Select the whole line when the end of line is reached.
  677. */
  678. if(direction > 0) {
  679. i = term.col;
  680. while(--i > 0 && term.line[*y][i].c[0] == ' ')
  681. /* nothing */;
  682. if(i > 0 && i < *x)
  683. *x = term.col - 1;
  684. }
  685. break;
  686. }
  687. }
  688. void
  689. getbuttoninfo(XEvent *e) {
  690. int type;
  691. uint state = e->xbutton.state &~Button1Mask;
  692. sel.alt = IS_SET(MODE_ALTSCREEN);
  693. sel.oe.x = x2col(e->xbutton.x);
  694. sel.oe.y = y2row(e->xbutton.y);
  695. if(sel.ob.y < sel.oe.y
  696. || (sel.ob.y == sel.oe.y && sel.ob.x < sel.oe.x)) {
  697. selsnap(sel.snap, &sel.ob.x, &sel.ob.y, -1);
  698. selsnap(sel.snap, &sel.oe.x, &sel.oe.y, +1);
  699. } else {
  700. selsnap(sel.snap, &sel.oe.x, &sel.oe.y, -1);
  701. selsnap(sel.snap, &sel.ob.x, &sel.ob.y, +1);
  702. }
  703. selsort();
  704. sel.type = SEL_REGULAR;
  705. for(type = 1; type < LEN(selmasks); ++type) {
  706. if(match(selmasks[type], state)) {
  707. sel.type = type;
  708. break;
  709. }
  710. }
  711. }
  712. void
  713. mousereport(XEvent *e) {
  714. int x = x2col(e->xbutton.x), y = y2row(e->xbutton.y),
  715. button = e->xbutton.button, state = e->xbutton.state,
  716. len;
  717. char buf[40];
  718. static int ox, oy;
  719. /* from urxvt */
  720. if(e->xbutton.type == MotionNotify) {
  721. if(x == ox && y == oy)
  722. return;
  723. if(!IS_SET(MODE_MOUSEMOTION) && !IS_SET(MODE_MOUSEMANY))
  724. return;
  725. /* MOUSE_MOTION: no reporting if no button is pressed */
  726. if(IS_SET(MODE_MOUSEMOTION) && oldbutton == 3)
  727. return;
  728. button = oldbutton + 32;
  729. ox = x;
  730. oy = y;
  731. } else if(!IS_SET(MODE_MOUSESGR)
  732. && (e->xbutton.type == ButtonRelease
  733. || button == AnyButton)) {
  734. button = 3;
  735. } else {
  736. button -= Button1;
  737. if(button >= 3)
  738. button += 64 - 3;
  739. if(e->xbutton.type == ButtonPress) {
  740. oldbutton = button;
  741. ox = x;
  742. oy = y;
  743. }
  744. }
  745. if(!IS_SET(MODE_MOUSEX10)) {
  746. button += (state & ShiftMask ? 4 : 0)
  747. + (state & Mod4Mask ? 8 : 0)
  748. + (state & ControlMask ? 16 : 0);
  749. }
  750. len = 0;
  751. if(IS_SET(MODE_MOUSESGR)) {
  752. len = snprintf(buf, sizeof(buf), "\033[<%d;%d;%d%c",
  753. button, x+1, y+1,
  754. e->xbutton.type == ButtonRelease ? 'm' : 'M');
  755. } else if(x < 223 && y < 223) {
  756. len = snprintf(buf, sizeof(buf), "\033[M%c%c%c",
  757. IS_SET(MODE_MOUSEX10)? button-1 : 32+button,
  758. 32+x+1, 32+y+1);
  759. } else {
  760. return;
  761. }
  762. ttywrite(buf, len);
  763. }
  764. void
  765. bpress(XEvent *e) {
  766. struct timeval now;
  767. Mousekey *mk;
  768. if(IS_SET(MODE_MOUSE)) {
  769. mousereport(e);
  770. return;
  771. }
  772. for(mk = mshortcuts; mk < mshortcuts + LEN(mshortcuts); mk++) {
  773. if(e->xbutton.button == mk->b
  774. && match(mk->mask, e->xbutton.state)) {
  775. ttywrite(mk->s, strlen(mk->s));
  776. if(IS_SET(MODE_ECHO))
  777. techo(mk->s, strlen(mk->s));
  778. return;
  779. }
  780. }
  781. if(e->xbutton.button == Button1) {
  782. gettimeofday(&now, NULL);
  783. /* Clear previous selection, logically and visually. */
  784. selclear(NULL);
  785. sel.mode = 1;
  786. sel.type = SEL_REGULAR;
  787. sel.oe.x = sel.ob.x = x2col(e->xbutton.x);
  788. sel.oe.y = sel.ob.y = y2row(e->xbutton.y);
  789. /*
  790. * If the user clicks below predefined timeouts specific
  791. * snapping behaviour is exposed.
  792. */
  793. if(TIMEDIFF(now, sel.tclick2) <= tripleclicktimeout) {
  794. sel.snap = SNAP_LINE;
  795. } else if(TIMEDIFF(now, sel.tclick1) <= doubleclicktimeout) {
  796. sel.snap = SNAP_WORD;
  797. } else {
  798. sel.snap = 0;
  799. }
  800. selsnap(sel.snap, &sel.ob.x, &sel.ob.y, -1);
  801. selsnap(sel.snap, &sel.oe.x, &sel.oe.y, +1);
  802. selsort();
  803. /*
  804. * Draw selection, unless it's regular and we don't want to
  805. * make clicks visible
  806. */
  807. if(sel.snap != 0) {
  808. sel.mode++;
  809. tsetdirt(sel.nb.y, sel.ne.y);
  810. }
  811. sel.tclick2 = sel.tclick1;
  812. sel.tclick1 = now;
  813. }
  814. }
  815. void
  816. selcopy(void) {
  817. char *str, *ptr;
  818. int x, y, bufsize, size, i, ex;
  819. Glyph *gp, *last;
  820. if(sel.ob.x == -1) {
  821. str = NULL;
  822. } else {
  823. bufsize = (term.col+1) * (sel.ne.y-sel.nb.y+1) * UTF_SIZ;
  824. ptr = str = xmalloc(bufsize);
  825. /* append every set & selected glyph to the selection */
  826. for(y = sel.nb.y; y < sel.ne.y + 1; y++) {
  827. gp = &term.line[y][0];
  828. last = gp + term.col;
  829. while(--last >= gp && !(selected(last - gp, y) && \
  830. strcmp(last->c, " ") != 0))
  831. /* nothing */;
  832. for(x = 0; gp <= last; x++, ++gp) {
  833. if(!selected(x, y))
  834. continue;
  835. size = utf8size(gp->c);
  836. memcpy(ptr, gp->c, size);
  837. ptr += size;
  838. }
  839. /*
  840. * Copy and pasting of line endings is inconsistent
  841. * in the inconsistent terminal and GUI world.
  842. * The best solution seems like to produce '\n' when
  843. * something is copied from st and convert '\n' to
  844. * '\r', when something to be pasted is received by
  845. * st.
  846. * FIXME: Fix the computer world.
  847. */
  848. if(y < sel.ne.y && !((gp-1)->mode & ATTR_WRAP))
  849. *ptr++ = '\n';
  850. /*
  851. * If the last selected line expands in the selection
  852. * after the visible text '\n' is appended.
  853. */
  854. if(y == sel.ne.y) {
  855. i = term.col;
  856. while(--i > 0 && term.line[y][i].c[0] == ' ')
  857. /* nothing */;
  858. ex = sel.ne.x;
  859. if(sel.nb.y == sel.ne.y && sel.ne.x < sel.nb.x)
  860. ex = sel.nb.x;
  861. if(i < ex)
  862. *ptr++ = '\n';
  863. }
  864. }
  865. *ptr = 0;
  866. }
  867. xsetsel(str);
  868. }
  869. void
  870. selnotify(XEvent *e) {
  871. ulong nitems, ofs, rem;
  872. int format;
  873. uchar *data, *last, *repl;
  874. Atom type;
  875. ofs = 0;
  876. do {
  877. if(XGetWindowProperty(xw.dpy, xw.win, XA_PRIMARY, ofs, BUFSIZ/4,
  878. False, AnyPropertyType, &type, &format,
  879. &nitems, &rem, &data)) {
  880. fprintf(stderr, "Clipboard allocation failed\n");
  881. return;
  882. }
  883. /*
  884. * As seen in selcopy:
  885. * Line endings are inconsistent in the terminal and GUI world
  886. * copy and pasting. When receiving some selection data,
  887. * replace all '\n' with '\r'.
  888. * FIXME: Fix the computer world.
  889. */
  890. repl = data;
  891. last = data + nitems * format / 8;
  892. while((repl = memchr(repl, '\n', last - repl))) {
  893. *repl++ = '\r';
  894. }
  895. ttywrite((const char *)data, nitems * format / 8);
  896. XFree(data);
  897. /* number of 32-bit chunks returned */
  898. ofs += nitems * format / 32;
  899. } while(rem > 0);
  900. }
  901. void
  902. selpaste(const Arg *dummy) {
  903. XConvertSelection(xw.dpy, XA_PRIMARY, sel.xtarget, XA_PRIMARY,
  904. xw.win, CurrentTime);
  905. }
  906. void
  907. clippaste(const Arg *dummy) {
  908. Atom clipboard;
  909. clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
  910. XConvertSelection(xw.dpy, clipboard, sel.xtarget, XA_PRIMARY,
  911. xw.win, CurrentTime);
  912. }
  913. void
  914. selclear(XEvent *e) {
  915. if(sel.ob.x == -1)
  916. return;
  917. sel.ob.x = -1;
  918. tsetdirt(sel.nb.y, sel.ne.y);
  919. }
  920. void
  921. selrequest(XEvent *e) {
  922. XSelectionRequestEvent *xsre;
  923. XSelectionEvent xev;
  924. Atom xa_targets, string;
  925. xsre = (XSelectionRequestEvent *) e;
  926. xev.type = SelectionNotify;
  927. xev.requestor = xsre->requestor;
  928. xev.selection = xsre->selection;
  929. xev.target = xsre->target;
  930. xev.time = xsre->time;
  931. /* reject */
  932. xev.property = None;
  933. xa_targets = XInternAtom(xw.dpy, "TARGETS", 0);
  934. if(xsre->target == xa_targets) {
  935. /* respond with the supported type */
  936. string = sel.xtarget;
  937. XChangeProperty(xsre->display, xsre->requestor, xsre->property,
  938. XA_ATOM, 32, PropModeReplace,
  939. (uchar *) &string, 1);
  940. xev.property = xsre->property;
  941. } else if(xsre->target == sel.xtarget && sel.clip != NULL) {
  942. XChangeProperty(xsre->display, xsre->requestor, xsre->property,
  943. xsre->target, 8, PropModeReplace,
  944. (uchar *) sel.clip, strlen(sel.clip));
  945. xev.property = xsre->property;
  946. }
  947. /* all done, send a notification to the listener */
  948. if(!XSendEvent(xsre->display, xsre->requestor, True, 0, (XEvent *) &xev))
  949. fprintf(stderr, "Error sending SelectionNotify event\n");
  950. }
  951. void
  952. xsetsel(char *str) {
  953. /* register the selection for both the clipboard and the primary */
  954. Atom clipboard;
  955. free(sel.clip);
  956. sel.clip = str;
  957. XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, CurrentTime);
  958. clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0);
  959. XSetSelectionOwner(xw.dpy, clipboard, xw.win, CurrentTime);
  960. }
  961. void
  962. brelease(XEvent *e) {
  963. if(IS_SET(MODE_MOUSE)) {
  964. mousereport(e);
  965. return;
  966. }
  967. if(e->xbutton.button == Button2) {
  968. selpaste(NULL);
  969. } else if(e->xbutton.button == Button1) {
  970. if(sel.mode < 2) {
  971. selclear(NULL);
  972. } else {
  973. getbuttoninfo(e);
  974. selcopy();
  975. }
  976. sel.mode = 0;
  977. tsetdirt(sel.nb.y, sel.ne.y);
  978. }
  979. }
  980. void
  981. bmotion(XEvent *e) {
  982. int oldey, oldex, oldsby, oldsey;
  983. if(IS_SET(MODE_MOUSE)) {
  984. mousereport(e);
  985. return;
  986. }
  987. if(!sel.mode)
  988. return;
  989. sel.mode++;
  990. oldey = sel.oe.y;
  991. oldex = sel.oe.x;
  992. oldsby = sel.nb.y;
  993. oldsey = sel.ne.y;
  994. getbuttoninfo(e);
  995. if(oldey != sel.oe.y || oldex != sel.oe.x)
  996. tsetdirt(MIN(sel.nb.y, oldsby), MAX(sel.ne.y, oldsey));
  997. }
  998. void
  999. die(const char *errstr, ...) {
  1000. va_list ap;
  1001. va_start(ap, errstr);
  1002. vfprintf(stderr, errstr, ap);
  1003. va_end(ap);
  1004. exit(EXIT_FAILURE);
  1005. }
  1006. void
  1007. execsh(void) {
  1008. char **args;
  1009. char *envshell = getenv("SHELL");
  1010. const struct passwd *pass = getpwuid(getuid());
  1011. char buf[sizeof(long) * 8 + 1];
  1012. unsetenv("COLUMNS");
  1013. unsetenv("LINES");
  1014. unsetenv("TERMCAP");
  1015. if(pass) {
  1016. setenv("LOGNAME", pass->pw_name, 1);
  1017. setenv("USER", pass->pw_name, 1);
  1018. setenv("SHELL", pass->pw_shell, 0);
  1019. setenv("HOME", pass->pw_dir, 0);
  1020. }
  1021. snprintf(buf, sizeof(buf), "%lu", xw.win);
  1022. setenv("WINDOWID", buf, 1);
  1023. signal(SIGCHLD, SIG_DFL);
  1024. signal(SIGHUP, SIG_DFL);
  1025. signal(SIGINT, SIG_DFL);
  1026. signal(SIGQUIT, SIG_DFL);
  1027. signal(SIGTERM, SIG_DFL);
  1028. signal(SIGALRM, SIG_DFL);
  1029. DEFAULT(envshell, shell);
  1030. setenv("TERM", termname, 1);
  1031. args = opt_cmd ? opt_cmd : (char *[]){envshell, "-i", NULL};
  1032. execvp(args[0], args);
  1033. exit(EXIT_FAILURE);
  1034. }
  1035. void
  1036. sigchld(int a) {
  1037. int stat = 0;
  1038. if(waitpid(pid, &stat, 0) < 0)
  1039. die("Waiting for pid %hd failed: %s\n", pid, SERRNO);
  1040. if(WIFEXITED(stat)) {
  1041. exit(WEXITSTATUS(stat));
  1042. } else {
  1043. exit(EXIT_FAILURE);
  1044. }
  1045. }
  1046. void
  1047. ttynew(void) {
  1048. int m, s;
  1049. struct winsize w = {term.row, term.col, 0, 0};
  1050. /* seems to work fine on linux, openbsd and freebsd */
  1051. if(openpty(&m, &s, NULL, NULL, &w) < 0)
  1052. die("openpty failed: %s\n", SERRNO);
  1053. switch(pid = fork()) {
  1054. case -1:
  1055. die("fork failed\n");
  1056. break;
  1057. case 0:
  1058. setsid(); /* create a new process group */
  1059. dup2(s, STDIN_FILENO);
  1060. dup2(s, STDOUT_FILENO);
  1061. dup2(s, STDERR_FILENO);
  1062. if(ioctl(s, TIOCSCTTY, NULL) < 0)
  1063. die("ioctl TIOCSCTTY failed: %s\n", SERRNO);
  1064. close(s);
  1065. close(m);
  1066. execsh();
  1067. break;
  1068. default:
  1069. close(s);
  1070. cmdfd = m;
  1071. signal(SIGCHLD, sigchld);
  1072. if(opt_io) {
  1073. iofd = (!strcmp(opt_io, "-")) ?
  1074. STDOUT_FILENO :
  1075. open(opt_io, O_WRONLY | O_CREAT, 0666);
  1076. if(iofd < 0) {
  1077. fprintf(stderr, "Error opening %s:%s\n",
  1078. opt_io, strerror(errno));
  1079. }
  1080. }
  1081. }
  1082. }
  1083. void
  1084. dump(char c) {
  1085. static int col;
  1086. fprintf(stderr, " %02x '%c' ", c, isprint(c)?c:'.');
  1087. if(++col % 10 == 0)
  1088. fprintf(stderr, "\n");
  1089. }
  1090. void
  1091. ttyread(void) {
  1092. static char buf[BUFSIZ];
  1093. static int buflen = 0;
  1094. char *ptr;
  1095. char s[UTF_SIZ];
  1096. int charsize; /* size of utf8 char in bytes */
  1097. long utf8c;
  1098. int ret;
  1099. /* append read bytes to unprocessed bytes */
  1100. if((ret = read(cmdfd, buf+buflen, LEN(buf)-buflen)) < 0)
  1101. die("Couldn't read from shell: %s\n", SERRNO);
  1102. /* process every complete utf8 char */
  1103. buflen += ret;
  1104. ptr = buf;
  1105. while(buflen >= UTF_SIZ || isfullutf8(ptr,buflen)) {
  1106. charsize = utf8decode(ptr, &utf8c);
  1107. utf8encode(&utf8c, s);
  1108. tputc(s, charsize);
  1109. ptr += charsize;
  1110. buflen -= charsize;
  1111. }
  1112. /* keep any uncomplete utf8 char for the next call */
  1113. memmove(buf, ptr, buflen);
  1114. }
  1115. void
  1116. ttywrite(const char *s, size_t n) {
  1117. if(write(cmdfd, s, n) == -1)
  1118. die("write error on tty: %s\n", SERRNO);
  1119. }
  1120. void
  1121. ttyresize(void) {
  1122. struct winsize w;
  1123. w.ws_row = term.row;
  1124. w.ws_col = term.col;
  1125. w.ws_xpixel = xw.tw;
  1126. w.ws_ypixel = xw.th;
  1127. if(ioctl(cmdfd, TIOCSWINSZ, &w) < 0)
  1128. fprintf(stderr, "Couldn't set window size: %s\n", SERRNO);
  1129. }
  1130. int
  1131. tattrset(int attr) {
  1132. int i, j;
  1133. for(i = 0; i < term.row-1; i++) {
  1134. for(j = 0; j < term.col-1; j++) {
  1135. if(term.line[i][j].mode & attr)
  1136. return 1;
  1137. }
  1138. }
  1139. return 0;
  1140. }
  1141. void
  1142. tsetdirt(int top, int bot) {
  1143. int i;
  1144. LIMIT(top, 0, term.row-1);
  1145. LIMIT(bot, 0, term.row-1);
  1146. for(i = top; i <= bot; i++)
  1147. term.dirty[i] = 1;
  1148. }
  1149. void
  1150. tsetdirtattr(int attr) {
  1151. int i, j;
  1152. for(i = 0; i < term.row-1; i++) {
  1153. for(j = 0; j < term.col-1; j++) {
  1154. if(term.line[i][j].mode & attr) {
  1155. tsetdirt(i, i);
  1156. break;
  1157. }
  1158. }
  1159. }
  1160. }
  1161. void
  1162. tfulldirt(void) {
  1163. tsetdirt(0, term.row-1);
  1164. }
  1165. void
  1166. tcursor(int mode) {
  1167. static TCursor c;
  1168. if(mode == CURSOR_SAVE) {
  1169. c = term.c;
  1170. } else if(mode == CURSOR_LOAD) {
  1171. term.c = c;
  1172. tmoveto(c.x, c.y);
  1173. }
  1174. }
  1175. void
  1176. treset(void) {
  1177. uint i;
  1178. term.c = (TCursor){{
  1179. .mode = ATTR_NULL,
  1180. .fg = defaultfg,
  1181. .bg = defaultbg
  1182. }, .x = 0, .y = 0, .state = CURSOR_DEFAULT};
  1183. memset(term.tabs, 0, term.col * sizeof(*term.tabs));
  1184. for(i = tabspaces; i < term.col; i += tabspaces)
  1185. term.tabs[i] = 1;
  1186. term.top = 0;
  1187. term.bot = term.row - 1;
  1188. term.mode = MODE_WRAP;
  1189. tclearregion(0, 0, term.col-1, term.row-1);
  1190. tmoveto(0, 0);
  1191. tcursor(CURSOR_SAVE);
  1192. }
  1193. void
  1194. tnew(int col, int row) {
  1195. memset(&term, 0, sizeof(Term));
  1196. tresize(col, row);
  1197. term.numlock = 1;
  1198. treset();
  1199. }
  1200. void
  1201. tswapscreen(void) {
  1202. Line *tmp = term.line;
  1203. term.line = term.alt;
  1204. term.alt = tmp;
  1205. term.mode ^= MODE_ALTSCREEN;
  1206. tfulldirt();
  1207. }
  1208. void
  1209. tscrolldown(int orig, int n) {
  1210. int i;
  1211. Line temp;
  1212. LIMIT(n, 0, term.bot-orig+1);
  1213. tclearregion(0, term.bot-n+1, term.col-1, term.bot);
  1214. for(i = term.bot; i >= orig+n; i--) {
  1215. temp = term.line[i];
  1216. term.line[i] = term.line[i-n];
  1217. term.line[i-n] = temp;
  1218. term.dirty[i] = 1;
  1219. term.dirty[i-n] = 1;
  1220. }
  1221. selscroll(orig, n);
  1222. }
  1223. void
  1224. tscrollup(int orig, int n) {
  1225. int i;
  1226. Line temp;
  1227. LIMIT(n, 0, term.bot-orig+1);
  1228. tclearregion(0, orig, term.col-1, orig+n-1);
  1229. for(i = orig; i <= term.bot-n; i++) {
  1230. temp = term.line[i];
  1231. term.line[i] = term.line[i+n];
  1232. term.line[i+n] = temp;
  1233. term.dirty[i] = 1;
  1234. term.dirty[i+n] = 1;
  1235. }
  1236. selscroll(orig, -n);
  1237. }
  1238. void
  1239. selscroll(int orig, int n) {
  1240. if(sel.ob.x == -1)
  1241. return;
  1242. if(BETWEEN(sel.ob.y, orig, term.bot) || BETWEEN(sel.oe.y, orig, term.bot)) {
  1243. if((sel.ob.y += n) > term.bot || (sel.oe.y += n) < term.top) {
  1244. selclear(NULL);
  1245. return;
  1246. }
  1247. if(sel.type == SEL_RECTANGULAR) {
  1248. if(sel.ob.y < term.top)
  1249. sel.ob.y = term.top;
  1250. if(sel.oe.y > term.bot)
  1251. sel.oe.y = term.bot;
  1252. } else {
  1253. if(sel.ob.y < term.top) {
  1254. sel.ob.y = term.top;
  1255. sel.ob.x = 0;
  1256. }
  1257. if(sel.oe.y > term.bot) {
  1258. sel.oe.y = term.bot;
  1259. sel.oe.x = term.col;
  1260. }
  1261. }
  1262. selsort();
  1263. }
  1264. }
  1265. void
  1266. tnewline(int first_col) {
  1267. int y = term.c.y;
  1268. if(y == term.bot) {
  1269. tscrollup(term.top, 1);
  1270. } else {
  1271. y++;
  1272. }
  1273. tmoveto(first_col ? 0 : term.c.x, y);
  1274. }
  1275. void
  1276. csiparse(void) {
  1277. char *p = csiescseq.buf, *np;
  1278. long int v;
  1279. csiescseq.narg = 0;
  1280. if(*p == '?') {
  1281. csiescseq.priv = 1;
  1282. p++;
  1283. }
  1284. csiescseq.buf[csiescseq.len] = '\0';
  1285. while(p < csiescseq.buf+csiescseq.len) {
  1286. np = NULL;
  1287. v = strtol(p, &np, 10);
  1288. if(np == p)
  1289. v = 0;
  1290. if(v == LONG_MAX || v == LONG_MIN)
  1291. v = -1;
  1292. csiescseq.arg[csiescseq.narg++] = v;
  1293. p = np;
  1294. if(*p != ';' || csiescseq.narg == ESC_ARG_SIZ)
  1295. break;
  1296. p++;
  1297. }
  1298. csiescseq.mode = *p;
  1299. }
  1300. /* for absolute user moves, when decom is set */
  1301. void
  1302. tmoveato(int x, int y) {
  1303. tmoveto(x, y + ((term.c.state & CURSOR_ORIGIN) ? term.top: 0));
  1304. }
  1305. void
  1306. tmoveto(int x, int y) {
  1307. int miny, maxy;
  1308. if(term.c.state & CURSOR_ORIGIN) {
  1309. miny = term.top;
  1310. maxy = term.bot;
  1311. } else {
  1312. miny = 0;
  1313. maxy = term.row - 1;
  1314. }
  1315. LIMIT(x, 0, term.col-1);
  1316. LIMIT(y, miny, maxy);
  1317. term.c.state &= ~CURSOR_WRAPNEXT;
  1318. term.c.x = x;
  1319. term.c.y = y;
  1320. }
  1321. void
  1322. tsetchar(char *c, Glyph *attr, int x, int y) {
  1323. static char *vt100_0[62] = { /* 0x41 - 0x7e */
  1324. "↑", "↓", "→", "←", "█", "▚", "☃", /* A - G */
  1325. 0, 0, 0, 0, 0, 0, 0, 0, /* H - O */
  1326. 0, 0, 0, 0, 0, 0, 0, 0, /* P - W */
  1327. 0, 0, 0, 0, 0, 0, 0, " ", /* X - _ */
  1328. "◆", "▒", "␉", "␌", "␍", "␊", "°", "±", /* ` - g */
  1329. "␤", "␋", "┘", "┐", "┌", "└", "┼", "⎺", /* h - o */
  1330. "⎻", "─", "⎼", "⎽", "├", "┤", "┴", "┬", /* p - w */
  1331. "│", "≤", "≥", "π", "≠", "£", "·", /* x - ~ */
  1332. };
  1333. /*
  1334. * The table is proudly stolen from rxvt.
  1335. */
  1336. if(attr->mode & ATTR_GFX) {
  1337. if(c[0] >= 0x41 && c[0] <= 0x7e
  1338. && vt100_0[c[0] - 0x41]) {
  1339. c = vt100_0[c[0] - 0x41];
  1340. }
  1341. }
  1342. term.dirty[y] = 1;
  1343. term.line[y][x] = *attr;
  1344. memcpy(term.line[y][x].c, c, UTF_SIZ);
  1345. }
  1346. void
  1347. tclearregion(int x1, int y1, int x2, int y2) {
  1348. int x, y, temp;
  1349. if(x1 > x2)
  1350. temp = x1, x1 = x2, x2 = temp;
  1351. if(y1 > y2)
  1352. temp = y1, y1 = y2, y2 = temp;
  1353. LIMIT(x1, 0, term.col-1);
  1354. LIMIT(x2, 0, term.col-1);
  1355. LIMIT(y1, 0, term.row-1);
  1356. LIMIT(y2, 0, term.row-1);
  1357. for(y = y1; y <= y2; y++) {
  1358. term.dirty[y] = 1;
  1359. for(x = x1; x <= x2; x++) {
  1360. if(selected(x, y))
  1361. selclear(NULL);
  1362. term.line[y][x] = term.c.attr;
  1363. memcpy(term.line[y][x].c, " ", 2);
  1364. }
  1365. }
  1366. }
  1367. void
  1368. tdeletechar(int n) {
  1369. int src = term.c.x + n;
  1370. int dst = term.c.x;
  1371. int size = term.col - src;
  1372. term.dirty[term.c.y] = 1;
  1373. if(src >= term.col) {
  1374. tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
  1375. return;
  1376. }
  1377. memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src],
  1378. size * sizeof(Glyph));
  1379. tclearregion(term.col-n, term.c.y, term.col-1, term.c.y);
  1380. }
  1381. void
  1382. tinsertblank(int n) {
  1383. int src = term.c.x;
  1384. int dst = src + n;
  1385. int size = term.col - dst;
  1386. term.dirty[term.c.y] = 1;
  1387. if(dst >= term.col) {
  1388. tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
  1389. return;
  1390. }
  1391. memmove(&term.line[term.c.y][dst], &term.line[term.c.y][src],
  1392. size * sizeof(Glyph));
  1393. tclearregion(src, term.c.y, dst - 1, term.c.y);
  1394. }
  1395. void
  1396. tinsertblankline(int n) {
  1397. if(term.c.y < term.top || term.c.y > term.bot)
  1398. return;
  1399. tscrolldown(term.c.y, n);
  1400. }
  1401. void
  1402. tdeleteline(int n) {
  1403. if(term.c.y < term.top || term.c.y > term.bot)
  1404. return;
  1405. tscrollup(term.c.y, n);
  1406. }
  1407. ulong
  1408. tdefcolor(int *attr, int *npar, int l) {
  1409. long idx = -1;
  1410. uint r, g, b;
  1411. switch (attr[*npar + 1]) {
  1412. case 2: /* direct colour in RGB space */
  1413. if (*npar + 4 >= l) {
  1414. fprintf(stderr,
  1415. "erresc(38): Incorrect number of parameters (%d)\n",
  1416. *npar);
  1417. break;
  1418. }
  1419. r = attr[*npar + 2];
  1420. g = attr[*npar + 3];
  1421. b = attr[*npar + 4];
  1422. *npar += 4;
  1423. if(!BETWEEN(r, 0, 255) || !BETWEEN(g, 0, 255) || !BETWEEN(b, 0, 255))
  1424. fprintf(stderr, "erresc: bad rgb color (%d,%d,%d)\n",
  1425. r, g, b);
  1426. else
  1427. idx = TRUECOLOR(r, g, b);
  1428. break;
  1429. case 5: /* indexed colour */
  1430. if (*npar + 2 >= l) {
  1431. fprintf(stderr,
  1432. "erresc(38): Incorrect number of parameters (%d)\n",
  1433. *npar);
  1434. break;
  1435. }
  1436. *npar += 2;
  1437. if(!BETWEEN(attr[*npar], 0, 255))
  1438. fprintf(stderr, "erresc: bad fgcolor %d\n", attr[*npar]);
  1439. else
  1440. idx = attr[*npar];
  1441. break;
  1442. case 0: /* implemented defined (only foreground) */
  1443. case 1: /* transparent */
  1444. case 3: /* direct colour in CMY space */
  1445. case 4: /* direct colour in CMYK space */
  1446. default:
  1447. fprintf(stderr,
  1448. "erresc(38): gfx attr %d unknown\n", attr[*npar]);
  1449. }
  1450. return idx;
  1451. }
  1452. void
  1453. tsetattr(int *attr, int l) {
  1454. int i;
  1455. ulong idx;
  1456. for(i = 0; i < l; i++) {
  1457. switch(attr[i]) {
  1458. case 0:
  1459. term.c.attr.mode &= ~(ATTR_REVERSE | ATTR_UNDERLINE \
  1460. | ATTR_BOLD | ATTR_ITALIC \
  1461. | ATTR_BLINK);
  1462. term.c.attr.fg = defaultfg;
  1463. term.c.attr.bg = defaultbg;
  1464. break;
  1465. case 1:
  1466. term.c.attr.mode |= ATTR_BOLD;
  1467. break;
  1468. case 3:
  1469. term.c.attr.mode |= ATTR_ITALIC;
  1470. break;
  1471. case 4:
  1472. term.c.attr.mode |= ATTR_UNDERLINE;
  1473. break;
  1474. case 5: /* slow blink */
  1475. case 6: /* rapid blink */
  1476. term.c.attr.mode |= ATTR_BLINK;
  1477. break;
  1478. case 7:
  1479. term.c.attr.mode |= ATTR_REVERSE;
  1480. break;
  1481. case 21:
  1482. case 22:
  1483. term.c.attr.mode &= ~ATTR_BOLD;
  1484. break;
  1485. case 23:
  1486. term.c.attr.mode &= ~ATTR_ITALIC;
  1487. break;
  1488. case 24:
  1489. term.c.attr.mode &= ~ATTR_UNDERLINE;
  1490. break;
  1491. case 25:
  1492. case 26:
  1493. term.c.attr.mode &= ~ATTR_BLINK;
  1494. break;
  1495. case 27:
  1496. term.c.attr.mode &= ~ATTR_REVERSE;
  1497. break;
  1498. case 38:
  1499. if ((idx = tdefcolor(attr, &i, l)) >= 0)
  1500. term.c.attr.fg = idx;
  1501. break;
  1502. case 39:
  1503. term.c.attr.fg = defaultfg;
  1504. break;
  1505. case 48:
  1506. if ((idx = tdefcolor(attr, &i, l)) >= 0)
  1507. term.c.attr.bg = idx;
  1508. break;
  1509. case 49:
  1510. term.c.attr.bg = defaultbg;
  1511. break;
  1512. default:
  1513. if(BETWEEN(attr[i], 30, 37)) {
  1514. term.c.attr.fg = attr[i] - 30;
  1515. } else if(BETWEEN(attr[i], 40, 47)) {
  1516. term.c.attr.bg = attr[i] - 40;
  1517. } else if(BETWEEN(attr[i], 90, 97)) {
  1518. term.c.attr.fg = attr[i] - 90 + 8;
  1519. } else if(BETWEEN(attr[i], 100, 107)) {
  1520. term.c.attr.bg = attr[i] - 100 + 8;
  1521. } else {
  1522. fprintf(stderr,
  1523. "erresc(default): gfx attr %d unknown\n",
  1524. attr[i]), csidump();
  1525. }
  1526. break;
  1527. }
  1528. }
  1529. }
  1530. void
  1531. tsetscroll(int t, int b) {
  1532. int temp;
  1533. LIMIT(t, 0, term.row-1);
  1534. LIMIT(b, 0, term.row-1);
  1535. if(t > b) {
  1536. temp = t;
  1537. t = b;
  1538. b = temp;
  1539. }
  1540. term.top = t;
  1541. term.bot = b;
  1542. }
  1543. #define MODBIT(x, set, bit) ((set) ? ((x) |= (bit)) : ((x) &= ~(bit)))
  1544. void
  1545. tsetmode(bool priv, bool set, int *args, int narg) {
  1546. int *lim, mode;
  1547. bool alt;
  1548. for(lim = args + narg; args < lim; ++args) {
  1549. if(priv) {
  1550. switch(*args) {
  1551. break;
  1552. case 1: /* DECCKM -- Cursor key */
  1553. MODBIT(term.mode, set, MODE_APPCURSOR);
  1554. break;
  1555. case 5: /* DECSCNM -- Reverse video */
  1556. mode = term.mode;
  1557. MODBIT(term.mode, set, MODE_REVERSE);
  1558. if(mode != term.mode)
  1559. redraw(REDRAW_TIMEOUT);
  1560. break;
  1561. case 6: /* DECOM -- Origin */
  1562. MODBIT(term.c.state, set, CURSOR_ORIGIN);
  1563. tmoveato(0, 0);
  1564. break;
  1565. case 7: /* DECAWM -- Auto wrap */
  1566. MODBIT(term.mode, set, MODE_WRAP);
  1567. break;
  1568. case 0: /* Error (IGNORED) */
  1569. case 2: /* DECANM -- ANSI/VT52 (IGNORED) */
  1570. case 3: /* DECCOLM -- Column (IGNORED) */
  1571. case 4: /* DECSCLM -- Scroll (IGNORED) */
  1572. case 8: /* DECARM -- Auto repeat (IGNORED) */
  1573. case 18: /* DECPFF -- Printer feed (IGNORED) */
  1574. case 19: /* DECPEX -- Printer extent (IGNORED) */
  1575. case 42: /* DECNRCM -- National characters (IGNORED) */
  1576. case 12: /* att610 -- Start blinking cursor (IGNORED) */
  1577. break;
  1578. case 25: /* DECTCEM -- Text Cursor Enable Mode */
  1579. MODBIT(term.mode, !set, MODE_HIDE);
  1580. break;
  1581. case 9: /* X10 mouse compatibility mode */
  1582. xsetpointermotion(0);
  1583. MODBIT(term.mode, 0, MODE_MOUSE);
  1584. MODBIT(term.mode, set, MODE_MOUSEX10);
  1585. break;
  1586. case 1000: /* 1000: report button press */
  1587. xsetpointermotion(0);
  1588. MODBIT(term.mode, 0, MODE_MOUSE);
  1589. MODBIT(term.mode, set, MODE_MOUSEBTN);
  1590. break;
  1591. case 1002: /* 1002: report motion on button press */
  1592. xsetpointermotion(0);
  1593. MODBIT(term.mode, 0, MODE_MOUSE);
  1594. MODBIT(term.mode, set, MODE_MOUSEMOTION);
  1595. break;
  1596. case 1003: /* 1003: enable all mouse motions */
  1597. xsetpointermotion(set);
  1598. MODBIT(term.mode, 0, MODE_MOUSE);
  1599. MODBIT(term.mode, set, MODE_MOUSEMANY);
  1600. break;
  1601. case 1004: /* 1004: send focus events to tty */
  1602. MODBIT(term.mode, set, MODE_FOCUS);
  1603. break;
  1604. case 1006: /* 1006: extended reporting mode */
  1605. MODBIT(term.mode, set, MODE_MOUSESGR);
  1606. break;
  1607. case 1034:
  1608. MODBIT(term.mode, set, MODE_8BIT);
  1609. break;
  1610. case 1049: /* = 1047 and 1048 */
  1611. case 47:
  1612. case 1047:
  1613. if (!allowaltscreen)
  1614. break;
  1615. alt = IS_SET(MODE_ALTSCREEN);
  1616. if(alt) {
  1617. tclearregion(0, 0, term.col-1,
  1618. term.row-1);
  1619. }
  1620. if(set ^ alt) /* set is always 1 or 0 */
  1621. tswapscreen();
  1622. if(*args != 1049)
  1623. break;
  1624. /* FALLTRU */
  1625. case 1048:
  1626. tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD);
  1627. break;
  1628. /* Not implemented mouse modes. See comments there. */
  1629. case 1001: /* mouse highlight mode; can hang the
  1630. terminal by design when implemented. */
  1631. case 1005: /* UTF-8 mouse mode; will confuse
  1632. applications not supporting UTF-8
  1633. and luit. */
  1634. case 1015: /* urxvt mangled mouse mode; incompatible
  1635. and can be mistaken for other control
  1636. codes. */
  1637. default:
  1638. fprintf(stderr,
  1639. "erresc: unknown private set/reset mode %d\n",
  1640. *args);
  1641. break;
  1642. }
  1643. } else {
  1644. switch(*args) {
  1645. case 0: /* Error (IGNORED) */
  1646. break;
  1647. case 2: /* KAM -- keyboard action */
  1648. MODBIT(term.mode, set, MODE_KBDLOCK);
  1649. break;
  1650. case 4: /* IRM -- Insertion-replacement */
  1651. MODBIT(term.mode, set, MODE_INSERT);
  1652. break;
  1653. case 12: /* SRM -- Send/Receive */
  1654. MODBIT(term.mode, !set, MODE_ECHO);
  1655. break;
  1656. case 20: /* LNM -- Linefeed/new line */
  1657. MODBIT(term.mode, set, MODE_CRLF);
  1658. break;
  1659. default:
  1660. fprintf(stderr,
  1661. "erresc: unknown set/reset mode %d\n",
  1662. *args);
  1663. break;
  1664. }
  1665. }
  1666. }
  1667. }
  1668. void
  1669. csihandle(void) {
  1670. switch(csiescseq.mode) {
  1671. default:
  1672. unknown:
  1673. fprintf(stderr, "erresc: unknown csi ");
  1674. csidump();
  1675. /* die(""); */
  1676. break;
  1677. case '@': /* ICH -- Insert <n> blank char */
  1678. DEFAULT(csiescseq.arg[0], 1);
  1679. tinsertblank(csiescseq.arg[0]);
  1680. break;
  1681. case 'A': /* CUU -- Cursor <n> Up */
  1682. DEFAULT(csiescseq.arg[0], 1);
  1683. tmoveto(term.c.x, term.c.y-csiescseq.arg[0]);
  1684. break;
  1685. case 'B': /* CUD -- Cursor <n> Down */
  1686. case 'e': /* VPR --Cursor <n> Down */
  1687. DEFAULT(csiescseq.arg[0], 1);
  1688. tmoveto(term.c.x, term.c.y+csiescseq.arg[0]);
  1689. break;
  1690. case 'c': /* DA -- Device Attributes */
  1691. if(csiescseq.arg[0] == 0)
  1692. ttywrite(VT102ID, sizeof(VT102ID) - 1);
  1693. break;
  1694. case 'C': /* CUF -- Cursor <n> Forward */
  1695. case 'a': /* HPR -- Cursor <n> Forward */
  1696. DEFAULT(csiescseq.arg[0], 1);
  1697. tmoveto(term.c.x+csiescseq.arg[0], term.c.y);
  1698. break;
  1699. case 'D': /* CUB -- Cursor <n> Backward */
  1700. DEFAULT(csiescseq.arg[0], 1);
  1701. tmoveto(term.c.x-csiescseq.arg[0], term.c.y);
  1702. break;
  1703. case 'E': /* CNL -- Cursor <n> Down and first col */
  1704. DEFAULT(csiescseq.arg[0], 1);
  1705. tmoveto(0, term.c.y+csiescseq.arg[0]);
  1706. break;
  1707. case 'F': /* CPL -- Cursor <n> Up and first col */
  1708. DEFAULT(csiescseq.arg[0], 1);
  1709. tmoveto(0, term.c.y-csiescseq.arg[0]);
  1710. break;
  1711. case 'g': /* TBC -- Tabulation clear */
  1712. switch(csiescseq.arg[0]) {
  1713. case 0: /* clear current tab stop */
  1714. term.tabs[term.c.x] = 0;
  1715. break;
  1716. case 3: /* clear all the tabs */
  1717. memset(term.tabs, 0, term.col * sizeof(*term.tabs));
  1718. break;
  1719. default:
  1720. goto unknown;
  1721. }
  1722. break;
  1723. case 'G': /* CHA -- Move to <col> */
  1724. case '`': /* HPA */
  1725. DEFAULT(csiescseq.arg[0], 1);
  1726. tmoveto(csiescseq.arg[0]-1, term.c.y);
  1727. break;
  1728. case 'H': /* CUP -- Move to <row> <col> */
  1729. case 'f': /* HVP */
  1730. DEFAULT(csiescseq.arg[0], 1);
  1731. DEFAULT(csiescseq.arg[1], 1);
  1732. tmoveato(csiescseq.arg[1]-1, csiescseq.arg[0]-1);
  1733. break;
  1734. case 'I': /* CHT -- Cursor Forward Tabulation <n> tab stops */
  1735. DEFAULT(csiescseq.arg[0], 1);
  1736. while(csiescseq.arg[0]--)
  1737. tputtab(1);
  1738. break;
  1739. case 'J': /* ED -- Clear screen */
  1740. selclear(NULL);
  1741. switch(csiescseq.arg[0]) {
  1742. case 0: /* below */
  1743. tclearregion(term.c.x, term.c.y, term.col-1, term.c.y);
  1744. if(term.c.y < term.row-1) {
  1745. tclearregion(0, term.c.y+1, term.col-1,
  1746. term.row-1);
  1747. }
  1748. break;
  1749. case 1: /* above */
  1750. if(term.c.y > 1)
  1751. tclearregion(0, 0, term.col-1, term.c.y-1);
  1752. tclearregion(0, term.c.y, term.c.x, term.c.y);
  1753. break;
  1754. case 2: /* all */
  1755. tclearregion(0, 0, term.col-1, term.row-1);
  1756. break;
  1757. default:
  1758. goto unknown;
  1759. }
  1760. break;
  1761. case 'K': /* EL -- Clear line */
  1762. switch(csiescseq.arg[0]) {
  1763. case 0: /* right */
  1764. tclearregion(term.c.x, term.c.y, term.col-1,
  1765. term.c.y);
  1766. break;
  1767. case 1: /* left */
  1768. tclearregion(0, term.c.y, term.c.x, term.c.y);
  1769. break;
  1770. case 2: /* all */
  1771. tclearregion(0, term.c.y, term.col-1, term.c.y);
  1772. break;
  1773. }
  1774. break;
  1775. case 'S': /* SU -- Scroll <n> line up */
  1776. DEFAULT(csiescseq.arg[0], 1);
  1777. tscrollup(term.top, csiescseq.arg[0]);
  1778. break;
  1779. case 'T': /* SD -- Scroll <n> line down */
  1780. DEFAULT(csiescseq.arg[0], 1);
  1781. tscrolldown(term.top, csiescseq.arg[0]);
  1782. break;
  1783. case 'L': /* IL -- Insert <n> blank lines */
  1784. DEFAULT(csiescseq.arg[0], 1);
  1785. tinsertblankline(csiescseq.arg[0]);
  1786. break;
  1787. case 'l': /* RM -- Reset Mode */
  1788. tsetmode(csiescseq.priv, 0, csiescseq.arg, csiescseq.narg);
  1789. break;
  1790. case 'M': /* DL -- Delete <n> lines */
  1791. DEFAULT(csiescseq.arg[0], 1);
  1792. tdeleteline(csiescseq.arg[0]);
  1793. break;
  1794. case 'X': /* ECH -- Erase <n> char */
  1795. DEFAULT(csiescseq.arg[0], 1);
  1796. tclearregion(term.c.x, term.c.y,
  1797. term.c.x + csiescseq.arg[0] - 1, term.c.y);
  1798. break;
  1799. case 'P': /* DCH -- Delete <n> char */
  1800. DEFAULT(csiescseq.arg[0], 1);
  1801. tdeletechar(csiescseq.arg[0]);
  1802. break;
  1803. case 'Z': /* CBT -- Cursor Backward Tabulation <n> tab stops */
  1804. DEFAULT(csiescseq.arg[0], 1);
  1805. while(csiescseq.arg[0]--)
  1806. tputtab(0);
  1807. break;
  1808. case 'd': /* VPA -- Move to <row> */
  1809. DEFAULT(csiescseq.arg[0], 1);
  1810. tmoveato(term.c.x, csiescseq.arg[0]-1);
  1811. break;
  1812. case 'h': /* SM -- Set terminal mode */
  1813. tsetmode(csiescseq.priv, 1, csiescseq.arg, csiescseq.narg);
  1814. break;
  1815. case 'm': /* SGR -- Terminal attribute (color) */
  1816. tsetattr(csiescseq.arg, csiescseq.narg);
  1817. break;
  1818. case 'r': /* DECSTBM -- Set Scrolling Region */
  1819. if(csiescseq.priv) {
  1820. goto unknown;
  1821. } else {
  1822. DEFAULT(csiescseq.arg[0], 1);
  1823. DEFAULT(csiescseq.arg[1], term.row);
  1824. tsetscroll(csiescseq.arg[0]-1, csiescseq.arg[1]-1);
  1825. tmoveato(0, 0);
  1826. }
  1827. break;
  1828. case 's': /* DECSC -- Save cursor position (ANSI.SYS) */
  1829. tcursor(CURSOR_SAVE);
  1830. break;
  1831. case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */
  1832. tcursor(CURSOR_LOAD);
  1833. break;
  1834. }
  1835. }
  1836. void
  1837. csidump(void) {
  1838. int i;
  1839. uint c;
  1840. printf("ESC[");
  1841. for(i = 0; i < csiescseq.len; i++) {
  1842. c = csiescseq.buf[i] & 0xff;
  1843. if(isprint(c)) {
  1844. putchar(c);
  1845. } else if(c == '\n') {
  1846. printf("(\\n)");
  1847. } else if(c == '\r') {
  1848. printf("(\\r)");
  1849. } else if(c == 0x1b) {
  1850. printf("(\\e)");
  1851. } else {
  1852. printf("(%02x)", c);
  1853. }
  1854. }
  1855. putchar('\n');
  1856. }
  1857. void
  1858. csireset(void) {
  1859. memset(&csiescseq, 0, sizeof(csiescseq));
  1860. }
  1861. void
  1862. strhandle(void) {
  1863. char *p = NULL;
  1864. int i, j, narg;
  1865. strparse();
  1866. narg = strescseq.narg;
  1867. switch(strescseq.type) {
  1868. case ']': /* OSC -- Operating System Command */
  1869. switch(i = atoi(strescseq.args[0])) {
  1870. case 0:
  1871. case 1:
  1872. case 2:
  1873. if(narg > 1)
  1874. xsettitle(strescseq.args[1]);
  1875. break;
  1876. case 4: /* color set */
  1877. if(narg < 3)
  1878. break;
  1879. p = strescseq.args[2];
  1880. /* fall through */
  1881. case 104: /* color reset, here p = NULL */
  1882. j = (narg > 1) ? atoi(strescseq.args[1]) : -1;
  1883. if (!xsetcolorname(j, p)) {
  1884. fprintf(stderr, "erresc: invalid color %s\n", p);
  1885. } else {
  1886. /*
  1887. * TODO if defaultbg color is changed, borders
  1888. * are dirty
  1889. */
  1890. redraw(0);
  1891. }
  1892. break;
  1893. default:
  1894. fprintf(stderr, "erresc: unknown str ");
  1895. strdump();
  1896. break;
  1897. }
  1898. break;
  1899. case 'k': /* old title set compatibility */
  1900. xsettitle(strescseq.args[0]);
  1901. break;
  1902. case 'P': /* DSC -- Device Control String */
  1903. case '_': /* APC -- Application Program Command */
  1904. case '^': /* PM -- Privacy Message */
  1905. default:
  1906. fprintf(stderr, "erresc: unknown str ");
  1907. strdump();
  1908. /* die(""); */
  1909. break;
  1910. }
  1911. }
  1912. void
  1913. strparse(void) {
  1914. char *p = strescseq.buf;
  1915. strescseq.narg = 0;
  1916. strescseq.buf[strescseq.len] = '\0';
  1917. while(p && strescseq.narg < STR_ARG_SIZ)
  1918. strescseq.args[strescseq.narg++] = strsep(&p, ";");
  1919. }
  1920. void
  1921. strdump(void) {
  1922. int i;
  1923. uint c;
  1924. printf("ESC%c", strescseq.type);
  1925. for(i = 0; i < strescseq.len; i++) {
  1926. c = strescseq.buf[i] & 0xff;
  1927. if(c == '\0') {
  1928. return;
  1929. } else if(isprint(c)) {
  1930. putchar(c);
  1931. } else if(c == '\n') {
  1932. printf("(\\n)");
  1933. } else if(c == '\r') {
  1934. printf("(\\r)");
  1935. } else if(c == 0x1b) {
  1936. printf("(\\e)");
  1937. } else {
  1938. printf("(%02x)", c);
  1939. }
  1940. }
  1941. printf("ESC\\\n");
  1942. }
  1943. void
  1944. strreset(void) {
  1945. memset(&strescseq, 0, sizeof(strescseq));
  1946. }
  1947. void
  1948. tputtab(bool forward) {
  1949. uint x = term.c.x;
  1950. if(forward) {
  1951. if(x == term.col)
  1952. return;
  1953. for(++x; x < term.col && !term.tabs[x]; ++x)
  1954. /* nothing */ ;
  1955. } else {
  1956. if(x == 0)
  1957. return;
  1958. for(--x; x > 0 && !term.tabs[x]; --x)
  1959. /* nothing */ ;
  1960. }
  1961. tmoveto(x, term.c.y);
  1962. }
  1963. void
  1964. techo(char *buf, int len) {
  1965. for(; len > 0; buf++, len--) {
  1966. char c = *buf;
  1967. if(c == '\033') { /* escape */
  1968. tputc("^", 1);
  1969. tputc("[", 1);
  1970. } else if(c < '\x20') { /* control code */
  1971. if(c != '\n' && c != '\r' && c != '\t') {
  1972. c |= '\x40';
  1973. tputc("^", 1);
  1974. }
  1975. tputc(&c, 1);
  1976. } else {
  1977. break;
  1978. }
  1979. }
  1980. if(len)
  1981. tputc(buf, len);
  1982. }
  1983. void
  1984. tputc(char *c, int len) {
  1985. uchar ascii = *c;
  1986. bool control = ascii < '\x20' || ascii == 0177;
  1987. if(iofd != -1) {
  1988. if(xwrite(iofd, c, len) < 0) {
  1989. fprintf(stderr, "Error writing in %s:%s\n",
  1990. opt_io, strerror(errno));
  1991. close(iofd);
  1992. iofd = -1;
  1993. }
  1994. }
  1995. /*
  1996. * STR sequences must be checked before anything else
  1997. * because it can use some control codes as part of the sequence.
  1998. */
  1999. if(term.esc & ESC_STR) {
  2000. switch(ascii) {
  2001. case '\033':
  2002. term.esc = ESC_START | ESC_STR_END;
  2003. break;
  2004. case '\a': /* backwards compatibility to xterm */
  2005. term.esc = 0;
  2006. strhandle();
  2007. break;
  2008. default:
  2009. if(strescseq.len + len < sizeof(strescseq.buf) - 1) {
  2010. memmove(&strescseq.buf[strescseq.len], c, len);
  2011. strescseq.len += len;
  2012. } else {
  2013. /*
  2014. * Here is a bug in terminals. If the user never sends
  2015. * some code to stop the str or esc command, then st
  2016. * will stop responding. But this is better than
  2017. * silently failing with unknown characters. At least
  2018. * then users will report back.
  2019. *
  2020. * In the case users ever get fixed, here is the code:
  2021. */
  2022. /*
  2023. * term.esc = 0;
  2024. * strhandle();
  2025. */
  2026. }
  2027. }
  2028. return;
  2029. }
  2030. /*
  2031. * Actions of control codes must be performed as soon they arrive
  2032. * because they can be embedded inside a control sequence, and
  2033. * they must not cause conflicts with sequences.
  2034. */
  2035. if(control) {
  2036. switch(ascii) {
  2037. case '\t': /* HT */
  2038. tputtab(1);
  2039. return;
  2040. case '\b': /* BS */
  2041. tmoveto(term.c.x-1, term.c.y);
  2042. return;
  2043. case '\r': /* CR */
  2044. tmoveto(0, term.c.y);
  2045. return;
  2046. case '\f': /* LF */
  2047. case '\v': /* VT */
  2048. case '\n': /* LF */
  2049. /* go to first col if the mode is set */
  2050. tnewline(IS_SET(MODE_CRLF));
  2051. return;
  2052. case '\a': /* BEL */
  2053. if(!(xw.state & WIN_FOCUSED))
  2054. xseturgency(1);
  2055. return;
  2056. case '\033': /* ESC */
  2057. csireset();
  2058. term.esc = ESC_START;
  2059. return;
  2060. case '\016': /* SO */
  2061. case '\017': /* SI */
  2062. /*
  2063. * Different charsets are hard to handle. Applications
  2064. * should use the right alt charset escapes for the
  2065. * only reason they still exist: line drawing. The
  2066. * rest is incompatible history st should not support.
  2067. */
  2068. return;
  2069. case '\032': /* SUB */
  2070. case '\030': /* CAN */
  2071. csireset();
  2072. return;
  2073. case '\005': /* ENQ (IGNORED) */
  2074. case '\000': /* NUL (IGNORED) */
  2075. case '\021': /* XON (IGNORED) */
  2076. case '\023': /* XOFF (IGNORED) */
  2077. case 0177: /* DEL (IGNORED) */
  2078. return;
  2079. }
  2080. } else if(term.esc & ESC_START) {
  2081. if(term.esc & ESC_CSI) {
  2082. csiescseq.buf[csiescseq.len++] = ascii;
  2083. if(BETWEEN(ascii, 0x40, 0x7E)
  2084. || csiescseq.len >= \
  2085. sizeof(csiescseq.buf)-1) {
  2086. term.esc = 0;
  2087. csiparse();
  2088. csihandle();
  2089. }
  2090. } else if(term.esc & ESC_STR_END) {
  2091. term.esc = 0;
  2092. if(ascii == '\\')
  2093. strhandle();
  2094. } else if(term.esc & ESC_ALTCHARSET) {
  2095. switch(ascii) {
  2096. case '0': /* Line drawing set */
  2097. term.c.attr.mode |= ATTR_GFX;
  2098. break;
  2099. case 'B': /* USASCII */
  2100. term.c.attr.mode &= ~ATTR_GFX;
  2101. break;
  2102. case 'A': /* UK (IGNORED) */
  2103. case '<': /* multinational charset (IGNORED) */
  2104. case '5': /* Finnish (IGNORED) */
  2105. case 'C': /* Finnish (IGNORED) */
  2106. case 'K': /* German (IGNORED) */
  2107. break;
  2108. default:
  2109. fprintf(stderr, "esc unhandled charset: ESC ( %c\n", ascii);
  2110. }
  2111. term.esc = 0;
  2112. } else if(term.esc & ESC_TEST) {
  2113. if(ascii == '8') { /* DEC screen alignment test. */
  2114. char E[UTF_SIZ] = "E";
  2115. int x, y;
  2116. for(x = 0; x < term.col; ++x) {
  2117. for(y = 0; y < term.row; ++y)
  2118. tsetchar(E, &term.c.attr, x, y);
  2119. }
  2120. }
  2121. term.esc = 0;
  2122. } else {
  2123. switch(ascii) {
  2124. case '[':
  2125. term.esc |= ESC_CSI;
  2126. break;
  2127. case '#':
  2128. term.esc |= ESC_TEST;
  2129. break;
  2130. case 'P': /* DCS -- Device Control String */
  2131. case '_': /* APC -- Application Program Command */
  2132. case '^': /* PM -- Privacy Message */
  2133. case ']': /* OSC -- Operating System Command */
  2134. case 'k': /* old title set compatibility */
  2135. strreset();
  2136. strescseq.type = ascii;
  2137. term.esc |= ESC_STR;
  2138. break;
  2139. case '(': /* set primary charset G0 */
  2140. term.esc |= ESC_ALTCHARSET;
  2141. break;
  2142. case ')': /* set secondary charset G1 (IGNORED) */
  2143. case '*': /* set tertiary charset G2 (IGNORED) */
  2144. case '+': /* set quaternary charset G3 (IGNORED) */
  2145. term.esc = 0;
  2146. break;
  2147. case 'D': /* IND -- Linefeed */
  2148. if(term.c.y == term.bot) {
  2149. tscrollup(term.top, 1);
  2150. } else {
  2151. tmoveto(term.c.x, term.c.y+1);
  2152. }
  2153. term.esc = 0;
  2154. break;
  2155. case 'E': /* NEL -- Next line */
  2156. tnewline(1); /* always go to first col */
  2157. term.esc = 0;
  2158. break;
  2159. case 'H': /* HTS -- Horizontal tab stop */
  2160. term.tabs[term.c.x] = 1;
  2161. term.esc = 0;
  2162. break;
  2163. case 'M': /* RI -- Reverse index */
  2164. if(term.c.y == term.top) {
  2165. tscrolldown(term.top, 1);
  2166. } else {
  2167. tmoveto(term.c.x, term.c.y-1);
  2168. }
  2169. term.esc = 0;
  2170. break;
  2171. case 'Z': /* DECID -- Identify Terminal */
  2172. ttywrite(VT102ID, sizeof(VT102ID) - 1);
  2173. term.esc = 0;
  2174. break;
  2175. case 'c': /* RIS -- Reset to inital state */
  2176. treset();
  2177. term.esc = 0;
  2178. xresettitle();
  2179. xloadcols();
  2180. break;
  2181. case '=': /* DECPAM -- Application keypad */
  2182. term.mode |= MODE_APPKEYPAD;
  2183. term.esc = 0;
  2184. break;
  2185. case '>': /* DECPNM -- Normal keypad */
  2186. term.mode &= ~MODE_APPKEYPAD;
  2187. term.esc = 0;
  2188. break;
  2189. case '7': /* DECSC -- Save Cursor */
  2190. tcursor(CURSOR_SAVE);
  2191. term.esc = 0;
  2192. break;
  2193. case '8': /* DECRC -- Restore Cursor */
  2194. tcursor(CURSOR_LOAD);
  2195. term.esc = 0;
  2196. break;
  2197. case '\\': /* ST -- Stop */
  2198. term.esc = 0;
  2199. break;
  2200. default:
  2201. fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n",
  2202. (uchar) ascii, isprint(ascii)? ascii:'.');
  2203. term.esc = 0;
  2204. }
  2205. }
  2206. /*
  2207. * All characters which form part of a sequence are not
  2208. * printed
  2209. */
  2210. return;
  2211. }
  2212. /*
  2213. * Display control codes only if we are in graphic mode
  2214. */
  2215. if(control && !(term.c.attr.mode & ATTR_GFX))
  2216. return;
  2217. if(sel.ob.x != -1 && BETWEEN(term.c.y, sel.ob.y, sel.oe.y))
  2218. selclear(NULL);
  2219. if(IS_SET(MODE_WRAP) && (term.c.state & CURSOR_WRAPNEXT)) {
  2220. term.line[term.c.y][term.c.x].mode |= ATTR_WRAP;
  2221. tnewline(1);
  2222. }
  2223. if(IS_SET(MODE_INSERT) && term.c.x+1 < term.col) {
  2224. memmove(&term.line[term.c.y][term.c.x+1],
  2225. &term.line[term.c.y][term.c.x],
  2226. (term.col - term.c.x - 1) * sizeof(Glyph));
  2227. }
  2228. tsetchar(c, &term.c.attr, term.c.x, term.c.y);
  2229. if(term.c.x+1 < term.col) {
  2230. tmoveto(term.c.x+1, term.c.y);
  2231. } else {
  2232. term.c.state |= CURSOR_WRAPNEXT;
  2233. }
  2234. }
  2235. int
  2236. tresize(int col, int row) {
  2237. int i;
  2238. int minrow = MIN(row, term.row);
  2239. int mincol = MIN(col, term.col);
  2240. int slide = term.c.y - row + 1;
  2241. bool *bp;
  2242. Line *orig;
  2243. if(col < 1 || row < 1)
  2244. return 0;
  2245. /* free unneeded rows */
  2246. i = 0;
  2247. if(slide > 0) {
  2248. /*
  2249. * slide screen to keep cursor where we expect it -
  2250. * tscrollup would work here, but we can optimize to
  2251. * memmove because we're freeing the earlier lines
  2252. */
  2253. for(/* i = 0 */; i < slide; i++) {
  2254. free(term.line[i]);
  2255. free(term.alt[i]);
  2256. }
  2257. memmove(term.line, term.line + slide, row * sizeof(Line));
  2258. memmove(term.alt, term.alt + slide, row * sizeof(Line));
  2259. }
  2260. for(i += row; i < term.row; i++) {
  2261. free(term.line[i]);
  2262. free(term.alt[i]);
  2263. }
  2264. /* resize to new height */
  2265. term.line = xrealloc(term.line, row * sizeof(Line));
  2266. term.alt = xrealloc(term.alt, row * sizeof(Line));
  2267. term.dirty = xrealloc(term.dirty, row * sizeof(*term.dirty));
  2268. term.tabs = xrealloc(term.tabs, col * sizeof(*term.tabs));
  2269. /* resize each row to new width, zero-pad if needed */
  2270. for(i = 0; i < minrow; i++) {
  2271. term.dirty[i] = 1;
  2272. term.line[i] = xrealloc(term.line[i], col * sizeof(Glyph));
  2273. term.alt[i] = xrealloc(term.alt[i], col * sizeof(Glyph));
  2274. }
  2275. /* allocate any new rows */
  2276. for(/* i == minrow */; i < row; i++) {
  2277. term.dirty[i] = 1;
  2278. term.line[i] = xcalloc(col, sizeof(Glyph));
  2279. term.alt [i] = xcalloc(col, sizeof(Glyph));
  2280. }
  2281. if(col > term.col) {
  2282. bp = term.tabs + term.col;
  2283. memset(bp, 0, sizeof(*term.tabs) * (col - term.col));
  2284. while(--bp > term.tabs && !*bp)
  2285. /* nothing */ ;
  2286. for(bp += tabspaces; bp < term.tabs + col; bp += tabspaces)
  2287. *bp = 1;
  2288. }
  2289. /* update terminal size */
  2290. term.col = col;
  2291. term.row = row;
  2292. /* reset scrolling region */
  2293. tsetscroll(0, row-1);
  2294. /* make use of the LIMIT in tmoveto */
  2295. tmoveto(term.c.x, term.c.y);
  2296. /* Clearing both screens */
  2297. orig = term.line;
  2298. do {
  2299. if(mincol < col && 0 < minrow) {
  2300. tclearregion(mincol, 0, col - 1, minrow - 1);
  2301. }
  2302. if(0 < col && minrow < row) {
  2303. tclearregion(0, minrow, col - 1, row - 1);
  2304. }
  2305. tswapscreen();
  2306. } while(orig != term.line);
  2307. return (slide > 0);
  2308. }
  2309. void
  2310. xresize(int col, int row) {
  2311. xw.tw = MAX(1, col * xw.cw);
  2312. xw.th = MAX(1, row * xw.ch);
  2313. XFreePixmap(xw.dpy, xw.buf);
  2314. xw.buf = XCreatePixmap(xw.dpy, xw.win, xw.w, xw.h,
  2315. DefaultDepth(xw.dpy, xw.scr));
  2316. XftDrawChange(xw.draw, xw.buf);
  2317. xclear(0, 0, xw.w, xw.h);
  2318. }
  2319. static inline ushort
  2320. sixd_to_16bit(int x) {
  2321. return x == 0 ? 0 : 0x3737 + 0x2828 * x;
  2322. }
  2323. void
  2324. xloadcols(void) {
  2325. int i, r, g, b;
  2326. XRenderColor color = { .alpha = 0xffff };
  2327. static bool loaded;
  2328. Colour *cp;
  2329. if(loaded) {
  2330. for (cp = dc.col; cp < dc.col + LEN(dc.col); ++cp)
  2331. XftColorFree(xw.dpy, xw.vis, xw.cmap, cp);
  2332. }
  2333. /* load colors [0-15] colors and [256-LEN(colorname)[ (config.h) */
  2334. for(i = 0; i < LEN(colorname); i++) {
  2335. if(!colorname[i])
  2336. continue;
  2337. if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, colorname[i], &dc.col[i])) {
  2338. die("Could not allocate color '%s'\n", colorname[i]);
  2339. }
  2340. }
  2341. /* load colors [16-255] ; same colors as xterm */
  2342. for(i = 16, r = 0; r < 6; r++) {
  2343. for(g = 0; g < 6; g++) {
  2344. for(b = 0; b < 6; b++) {
  2345. color.red = sixd_to_16bit(r);
  2346. color.green = sixd_to_16bit(g);
  2347. color.blue = sixd_to_16bit(b);
  2348. if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &dc.col[i])) {
  2349. die("Could not allocate color %d\n", i);
  2350. }
  2351. i++;
  2352. }
  2353. }
  2354. }
  2355. for(r = 0; r < 24; r++, i++) {
  2356. color.red = color.green = color.blue = 0x0808 + 0x0a0a * r;
  2357. if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color,
  2358. &dc.col[i])) {
  2359. die("Could not allocate color %d\n", i);
  2360. }
  2361. }
  2362. loaded = true;
  2363. }
  2364. int
  2365. xsetcolorname(int x, const char *name) {
  2366. XRenderColor color = { .alpha = 0xffff };
  2367. Colour colour;
  2368. if (x < 0 || x > LEN(colorname))
  2369. return -1;
  2370. if(!name) {
  2371. if(16 <= x && x < 16 + 216) {
  2372. int r = (x - 16) / 36, g = ((x - 16) % 36) / 6, b = (x - 16) % 6;
  2373. color.red = sixd_to_16bit(r);
  2374. color.green = sixd_to_16bit(g);
  2375. color.blue = sixd_to_16bit(b);
  2376. if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &colour))
  2377. return 0; /* something went wrong */
  2378. dc.col[x] = colour;
  2379. return 1;
  2380. } else if (16 + 216 <= x && x < 256) {
  2381. color.red = color.green = color.blue = 0x0808 + 0x0a0a * (x - (16 + 216));
  2382. if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &colour))
  2383. return 0; /* something went wrong */
  2384. dc.col[x] = colour;
  2385. return 1;
  2386. } else {
  2387. name = colorname[x];
  2388. }
  2389. }
  2390. if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, name, &colour))
  2391. return 0;
  2392. dc.col[x] = colour;
  2393. return 1;
  2394. }
  2395. void
  2396. xtermclear(int col1, int row1, int col2, int row2) {
  2397. XftDrawRect(xw.draw,
  2398. &dc.col[IS_SET(MODE_REVERSE) ? defaultfg : defaultbg],
  2399. borderpx + col1 * xw.cw,
  2400. borderpx + row1 * xw.ch,
  2401. (col2-col1+1) * xw.cw,
  2402. (row2-row1+1) * xw.ch);
  2403. }
  2404. /*
  2405. * Absolute coordinates.
  2406. */
  2407. void
  2408. xclear(int x1, int y1, int x2, int y2) {
  2409. XftDrawRect(xw.draw,
  2410. &dc.col[IS_SET(MODE_REVERSE)? defaultfg : defaultbg],
  2411. x1, y1, x2-x1, y2-y1);
  2412. }
  2413. void
  2414. xhints(void) {
  2415. XClassHint class = {opt_class ? opt_class : termname, termname};
  2416. XWMHints wm = {.flags = InputHint, .input = 1};
  2417. XSizeHints *sizeh = NULL;
  2418. sizeh = XAllocSizeHints();
  2419. if(xw.isfixed == False) {
  2420. sizeh->flags = PSize | PResizeInc | PBaseSize;
  2421. sizeh->height = xw.h;
  2422. sizeh->width = xw.w;
  2423. sizeh->height_inc = xw.ch;
  2424. sizeh->width_inc = xw.cw;
  2425. sizeh->base_height = 2 * borderpx;
  2426. sizeh->base_width = 2 * borderpx;
  2427. } else {
  2428. sizeh->flags = PMaxSize | PMinSize;
  2429. sizeh->min_width = sizeh->max_width = xw.fw;
  2430. sizeh->min_height = sizeh->max_height = xw.fh;
  2431. }
  2432. XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm, &class);
  2433. XFree(sizeh);
  2434. }
  2435. int
  2436. xloadfont(Font *f, FcPattern *pattern) {
  2437. FcPattern *match;
  2438. FcResult result;
  2439. match = FcFontMatch(NULL, pattern, &result);
  2440. if(!match)
  2441. return 1;
  2442. if(!(f->match = XftFontOpenPattern(xw.dpy, match))) {
  2443. FcPatternDestroy(match);
  2444. return 1;
  2445. }
  2446. f->set = NULL;
  2447. f->pattern = FcPatternDuplicate(pattern);
  2448. f->ascent = f->match->ascent;
  2449. f->descent = f->match->descent;
  2450. f->lbearing = 0;
  2451. f->rbearing = f->match->max_advance_width;
  2452. f->height = f->ascent + f->descent;
  2453. f->width = f->lbearing + f->rbearing;
  2454. return 0;
  2455. }
  2456. void
  2457. xloadfonts(char *fontstr, int fontsize) {
  2458. FcPattern *pattern;
  2459. FcResult result;
  2460. double fontval;
  2461. if(fontstr[0] == '-') {
  2462. pattern = XftXlfdParse(fontstr, False, False);
  2463. } else {
  2464. pattern = FcNameParse((FcChar8 *)fontstr);
  2465. }
  2466. if(!pattern)
  2467. die("st: can't open font %s\n", fontstr);
  2468. if(fontsize > 0) {
  2469. FcPatternDel(pattern, FC_PIXEL_SIZE);
  2470. FcPatternAddDouble(pattern, FC_PIXEL_SIZE, (double)fontsize);
  2471. usedfontsize = fontsize;
  2472. } else {
  2473. result = FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &fontval);
  2474. if(result == FcResultMatch) {
  2475. usedfontsize = (int)fontval;
  2476. } else {
  2477. /*
  2478. * Default font size is 12, if none given. This is to
  2479. * have a known usedfontsize value.
  2480. */
  2481. FcPatternAddDouble(pattern, FC_PIXEL_SIZE, 12);
  2482. usedfontsize = 12;
  2483. }
  2484. }
  2485. FcConfigSubstitute(0, pattern, FcMatchPattern);
  2486. FcDefaultSubstitute(pattern);
  2487. if(xloadfont(&dc.font, pattern))
  2488. die("st: can't open font %s\n", fontstr);
  2489. /* Setting character width and height. */
  2490. xw.cw = CEIL(dc.font.width * cwscale);
  2491. xw.ch = CEIL(dc.font.height * chscale);
  2492. FcPatternDel(pattern, FC_SLANT);
  2493. FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC);
  2494. if(xloadfont(&dc.ifont, pattern))
  2495. die("st: can't open font %s\n", fontstr);
  2496. FcPatternDel(pattern, FC_WEIGHT);
  2497. FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD);
  2498. if(xloadfont(&dc.ibfont, pattern))
  2499. die("st: can't open font %s\n", fontstr);
  2500. FcPatternDel(pattern, FC_SLANT);
  2501. FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ROMAN);
  2502. if(xloadfont(&dc.bfont, pattern))
  2503. die("st: can't open font %s\n", fontstr);
  2504. FcPatternDestroy(pattern);
  2505. }
  2506. int
  2507. xloadfontset(Font *f) {
  2508. FcResult result;
  2509. if(!(f->set = FcFontSort(0, f->pattern, FcTrue, 0, &result)))
  2510. return 1;
  2511. return 0;
  2512. }
  2513. void
  2514. xunloadfont(Font *f) {
  2515. XftFontClose(xw.dpy, f->match);
  2516. FcPatternDestroy(f->pattern);
  2517. if(f->set)
  2518. FcFontSetDestroy(f->set);
  2519. }
  2520. void
  2521. xunloadfonts(void) {
  2522. int i;
  2523. /* Free the loaded fonts in the font cache. */
  2524. for(i = 0; i < frclen; i++) {
  2525. XftFontClose(xw.dpy, frc[i].font);
  2526. }
  2527. frclen = 0;
  2528. xunloadfont(&dc.font);
  2529. xunloadfont(&dc.bfont);
  2530. xunloadfont(&dc.ifont);
  2531. xunloadfont(&dc.ibfont);
  2532. }
  2533. void
  2534. xzoom(const Arg *arg) {
  2535. xunloadfonts();
  2536. xloadfonts(usedfont, usedfontsize + arg->i);
  2537. cresize(0, 0);
  2538. redraw(0);
  2539. }
  2540. void
  2541. xinit(void) {
  2542. XGCValues gcvalues;
  2543. Cursor cursor;
  2544. Window parent;
  2545. int sw, sh;
  2546. if(!(xw.dpy = XOpenDisplay(NULL)))
  2547. die("Can't open display\n");
  2548. xw.scr = XDefaultScreen(xw.dpy);
  2549. xw.vis = XDefaultVisual(xw.dpy, xw.scr);
  2550. /* font */
  2551. if(!FcInit())
  2552. die("Could not init fontconfig.\n");
  2553. usedfont = (opt_font == NULL)? font : opt_font;
  2554. xloadfonts(usedfont, 0);
  2555. /* colors */
  2556. xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
  2557. xloadcols();
  2558. /* adjust fixed window geometry */
  2559. if(xw.isfixed) {
  2560. sw = DisplayWidth(xw.dpy, xw.scr);
  2561. sh = DisplayHeight(xw.dpy, xw.scr);
  2562. if(xw.fx < 0)
  2563. xw.fx = sw + xw.fx - xw.fw - 1;
  2564. if(xw.fy < 0)
  2565. xw.fy = sh + xw.fy - xw.fh - 1;
  2566. xw.h = xw.fh;
  2567. xw.w = xw.fw;
  2568. } else {
  2569. /* window - default size */
  2570. xw.h = 2 * borderpx + term.row * xw.ch;
  2571. xw.w = 2 * borderpx + term.col * xw.cw;
  2572. xw.fx = 0;
  2573. xw.fy = 0;
  2574. }
  2575. /* Events */
  2576. xw.attrs.background_pixel = dc.col[defaultbg].pixel;
  2577. xw.attrs.border_pixel = dc.col[defaultbg].pixel;
  2578. xw.attrs.bit_gravity = NorthWestGravity;
  2579. xw.attrs.event_mask = FocusChangeMask | KeyPressMask
  2580. | ExposureMask | VisibilityChangeMask | StructureNotifyMask
  2581. | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
  2582. xw.attrs.colormap = xw.cmap;
  2583. parent = opt_embed ? strtol(opt_embed, NULL, 0) : \
  2584. XRootWindow(xw.dpy, xw.scr);
  2585. xw.win = XCreateWindow(xw.dpy, parent, xw.fx, xw.fy,
  2586. xw.w, xw.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
  2587. xw.vis, CWBackPixel | CWBorderPixel | CWBitGravity
  2588. | CWEventMask | CWColormap, &xw.attrs);
  2589. memset(&gcvalues, 0, sizeof(gcvalues));
  2590. gcvalues.graphics_exposures = False;
  2591. dc.gc = XCreateGC(xw.dpy, parent, GCGraphicsExposures,
  2592. &gcvalues);
  2593. xw.buf = XCreatePixmap(xw.dpy, xw.win, xw.w, xw.h,
  2594. DefaultDepth(xw.dpy, xw.scr));
  2595. XSetForeground(xw.dpy, dc.gc, dc.col[defaultbg].pixel);
  2596. XFillRectangle(xw.dpy, xw.buf, dc.gc, 0, 0, xw.w, xw.h);
  2597. /* Xft rendering context */
  2598. xw.draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
  2599. /* input methods */
  2600. if((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
  2601. XSetLocaleModifiers("@im=local");
  2602. if((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
  2603. XSetLocaleModifiers("@im=");
  2604. if((xw.xim = XOpenIM(xw.dpy,
  2605. NULL, NULL, NULL)) == NULL) {
  2606. die("XOpenIM failed. Could not open input"
  2607. " device.\n");
  2608. }
  2609. }
  2610. }
  2611. xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
  2612. | XIMStatusNothing, XNClientWindow, xw.win,
  2613. XNFocusWindow, xw.win, NULL);
  2614. if(xw.xic == NULL)
  2615. die("XCreateIC failed. Could not obtain input method.\n");
  2616. /* white cursor, black outline */
  2617. cursor = XCreateFontCursor(xw.dpy, XC_xterm);
  2618. XDefineCursor(xw.dpy, xw.win, cursor);
  2619. XRecolorCursor(xw.dpy, cursor,
  2620. &(XColor){.red = 0xffff, .green = 0xffff, .blue = 0xffff},
  2621. &(XColor){.red = 0x0000, .green = 0x0000, .blue = 0x0000});
  2622. xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
  2623. xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
  2624. XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
  2625. xresettitle();
  2626. XMapWindow(xw.dpy, xw.win);
  2627. xhints();
  2628. XSync(xw.dpy, 0);
  2629. }
  2630. void
  2631. xdraws(char *s, Glyph base, int x, int y, int charlen, int bytelen) {
  2632. int winx = borderpx + x * xw.cw, winy = borderpx + y * xw.ch,
  2633. width = charlen * xw.cw, xp, i;
  2634. int frcflags;
  2635. int u8fl, u8fblen, u8cblen, doesexist;
  2636. char *u8c, *u8fs;
  2637. long u8char;
  2638. Font *font = &dc.font;
  2639. FcResult fcres;
  2640. FcPattern *fcpattern, *fontpattern;
  2641. FcFontSet *fcsets[] = { NULL };
  2642. FcCharSet *fccharset;
  2643. Colour *fg, *bg, *temp, revfg, revbg, truefg, truebg;
  2644. XRenderColor colfg, colbg;
  2645. Rectangle r;
  2646. int oneatatime;
  2647. frcflags = FRC_NORMAL;
  2648. if(base.mode & ATTR_ITALIC) {
  2649. if(base.fg == defaultfg)
  2650. base.fg = defaultitalic;
  2651. font = &dc.ifont;
  2652. frcflags = FRC_ITALIC;
  2653. } else if((base.mode & ATTR_ITALIC) && (base.mode & ATTR_BOLD)) {
  2654. if(base.fg == defaultfg)
  2655. base.fg = defaultitalic;
  2656. font = &dc.ibfont;
  2657. frcflags = FRC_ITALICBOLD;
  2658. } else if(base.mode & ATTR_UNDERLINE) {
  2659. if(base.fg == defaultfg)
  2660. base.fg = defaultunderline;
  2661. }
  2662. if(IS_TRUECOL(base.fg)) {
  2663. colfg.red = TRUERED(base.fg);
  2664. colfg.green = TRUEGREEN(base.fg);
  2665. colfg.blue = TRUEBLUE(base.fg);
  2666. XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &truefg);
  2667. fg = &truefg;
  2668. } else {
  2669. fg = &dc.col[base.fg];
  2670. }
  2671. if(IS_TRUECOL(base.bg)) {
  2672. colbg.green = TRUEGREEN(base.bg);
  2673. colbg.red = TRUERED(base.bg);
  2674. colbg.blue = TRUEBLUE(base.bg);
  2675. XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &truebg);
  2676. bg = &truebg;
  2677. } else {
  2678. bg = &dc.col[base.bg];
  2679. }
  2680. if(base.mode & ATTR_BOLD) {
  2681. if(BETWEEN(base.fg, 0, 7)) {
  2682. /* basic system colors */
  2683. fg = &dc.col[base.fg + 8];
  2684. } else if(BETWEEN(base.fg, 16, 195)) {
  2685. /* 256 colors */
  2686. fg = &dc.col[base.fg + 36];
  2687. } else if(BETWEEN(base.fg, 232, 251)) {
  2688. /* greyscale */
  2689. fg = &dc.col[base.fg + 4];
  2690. }
  2691. /*
  2692. * Those ranges will not be brightened:
  2693. * 8 - 15 – bright system colors
  2694. * 196 - 231 – highest 256 color cube
  2695. * 252 - 255 – brightest colors in greyscale
  2696. */
  2697. font = &dc.bfont;
  2698. frcflags = FRC_BOLD;
  2699. }
  2700. if(IS_SET(MODE_REVERSE)) {
  2701. if(fg == &dc.col[defaultfg]) {
  2702. fg = &dc.col[defaultbg];
  2703. } else {
  2704. colfg.red = ~fg->color.red;
  2705. colfg.green = ~fg->color.green;
  2706. colfg.blue = ~fg->color.blue;
  2707. colfg.alpha = fg->color.alpha;
  2708. XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
  2709. fg = &revfg;
  2710. }
  2711. if(bg == &dc.col[defaultbg]) {
  2712. bg = &dc.col[defaultfg];
  2713. } else {
  2714. colbg.red = ~bg->color.red;
  2715. colbg.green = ~bg->color.green;
  2716. colbg.blue = ~bg->color.blue;
  2717. colbg.alpha = bg->color.alpha;
  2718. XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &revbg);
  2719. bg = &revbg;
  2720. }
  2721. }
  2722. if(base.mode & ATTR_REVERSE) {
  2723. temp = fg;
  2724. fg = bg;
  2725. bg = temp;
  2726. }
  2727. if(base.mode & ATTR_BLINK && term.mode & MODE_BLINK)
  2728. fg = bg;
  2729. /* Intelligent cleaning up of the borders. */
  2730. if(x == 0) {
  2731. xclear(0, (y == 0)? 0 : winy, borderpx,
  2732. winy + xw.ch + ((y >= term.row-1)? xw.h : 0));
  2733. }
  2734. if(x + charlen >= term.col) {
  2735. xclear(winx + width, (y == 0)? 0 : winy, xw.w,
  2736. ((y >= term.row-1)? xw.h : (winy + xw.ch)));
  2737. }
  2738. if(y == 0)
  2739. xclear(winx, 0, winx + width, borderpx);
  2740. if(y == term.row-1)
  2741. xclear(winx, winy + xw.ch, winx + width, xw.h);
  2742. /* Clean up the region we want to draw to. */
  2743. XftDrawRect(xw.draw, bg, winx, winy, width, xw.ch);
  2744. /* Set the clip region because Xft is sometimes dirty. */
  2745. r.x = 0;
  2746. r.y = 0;
  2747. r.height = xw.ch;
  2748. r.width = width;
  2749. XftDrawSetClipRectangles(xw.draw, winx, winy, &r, 1);
  2750. for(xp = winx; bytelen > 0;) {
  2751. /*
  2752. * Search for the range in the to be printed string of glyphs
  2753. * that are in the main font. Then print that range. If
  2754. * some glyph is found that is not in the font, do the
  2755. * fallback dance.
  2756. */
  2757. u8fs = s;
  2758. u8fblen = 0;
  2759. u8fl = 0;
  2760. oneatatime = font->width != xw.cw;
  2761. for(;;) {
  2762. u8c = s;
  2763. u8cblen = utf8decode(s, &u8char);
  2764. s += u8cblen;
  2765. bytelen -= u8cblen;
  2766. doesexist = XftCharExists(xw.dpy, font->match, u8char);
  2767. if(oneatatime || !doesexist || bytelen <= 0) {
  2768. if(oneatatime || bytelen <= 0) {
  2769. if(doesexist) {
  2770. u8fl++;
  2771. u8fblen += u8cblen;
  2772. }
  2773. }
  2774. if(u8fl > 0) {
  2775. XftDrawStringUtf8(xw.draw, fg,
  2776. font->match, xp,
  2777. winy + font->ascent,
  2778. (FcChar8 *)u8fs,
  2779. u8fblen);
  2780. xp += CEIL(font->width * cwscale * u8fl);
  2781. }
  2782. break;
  2783. }
  2784. u8fl++;
  2785. u8fblen += u8cblen;
  2786. }
  2787. if(doesexist) {
  2788. if (oneatatime);
  2789. continue;
  2790. break;
  2791. }
  2792. /* Search the font cache. */
  2793. for(i = 0; i < frclen; i++) {
  2794. if(XftCharExists(xw.dpy, frc[i].font, u8char)
  2795. && frc[i].flags == frcflags) {
  2796. break;
  2797. }
  2798. }
  2799. /* Nothing was found. */
  2800. if(i >= frclen) {
  2801. if(!font->set)
  2802. xloadfontset(font);
  2803. fcsets[0] = font->set;
  2804. /*
  2805. * Nothing was found in the cache. Now use
  2806. * some dozen of Fontconfig calls to get the
  2807. * font for one single character.
  2808. */
  2809. fcpattern = FcPatternDuplicate(font->pattern);
  2810. fccharset = FcCharSetCreate();
  2811. FcCharSetAddChar(fccharset, u8char);
  2812. FcPatternAddCharSet(fcpattern, FC_CHARSET,
  2813. fccharset);
  2814. FcPatternAddBool(fcpattern, FC_SCALABLE,
  2815. FcTrue);
  2816. FcConfigSubstitute(0, fcpattern,
  2817. FcMatchPattern);
  2818. FcDefaultSubstitute(fcpattern);
  2819. fontpattern = FcFontSetMatch(0, fcsets,
  2820. FcTrue, fcpattern, &fcres);
  2821. /*
  2822. * Overwrite or create the new cache entry.
  2823. */
  2824. if(frclen >= LEN(frc)) {
  2825. frclen = LEN(frc) - 1;
  2826. XftFontClose(xw.dpy, frc[frclen].font);
  2827. }
  2828. frc[frclen].font = XftFontOpenPattern(xw.dpy,
  2829. fontpattern);
  2830. frc[frclen].flags = frcflags;
  2831. i = frclen;
  2832. frclen++;
  2833. FcPatternDestroy(fcpattern);
  2834. FcCharSetDestroy(fccharset);
  2835. }
  2836. XftDrawStringUtf8(xw.draw, fg, frc[i].font,
  2837. xp, winy + frc[i].font->ascent,
  2838. (FcChar8 *)u8c, u8cblen);
  2839. xp += CEIL(font->width * cwscale);
  2840. }
  2841. /*
  2842. XftDrawStringUtf8(xw.draw, fg, font->set, winx,
  2843. winy + font->ascent, (FcChar8 *)s, bytelen);
  2844. */
  2845. if(base.mode & ATTR_UNDERLINE) {
  2846. XftDrawRect(xw.draw, fg, winx, winy + font->ascent + 1,
  2847. width, 1);
  2848. }
  2849. /* Reset clip to none. */
  2850. XftDrawSetClip(xw.draw, 0);
  2851. }
  2852. void
  2853. xdrawcursor(void) {
  2854. static int oldx = 0, oldy = 0;
  2855. int sl;
  2856. Glyph g = {{' '}, ATTR_NULL, defaultbg, defaultcs};
  2857. LIMIT(oldx, 0, term.col-1);
  2858. LIMIT(oldy, 0, term.row-1);
  2859. memcpy(g.c, term.line[term.c.y][term.c.x].c, UTF_SIZ);
  2860. /* remove the old cursor */
  2861. sl = utf8size(term.line[oldy][oldx].c);
  2862. xdraws(term.line[oldy][oldx].c, term.line[oldy][oldx], oldx,
  2863. oldy, 1, sl);
  2864. /* draw the new one */
  2865. if(!(IS_SET(MODE_HIDE))) {
  2866. if(xw.state & WIN_FOCUSED) {
  2867. if(IS_SET(MODE_REVERSE)) {
  2868. g.mode |= ATTR_REVERSE;
  2869. g.fg = defaultcs;
  2870. g.bg = defaultfg;
  2871. }
  2872. sl = utf8size(g.c);
  2873. xdraws(g.c, g, term.c.x, term.c.y, 1, sl);
  2874. } else {
  2875. XftDrawRect(xw.draw, &dc.col[defaultcs],
  2876. borderpx + term.c.x * xw.cw,
  2877. borderpx + term.c.y * xw.ch,
  2878. xw.cw - 1, 1);
  2879. XftDrawRect(xw.draw, &dc.col[defaultcs],
  2880. borderpx + term.c.x * xw.cw,
  2881. borderpx + term.c.y * xw.ch,
  2882. 1, xw.ch - 1);
  2883. XftDrawRect(xw.draw, &dc.col[defaultcs],
  2884. borderpx + (term.c.x + 1) * xw.cw - 1,
  2885. borderpx + term.c.y * xw.ch,
  2886. 1, xw.ch - 1);
  2887. XftDrawRect(xw.draw, &dc.col[defaultcs],
  2888. borderpx + term.c.x * xw.cw,
  2889. borderpx + (term.c.y + 1) * xw.ch - 1,
  2890. xw.cw, 1);
  2891. }
  2892. oldx = term.c.x, oldy = term.c.y;
  2893. }
  2894. }
  2895. void
  2896. xsettitle(char *p) {
  2897. XTextProperty prop;
  2898. Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle,
  2899. &prop);
  2900. XSetWMName(xw.dpy, xw.win, &prop);
  2901. }
  2902. void
  2903. xresettitle(void) {
  2904. xsettitle(opt_title ? opt_title : "st");
  2905. }
  2906. void
  2907. redraw(int timeout) {
  2908. struct timespec tv = {0, timeout * 1000};
  2909. tfulldirt();
  2910. draw();
  2911. if(timeout > 0) {
  2912. nanosleep(&tv, NULL);
  2913. XSync(xw.dpy, False); /* necessary for a good tput flash */
  2914. }
  2915. }
  2916. void
  2917. draw(void) {
  2918. drawregion(0, 0, term.col, term.row);
  2919. XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, 0, 0, xw.w,
  2920. xw.h, 0, 0);
  2921. XSetForeground(xw.dpy, dc.gc,
  2922. dc.col[IS_SET(MODE_REVERSE)?
  2923. defaultfg : defaultbg].pixel);
  2924. }
  2925. void
  2926. drawregion(int x1, int y1, int x2, int y2) {
  2927. int ic, ib, x, y, ox, sl;
  2928. Glyph base, new;
  2929. char buf[DRAW_BUF_SIZ];
  2930. bool ena_sel = sel.ob.x != -1;
  2931. if(sel.alt ^ IS_SET(MODE_ALTSCREEN))
  2932. ena_sel = 0;
  2933. if(!(xw.state & WIN_VISIBLE))
  2934. return;
  2935. for(y = y1; y < y2; y++) {
  2936. if(!term.dirty[y])
  2937. continue;
  2938. xtermclear(0, y, term.col, y);
  2939. term.dirty[y] = 0;
  2940. base = term.line[y][0];
  2941. ic = ib = ox = 0;
  2942. for(x = x1; x < x2; x++) {
  2943. new = term.line[y][x];
  2944. if(ena_sel && selected(x, y))
  2945. new.mode ^= ATTR_REVERSE;
  2946. if(ib > 0 && (ATTRCMP(base, new)
  2947. || ib >= DRAW_BUF_SIZ-UTF_SIZ)) {
  2948. xdraws(buf, base, ox, y, ic, ib);
  2949. ic = ib = 0;
  2950. }
  2951. if(ib == 0) {
  2952. ox = x;
  2953. base = new;
  2954. }
  2955. sl = utf8size(new.c);
  2956. memcpy(buf+ib, new.c, sl);
  2957. ib += sl;
  2958. ++ic;
  2959. }
  2960. if(ib > 0)
  2961. xdraws(buf, base, ox, y, ic, ib);
  2962. }
  2963. xdrawcursor();
  2964. }
  2965. void
  2966. expose(XEvent *ev) {
  2967. XExposeEvent *e = &ev->xexpose;
  2968. if(xw.state & WIN_REDRAW) {
  2969. if(!e->count)
  2970. xw.state &= ~WIN_REDRAW;
  2971. }
  2972. redraw(0);
  2973. }
  2974. void
  2975. visibility(XEvent *ev) {
  2976. XVisibilityEvent *e = &ev->xvisibility;
  2977. if(e->state == VisibilityFullyObscured) {
  2978. xw.state &= ~WIN_VISIBLE;
  2979. } else if(!(xw.state & WIN_VISIBLE)) {
  2980. /* need a full redraw for next Expose, not just a buf copy */
  2981. xw.state |= WIN_VISIBLE | WIN_REDRAW;
  2982. }
  2983. }
  2984. void
  2985. unmap(XEvent *ev) {
  2986. xw.state &= ~WIN_VISIBLE;
  2987. }
  2988. void
  2989. xsetpointermotion(int set) {
  2990. MODBIT(xw.attrs.event_mask, set, PointerMotionMask);
  2991. XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask, &xw.attrs);
  2992. }
  2993. void
  2994. xseturgency(int add) {
  2995. XWMHints *h = XGetWMHints(xw.dpy, xw.win);
  2996. h->flags = add ? (h->flags | XUrgencyHint) : (h->flags & ~XUrgencyHint);
  2997. XSetWMHints(xw.dpy, xw.win, h);
  2998. XFree(h);
  2999. }
  3000. void
  3001. focus(XEvent *ev) {
  3002. XFocusChangeEvent *e = &ev->xfocus;
  3003. if(e->mode == NotifyGrab)
  3004. return;
  3005. if(ev->type == FocusIn) {
  3006. XSetICFocus(xw.xic);
  3007. xw.state |= WIN_FOCUSED;
  3008. xseturgency(0);
  3009. if(IS_SET(MODE_FOCUS))
  3010. ttywrite("\033[I", 3);
  3011. } else {
  3012. XUnsetICFocus(xw.xic);
  3013. xw.state &= ~WIN_FOCUSED;
  3014. if(IS_SET(MODE_FOCUS))
  3015. ttywrite("\033[O", 3);
  3016. }
  3017. }
  3018. static inline bool
  3019. match(uint mask, uint state) {
  3020. state &= ~ignoremod;
  3021. if(mask == XK_NO_MOD && state)
  3022. return false;
  3023. if(mask != XK_ANY_MOD && mask != XK_NO_MOD && !state)
  3024. return false;
  3025. if(mask == XK_ANY_MOD)
  3026. return true;
  3027. return state == mask;
  3028. }
  3029. void
  3030. numlock(const Arg *dummy) {
  3031. term.numlock ^= 1;
  3032. }
  3033. char*
  3034. kmap(KeySym k, uint state) {
  3035. Key *kp;
  3036. int i;
  3037. /* Check for mapped keys out of X11 function keys. */
  3038. for(i = 0; i < LEN(mappedkeys); i++) {
  3039. if(mappedkeys[i] == k)
  3040. break;
  3041. }
  3042. if(i == LEN(mappedkeys)) {
  3043. if((k & 0xFFFF) < 0xFD00)
  3044. return NULL;
  3045. }
  3046. for(kp = key; kp < key + LEN(key); kp++) {
  3047. if(kp->k != k)
  3048. continue;
  3049. if(!match(kp->mask, state))
  3050. continue;
  3051. if(kp->appkey > 0) {
  3052. if(!IS_SET(MODE_APPKEYPAD))
  3053. continue;
  3054. if(term.numlock && kp->appkey == 2)
  3055. continue;
  3056. } else if(kp->appkey < 0 && IS_SET(MODE_APPKEYPAD)) {
  3057. continue;
  3058. }
  3059. if((kp->appcursor < 0 && IS_SET(MODE_APPCURSOR)) ||
  3060. (kp->appcursor > 0
  3061. && !IS_SET(MODE_APPCURSOR))) {
  3062. continue;
  3063. }
  3064. if((kp->crlf < 0 && IS_SET(MODE_CRLF)) ||
  3065. (kp->crlf > 0 && !IS_SET(MODE_CRLF))) {
  3066. continue;
  3067. }
  3068. return kp->s;
  3069. }
  3070. return NULL;
  3071. }
  3072. void
  3073. kpress(XEvent *ev) {
  3074. XKeyEvent *e = &ev->xkey;
  3075. KeySym ksym;
  3076. char xstr[31], buf[32], *customkey, *cp = buf;
  3077. int len, ret;
  3078. long c;
  3079. Status status;
  3080. Shortcut *bp;
  3081. if(IS_SET(MODE_KBDLOCK))
  3082. return;
  3083. len = XmbLookupString(xw.xic, e, xstr, sizeof(xstr), &ksym, &status);
  3084. e->state &= ~Mod2Mask;
  3085. /* 1. shortcuts */
  3086. for(bp = shortcuts; bp < shortcuts + LEN(shortcuts); bp++) {
  3087. if(ksym == bp->keysym && match(bp->mod, e->state)) {
  3088. bp->func(&(bp->arg));
  3089. return;
  3090. }
  3091. }
  3092. /* 2. custom keys from config.h */
  3093. if((customkey = kmap(ksym, e->state))) {
  3094. len = strlen(customkey);
  3095. memcpy(buf, customkey, len);
  3096. /* 3. hardcoded (overrides X lookup) */
  3097. } else {
  3098. if(len == 0)
  3099. return;
  3100. if(len == 1 && e->state & Mod1Mask) {
  3101. if(IS_SET(MODE_8BIT)) {
  3102. if(*xstr < 0177) {
  3103. c = *xstr | 0x80;
  3104. ret = utf8encode(&c, cp);
  3105. cp += ret;
  3106. len = 0;
  3107. }
  3108. } else {
  3109. *cp++ = '\033';
  3110. }
  3111. }
  3112. memcpy(cp, xstr, len);
  3113. len = cp - buf + len;
  3114. }
  3115. ttywrite(buf, len);
  3116. if(IS_SET(MODE_ECHO))
  3117. techo(buf, len);
  3118. }
  3119. void
  3120. cmessage(XEvent *e) {
  3121. /*
  3122. * See xembed specs
  3123. * http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html
  3124. */
  3125. if(e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
  3126. if(e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
  3127. xw.state |= WIN_FOCUSED;
  3128. xseturgency(0);
  3129. } else if(e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
  3130. xw.state &= ~WIN_FOCUSED;
  3131. }
  3132. } else if(e->xclient.data.l[0] == xw.wmdeletewin) {
  3133. /* Send SIGHUP to shell */
  3134. kill(pid, SIGHUP);
  3135. exit(EXIT_SUCCESS);
  3136. }
  3137. }
  3138. void
  3139. cresize(int width, int height) {
  3140. int col, row;
  3141. if(width != 0)
  3142. xw.w = width;
  3143. if(height != 0)
  3144. xw.h = height;
  3145. col = (xw.w - 2 * borderpx) / xw.cw;
  3146. row = (xw.h - 2 * borderpx) / xw.ch;
  3147. tresize(col, row);
  3148. xresize(col, row);
  3149. ttyresize();
  3150. }
  3151. void
  3152. resize(XEvent *e) {
  3153. if(e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
  3154. return;
  3155. cresize(e->xconfigure.width, e->xconfigure.height);
  3156. }
  3157. void
  3158. run(void) {
  3159. XEvent ev;
  3160. int w = xw.w, h = xw.h;
  3161. fd_set rfd;
  3162. int xfd = XConnectionNumber(xw.dpy), xev, blinkset = 0, dodraw = 0;
  3163. struct timeval drawtimeout, *tv = NULL, now, last, lastblink;
  3164. /* Waiting for window mapping */
  3165. while(1) {
  3166. XNextEvent(xw.dpy, &ev);
  3167. if(ev.type == ConfigureNotify) {
  3168. w = ev.xconfigure.width;
  3169. h = ev.xconfigure.height;
  3170. } else if(ev.type == MapNotify) {
  3171. break;
  3172. }
  3173. }
  3174. if(!xw.isfixed)
  3175. cresize(w, h);
  3176. else
  3177. cresize(xw.fw, xw.fh);
  3178. ttynew();
  3179. gettimeofday(&lastblink, NULL);
  3180. gettimeofday(&last, NULL);
  3181. for(xev = actionfps;;) {
  3182. FD_ZERO(&rfd);
  3183. FD_SET(cmdfd, &rfd);
  3184. FD_SET(xfd, &rfd);
  3185. if(select(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, tv) < 0) {
  3186. if(errno == EINTR)
  3187. continue;
  3188. die("select failed: %s\n", SERRNO);
  3189. }
  3190. if(FD_ISSET(cmdfd, &rfd)) {
  3191. ttyread();
  3192. if(blinktimeout) {
  3193. blinkset = tattrset(ATTR_BLINK);
  3194. if(!blinkset)
  3195. MODBIT(term.mode, 0, MODE_BLINK);
  3196. }
  3197. }
  3198. if(FD_ISSET(xfd, &rfd))
  3199. xev = actionfps;
  3200. gettimeofday(&now, NULL);
  3201. drawtimeout.tv_sec = 0;
  3202. drawtimeout.tv_usec = (1000/xfps) * 1000;
  3203. tv = &drawtimeout;
  3204. dodraw = 0;
  3205. if(blinktimeout && TIMEDIFF(now, lastblink) > blinktimeout) {
  3206. tsetdirtattr(ATTR_BLINK);
  3207. term.mode ^= MODE_BLINK;
  3208. gettimeofday(&lastblink, NULL);
  3209. dodraw = 1;
  3210. }
  3211. if(TIMEDIFF(now, last) \
  3212. > (xev? (1000/xfps) : (1000/actionfps))) {
  3213. dodraw = 1;
  3214. last = now;
  3215. }
  3216. if(dodraw) {
  3217. while(XPending(xw.dpy)) {
  3218. XNextEvent(xw.dpy, &ev);
  3219. if(XFilterEvent(&ev, None))
  3220. continue;
  3221. if(handler[ev.type])
  3222. (handler[ev.type])(&ev);
  3223. }
  3224. draw();
  3225. XFlush(xw.dpy);
  3226. if(xev && !FD_ISSET(xfd, &rfd))
  3227. xev--;
  3228. if(!FD_ISSET(cmdfd, &rfd) && !FD_ISSET(xfd, &rfd)) {
  3229. if(blinkset) {
  3230. if(TIMEDIFF(now, lastblink) \
  3231. > blinktimeout) {
  3232. drawtimeout.tv_usec = 1;
  3233. } else {
  3234. drawtimeout.tv_usec = (1000 * \
  3235. (blinktimeout - \
  3236. TIMEDIFF(now,
  3237. lastblink)));
  3238. }
  3239. } else {
  3240. tv = NULL;
  3241. }
  3242. }
  3243. }
  3244. }
  3245. }
  3246. void
  3247. usage(void) {
  3248. die("%s " VERSION " (c) 2010-2013 st engineers\n" \
  3249. "usage: st [-a] [-v] [-c class] [-f font] [-g geometry] [-o file]" \
  3250. " [-t title] [-w windowid] [-e command ...]\n", argv0);
  3251. }
  3252. int
  3253. main(int argc, char *argv[]) {
  3254. int bitm, xr, yr;
  3255. uint wr, hr;
  3256. char *titles;
  3257. xw.fw = xw.fh = xw.fx = xw.fy = 0;
  3258. xw.isfixed = False;
  3259. ARGBEGIN {
  3260. case 'a':
  3261. allowaltscreen = false;
  3262. break;
  3263. case 'c':
  3264. opt_class = EARGF(usage());
  3265. break;
  3266. case 'e':
  3267. /* eat all remaining arguments */
  3268. if(argc > 1) {
  3269. opt_cmd = &argv[1];
  3270. if(argv[1] != NULL && opt_title == NULL) {
  3271. titles = strdup(argv[1]);
  3272. opt_title = basename(titles);
  3273. }
  3274. }
  3275. goto run;
  3276. case 'f':
  3277. opt_font = EARGF(usage());
  3278. break;
  3279. case 'g':
  3280. bitm = XParseGeometry(EARGF(usage()), &xr, &yr, &wr, &hr);
  3281. if(bitm & XValue)
  3282. xw.fx = xr;
  3283. if(bitm & YValue)
  3284. xw.fy = yr;
  3285. if(bitm & WidthValue)
  3286. xw.fw = (int)wr;
  3287. if(bitm & HeightValue)
  3288. xw.fh = (int)hr;
  3289. if(bitm & XNegative && xw.fx == 0)
  3290. xw.fx = -1;
  3291. if(bitm & XNegative && xw.fy == 0)
  3292. xw.fy = -1;
  3293. if(xw.fh != 0 && xw.fw != 0)
  3294. xw.isfixed = True;
  3295. break;
  3296. case 'o':
  3297. opt_io = EARGF(usage());
  3298. break;
  3299. case 't':
  3300. opt_title = EARGF(usage());
  3301. break;
  3302. case 'w':
  3303. opt_embed = EARGF(usage());
  3304. break;
  3305. case 'v':
  3306. default:
  3307. usage();
  3308. } ARGEND;
  3309. run:
  3310. setlocale(LC_CTYPE, "");
  3311. XSetLocaleModifiers("");
  3312. tnew(80, 24);
  3313. xinit();
  3314. selinit();
  3315. run();
  3316. return 0;
  3317. }