st.c 87 KB

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