st.c 89 KB

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