st.c 82 KB

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