st.c 93 KB

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