st.c 87 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953
  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 << 0,
  80. ATTR_FAINT = 1 << 1,
  81. ATTR_ITALIC = 1 << 2,
  82. ATTR_UNDERLINE = 1 << 3,
  83. ATTR_BLINK = 1 << 4,
  84. ATTR_REVERSE = 1 << 5,
  85. ATTR_INVISIBLE = 1 << 6,
  86. ATTR_STRUCK = 1 << 7,
  87. ATTR_WRAP = 1 << 8,
  88. ATTR_WIDE = 1 << 9,
  89. ATTR_WDUMMY = 1 << 10,
  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 << 0,
  102. MODE_INSERT = 1 << 1,
  103. MODE_APPKEYPAD = 1 << 2,
  104. MODE_ALTSCREEN = 1 << 3,
  105. MODE_CRLF = 1 << 4,
  106. MODE_MOUSEBTN = 1 << 5,
  107. MODE_MOUSEMOTION = 1 << 6,
  108. MODE_REVERSE = 1 << 7,
  109. MODE_KBDLOCK = 1 << 8,
  110. MODE_HIDE = 1 << 9,
  111. MODE_ECHO = 1 << 10,
  112. MODE_APPCURSOR = 1 << 11,
  113. MODE_MOUSESGR = 1 << 12,
  114. MODE_8BIT = 1 << 13,
  115. MODE_BLINK = 1 << 14,
  116. MODE_FBLINK = 1 << 15,
  117. MODE_FOCUS = 1 << 16,
  118. MODE_MOUSEX10 = 1 << 17,
  119. MODE_MOUSEMANY = 1 << 18,
  120. MODE_BRCKTPASTE = 1 << 19,
  121. MODE_PRINT = 1 << 20,
  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 int eschandle(uchar ascii);
  319. static void strdump(void);
  320. static void strhandle(void);
  321. static void strparse(void);
  322. static void strreset(void);
  323. static int tattrset(int);
  324. static void tprinter(char *, size_t);
  325. static void tdumpsel(void);
  326. static void tdumpline(int);
  327. static void tdump(void);
  328. static void tclearregion(int, int, int, int);
  329. static void tcursor(int);
  330. static void tdeletechar(int);
  331. static void tdeleteline(int);
  332. static void tinsertblank(int);
  333. static void tinsertblankline(int);
  334. static int tlinelen(int);
  335. static void tmoveto(int, int);
  336. static void tmoveato(int, int);
  337. static void tnew(int, int);
  338. static void tnewline(int);
  339. static void tputtab(int);
  340. static void tputc(char *, int);
  341. static void treset(void);
  342. static void tresize(int, int);
  343. static void tscrollup(int, int);
  344. static void tscrolldown(int, int);
  345. static void tsetattr(int *, int);
  346. static void tsetchar(char *, Glyph *, int, int);
  347. static void tsetscroll(int, int);
  348. static void tswapscreen(void);
  349. static void tsetdirt(int, int);
  350. static void tsetdirtattr(int);
  351. static void tsetmode(bool, bool, int *, int);
  352. static void tfulldirt(void);
  353. static void techo(char *, int);
  354. static void tcontrolcode(uchar );
  355. static void tdectest(char );
  356. static int32_t tdefcolor(int *, int *, int);
  357. static void tdeftran(char);
  358. static inline bool match(uint, uint);
  359. static void ttynew(void);
  360. static void ttyread(void);
  361. static void ttyresize(void);
  362. static void ttysend(char *, size_t);
  363. static void ttywrite(const char *, size_t);
  364. static void tstrsequence(uchar c);
  365. static void xdraws(char *, Glyph, int, int, int, int);
  366. static void xhints(void);
  367. static void xclear(int, int, int, int);
  368. static void xdrawcursor(void);
  369. static void xinit(void);
  370. static void xloadcols(void);
  371. static int xsetcolorname(int, const char *);
  372. static int xgeommasktogravity(int);
  373. static int xloadfont(Font *, FcPattern *);
  374. static void xloadfonts(char *, double);
  375. static int xloadfontset(Font *);
  376. static void xsettitle(char *);
  377. static void xresettitle(void);
  378. static void xsetpointermotion(int);
  379. static void xseturgency(int);
  380. static void xsetsel(char *);
  381. static void xtermclear(int, int, int, int);
  382. static void xunloadfont(Font *);
  383. static void xunloadfonts(void);
  384. static void xresize(int, int);
  385. static void expose(XEvent *);
  386. static void visibility(XEvent *);
  387. static void unmap(XEvent *);
  388. static char *kmap(KeySym, uint);
  389. static void kpress(XEvent *);
  390. static void cmessage(XEvent *);
  391. static void cresize(int, int);
  392. static void resize(XEvent *);
  393. static void focus(XEvent *);
  394. static void brelease(XEvent *);
  395. static void bpress(XEvent *);
  396. static void bmotion(XEvent *);
  397. static void selnotify(XEvent *);
  398. static void selclear(XEvent *);
  399. static void selrequest(XEvent *);
  400. static void selinit(void);
  401. static void selnormalize(void);
  402. static inline bool selected(int, int);
  403. static char *getsel(void);
  404. static void selcopy(void);
  405. static void selscroll(int, int);
  406. static void selsnap(int, int *, int *, int);
  407. static void getbuttoninfo(XEvent *);
  408. static void mousereport(XEvent *);
  409. static size_t utf8decode(char *, long *, size_t);
  410. static long utf8decodebyte(char, size_t *);
  411. static size_t utf8encode(long, char *, size_t);
  412. static char utf8encodebyte(long, size_t);
  413. static size_t utf8len(char *);
  414. static size_t utf8validate(long *, size_t);
  415. static ssize_t xwrite(int, const char *, size_t);
  416. static void *xmalloc(size_t);
  417. static void *xrealloc(void *, size_t);
  418. static char *xstrdup(char *);
  419. static void usage(void);
  420. static void (*handler[LASTEvent])(XEvent *) = {
  421. [KeyPress] = kpress,
  422. [ClientMessage] = cmessage,
  423. [ConfigureNotify] = resize,
  424. [VisibilityNotify] = visibility,
  425. [UnmapNotify] = unmap,
  426. [Expose] = expose,
  427. [FocusIn] = focus,
  428. [FocusOut] = focus,
  429. [MotionNotify] = bmotion,
  430. [ButtonPress] = bpress,
  431. [ButtonRelease] = brelease,
  432. [SelectionClear] = selclear,
  433. [SelectionNotify] = selnotify,
  434. [SelectionRequest] = selrequest,
  435. };
  436. /* Globals */
  437. static DC dc;
  438. static XWindow xw;
  439. static Term term;
  440. static CSIEscape csiescseq;
  441. static STREscape strescseq;
  442. static int cmdfd;
  443. static pid_t pid;
  444. static Selection sel;
  445. static int iofd = STDOUT_FILENO;
  446. static char **opt_cmd = NULL;
  447. static char *opt_io = NULL;
  448. static char *opt_title = NULL;
  449. static char *opt_embed = NULL;
  450. static char *opt_class = NULL;
  451. static char *opt_font = NULL;
  452. static int oldbutton = 3; /* button event on startup: 3 = release */
  453. static char *usedfont = NULL;
  454. static double usedfontsize = 0;
  455. static uchar utfbyte[UTF_SIZ + 1] = {0x80, 0, 0xC0, 0xE0, 0xF0};
  456. static uchar utfmask[UTF_SIZ + 1] = {0xC0, 0x80, 0xE0, 0xF0, 0xF8};
  457. static long utfmin[UTF_SIZ + 1] = { 0, 0, 0x80, 0x800, 0x10000};
  458. static long utfmax[UTF_SIZ + 1] = {0x10FFFF, 0x7F, 0x7FF, 0xFFFF, 0x10FFFF};
  459. /* Font Ring Cache */
  460. enum {
  461. FRC_NORMAL,
  462. FRC_ITALIC,
  463. FRC_BOLD,
  464. FRC_ITALICBOLD
  465. };
  466. typedef struct {
  467. XftFont *font;
  468. int flags;
  469. } Fontcache;
  470. /* Fontcache is an array now. A new font will be appended to the array. */
  471. static Fontcache frc[16];
  472. static int frclen = 0;
  473. ssize_t
  474. xwrite(int fd, const char *s, size_t len) {
  475. size_t aux = len;
  476. while(len > 0) {
  477. ssize_t r = write(fd, s, len);
  478. if(r < 0)
  479. return r;
  480. len -= r;
  481. s += r;
  482. }
  483. return aux;
  484. }
  485. void *
  486. xmalloc(size_t len) {
  487. void *p = malloc(len);
  488. if(!p)
  489. die("Out of memory\n");
  490. return p;
  491. }
  492. void *
  493. xrealloc(void *p, size_t len) {
  494. if((p = realloc(p, len)) == NULL)
  495. die("Out of memory\n");
  496. return p;
  497. }
  498. char *
  499. xstrdup(char *s) {
  500. if((s = strdup(s)) == NULL)
  501. die("Out of memory\n");
  502. return s;
  503. }
  504. size_t
  505. utf8decode(char *c, long *u, size_t clen) {
  506. size_t i, j, len, type;
  507. long udecoded;
  508. *u = UTF_INVALID;
  509. if(!clen)
  510. return 0;
  511. udecoded = utf8decodebyte(c[0], &len);
  512. if(!BETWEEN(len, 1, UTF_SIZ))
  513. return 1;
  514. for(i = 1, j = 1; i < clen && j < len; ++i, ++j) {
  515. udecoded = (udecoded << 6) | utf8decodebyte(c[i], &type);
  516. if(type != 0)
  517. return j;
  518. }
  519. if(j < len)
  520. return 0;
  521. *u = udecoded;
  522. utf8validate(u, len);
  523. return len;
  524. }
  525. long
  526. utf8decodebyte(char c, size_t *i) {
  527. for(*i = 0; *i < LEN(utfmask); ++(*i))
  528. if(((uchar)c & utfmask[*i]) == utfbyte[*i])
  529. return (uchar)c & ~utfmask[*i];
  530. return 0;
  531. }
  532. size_t
  533. utf8encode(long u, char *c, size_t clen) {
  534. size_t len, i;
  535. len = utf8validate(&u, 0);
  536. if(clen < len)
  537. return 0;
  538. for(i = len - 1; i != 0; --i) {
  539. c[i] = utf8encodebyte(u, 0);
  540. u >>= 6;
  541. }
  542. c[0] = utf8encodebyte(u, len);
  543. return len;
  544. }
  545. char
  546. utf8encodebyte(long u, size_t i) {
  547. return utfbyte[i] | (u & ~utfmask[i]);
  548. }
  549. size_t
  550. utf8len(char *c) {
  551. return utf8decode(c, &(long){0}, UTF_SIZ);
  552. }
  553. size_t
  554. utf8validate(long *u, size_t i) {
  555. if(!BETWEEN(*u, utfmin[i], utfmax[i]) || BETWEEN(*u, 0xD800, 0xDFFF))
  556. *u = UTF_INVALID;
  557. for(i = 1; *u > utfmax[i]; ++i)
  558. ;
  559. return i;
  560. }
  561. static void
  562. selinit(void) {
  563. memset(&sel.tclick1, 0, sizeof(sel.tclick1));
  564. memset(&sel.tclick2, 0, sizeof(sel.tclick2));
  565. sel.mode = 0;
  566. sel.ob.x = -1;
  567. sel.clip = NULL;
  568. sel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0);
  569. if(sel.xtarget == None)
  570. sel.xtarget = XA_STRING;
  571. }
  572. static int
  573. x2col(int x) {
  574. x -= borderpx;
  575. x /= xw.cw;
  576. return LIMIT(x, 0, term.col-1);
  577. }
  578. static int
  579. y2row(int y) {
  580. y -= borderpx;
  581. y /= xw.ch;
  582. return LIMIT(y, 0, term.row-1);
  583. }
  584. static int tlinelen(int y) {
  585. int i = term.col;
  586. while (i > 0 && term.line[y][i - 1].c[0] == ' ')
  587. --i;
  588. return i;
  589. }
  590. static void
  591. selnormalize(void) {
  592. int i;
  593. if(sel.ob.y == sel.oe.y || sel.type == SEL_RECTANGULAR) {
  594. sel.nb.x = MIN(sel.ob.x, sel.oe.x);
  595. sel.ne.x = MAX(sel.ob.x, sel.oe.x);
  596. } else {
  597. sel.nb.x = sel.ob.y < sel.oe.y ? sel.ob.x : sel.oe.x;
  598. sel.ne.x = sel.ob.y < sel.oe.y ? sel.oe.x : sel.ob.x;
  599. }
  600. sel.nb.y = MIN(sel.ob.y, sel.oe.y);
  601. sel.ne.y = MAX(sel.ob.y, sel.oe.y);
  602. selsnap(sel.snap, &sel.nb.x, &sel.nb.y, -1);
  603. selsnap(sel.snap, &sel.ne.x, &sel.ne.y, +1);
  604. /* expand selection over line breaks */
  605. if (sel.type == SEL_RECTANGULAR)
  606. return;
  607. i = tlinelen(sel.nb.y);
  608. if (i < sel.nb.x)
  609. sel.nb.x = i;
  610. if (tlinelen(sel.ne.y) <= sel.ne.x)
  611. sel.ne.x = term.col - 1;
  612. }
  613. static inline bool
  614. selected(int x, int y) {
  615. if(sel.type == SEL_RECTANGULAR)
  616. return BETWEEN(y, sel.nb.y, sel.ne.y)
  617. && BETWEEN(x, sel.nb.x, sel.ne.x);
  618. return BETWEEN(y, sel.nb.y, sel.ne.y)
  619. && (y != sel.nb.y || x >= sel.nb.x)
  620. && (y != sel.ne.y || x <= sel.ne.x);
  621. }
  622. void
  623. selsnap(int mode, int *x, int *y, int direction) {
  624. int newx, newy, xt, yt;
  625. bool delim, prevdelim;
  626. Glyph *gp, *prevgp;
  627. switch(mode) {
  628. case SNAP_WORD:
  629. /*
  630. * Snap around if the word wraps around at the end or
  631. * beginning of a line.
  632. */
  633. prevgp = &term.line[*y][*x];
  634. prevdelim = strchr(worddelimiters, prevgp->c[0]) != NULL;
  635. for(;;) {
  636. newx = *x + direction;
  637. newy = *y;
  638. if(!BETWEEN(newx, 0, term.col - 1)) {
  639. newy += direction;
  640. newx = (newx + term.col) % term.col;
  641. if (!BETWEEN(newy, 0, term.row - 1))
  642. break;
  643. if(direction > 0)
  644. yt = *y, xt = *x;
  645. else
  646. yt = newy, xt = newx;
  647. if(!(term.line[yt][xt].mode & ATTR_WRAP))
  648. break;
  649. }
  650. if (newx >= tlinelen(newy))
  651. break;
  652. gp = &term.line[newy][newx];
  653. delim = strchr(worddelimiters, gp->c[0]) != NULL;
  654. if(!(gp->mode & ATTR_WDUMMY) && (delim != prevdelim
  655. || (delim && gp->c[0] != prevgp->c[0])))
  656. break;
  657. *x = newx;
  658. *y = newy;
  659. prevgp = gp;
  660. prevdelim = delim;
  661. }
  662. break;
  663. case SNAP_LINE:
  664. /*
  665. * Snap around if the the previous line or the current one
  666. * has set ATTR_WRAP at its end. Then the whole next or
  667. * previous line will be selected.
  668. */
  669. *x = (direction < 0) ? 0 : term.col - 1;
  670. if(direction < 0 && *y > 0) {
  671. for(; *y > 0; *y += direction) {
  672. if(!(term.line[*y-1][term.col-1].mode
  673. & ATTR_WRAP)) {
  674. break;
  675. }
  676. }
  677. } else if(direction > 0 && *y < term.row-1) {
  678. for(; *y < term.row; *y += direction) {
  679. if(!(term.line[*y][term.col-1].mode
  680. & ATTR_WRAP)) {
  681. break;
  682. }
  683. }
  684. }
  685. break;
  686. }
  687. }
  688. void
  689. getbuttoninfo(XEvent *e) {
  690. int type;
  691. uint state = e->xbutton.state & ~(Button1Mask | forceselmod);
  692. sel.alt = IS_SET(MODE_ALTSCREEN);
  693. sel.oe.x = x2col(e->xbutton.x);
  694. sel.oe.y = y2row(e->xbutton.y);
  695. selnormalize();
  696. sel.type = SEL_REGULAR;
  697. for(type = 1; type < LEN(selmasks); ++type) {
  698. if(match(selmasks[type], state)) {
  699. sel.type = type;
  700. break;
  701. }
  702. }
  703. }
  704. void
  705. mousereport(XEvent *e) {
  706. int x = x2col(e->xbutton.x), y = y2row(e->xbutton.y),
  707. button = e->xbutton.button, state = e->xbutton.state,
  708. len;
  709. char buf[40];
  710. static int ox, oy;
  711. /* from urxvt */
  712. if(e->xbutton.type == MotionNotify) {
  713. if(x == ox && y == oy)
  714. return;
  715. if(!IS_SET(MODE_MOUSEMOTION) && !IS_SET(MODE_MOUSEMANY))
  716. return;
  717. /* MOUSE_MOTION: no reporting if no button is pressed */
  718. if(IS_SET(MODE_MOUSEMOTION) && oldbutton == 3)
  719. return;
  720. button = oldbutton + 32;
  721. ox = x;
  722. oy = y;
  723. } else {
  724. if(!IS_SET(MODE_MOUSESGR) && e->xbutton.type == ButtonRelease) {
  725. button = 3;
  726. } else {
  727. button -= Button1;
  728. if(button >= 3)
  729. button += 64 - 3;
  730. }
  731. if(e->xbutton.type == ButtonPress) {
  732. oldbutton = button;
  733. ox = x;
  734. oy = y;
  735. } else if(e->xbutton.type == ButtonRelease) {
  736. oldbutton = 3;
  737. /* MODE_MOUSEX10: no button release reporting */
  738. if(IS_SET(MODE_MOUSEX10))
  739. return;
  740. if (button == 64 || button == 65)
  741. return;
  742. }
  743. }
  744. if(!IS_SET(MODE_MOUSEX10)) {
  745. button += (state & ShiftMask ? 4 : 0)
  746. + (state & Mod4Mask ? 8 : 0)
  747. + (state & ControlMask ? 16 : 0);
  748. }
  749. len = 0;
  750. if(IS_SET(MODE_MOUSESGR)) {
  751. len = snprintf(buf, sizeof(buf), "\033[<%d;%d;%d%c",
  752. button, x+1, y+1,
  753. e->xbutton.type == ButtonRelease ? 'm' : 'M');
  754. } else if(x < 223 && y < 223) {
  755. len = snprintf(buf, sizeof(buf), "\033[M%c%c%c",
  756. 32+button, 32+x+1, 32+y+1);
  757. } else {
  758. return;
  759. }
  760. ttywrite(buf, len);
  761. }
  762. void
  763. bpress(XEvent *e) {
  764. struct timespec now;
  765. Mousekey *mk;
  766. if(IS_SET(MODE_MOUSE) && !(e->xbutton.state & forceselmod)) {
  767. mousereport(e);
  768. return;
  769. }
  770. for(mk = mshortcuts; mk < mshortcuts + LEN(mshortcuts); mk++) {
  771. if(e->xbutton.button == mk->b
  772. && match(mk->mask, e->xbutton.state)) {
  773. ttysend(mk->s, strlen(mk->s));
  774. return;
  775. }
  776. }
  777. if(e->xbutton.button == Button1) {
  778. clock_gettime(CLOCK_MONOTONIC, &now);
  779. /* Clear previous selection, logically and visually. */
  780. selclear(NULL);
  781. sel.mode = 1;
  782. sel.type = SEL_REGULAR;
  783. sel.oe.x = sel.ob.x = x2col(e->xbutton.x);
  784. sel.oe.y = sel.ob.y = y2row(e->xbutton.y);
  785. /*
  786. * If the user clicks below predefined timeouts specific
  787. * snapping behaviour is exposed.
  788. */
  789. if(TIMEDIFF(now, sel.tclick2) <= tripleclicktimeout) {
  790. sel.snap = SNAP_LINE;
  791. } else if(TIMEDIFF(now, sel.tclick1) <= doubleclicktimeout) {
  792. sel.snap = SNAP_WORD;
  793. } else {
  794. sel.snap = 0;
  795. }
  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. tdectest(char c) {
  2092. static char E[UTF_SIZ] = "E";
  2093. int x, y;
  2094. if(c == '8') { /* DEC screen alignment test. */
  2095. for(x = 0; x < term.col; ++x) {
  2096. for(y = 0; y < term.row; ++y)
  2097. tsetchar(E, &term.c.attr, x, y);
  2098. }
  2099. }
  2100. }
  2101. void
  2102. tstrsequence(uchar c) {
  2103. if (c & 0x80) {
  2104. switch (c) {
  2105. case 0x90: /* DCS -- Device Control String */
  2106. c = 'P';
  2107. break;
  2108. case 0x9f: /* APC -- Application Program Command */
  2109. c = '_';
  2110. break;
  2111. case 0x9e: /* PM -- Privacy Message */
  2112. c = '^';
  2113. break;
  2114. case 0x9d: /* OSC -- Operating System Command */
  2115. c = ']';
  2116. break;
  2117. }
  2118. }
  2119. strreset();
  2120. strescseq.type = c;
  2121. term.esc |= ESC_STR;
  2122. return;
  2123. }
  2124. void
  2125. tcontrolcode(uchar ascii) {
  2126. static char question[UTF_SIZ] = "?";
  2127. switch(ascii) {
  2128. case '\t': /* HT */
  2129. tputtab(1);
  2130. return;
  2131. case '\b': /* BS */
  2132. tmoveto(term.c.x-1, term.c.y);
  2133. return;
  2134. case '\r': /* CR */
  2135. tmoveto(0, term.c.y);
  2136. return;
  2137. case '\f': /* LF */
  2138. case '\v': /* VT */
  2139. case '\n': /* LF */
  2140. /* go to first col if the mode is set */
  2141. tnewline(IS_SET(MODE_CRLF));
  2142. return;
  2143. case '\a': /* BEL */
  2144. if(term.esc & ESC_STR_END) {
  2145. /* backwards compatibility to xterm */
  2146. strhandle();
  2147. } else {
  2148. if(!(xw.state & WIN_FOCUSED))
  2149. xseturgency(1);
  2150. if (bellvolume)
  2151. XBell(xw.dpy, bellvolume);
  2152. }
  2153. break;
  2154. case '\033': /* ESC */
  2155. csireset();
  2156. term.esc &= ~(ESC_CSI|ESC_ALTCHARSET|ESC_TEST);
  2157. term.esc |= ESC_START;
  2158. return;
  2159. case '\016': /* SO */
  2160. term.charset = 0;
  2161. return;
  2162. case '\017': /* SI */
  2163. term.charset = 1;
  2164. return;
  2165. case '\032': /* SUB */
  2166. tsetchar(question, &term.c.attr, term.c.x, term.c.y);
  2167. case '\030': /* CAN */
  2168. csireset();
  2169. break;
  2170. case '\005': /* ENQ (IGNORED) */
  2171. case '\000': /* NUL (IGNORED) */
  2172. case '\021': /* XON (IGNORED) */
  2173. case '\023': /* XOFF (IGNORED) */
  2174. case 0177: /* DEL (IGNORED) */
  2175. return;
  2176. case 0x84: /* TODO: IND */
  2177. break;
  2178. case 0x85: /* NEL -- Next line */
  2179. tnewline(1); /* always go to first col */
  2180. break;
  2181. case 0x88: /* HTS -- Horizontal tab stop */
  2182. term.tabs[term.c.x] = 1;
  2183. break;
  2184. case 0x8d: /* TODO: RI */
  2185. case 0x8e: /* TODO: SS2 */
  2186. case 0x8f: /* TODO: SS3 */
  2187. case 0x98: /* TODO: SOS */
  2188. break;
  2189. case 0x9a: /* DECID -- Identify Terminal */
  2190. ttywrite(vtiden, sizeof(vtiden) - 1);
  2191. break;
  2192. case 0x9b: /* TODO: CSI */
  2193. case 0x9c: /* TODO: ST */
  2194. break;
  2195. case 0x90: /* DCS -- Device Control String */
  2196. case 0x9f: /* APC -- Application Program Command */
  2197. case 0x9e: /* PM -- Privacy Message */
  2198. case 0x9d: /* OSC -- Operating System Command */
  2199. tstrsequence(ascii);
  2200. return;
  2201. }
  2202. /* only CAN, SUB, \a and C1 chars interrupt a sequence */
  2203. term.esc &= ~(ESC_STR_END|ESC_STR);
  2204. return;
  2205. }
  2206. /*
  2207. * returns 1 when the sequence is finished and it hasn't to read
  2208. * more characters for this sequence, otherwise 0
  2209. */
  2210. int
  2211. eschandle(uchar ascii) {
  2212. switch(ascii) {
  2213. case '[':
  2214. term.esc |= ESC_CSI;
  2215. return 0;
  2216. case '#':
  2217. term.esc |= ESC_TEST;
  2218. return 0;
  2219. case 'P': /* DCS -- Device Control String */
  2220. case '_': /* APC -- Application Program Command */
  2221. case '^': /* PM -- Privacy Message */
  2222. case ']': /* OSC -- Operating System Command */
  2223. case 'k': /* old title set compatibility */
  2224. tstrsequence(ascii);
  2225. return 0;
  2226. case '(': /* set primary charset G0 */
  2227. case ')': /* set secondary charset G1 */
  2228. case '*': /* set tertiary charset G2 */
  2229. case '+': /* set quaternary charset G3 */
  2230. term.icharset = ascii - '(';
  2231. term.esc |= ESC_ALTCHARSET;
  2232. return 0;
  2233. case 'D': /* IND -- Linefeed */
  2234. if(term.c.y == term.bot) {
  2235. tscrollup(term.top, 1);
  2236. } else {
  2237. tmoveto(term.c.x, term.c.y+1);
  2238. }
  2239. break;
  2240. case 'E': /* NEL -- Next line */
  2241. tnewline(1); /* always go to first col */
  2242. break;
  2243. case 'H': /* HTS -- Horizontal tab stop */
  2244. term.tabs[term.c.x] = 1;
  2245. break;
  2246. case 'M': /* RI -- Reverse index */
  2247. if(term.c.y == term.top) {
  2248. tscrolldown(term.top, 1);
  2249. } else {
  2250. tmoveto(term.c.x, term.c.y-1);
  2251. }
  2252. break;
  2253. case 'Z': /* DECID -- Identify Terminal */
  2254. ttywrite(vtiden, sizeof(vtiden) - 1);
  2255. break;
  2256. case 'c': /* RIS -- Reset to inital state */
  2257. treset();
  2258. xresettitle();
  2259. xloadcols();
  2260. break;
  2261. case '=': /* DECPAM -- Application keypad */
  2262. term.mode |= MODE_APPKEYPAD;
  2263. break;
  2264. case '>': /* DECPNM -- Normal keypad */
  2265. term.mode &= ~MODE_APPKEYPAD;
  2266. break;
  2267. case '7': /* DECSC -- Save Cursor */
  2268. tcursor(CURSOR_SAVE);
  2269. break;
  2270. case '8': /* DECRC -- Restore Cursor */
  2271. tcursor(CURSOR_LOAD);
  2272. break;
  2273. case '\\': /* ST -- String Terminator */
  2274. if(term.esc & ESC_STR_END)
  2275. strhandle();
  2276. break;
  2277. default:
  2278. fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n",
  2279. (uchar) ascii, isprint(ascii)? ascii:'.');
  2280. break;
  2281. }
  2282. return 1;
  2283. }
  2284. void
  2285. tputc(char *c, int len) {
  2286. uchar ascii;
  2287. bool control;
  2288. long unicodep;
  2289. int width;
  2290. Glyph *gp;
  2291. if(len == 1) {
  2292. width = 1;
  2293. unicodep = ascii = *c;
  2294. } else {
  2295. utf8decode(c, &unicodep, UTF_SIZ);
  2296. width = wcwidth(unicodep);
  2297. control = ISCONTROLC1(unicodep);
  2298. ascii = unicodep;
  2299. }
  2300. if(IS_SET(MODE_PRINT))
  2301. tprinter(c, len);
  2302. control = ISCONTROL(unicodep);
  2303. /*
  2304. * STR sequence must be checked before anything else
  2305. * because it uses all following characters until it
  2306. * receives a ESC, a SUB, a ST or any other C1 control
  2307. * character.
  2308. */
  2309. if(term.esc & ESC_STR) {
  2310. if(width == 1 &&
  2311. (ascii == '\a' || ascii == 030 ||
  2312. ascii == 032 || ascii == 033 ||
  2313. ISCONTROLC1(unicodep))) {
  2314. term.esc &= ~(ESC_START|ESC_STR);
  2315. term.esc |= ESC_STR_END;
  2316. } else if(strescseq.len + len < sizeof(strescseq.buf) - 1) {
  2317. memmove(&strescseq.buf[strescseq.len], c, len);
  2318. strescseq.len += len;
  2319. return;
  2320. } else {
  2321. /*
  2322. * Here is a bug in terminals. If the user never sends
  2323. * some code to stop the str or esc command, then st
  2324. * will stop responding. But this is better than
  2325. * silently failing with unknown characters. At least
  2326. * then users will report back.
  2327. *
  2328. * In the case users ever get fixed, here is the code:
  2329. */
  2330. /*
  2331. * term.esc = 0;
  2332. * strhandle();
  2333. */
  2334. return;
  2335. }
  2336. }
  2337. /*
  2338. * Actions of control codes must be performed as soon they arrive
  2339. * because they can be embedded inside a control sequence, and
  2340. * they must not cause conflicts with sequences.
  2341. */
  2342. if(control) {
  2343. tcontrolcode(ascii);
  2344. /*
  2345. * control codes are not shown ever
  2346. */
  2347. return;
  2348. } else if(term.esc & ESC_START) {
  2349. if(term.esc & ESC_CSI) {
  2350. csiescseq.buf[csiescseq.len++] = ascii;
  2351. if(BETWEEN(ascii, 0x40, 0x7E)
  2352. || csiescseq.len >= \
  2353. sizeof(csiescseq.buf)-1) {
  2354. term.esc = 0;
  2355. csiparse();
  2356. csihandle();
  2357. }
  2358. return;
  2359. } else if(term.esc & ESC_ALTCHARSET) {
  2360. tdeftran(ascii);
  2361. } else if(term.esc & ESC_TEST) {
  2362. tdectest(ascii);
  2363. } else {
  2364. if (!eschandle(ascii))
  2365. return;
  2366. /* sequence already finished */
  2367. }
  2368. term.esc = 0;
  2369. /*
  2370. * All characters which form part of a sequence are not
  2371. * printed
  2372. */
  2373. return;
  2374. }
  2375. if(sel.ob.x != -1 && BETWEEN(term.c.y, sel.ob.y, sel.oe.y))
  2376. selclear(NULL);
  2377. gp = &term.line[term.c.y][term.c.x];
  2378. if(IS_SET(MODE_WRAP) && (term.c.state & CURSOR_WRAPNEXT)) {
  2379. gp->mode |= ATTR_WRAP;
  2380. tnewline(1);
  2381. }
  2382. if(IS_SET(MODE_INSERT) && term.c.x+1 < term.col)
  2383. memmove(gp+1, gp, (term.col - term.c.x - 1) * sizeof(Glyph));
  2384. if(term.c.x+width > term.col)
  2385. tnewline(1);
  2386. tsetchar(c, &term.c.attr, term.c.x, term.c.y);
  2387. if(width == 2) {
  2388. gp->mode |= ATTR_WIDE;
  2389. if(term.c.x+1 < term.col) {
  2390. gp[1].c[0] = '\0';
  2391. gp[1].mode = ATTR_WDUMMY;
  2392. }
  2393. }
  2394. if(term.c.x+width < term.col) {
  2395. tmoveto(term.c.x+width, term.c.y);
  2396. } else {
  2397. term.c.state |= CURSOR_WRAPNEXT;
  2398. }
  2399. }
  2400. void
  2401. tresize(int col, int row) {
  2402. int i;
  2403. int minrow = MIN(row, term.row);
  2404. int mincol = MIN(col, term.col);
  2405. int slide = term.c.y - row + 1;
  2406. bool *bp;
  2407. TCursor c;
  2408. if(col < 1 || row < 1) {
  2409. fprintf(stderr,
  2410. "tresize: error resizing to %dx%d\n", col, row);
  2411. return;
  2412. }
  2413. /* free unneeded rows */
  2414. i = 0;
  2415. if(slide > 0) {
  2416. /*
  2417. * slide screen to keep cursor where we expect it -
  2418. * tscrollup would work here, but we can optimize to
  2419. * memmove because we're freeing the earlier lines
  2420. */
  2421. for(/* i = 0 */; i < slide; i++) {
  2422. free(term.line[i]);
  2423. free(term.alt[i]);
  2424. }
  2425. memmove(term.line, term.line + slide, row * sizeof(Line));
  2426. memmove(term.alt, term.alt + slide, row * sizeof(Line));
  2427. }
  2428. for(i += row; i < term.row; i++) {
  2429. free(term.line[i]);
  2430. free(term.alt[i]);
  2431. }
  2432. /* resize to new height */
  2433. term.line = xrealloc(term.line, row * sizeof(Line));
  2434. term.alt = xrealloc(term.alt, row * sizeof(Line));
  2435. term.dirty = xrealloc(term.dirty, row * sizeof(*term.dirty));
  2436. term.tabs = xrealloc(term.tabs, col * sizeof(*term.tabs));
  2437. /* resize each row to new width, zero-pad if needed */
  2438. for(i = 0; i < minrow; i++) {
  2439. term.line[i] = xrealloc(term.line[i], col * sizeof(Glyph));
  2440. term.alt[i] = xrealloc(term.alt[i], col * sizeof(Glyph));
  2441. }
  2442. /* allocate any new rows */
  2443. for(/* i == minrow */; i < row; i++) {
  2444. term.line[i] = xmalloc(col * sizeof(Glyph));
  2445. term.alt[i] = xmalloc(col * sizeof(Glyph));
  2446. }
  2447. if(col > term.col) {
  2448. bp = term.tabs + term.col;
  2449. memset(bp, 0, sizeof(*term.tabs) * (col - term.col));
  2450. while(--bp > term.tabs && !*bp)
  2451. /* nothing */ ;
  2452. for(bp += tabspaces; bp < term.tabs + col; bp += tabspaces)
  2453. *bp = 1;
  2454. }
  2455. /* update terminal size */
  2456. term.col = col;
  2457. term.row = row;
  2458. /* reset scrolling region */
  2459. tsetscroll(0, row-1);
  2460. /* make use of the LIMIT in tmoveto */
  2461. tmoveto(term.c.x, term.c.y);
  2462. /* Clearing both screens (it makes dirty all lines) */
  2463. c = term.c;
  2464. for(i = 0; i < 2; i++) {
  2465. if(mincol < col && 0 < minrow) {
  2466. tclearregion(mincol, 0, col - 1, minrow - 1);
  2467. }
  2468. if(0 < col && minrow < row) {
  2469. tclearregion(0, minrow, col - 1, row - 1);
  2470. }
  2471. tswapscreen();
  2472. tcursor(CURSOR_LOAD);
  2473. }
  2474. term.c = c;
  2475. }
  2476. void
  2477. xresize(int col, int row) {
  2478. xw.tw = MAX(1, col * xw.cw);
  2479. xw.th = MAX(1, row * xw.ch);
  2480. XFreePixmap(xw.dpy, xw.buf);
  2481. xw.buf = XCreatePixmap(xw.dpy, xw.win, xw.w, xw.h,
  2482. DefaultDepth(xw.dpy, xw.scr));
  2483. XftDrawChange(xw.draw, xw.buf);
  2484. xclear(0, 0, xw.w, xw.h);
  2485. }
  2486. static inline ushort
  2487. sixd_to_16bit(int x) {
  2488. return x == 0 ? 0 : 0x3737 + 0x2828 * x;
  2489. }
  2490. void
  2491. xloadcols(void) {
  2492. int i;
  2493. XRenderColor color = { .alpha = 0xffff };
  2494. static bool loaded;
  2495. Color *cp;
  2496. if(loaded) {
  2497. for (cp = dc.col; cp < dc.col + LEN(dc.col); ++cp)
  2498. XftColorFree(xw.dpy, xw.vis, xw.cmap, cp);
  2499. }
  2500. /* load colors [0-15] and [256-LEN(colorname)] (config.h) */
  2501. for(i = 0; i < LEN(colorname); i++) {
  2502. if(!colorname[i])
  2503. continue;
  2504. if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, colorname[i], &dc.col[i])) {
  2505. die("Could not allocate color '%s'\n", colorname[i]);
  2506. }
  2507. }
  2508. /* load colors [16-231] ; same colors as xterm */
  2509. for(i = 16; i < 6*6*6+16; i++) {
  2510. color.red = sixd_to_16bit( ((i-16)/36)%6 );
  2511. color.green = sixd_to_16bit( ((i-16)/6) %6 );
  2512. color.blue = sixd_to_16bit( ((i-16)/1) %6 );
  2513. if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &dc.col[i]))
  2514. die("Could not allocate color %d\n", i);
  2515. }
  2516. /* load colors [232-255] ; grayscale */
  2517. for(; i < 256; i++) {
  2518. color.red = color.green = color.blue = 0x0808 + 0x0a0a * (i-(6*6*6+16));
  2519. if(!XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &color, &dc.col[i]))
  2520. die("Could not allocate color %d\n", i);
  2521. }
  2522. loaded = true;
  2523. }
  2524. int
  2525. xsetcolorname(int x, const char *name) {
  2526. XRenderColor color = { .alpha = 0xffff };
  2527. Color ncolor;
  2528. if(!BETWEEN(x, 0, LEN(colorname)))
  2529. return 1;
  2530. if(!name) {
  2531. if(BETWEEN(x, 16, 16 + 215)) { /* 256 color */
  2532. color.red = sixd_to_16bit( ((x-16)/36)%6 );
  2533. color.green = sixd_to_16bit( ((x-16)/6) %6 );
  2534. color.blue = sixd_to_16bit( ((x-16)/1) %6 );
  2535. if(!XftColorAllocValue(xw.dpy, xw.vis,
  2536. xw.cmap, &color, &ncolor)) {
  2537. return 1;
  2538. }
  2539. XftColorFree(xw.dpy, xw.vis, xw.cmap, &dc.col[x]);
  2540. dc.col[x] = ncolor;
  2541. return 0;
  2542. } else if(BETWEEN(x, 16 + 216, 255)) { /* greyscale */
  2543. color.red = color.green = color.blue = \
  2544. 0x0808 + 0x0a0a * (x - (16 + 216));
  2545. if(!XftColorAllocValue(xw.dpy, xw.vis,
  2546. xw.cmap, &color, &ncolor)) {
  2547. return 1;
  2548. }
  2549. XftColorFree(xw.dpy, xw.vis, xw.cmap, &dc.col[x]);
  2550. dc.col[x] = ncolor;
  2551. return 0;
  2552. } else { /* system colors */
  2553. name = colorname[x];
  2554. }
  2555. }
  2556. if(!XftColorAllocName(xw.dpy, xw.vis, xw.cmap, name, &ncolor))
  2557. return 1;
  2558. XftColorFree(xw.dpy, xw.vis, xw.cmap, &dc.col[x]);
  2559. dc.col[x] = ncolor;
  2560. return 0;
  2561. }
  2562. void
  2563. xtermclear(int col1, int row1, int col2, int row2) {
  2564. XftDrawRect(xw.draw,
  2565. &dc.col[IS_SET(MODE_REVERSE) ? defaultfg : defaultbg],
  2566. borderpx + col1 * xw.cw,
  2567. borderpx + row1 * xw.ch,
  2568. (col2-col1+1) * xw.cw,
  2569. (row2-row1+1) * xw.ch);
  2570. }
  2571. /*
  2572. * Absolute coordinates.
  2573. */
  2574. void
  2575. xclear(int x1, int y1, int x2, int y2) {
  2576. XftDrawRect(xw.draw,
  2577. &dc.col[IS_SET(MODE_REVERSE)? defaultfg : defaultbg],
  2578. x1, y1, x2-x1, y2-y1);
  2579. }
  2580. void
  2581. xhints(void) {
  2582. XClassHint class = {opt_class ? opt_class : termname, termname};
  2583. XWMHints wm = {.flags = InputHint, .input = 1};
  2584. XSizeHints *sizeh = NULL;
  2585. sizeh = XAllocSizeHints();
  2586. sizeh->flags = PSize | PResizeInc | PBaseSize;
  2587. sizeh->height = xw.h;
  2588. sizeh->width = xw.w;
  2589. sizeh->height_inc = xw.ch;
  2590. sizeh->width_inc = xw.cw;
  2591. sizeh->base_height = 2 * borderpx;
  2592. sizeh->base_width = 2 * borderpx;
  2593. if(xw.isfixed == True) {
  2594. sizeh->flags |= PMaxSize | PMinSize;
  2595. sizeh->min_width = sizeh->max_width = xw.w;
  2596. sizeh->min_height = sizeh->max_height = xw.h;
  2597. }
  2598. if(xw.gm & (XValue|YValue)) {
  2599. sizeh->flags |= USPosition | PWinGravity;
  2600. sizeh->x = xw.l;
  2601. sizeh->y = xw.t;
  2602. sizeh->win_gravity = xgeommasktogravity(xw.gm);
  2603. }
  2604. XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm,
  2605. &class);
  2606. XFree(sizeh);
  2607. }
  2608. int
  2609. xgeommasktogravity(int mask) {
  2610. switch(mask & (XNegative|YNegative)) {
  2611. case 0:
  2612. return NorthWestGravity;
  2613. case XNegative:
  2614. return NorthEastGravity;
  2615. case YNegative:
  2616. return SouthWestGravity;
  2617. }
  2618. return SouthEastGravity;
  2619. }
  2620. int
  2621. xloadfont(Font *f, FcPattern *pattern) {
  2622. FcPattern *match;
  2623. FcResult result;
  2624. match = FcFontMatch(NULL, pattern, &result);
  2625. if(!match)
  2626. return 1;
  2627. if(!(f->match = XftFontOpenPattern(xw.dpy, match))) {
  2628. FcPatternDestroy(match);
  2629. return 1;
  2630. }
  2631. f->set = NULL;
  2632. f->pattern = FcPatternDuplicate(pattern);
  2633. f->ascent = f->match->ascent;
  2634. f->descent = f->match->descent;
  2635. f->lbearing = 0;
  2636. f->rbearing = f->match->max_advance_width;
  2637. f->height = f->ascent + f->descent;
  2638. f->width = f->lbearing + f->rbearing;
  2639. return 0;
  2640. }
  2641. void
  2642. xloadfonts(char *fontstr, double fontsize) {
  2643. FcPattern *pattern;
  2644. FcResult r_sz, r_psz;
  2645. double fontval;
  2646. float ceilf(float);
  2647. if(fontstr[0] == '-') {
  2648. pattern = XftXlfdParse(fontstr, False, False);
  2649. } else {
  2650. pattern = FcNameParse((FcChar8 *)fontstr);
  2651. }
  2652. if(!pattern)
  2653. die("st: can't open font %s\n", fontstr);
  2654. if(fontsize > 0) {
  2655. FcPatternDel(pattern, FC_PIXEL_SIZE);
  2656. FcPatternDel(pattern, FC_SIZE);
  2657. FcPatternAddDouble(pattern, FC_PIXEL_SIZE, (double)fontsize);
  2658. usedfontsize = fontsize;
  2659. } else {
  2660. r_psz = FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &fontval);
  2661. r_sz = FcPatternGetDouble(pattern, FC_SIZE, 0, &fontval);
  2662. if(r_psz == FcResultMatch) {
  2663. usedfontsize = fontval;
  2664. } else if(r_sz == FcResultMatch) {
  2665. usedfontsize = -1;
  2666. } else {
  2667. /*
  2668. * Default font size is 12, if none given. This is to
  2669. * have a known usedfontsize value.
  2670. */
  2671. FcPatternAddDouble(pattern, FC_PIXEL_SIZE, 12);
  2672. usedfontsize = 12;
  2673. }
  2674. }
  2675. FcConfigSubstitute(0, pattern, FcMatchPattern);
  2676. FcDefaultSubstitute(pattern);
  2677. if(xloadfont(&dc.font, pattern))
  2678. die("st: can't open font %s\n", fontstr);
  2679. if(usedfontsize < 0) {
  2680. FcPatternGetDouble(dc.font.match->pattern,
  2681. FC_PIXEL_SIZE, 0, &fontval);
  2682. usedfontsize = fontval;
  2683. }
  2684. /* Setting character width and height. */
  2685. xw.cw = ceilf(dc.font.width * cwscale);
  2686. xw.ch = ceilf(dc.font.height * chscale);
  2687. FcPatternDel(pattern, FC_SLANT);
  2688. FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC);
  2689. if(xloadfont(&dc.ifont, pattern))
  2690. die("st: can't open font %s\n", fontstr);
  2691. FcPatternDel(pattern, FC_WEIGHT);
  2692. FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD);
  2693. if(xloadfont(&dc.ibfont, pattern))
  2694. die("st: can't open font %s\n", fontstr);
  2695. FcPatternDel(pattern, FC_SLANT);
  2696. FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ROMAN);
  2697. if(xloadfont(&dc.bfont, pattern))
  2698. die("st: can't open font %s\n", fontstr);
  2699. FcPatternDestroy(pattern);
  2700. }
  2701. int
  2702. xloadfontset(Font *f) {
  2703. FcResult result;
  2704. if(!(f->set = FcFontSort(0, f->pattern, FcTrue, 0, &result)))
  2705. return 1;
  2706. return 0;
  2707. }
  2708. void
  2709. xunloadfont(Font *f) {
  2710. XftFontClose(xw.dpy, f->match);
  2711. FcPatternDestroy(f->pattern);
  2712. if(f->set)
  2713. FcFontSetDestroy(f->set);
  2714. }
  2715. void
  2716. xunloadfonts(void) {
  2717. /* Free the loaded fonts in the font cache. */
  2718. while(frclen > 0)
  2719. XftFontClose(xw.dpy, frc[--frclen].font);
  2720. xunloadfont(&dc.font);
  2721. xunloadfont(&dc.bfont);
  2722. xunloadfont(&dc.ifont);
  2723. xunloadfont(&dc.ibfont);
  2724. }
  2725. void
  2726. xzoom(const Arg *arg) {
  2727. xunloadfonts();
  2728. xloadfonts(usedfont, usedfontsize + arg->i);
  2729. cresize(0, 0);
  2730. redraw(0);
  2731. xhints();
  2732. }
  2733. void
  2734. xinit(void) {
  2735. XGCValues gcvalues;
  2736. Cursor cursor;
  2737. Window parent;
  2738. pid_t thispid = getpid();
  2739. if(!(xw.dpy = XOpenDisplay(NULL)))
  2740. die("Can't open display\n");
  2741. xw.scr = XDefaultScreen(xw.dpy);
  2742. xw.vis = XDefaultVisual(xw.dpy, xw.scr);
  2743. /* font */
  2744. if(!FcInit())
  2745. die("Could not init fontconfig.\n");
  2746. usedfont = (opt_font == NULL)? font : opt_font;
  2747. xloadfonts(usedfont, 0);
  2748. /* colors */
  2749. xw.cmap = XDefaultColormap(xw.dpy, xw.scr);
  2750. xloadcols();
  2751. /* adjust fixed window geometry */
  2752. xw.w = 2 * borderpx + term.col * xw.cw;
  2753. xw.h = 2 * borderpx + term.row * xw.ch;
  2754. if(xw.gm & XNegative)
  2755. xw.l += DisplayWidth(xw.dpy, xw.scr) - xw.w - 2;
  2756. if(xw.gm & YNegative)
  2757. xw.t += DisplayWidth(xw.dpy, xw.scr) - xw.h - 2;
  2758. /* Events */
  2759. xw.attrs.background_pixel = dc.col[defaultbg].pixel;
  2760. xw.attrs.border_pixel = dc.col[defaultbg].pixel;
  2761. xw.attrs.bit_gravity = NorthWestGravity;
  2762. xw.attrs.event_mask = FocusChangeMask | KeyPressMask
  2763. | ExposureMask | VisibilityChangeMask | StructureNotifyMask
  2764. | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask;
  2765. xw.attrs.colormap = xw.cmap;
  2766. parent = opt_embed ? strtol(opt_embed, NULL, 0) : \
  2767. XRootWindow(xw.dpy, xw.scr);
  2768. xw.win = XCreateWindow(xw.dpy, parent, xw.l, xw.t,
  2769. xw.w, xw.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput,
  2770. xw.vis, CWBackPixel | CWBorderPixel | CWBitGravity
  2771. | CWEventMask | CWColormap, &xw.attrs);
  2772. memset(&gcvalues, 0, sizeof(gcvalues));
  2773. gcvalues.graphics_exposures = False;
  2774. dc.gc = XCreateGC(xw.dpy, parent, GCGraphicsExposures,
  2775. &gcvalues);
  2776. xw.buf = XCreatePixmap(xw.dpy, xw.win, xw.w, xw.h,
  2777. DefaultDepth(xw.dpy, xw.scr));
  2778. XSetForeground(xw.dpy, dc.gc, dc.col[defaultbg].pixel);
  2779. XFillRectangle(xw.dpy, xw.buf, dc.gc, 0, 0, xw.w, xw.h);
  2780. /* Xft rendering context */
  2781. xw.draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap);
  2782. /* input methods */
  2783. if((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
  2784. XSetLocaleModifiers("@im=local");
  2785. if((xw.xim = XOpenIM(xw.dpy, NULL, NULL, NULL)) == NULL) {
  2786. XSetLocaleModifiers("@im=");
  2787. if((xw.xim = XOpenIM(xw.dpy,
  2788. NULL, NULL, NULL)) == NULL) {
  2789. die("XOpenIM failed. Could not open input"
  2790. " device.\n");
  2791. }
  2792. }
  2793. }
  2794. xw.xic = XCreateIC(xw.xim, XNInputStyle, XIMPreeditNothing
  2795. | XIMStatusNothing, XNClientWindow, xw.win,
  2796. XNFocusWindow, xw.win, NULL);
  2797. if(xw.xic == NULL)
  2798. die("XCreateIC failed. Could not obtain input method.\n");
  2799. /* white cursor, black outline */
  2800. cursor = XCreateFontCursor(xw.dpy, XC_xterm);
  2801. XDefineCursor(xw.dpy, xw.win, cursor);
  2802. XRecolorCursor(xw.dpy, cursor,
  2803. &(XColor){.red = 0xffff, .green = 0xffff, .blue = 0xffff},
  2804. &(XColor){.red = 0x0000, .green = 0x0000, .blue = 0x0000});
  2805. xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False);
  2806. xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False);
  2807. xw.netwmname = XInternAtom(xw.dpy, "_NET_WM_NAME", False);
  2808. XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1);
  2809. xw.netwmpid = XInternAtom(xw.dpy, "_NET_WM_PID", False);
  2810. XChangeProperty(xw.dpy, xw.win, xw.netwmpid, XA_CARDINAL, 32,
  2811. PropModeReplace, (uchar *)&thispid, 1);
  2812. xresettitle();
  2813. XMapWindow(xw.dpy, xw.win);
  2814. xhints();
  2815. XSync(xw.dpy, False);
  2816. }
  2817. void
  2818. xdraws(char *s, Glyph base, int x, int y, int charlen, int bytelen) {
  2819. int winx = borderpx + x * xw.cw, winy = borderpx + y * xw.ch,
  2820. width = charlen * xw.cw, xp, i;
  2821. int frcflags;
  2822. int u8fl, u8fblen, u8cblen, doesexist;
  2823. char *u8c, *u8fs;
  2824. long unicodep;
  2825. Font *font = &dc.font;
  2826. FcResult fcres;
  2827. FcPattern *fcpattern, *fontpattern;
  2828. FcFontSet *fcsets[] = { NULL };
  2829. FcCharSet *fccharset;
  2830. Color *fg, *bg, *temp, revfg, revbg, truefg, truebg;
  2831. XRenderColor colfg, colbg;
  2832. XRectangle r;
  2833. int oneatatime;
  2834. frcflags = FRC_NORMAL;
  2835. if(base.mode & ATTR_ITALIC) {
  2836. if(base.fg == defaultfg)
  2837. base.fg = defaultitalic;
  2838. font = &dc.ifont;
  2839. frcflags = FRC_ITALIC;
  2840. } else if((base.mode & ATTR_ITALIC) && (base.mode & ATTR_BOLD)) {
  2841. if(base.fg == defaultfg)
  2842. base.fg = defaultitalic;
  2843. font = &dc.ibfont;
  2844. frcflags = FRC_ITALICBOLD;
  2845. } else if(base.mode & ATTR_UNDERLINE) {
  2846. if(base.fg == defaultfg)
  2847. base.fg = defaultunderline;
  2848. }
  2849. if(IS_TRUECOL(base.fg)) {
  2850. colfg.alpha = 0xffff;
  2851. colfg.red = TRUERED(base.fg);
  2852. colfg.green = TRUEGREEN(base.fg);
  2853. colfg.blue = TRUEBLUE(base.fg);
  2854. XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &truefg);
  2855. fg = &truefg;
  2856. } else {
  2857. fg = &dc.col[base.fg];
  2858. }
  2859. if(IS_TRUECOL(base.bg)) {
  2860. colbg.alpha = 0xffff;
  2861. colbg.green = TRUEGREEN(base.bg);
  2862. colbg.red = TRUERED(base.bg);
  2863. colbg.blue = TRUEBLUE(base.bg);
  2864. XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &truebg);
  2865. bg = &truebg;
  2866. } else {
  2867. bg = &dc.col[base.bg];
  2868. }
  2869. if(base.mode & ATTR_BOLD) {
  2870. /*
  2871. * change basic system colors [0-7]
  2872. * to bright system colors [8-15]
  2873. */
  2874. if(BETWEEN(base.fg, 0, 7) && !(base.mode & ATTR_FAINT))
  2875. fg = &dc.col[base.fg + 8];
  2876. if(base.mode & ATTR_ITALIC) {
  2877. font = &dc.ibfont;
  2878. frcflags = FRC_ITALICBOLD;
  2879. } else {
  2880. font = &dc.bfont;
  2881. frcflags = FRC_BOLD;
  2882. }
  2883. }
  2884. if(IS_SET(MODE_REVERSE)) {
  2885. if(fg == &dc.col[defaultfg]) {
  2886. fg = &dc.col[defaultbg];
  2887. } else {
  2888. colfg.red = ~fg->color.red;
  2889. colfg.green = ~fg->color.green;
  2890. colfg.blue = ~fg->color.blue;
  2891. colfg.alpha = fg->color.alpha;
  2892. XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg,
  2893. &revfg);
  2894. fg = &revfg;
  2895. }
  2896. if(bg == &dc.col[defaultbg]) {
  2897. bg = &dc.col[defaultfg];
  2898. } else {
  2899. colbg.red = ~bg->color.red;
  2900. colbg.green = ~bg->color.green;
  2901. colbg.blue = ~bg->color.blue;
  2902. colbg.alpha = bg->color.alpha;
  2903. XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg,
  2904. &revbg);
  2905. bg = &revbg;
  2906. }
  2907. }
  2908. if(base.mode & ATTR_REVERSE) {
  2909. temp = fg;
  2910. fg = bg;
  2911. bg = temp;
  2912. }
  2913. if(base.mode & ATTR_FAINT && !(base.mode & ATTR_BOLD)) {
  2914. colfg.red = fg->color.red / 2;
  2915. colfg.green = fg->color.green / 2;
  2916. colfg.blue = fg->color.blue / 2;
  2917. XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg);
  2918. fg = &revfg;
  2919. }
  2920. if(base.mode & ATTR_BLINK && term.mode & MODE_BLINK)
  2921. fg = bg;
  2922. if(base.mode & ATTR_INVISIBLE)
  2923. fg = bg;
  2924. /* Intelligent cleaning up of the borders. */
  2925. if(x == 0) {
  2926. xclear(0, (y == 0)? 0 : winy, borderpx,
  2927. winy + xw.ch + ((y >= term.row-1)? xw.h : 0));
  2928. }
  2929. if(x + charlen >= term.col) {
  2930. xclear(winx + width, (y == 0)? 0 : winy, xw.w,
  2931. ((y >= term.row-1)? xw.h : (winy + xw.ch)));
  2932. }
  2933. if(y == 0)
  2934. xclear(winx, 0, winx + width, borderpx);
  2935. if(y == term.row-1)
  2936. xclear(winx, winy + xw.ch, winx + width, xw.h);
  2937. /* Clean up the region we want to draw to. */
  2938. XftDrawRect(xw.draw, bg, winx, winy, width, xw.ch);
  2939. /* Set the clip region because Xft is sometimes dirty. */
  2940. r.x = 0;
  2941. r.y = 0;
  2942. r.height = xw.ch;
  2943. r.width = width;
  2944. XftDrawSetClipRectangles(xw.draw, winx, winy, &r, 1);
  2945. for(xp = winx; bytelen > 0;) {
  2946. /*
  2947. * Search for the range in the to be printed string of glyphs
  2948. * that are in the main font. Then print that range. If
  2949. * some glyph is found that is not in the font, do the
  2950. * fallback dance.
  2951. */
  2952. u8fs = s;
  2953. u8fblen = 0;
  2954. u8fl = 0;
  2955. oneatatime = font->width != xw.cw;
  2956. for(;;) {
  2957. u8c = s;
  2958. u8cblen = utf8decode(s, &unicodep, UTF_SIZ);
  2959. s += u8cblen;
  2960. bytelen -= u8cblen;
  2961. doesexist = XftCharExists(xw.dpy, font->match, unicodep);
  2962. if(doesexist) {
  2963. u8fl++;
  2964. u8fblen += u8cblen;
  2965. if(!oneatatime && bytelen > 0)
  2966. continue;
  2967. }
  2968. if(u8fl > 0) {
  2969. XftDrawStringUtf8(xw.draw, fg,
  2970. font->match, xp,
  2971. winy + font->ascent,
  2972. (FcChar8 *)u8fs,
  2973. u8fblen);
  2974. xp += xw.cw * u8fl;
  2975. }
  2976. break;
  2977. }
  2978. if(doesexist) {
  2979. if(oneatatime)
  2980. continue;
  2981. break;
  2982. }
  2983. /* Search the font cache. */
  2984. for(i = 0; i < frclen; i++) {
  2985. if(XftCharExists(xw.dpy, frc[i].font, unicodep)
  2986. && frc[i].flags == frcflags) {
  2987. break;
  2988. }
  2989. }
  2990. /* Nothing was found. */
  2991. if(i >= frclen) {
  2992. if(!font->set)
  2993. xloadfontset(font);
  2994. fcsets[0] = font->set;
  2995. /*
  2996. * Nothing was found in the cache. Now use
  2997. * some dozen of Fontconfig calls to get the
  2998. * font for one single character.
  2999. *
  3000. * Xft and fontconfig are design failures.
  3001. */
  3002. fcpattern = FcPatternDuplicate(font->pattern);
  3003. fccharset = FcCharSetCreate();
  3004. FcCharSetAddChar(fccharset, unicodep);
  3005. FcPatternAddCharSet(fcpattern, FC_CHARSET,
  3006. fccharset);
  3007. FcPatternAddBool(fcpattern, FC_SCALABLE,
  3008. FcTrue);
  3009. FcConfigSubstitute(0, fcpattern,
  3010. FcMatchPattern);
  3011. FcDefaultSubstitute(fcpattern);
  3012. fontpattern = FcFontSetMatch(0, fcsets,
  3013. FcTrue, fcpattern, &fcres);
  3014. /*
  3015. * Overwrite or create the new cache entry.
  3016. */
  3017. if(frclen >= LEN(frc)) {
  3018. frclen = LEN(frc) - 1;
  3019. XftFontClose(xw.dpy, frc[frclen].font);
  3020. }
  3021. frc[frclen].font = XftFontOpenPattern(xw.dpy,
  3022. fontpattern);
  3023. frc[frclen].flags = frcflags;
  3024. i = frclen;
  3025. frclen++;
  3026. FcPatternDestroy(fcpattern);
  3027. FcCharSetDestroy(fccharset);
  3028. }
  3029. XftDrawStringUtf8(xw.draw, fg, frc[i].font,
  3030. xp, winy + frc[i].font->ascent,
  3031. (FcChar8 *)u8c, u8cblen);
  3032. xp += xw.cw * wcwidth(unicodep);
  3033. }
  3034. /*
  3035. * This is how the loop above actually should be. Why does the
  3036. * application have to care about font details?
  3037. *
  3038. * I have to repeat: Xft and Fontconfig are design failures.
  3039. */
  3040. /*
  3041. XftDrawStringUtf8(xw.draw, fg, font->set, winx,
  3042. winy + font->ascent, (FcChar8 *)s, bytelen);
  3043. */
  3044. if(base.mode & ATTR_UNDERLINE) {
  3045. XftDrawRect(xw.draw, fg, winx, winy + font->ascent + 1,
  3046. width, 1);
  3047. }
  3048. if(base.mode & ATTR_STRUCK) {
  3049. XftDrawRect(xw.draw, fg, winx, winy + 2 * font->ascent / 3,
  3050. width, 1);
  3051. }
  3052. /* Reset clip to none. */
  3053. XftDrawSetClip(xw.draw, 0);
  3054. }
  3055. void
  3056. xdrawcursor(void) {
  3057. static int oldx = 0, oldy = 0;
  3058. int sl, width, curx;
  3059. Glyph g = {{' '}, ATTR_NULL, defaultbg, defaultcs};
  3060. LIMIT(oldx, 0, term.col-1);
  3061. LIMIT(oldy, 0, term.row-1);
  3062. curx = term.c.x;
  3063. /* adjust position if in dummy */
  3064. if(term.line[oldy][oldx].mode & ATTR_WDUMMY)
  3065. oldx--;
  3066. if(term.line[term.c.y][curx].mode & ATTR_WDUMMY)
  3067. curx--;
  3068. memcpy(g.c, term.line[term.c.y][term.c.x].c, UTF_SIZ);
  3069. /* remove the old cursor */
  3070. sl = utf8len(term.line[oldy][oldx].c);
  3071. width = (term.line[oldy][oldx].mode & ATTR_WIDE)? 2 : 1;
  3072. xdraws(term.line[oldy][oldx].c, term.line[oldy][oldx], oldx,
  3073. oldy, width, sl);
  3074. /* draw the new one */
  3075. if(!(IS_SET(MODE_HIDE))) {
  3076. if(xw.state & WIN_FOCUSED) {
  3077. if(IS_SET(MODE_REVERSE)) {
  3078. g.mode |= ATTR_REVERSE;
  3079. g.fg = defaultcs;
  3080. g.bg = defaultfg;
  3081. }
  3082. sl = utf8len(g.c);
  3083. width = (term.line[term.c.y][curx].mode & ATTR_WIDE)\
  3084. ? 2 : 1;
  3085. xdraws(g.c, g, term.c.x, term.c.y, width, sl);
  3086. } else {
  3087. XftDrawRect(xw.draw, &dc.col[defaultcs],
  3088. borderpx + curx * xw.cw,
  3089. borderpx + term.c.y * xw.ch,
  3090. xw.cw - 1, 1);
  3091. XftDrawRect(xw.draw, &dc.col[defaultcs],
  3092. borderpx + curx * xw.cw,
  3093. borderpx + term.c.y * xw.ch,
  3094. 1, xw.ch - 1);
  3095. XftDrawRect(xw.draw, &dc.col[defaultcs],
  3096. borderpx + (curx + 1) * xw.cw - 1,
  3097. borderpx + term.c.y * xw.ch,
  3098. 1, xw.ch - 1);
  3099. XftDrawRect(xw.draw, &dc.col[defaultcs],
  3100. borderpx + curx * xw.cw,
  3101. borderpx + (term.c.y + 1) * xw.ch - 1,
  3102. xw.cw, 1);
  3103. }
  3104. oldx = curx, oldy = term.c.y;
  3105. }
  3106. }
  3107. void
  3108. xsettitle(char *p) {
  3109. XTextProperty prop;
  3110. Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle,
  3111. &prop);
  3112. XSetWMName(xw.dpy, xw.win, &prop);
  3113. XSetTextProperty(xw.dpy, xw.win, &prop, xw.netwmname);
  3114. XFree(prop.value);
  3115. }
  3116. void
  3117. xresettitle(void) {
  3118. xsettitle(opt_title ? opt_title : "st");
  3119. }
  3120. void
  3121. redraw(int timeout) {
  3122. struct timespec tv = {0, timeout * 1000};
  3123. tfulldirt();
  3124. draw();
  3125. if(timeout > 0) {
  3126. nanosleep(&tv, NULL);
  3127. XSync(xw.dpy, False); /* necessary for a good tput flash */
  3128. }
  3129. }
  3130. void
  3131. draw(void) {
  3132. drawregion(0, 0, term.col, term.row);
  3133. XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, 0, 0, xw.w,
  3134. xw.h, 0, 0);
  3135. XSetForeground(xw.dpy, dc.gc,
  3136. dc.col[IS_SET(MODE_REVERSE)?
  3137. defaultfg : defaultbg].pixel);
  3138. }
  3139. void
  3140. drawregion(int x1, int y1, int x2, int y2) {
  3141. int ic, ib, x, y, ox, sl;
  3142. Glyph base, new;
  3143. char buf[DRAW_BUF_SIZ];
  3144. bool ena_sel = sel.ob.x != -1 && sel.alt == IS_SET(MODE_ALTSCREEN);
  3145. long unicodep;
  3146. if(!(xw.state & WIN_VISIBLE))
  3147. return;
  3148. for(y = y1; y < y2; y++) {
  3149. if(!term.dirty[y])
  3150. continue;
  3151. xtermclear(0, y, term.col, y);
  3152. term.dirty[y] = 0;
  3153. base = term.line[y][0];
  3154. ic = ib = ox = 0;
  3155. for(x = x1; x < x2; x++) {
  3156. new = term.line[y][x];
  3157. if(new.mode == ATTR_WDUMMY)
  3158. continue;
  3159. if(ena_sel && selected(x, y))
  3160. new.mode ^= ATTR_REVERSE;
  3161. if(ib > 0 && (ATTRCMP(base, new)
  3162. || ib >= DRAW_BUF_SIZ-UTF_SIZ)) {
  3163. xdraws(buf, base, ox, y, ic, ib);
  3164. ic = ib = 0;
  3165. }
  3166. if(ib == 0) {
  3167. ox = x;
  3168. base = new;
  3169. }
  3170. sl = utf8decode(new.c, &unicodep, UTF_SIZ);
  3171. memcpy(buf+ib, new.c, sl);
  3172. ib += sl;
  3173. ic += (new.mode & ATTR_WIDE)? 2 : 1;
  3174. }
  3175. if(ib > 0)
  3176. xdraws(buf, base, ox, y, ic, ib);
  3177. }
  3178. xdrawcursor();
  3179. }
  3180. void
  3181. expose(XEvent *ev) {
  3182. XExposeEvent *e = &ev->xexpose;
  3183. if(xw.state & WIN_REDRAW) {
  3184. if(!e->count)
  3185. xw.state &= ~WIN_REDRAW;
  3186. }
  3187. redraw(0);
  3188. }
  3189. void
  3190. visibility(XEvent *ev) {
  3191. XVisibilityEvent *e = &ev->xvisibility;
  3192. if(e->state == VisibilityFullyObscured) {
  3193. xw.state &= ~WIN_VISIBLE;
  3194. } else if(!(xw.state & WIN_VISIBLE)) {
  3195. /* need a full redraw for next Expose, not just a buf copy */
  3196. xw.state |= WIN_VISIBLE | WIN_REDRAW;
  3197. }
  3198. }
  3199. void
  3200. unmap(XEvent *ev) {
  3201. xw.state &= ~WIN_VISIBLE;
  3202. }
  3203. void
  3204. xsetpointermotion(int set) {
  3205. MODBIT(xw.attrs.event_mask, set, PointerMotionMask);
  3206. XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask, &xw.attrs);
  3207. }
  3208. void
  3209. xseturgency(int add) {
  3210. XWMHints *h = XGetWMHints(xw.dpy, xw.win);
  3211. MODBIT(h->flags, add, XUrgencyHint);
  3212. XSetWMHints(xw.dpy, xw.win, h);
  3213. XFree(h);
  3214. }
  3215. void
  3216. focus(XEvent *ev) {
  3217. XFocusChangeEvent *e = &ev->xfocus;
  3218. if(e->mode == NotifyGrab)
  3219. return;
  3220. if(ev->type == FocusIn) {
  3221. XSetICFocus(xw.xic);
  3222. xw.state |= WIN_FOCUSED;
  3223. xseturgency(0);
  3224. if(IS_SET(MODE_FOCUS))
  3225. ttywrite("\033[I", 3);
  3226. } else {
  3227. XUnsetICFocus(xw.xic);
  3228. xw.state &= ~WIN_FOCUSED;
  3229. if(IS_SET(MODE_FOCUS))
  3230. ttywrite("\033[O", 3);
  3231. }
  3232. }
  3233. static inline bool
  3234. match(uint mask, uint state) {
  3235. return mask == XK_ANY_MOD || mask == (state & ~ignoremod);
  3236. }
  3237. void
  3238. numlock(const Arg *dummy) {
  3239. term.numlock ^= 1;
  3240. }
  3241. char*
  3242. kmap(KeySym k, uint state) {
  3243. Key *kp;
  3244. int i;
  3245. /* Check for mapped keys out of X11 function keys. */
  3246. for(i = 0; i < LEN(mappedkeys); i++) {
  3247. if(mappedkeys[i] == k)
  3248. break;
  3249. }
  3250. if(i == LEN(mappedkeys)) {
  3251. if((k & 0xFFFF) < 0xFD00)
  3252. return NULL;
  3253. }
  3254. for(kp = key; kp < key + LEN(key); kp++) {
  3255. if(kp->k != k)
  3256. continue;
  3257. if(!match(kp->mask, state))
  3258. continue;
  3259. if(IS_SET(MODE_APPKEYPAD) ? kp->appkey < 0 : kp->appkey > 0)
  3260. continue;
  3261. if(term.numlock && kp->appkey == 2)
  3262. continue;
  3263. if(IS_SET(MODE_APPCURSOR) ? kp->appcursor < 0 : kp->appcursor > 0)
  3264. continue;
  3265. if(IS_SET(MODE_CRLF) ? kp->crlf < 0 : kp->crlf > 0)
  3266. continue;
  3267. return kp->s;
  3268. }
  3269. return NULL;
  3270. }
  3271. void
  3272. kpress(XEvent *ev) {
  3273. XKeyEvent *e = &ev->xkey;
  3274. KeySym ksym;
  3275. char buf[32], *customkey;
  3276. int len;
  3277. long c;
  3278. Status status;
  3279. Shortcut *bp;
  3280. if(IS_SET(MODE_KBDLOCK))
  3281. return;
  3282. len = XmbLookupString(xw.xic, e, buf, sizeof buf, &ksym, &status);
  3283. /* 1. shortcuts */
  3284. for(bp = shortcuts; bp < shortcuts + LEN(shortcuts); bp++) {
  3285. if(ksym == bp->keysym && match(bp->mod, e->state)) {
  3286. bp->func(&(bp->arg));
  3287. return;
  3288. }
  3289. }
  3290. /* 2. custom keys from config.h */
  3291. if((customkey = kmap(ksym, e->state))) {
  3292. ttysend(customkey, strlen(customkey));
  3293. return;
  3294. }
  3295. /* 3. composed string from input method */
  3296. if(len == 0)
  3297. return;
  3298. if(len == 1 && e->state & Mod1Mask) {
  3299. if(IS_SET(MODE_8BIT)) {
  3300. if(*buf < 0177) {
  3301. c = *buf | 0x80;
  3302. len = utf8encode(c, buf, UTF_SIZ);
  3303. }
  3304. } else {
  3305. buf[1] = buf[0];
  3306. buf[0] = '\033';
  3307. len = 2;
  3308. }
  3309. }
  3310. ttysend(buf, len);
  3311. }
  3312. void
  3313. cmessage(XEvent *e) {
  3314. /*
  3315. * See xembed specs
  3316. * http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html
  3317. */
  3318. if(e->xclient.message_type == xw.xembed && e->xclient.format == 32) {
  3319. if(e->xclient.data.l[1] == XEMBED_FOCUS_IN) {
  3320. xw.state |= WIN_FOCUSED;
  3321. xseturgency(0);
  3322. } else if(e->xclient.data.l[1] == XEMBED_FOCUS_OUT) {
  3323. xw.state &= ~WIN_FOCUSED;
  3324. }
  3325. } else if(e->xclient.data.l[0] == xw.wmdeletewin) {
  3326. /* Send SIGHUP to shell */
  3327. kill(pid, SIGHUP);
  3328. exit(EXIT_SUCCESS);
  3329. }
  3330. }
  3331. void
  3332. cresize(int width, int height) {
  3333. int col, row;
  3334. if(width != 0)
  3335. xw.w = width;
  3336. if(height != 0)
  3337. xw.h = height;
  3338. col = (xw.w - 2 * borderpx) / xw.cw;
  3339. row = (xw.h - 2 * borderpx) / xw.ch;
  3340. tresize(col, row);
  3341. xresize(col, row);
  3342. ttyresize();
  3343. }
  3344. void
  3345. resize(XEvent *e) {
  3346. if(e->xconfigure.width == xw.w && e->xconfigure.height == xw.h)
  3347. return;
  3348. cresize(e->xconfigure.width, e->xconfigure.height);
  3349. }
  3350. void
  3351. run(void) {
  3352. XEvent ev;
  3353. int w = xw.w, h = xw.h;
  3354. fd_set rfd;
  3355. int xfd = XConnectionNumber(xw.dpy), xev, blinkset = 0, dodraw = 0;
  3356. struct timespec drawtimeout, *tv = NULL, now, last, lastblink;
  3357. long deltatime;
  3358. /* Waiting for window mapping */
  3359. while(1) {
  3360. XNextEvent(xw.dpy, &ev);
  3361. if(XFilterEvent(&ev, None))
  3362. continue;
  3363. if(ev.type == ConfigureNotify) {
  3364. w = ev.xconfigure.width;
  3365. h = ev.xconfigure.height;
  3366. } else if(ev.type == MapNotify) {
  3367. break;
  3368. }
  3369. }
  3370. ttynew();
  3371. cresize(w, h);
  3372. clock_gettime(CLOCK_MONOTONIC, &last);
  3373. lastblink = last;
  3374. for(xev = actionfps;;) {
  3375. FD_ZERO(&rfd);
  3376. FD_SET(cmdfd, &rfd);
  3377. FD_SET(xfd, &rfd);
  3378. if(pselect(MAX(xfd, cmdfd)+1, &rfd, NULL, NULL, tv, NULL) < 0) {
  3379. if(errno == EINTR)
  3380. continue;
  3381. die("select failed: %s\n", strerror(errno));
  3382. }
  3383. if(FD_ISSET(cmdfd, &rfd)) {
  3384. ttyread();
  3385. if(blinktimeout) {
  3386. blinkset = tattrset(ATTR_BLINK);
  3387. if(!blinkset)
  3388. MODBIT(term.mode, 0, MODE_BLINK);
  3389. }
  3390. }
  3391. if(FD_ISSET(xfd, &rfd))
  3392. xev = actionfps;
  3393. clock_gettime(CLOCK_MONOTONIC, &now);
  3394. drawtimeout.tv_sec = 0;
  3395. drawtimeout.tv_nsec = (1000/xfps) * 1E6;
  3396. tv = &drawtimeout;
  3397. dodraw = 0;
  3398. if(blinktimeout && TIMEDIFF(now, lastblink) > blinktimeout) {
  3399. tsetdirtattr(ATTR_BLINK);
  3400. term.mode ^= MODE_BLINK;
  3401. lastblink = now;
  3402. dodraw = 1;
  3403. }
  3404. deltatime = TIMEDIFF(now, last);
  3405. if(deltatime > (xev? (1000/xfps) : (1000/actionfps))
  3406. || deltatime < 0) {
  3407. dodraw = 1;
  3408. last = now;
  3409. }
  3410. if(dodraw) {
  3411. while(XPending(xw.dpy)) {
  3412. XNextEvent(xw.dpy, &ev);
  3413. if(XFilterEvent(&ev, None))
  3414. continue;
  3415. if(handler[ev.type])
  3416. (handler[ev.type])(&ev);
  3417. }
  3418. draw();
  3419. XFlush(xw.dpy);
  3420. if(xev && !FD_ISSET(xfd, &rfd))
  3421. xev--;
  3422. if(!FD_ISSET(cmdfd, &rfd) && !FD_ISSET(xfd, &rfd)) {
  3423. if(blinkset) {
  3424. if(TIMEDIFF(now, lastblink) \
  3425. > blinktimeout) {
  3426. drawtimeout.tv_nsec = 1000;
  3427. } else {
  3428. drawtimeout.tv_nsec = (1E6 * \
  3429. (blinktimeout - \
  3430. TIMEDIFF(now,
  3431. lastblink)));
  3432. }
  3433. } else {
  3434. tv = NULL;
  3435. }
  3436. }
  3437. }
  3438. }
  3439. }
  3440. void
  3441. usage(void) {
  3442. die("%s " VERSION " (c) 2010-2014 st engineers\n" \
  3443. "usage: st [-a] [-v] [-c class] [-f font] [-g geometry] [-o file]\n"
  3444. " [-i] [-t title] [-w windowid] [-e command ...]\n", argv0);
  3445. }
  3446. int
  3447. main(int argc, char *argv[]) {
  3448. char *titles;
  3449. uint cols = 80, rows = 24;
  3450. xw.l = xw.t = 0;
  3451. xw.isfixed = False;
  3452. ARGBEGIN {
  3453. case 'a':
  3454. allowaltscreen = false;
  3455. break;
  3456. case 'c':
  3457. opt_class = EARGF(usage());
  3458. break;
  3459. case 'e':
  3460. /* eat all remaining arguments */
  3461. if(argc > 1) {
  3462. opt_cmd = &argv[1];
  3463. if(argv[1] != NULL && opt_title == NULL) {
  3464. titles = xstrdup(argv[1]);
  3465. opt_title = basename(titles);
  3466. }
  3467. }
  3468. goto run;
  3469. case 'f':
  3470. opt_font = EARGF(usage());
  3471. break;
  3472. case 'g':
  3473. xw.gm = XParseGeometry(EARGF(usage()),
  3474. &xw.l, &xw.t, &cols, &rows);
  3475. break;
  3476. case 'i':
  3477. xw.isfixed = True;
  3478. break;
  3479. case 'o':
  3480. opt_io = EARGF(usage());
  3481. break;
  3482. case 't':
  3483. opt_title = EARGF(usage());
  3484. break;
  3485. case 'w':
  3486. opt_embed = EARGF(usage());
  3487. break;
  3488. case 'v':
  3489. default:
  3490. usage();
  3491. } ARGEND;
  3492. run:
  3493. setlocale(LC_CTYPE, "");
  3494. XSetLocaleModifiers("");
  3495. tnew(cols? cols : 1, rows? rows : 1);
  3496. xinit();
  3497. selinit();
  3498. run();
  3499. return 0;
  3500. }