st.c 93 KB

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