st.c 87 KB

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