dwm.c 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742
  1. /* See LICENSE file for copyright and license details.
  2. *
  3. * dynamic window manager is designed like any other X client as well. It is
  4. * driven through handling X events. In contrast to other X clients, a window
  5. * manager selects for SubstructureRedirectMask on the root window, to receive
  6. * events about window (dis-)appearance. Only one X connection at a time is
  7. * allowed to select for this event mask.
  8. *
  9. * Calls to fetch an X event from the event queue are blocking. Due reading
  10. * status text from standard input, a select()-driven main loop has been
  11. * implemented which selects for reads on the X connection and STDIN_FILENO to
  12. * handle all data smoothly. The event handlers of dwm are organized in an
  13. * array which is accessed whenever a new event has been fetched. This allows
  14. * event dispatching in O(1) time.
  15. *
  16. * Each child of the root window is called a client, except windows which have
  17. * set the override_redirect flag. Clients are organized in a global
  18. * doubly-linked client list, the focus history is remembered through a global
  19. * stack list. Each client contains an array of Bools of the same size as the
  20. * global tags array to indicate the tags of a client.
  21. *
  22. * Keys and tagging rules are organized as arrays and defined in config.h.
  23. *
  24. * To understand everything else, start reading main().
  25. */
  26. #include <errno.h>
  27. #include <locale.h>
  28. #include <stdarg.h>
  29. #include <stdio.h>
  30. #include <stdlib.h>
  31. #include <string.h>
  32. #include <unistd.h>
  33. #include <sys/select.h>
  34. #include <sys/types.h>
  35. #include <sys/wait.h>
  36. #include <X11/cursorfont.h>
  37. #include <X11/keysym.h>
  38. #include <X11/Xatom.h>
  39. #include <X11/Xlib.h>
  40. #include <X11/Xproto.h>
  41. #include <X11/Xutil.h>
  42. /* macros */
  43. #define MAX(a, b) ((a) > (b) ? (a) : (b))
  44. #define MIN(a, b) ((a) < (b) ? (a) : (b))
  45. #define BUTTONMASK (ButtonPressMask|ButtonReleaseMask)
  46. #define CLEANMASK(mask) (mask & ~(numlockmask|LockMask))
  47. #define LENGTH(x) (sizeof x / sizeof x[0])
  48. #define MAXTAGLEN 16
  49. #define MOUSEMASK (BUTTONMASK|PointerMotionMask)
  50. /* enums */
  51. enum { BarTop, BarBot, BarOff, BarLast }; /* bar appearance */
  52. enum { CurNormal, CurResize, CurMove, CurLast }; /* cursor */
  53. enum { ColBorder, ColFG, ColBG, ColLast }; /* color */
  54. enum { NetSupported, NetWMName, NetLast }; /* EWMH atoms */
  55. enum { WMProtocols, WMDelete, WMName, WMState, WMLast };/* default atoms */
  56. /* typedefs */
  57. typedef struct Client Client;
  58. struct Client {
  59. char name[256];
  60. int x, y, w, h;
  61. int basew, baseh, incw, inch, maxw, maxh, minw, minh;
  62. int minax, maxax, minay, maxay;
  63. long flags;
  64. unsigned int bw, oldbw;
  65. Bool isbanned, isfixed, isfloating, isurgent;
  66. Bool *tags;
  67. Client *next;
  68. Client *prev;
  69. Client *snext;
  70. Window win;
  71. };
  72. typedef struct {
  73. int x, y, w, h;
  74. unsigned long norm[ColLast];
  75. unsigned long sel[ColLast];
  76. Drawable drawable;
  77. GC gc;
  78. struct {
  79. int ascent;
  80. int descent;
  81. int height;
  82. XFontSet set;
  83. XFontStruct *xfont;
  84. } font;
  85. } DC; /* draw context */
  86. typedef struct {
  87. unsigned long mod;
  88. KeySym keysym;
  89. void (*func)(const char *arg);
  90. const char *arg;
  91. } Key;
  92. typedef struct {
  93. const char *symbol;
  94. void (*arrange)(void);
  95. void (*updategeom)(void);
  96. } Layout;
  97. typedef struct {
  98. const char *class;
  99. const char *instance;
  100. const char *title;
  101. const char *tag;
  102. Bool isfloating;
  103. } Rule;
  104. /* function declarations */
  105. void applyrules(Client *c);
  106. void arrange(void);
  107. void attach(Client *c);
  108. void attachstack(Client *c);
  109. void ban(Client *c);
  110. void buttonpress(XEvent *e);
  111. void checkotherwm(void);
  112. void cleanup(void);
  113. void configure(Client *c);
  114. void configurenotify(XEvent *e);
  115. void configurerequest(XEvent *e);
  116. void destroynotify(XEvent *e);
  117. void detach(Client *c);
  118. void detachstack(Client *c);
  119. void drawbar(void);
  120. void drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]);
  121. void drawtext(const char *text, unsigned long col[ColLast], Bool invert);
  122. void *emallocz(unsigned int size);
  123. void enternotify(XEvent *e);
  124. void eprint(const char *errstr, ...);
  125. void expose(XEvent *e);
  126. void focus(Client *c);
  127. void focusin(XEvent *e);
  128. void focusnext(const char *arg);
  129. void focusprev(const char *arg);
  130. Client *getclient(Window w);
  131. unsigned long getcolor(const char *colstr);
  132. long getstate(Window w);
  133. Bool gettextprop(Window w, Atom atom, char *text, unsigned int size);
  134. void grabbuttons(Client *c, Bool focused);
  135. void grabkeys(void);
  136. unsigned int idxoftag(const char *t);
  137. void initfont(const char *fontstr);
  138. Bool isoccupied(unsigned int t);
  139. Bool isprotodel(Client *c);
  140. Bool isurgent(unsigned int t);
  141. Bool isvisible(Client *c);
  142. void keypress(XEvent *e);
  143. void killclient(const char *arg);
  144. void manage(Window w, XWindowAttributes *wa);
  145. void mappingnotify(XEvent *e);
  146. void maprequest(XEvent *e);
  147. void movemouse(Client *c);
  148. Client *nextunfloating(Client *c);
  149. void propertynotify(XEvent *e);
  150. void quit(const char *arg);
  151. void resize(Client *c, int x, int y, int w, int h, Bool sizehints);
  152. void resizemouse(Client *c);
  153. void restack(void);
  154. void run(void);
  155. void scan(void);
  156. void setclientstate(Client *c, long state);
  157. void setup(void);
  158. void spawn(const char *arg);
  159. void tag(const char *arg);
  160. unsigned int textnw(const char *text, unsigned int len);
  161. unsigned int textw(const char *text);
  162. void togglebar(const char *arg);
  163. void togglefloating(const char *arg);
  164. void togglelayout(const char *arg);
  165. void toggletag(const char *arg);
  166. void toggleview(const char *arg);
  167. void unban(Client *c);
  168. void unmanage(Client *c);
  169. void unmapnotify(XEvent *e);
  170. void updatebar(void);
  171. void updategeom(void);
  172. void updatesizehints(Client *c);
  173. void updatetitle(Client *c);
  174. void updatewmhints(Client *c);
  175. void view(const char *arg);
  176. void viewprevtag(const char *arg);
  177. int xerror(Display *dpy, XErrorEvent *ee);
  178. int xerrordummy(Display *dpy, XErrorEvent *ee);
  179. int xerrorstart(Display *dpy, XErrorEvent *ee);
  180. void zoom(const char *arg);
  181. /* variables */
  182. char stext[256];
  183. int screen, sx, sy, sw, sh;
  184. int bx, by, bw, bh, blw, wx, wy, ww, wh;
  185. int seltags = 0;
  186. int (*xerrorxlib)(Display *, XErrorEvent *);
  187. unsigned int numlockmask = 0;
  188. void (*handler[LASTEvent]) (XEvent *) = {
  189. [ButtonPress] = buttonpress,
  190. [ConfigureRequest] = configurerequest,
  191. [ConfigureNotify] = configurenotify,
  192. [DestroyNotify] = destroynotify,
  193. [EnterNotify] = enternotify,
  194. [Expose] = expose,
  195. [FocusIn] = focusin,
  196. [KeyPress] = keypress,
  197. [MappingNotify] = mappingnotify,
  198. [MapRequest] = maprequest,
  199. [PropertyNotify] = propertynotify,
  200. [UnmapNotify] = unmapnotify
  201. };
  202. Atom wmatom[WMLast], netatom[NetLast];
  203. Bool otherwm, readin;
  204. Bool running = True;
  205. Bool *tagset[2];
  206. Client *clients = NULL;
  207. Client *sel = NULL;
  208. Client *stack = NULL;
  209. Cursor cursor[CurLast];
  210. Display *dpy;
  211. DC dc = {0};
  212. Layout layouts[];
  213. Layout *lt = layouts;
  214. Window root, barwin;
  215. /* configuration, allows nested code to access above variables */
  216. #include "config.h"
  217. #define TAGSZ (LENGTH(tags) * sizeof(Bool))
  218. /* function implementations */
  219. void
  220. applyrules(Client *c) {
  221. unsigned int i;
  222. Bool matched = False;
  223. Rule *r;
  224. XClassHint ch = { 0 };
  225. /* rule matching */
  226. XGetClassHint(dpy, c->win, &ch);
  227. for(i = 0; i < LENGTH(rules); i++) {
  228. r = &rules[i];
  229. if((!r->title || strstr(c->name, r->title))
  230. && (!r->class || (ch.res_class && strstr(ch.res_class, r->class)))
  231. && (!r->instance || (ch.res_name && strstr(ch.res_name, r->instance)))) {
  232. c->isfloating = r->isfloating;
  233. if(r->tag) {
  234. c->tags[idxoftag(r->tag)] = True;
  235. matched = True;
  236. }
  237. }
  238. }
  239. if(ch.res_class)
  240. XFree(ch.res_class);
  241. if(ch.res_name)
  242. XFree(ch.res_name);
  243. if(!matched)
  244. memcpy(c->tags, tagset[seltags], TAGSZ);
  245. }
  246. void
  247. arrange(void) {
  248. Client *c;
  249. for(c = clients; c; c = c->next)
  250. if(isvisible(c)) {
  251. unban(c);
  252. if(!lt->arrange || c->isfloating)
  253. resize(c, c->x, c->y, c->w, c->h, True);
  254. }
  255. else
  256. ban(c);
  257. focus(NULL);
  258. if(lt->arrange)
  259. lt->arrange();
  260. restack();
  261. }
  262. void
  263. attach(Client *c) {
  264. if(clients)
  265. clients->prev = c;
  266. c->next = clients;
  267. clients = c;
  268. }
  269. void
  270. attachstack(Client *c) {
  271. c->snext = stack;
  272. stack = c;
  273. }
  274. void
  275. ban(Client *c) {
  276. if(c->isbanned)
  277. return;
  278. XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
  279. c->isbanned = True;
  280. }
  281. void
  282. buttonpress(XEvent *e) {
  283. unsigned int i, x;
  284. Client *c;
  285. XButtonPressedEvent *ev = &e->xbutton;
  286. if(ev->window == barwin) {
  287. x = 0;
  288. for(i = 0; i < LENGTH(tags); i++) {
  289. x += textw(tags[i]);
  290. if(ev->x < x) {
  291. if(ev->button == Button1) {
  292. if(ev->state & MODKEY)
  293. tag(tags[i]);
  294. else
  295. view(tags[i]);
  296. }
  297. else if(ev->button == Button3) {
  298. if(ev->state & MODKEY)
  299. toggletag(tags[i]);
  300. else
  301. toggleview(tags[i]);
  302. }
  303. return;
  304. }
  305. }
  306. if((ev->x < x + blw) && ev->button == Button1)
  307. togglelayout(NULL);
  308. }
  309. else if((c = getclient(ev->window))) {
  310. focus(c);
  311. if(CLEANMASK(ev->state) != MODKEY)
  312. return;
  313. if(ev->button == Button1) {
  314. restack();
  315. movemouse(c);
  316. }
  317. else if(ev->button == Button2) {
  318. if(lt->arrange && c->isfloating)
  319. togglefloating(NULL);
  320. }
  321. else if(ev->button == Button3 && !c->isfixed) {
  322. restack();
  323. resizemouse(c);
  324. }
  325. }
  326. }
  327. void
  328. checkotherwm(void) {
  329. otherwm = False;
  330. XSetErrorHandler(xerrorstart);
  331. /* this causes an error if some other window manager is running */
  332. XSelectInput(dpy, DefaultRootWindow(dpy), SubstructureRedirectMask);
  333. XSync(dpy, False);
  334. if(otherwm)
  335. eprint("dwm: another window manager is already running\n");
  336. XSync(dpy, False);
  337. XSetErrorHandler(NULL);
  338. xerrorxlib = XSetErrorHandler(xerror);
  339. XSync(dpy, False);
  340. }
  341. void
  342. cleanup(void) {
  343. close(STDIN_FILENO);
  344. while(stack) {
  345. unban(stack);
  346. unmanage(stack);
  347. }
  348. if(dc.font.set)
  349. XFreeFontSet(dpy, dc.font.set);
  350. else
  351. XFreeFont(dpy, dc.font.xfont);
  352. XUngrabKey(dpy, AnyKey, AnyModifier, root);
  353. XFreePixmap(dpy, dc.drawable);
  354. XFreeGC(dpy, dc.gc);
  355. XFreeCursor(dpy, cursor[CurNormal]);
  356. XFreeCursor(dpy, cursor[CurResize]);
  357. XFreeCursor(dpy, cursor[CurMove]);
  358. XDestroyWindow(dpy, barwin);
  359. XSync(dpy, False);
  360. XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
  361. }
  362. void
  363. configure(Client *c) {
  364. XConfigureEvent ce;
  365. ce.type = ConfigureNotify;
  366. ce.display = dpy;
  367. ce.event = c->win;
  368. ce.window = c->win;
  369. ce.x = c->x;
  370. ce.y = c->y;
  371. ce.width = c->w;
  372. ce.height = c->h;
  373. ce.border_width = c->bw;
  374. ce.above = None;
  375. ce.override_redirect = False;
  376. XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce);
  377. }
  378. void
  379. configurenotify(XEvent *e) {
  380. XConfigureEvent *ev = &e->xconfigure;
  381. if(ev->window == root && (ev->width != sw || ev->height != sh)) {
  382. sw = ev->width;
  383. sh = ev->height;
  384. updategeom();
  385. updatebar();
  386. arrange();
  387. }
  388. }
  389. void
  390. configurerequest(XEvent *e) {
  391. Client *c;
  392. XConfigureRequestEvent *ev = &e->xconfigurerequest;
  393. XWindowChanges wc;
  394. if((c = getclient(ev->window))) {
  395. if(ev->value_mask & CWBorderWidth)
  396. c->bw = ev->border_width;
  397. if(c->isfixed || c->isfloating || !lt->arrange) {
  398. if(ev->value_mask & CWX)
  399. c->x = sx + ev->x;
  400. if(ev->value_mask & CWY)
  401. c->y = sy + ev->y;
  402. if(ev->value_mask & CWWidth)
  403. c->w = ev->width;
  404. if(ev->value_mask & CWHeight)
  405. c->h = ev->height;
  406. if((c->x - sx + c->w) > sw && c->isfloating)
  407. c->x = sx + (sw / 2 - c->w / 2); /* center in x direction */
  408. if((c->y - sy + c->h) > sh && c->isfloating)
  409. c->y = sy + (sh / 2 - c->h / 2); /* center in y direction */
  410. if((ev->value_mask & (CWX|CWY))
  411. && !(ev->value_mask & (CWWidth|CWHeight)))
  412. configure(c);
  413. if(isvisible(c))
  414. XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h);
  415. }
  416. else
  417. configure(c);
  418. }
  419. else {
  420. wc.x = ev->x;
  421. wc.y = ev->y;
  422. wc.width = ev->width;
  423. wc.height = ev->height;
  424. wc.border_width = ev->border_width;
  425. wc.sibling = ev->above;
  426. wc.stack_mode = ev->detail;
  427. XConfigureWindow(dpy, ev->window, ev->value_mask, &wc);
  428. }
  429. XSync(dpy, False);
  430. }
  431. void
  432. destroynotify(XEvent *e) {
  433. Client *c;
  434. XDestroyWindowEvent *ev = &e->xdestroywindow;
  435. if((c = getclient(ev->window)))
  436. unmanage(c);
  437. }
  438. void
  439. detach(Client *c) {
  440. if(c->prev)
  441. c->prev->next = c->next;
  442. if(c->next)
  443. c->next->prev = c->prev;
  444. if(c == clients)
  445. clients = c->next;
  446. c->next = c->prev = NULL;
  447. }
  448. void
  449. detachstack(Client *c) {
  450. Client **tc;
  451. for(tc = &stack; *tc && *tc != c; tc = &(*tc)->snext);
  452. *tc = c->snext;
  453. }
  454. void
  455. drawbar(void) {
  456. int i, x;
  457. Client *c;
  458. dc.x = 0;
  459. for(c = stack; c && !isvisible(c); c = c->snext);
  460. for(i = 0; i < LENGTH(tags); i++) {
  461. dc.w = textw(tags[i]);
  462. if(tagset[seltags][i]) {
  463. drawtext(tags[i], dc.sel, isurgent(i));
  464. drawsquare(c && c->tags[i], isoccupied(i), isurgent(i), dc.sel);
  465. }
  466. else {
  467. drawtext(tags[i], dc.norm, isurgent(i));
  468. drawsquare(c && c->tags[i], isoccupied(i), isurgent(i), dc.norm);
  469. }
  470. dc.x += dc.w;
  471. }
  472. if(blw > 0) {
  473. dc.w = blw;
  474. drawtext(lt->symbol, dc.norm, False);
  475. x = dc.x + dc.w;
  476. }
  477. else
  478. x = dc.x;
  479. dc.w = textw(stext);
  480. dc.x = bw - dc.w;
  481. if(dc.x < x) {
  482. dc.x = x;
  483. dc.w = bw - x;
  484. }
  485. drawtext(stext, dc.norm, False);
  486. if((dc.w = dc.x - x) > bh) {
  487. dc.x = x;
  488. if(c) {
  489. drawtext(c->name, dc.sel, False);
  490. drawsquare(False, c->isfloating, False, dc.sel);
  491. }
  492. else
  493. drawtext(NULL, dc.norm, False);
  494. }
  495. XCopyArea(dpy, dc.drawable, barwin, dc.gc, 0, 0, bw, bh, 0, 0);
  496. XSync(dpy, False);
  497. }
  498. void
  499. drawsquare(Bool filled, Bool empty, Bool invert, unsigned long col[ColLast]) {
  500. int x;
  501. XGCValues gcv;
  502. XRectangle r = { dc.x, dc.y, dc.w, dc.h };
  503. gcv.foreground = col[invert ? ColBG : ColFG];
  504. XChangeGC(dpy, dc.gc, GCForeground, &gcv);
  505. x = (dc.font.ascent + dc.font.descent + 2) / 4;
  506. r.x = dc.x + 1;
  507. r.y = dc.y + 1;
  508. if(filled) {
  509. r.width = r.height = x + 1;
  510. XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
  511. }
  512. else if(empty) {
  513. r.width = r.height = x;
  514. XDrawRectangles(dpy, dc.drawable, dc.gc, &r, 1);
  515. }
  516. }
  517. void
  518. drawtext(const char *text, unsigned long col[ColLast], Bool invert) {
  519. int x, y, w, h;
  520. unsigned int len, olen;
  521. XRectangle r = { dc.x, dc.y, dc.w, dc.h };
  522. char buf[256];
  523. XSetForeground(dpy, dc.gc, col[invert ? ColFG : ColBG]);
  524. XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
  525. if(!text)
  526. return;
  527. olen = strlen(text);
  528. len = MIN(olen, sizeof buf);
  529. memcpy(buf, text, len);
  530. w = 0;
  531. h = dc.font.ascent + dc.font.descent;
  532. y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
  533. x = dc.x + (h / 2);
  534. /* shorten text if necessary */
  535. for(; len && (w = textnw(buf, len)) > dc.w - h; len--);
  536. if(!len)
  537. return;
  538. if(len < olen) {
  539. if(len > 1)
  540. buf[len - 1] = '.';
  541. if(len > 2)
  542. buf[len - 2] = '.';
  543. if(len > 3)
  544. buf[len - 3] = '.';
  545. }
  546. XSetForeground(dpy, dc.gc, col[invert ? ColBG : ColFG]);
  547. if(dc.font.set)
  548. XmbDrawString(dpy, dc.drawable, dc.font.set, dc.gc, x, y, buf, len);
  549. else
  550. XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
  551. }
  552. void *
  553. emallocz(unsigned int size) {
  554. void *res = calloc(1, size);
  555. if(!res)
  556. eprint("fatal: could not malloc() %u bytes\n", size);
  557. return res;
  558. }
  559. void
  560. enternotify(XEvent *e) {
  561. Client *c;
  562. XCrossingEvent *ev = &e->xcrossing;
  563. if((ev->mode != NotifyNormal || ev->detail == NotifyInferior) && ev->window != root)
  564. return;
  565. if((c = getclient(ev->window)))
  566. focus(c);
  567. else
  568. focus(NULL);
  569. }
  570. void
  571. eprint(const char *errstr, ...) {
  572. va_list ap;
  573. va_start(ap, errstr);
  574. vfprintf(stderr, errstr, ap);
  575. va_end(ap);
  576. exit(EXIT_FAILURE);
  577. }
  578. void
  579. expose(XEvent *e) {
  580. XExposeEvent *ev = &e->xexpose;
  581. if(ev->count == 0 && (ev->window == barwin))
  582. drawbar();
  583. }
  584. void
  585. focus(Client *c) {
  586. if(!c || (c && !isvisible(c)))
  587. for(c = stack; c && !isvisible(c); c = c->snext);
  588. if(sel && sel != c) {
  589. grabbuttons(sel, False);
  590. XSetWindowBorder(dpy, sel->win, dc.norm[ColBorder]);
  591. }
  592. if(c) {
  593. detachstack(c);
  594. attachstack(c);
  595. grabbuttons(c, True);
  596. }
  597. sel = c;
  598. if(c) {
  599. XSetWindowBorder(dpy, c->win, dc.sel[ColBorder]);
  600. XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
  601. }
  602. else
  603. XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime);
  604. drawbar();
  605. }
  606. void
  607. focusin(XEvent *e) { /* there are some broken focus acquiring clients */
  608. XFocusChangeEvent *ev = &e->xfocus;
  609. if(sel && ev->window != sel->win)
  610. XSetInputFocus(dpy, sel->win, RevertToPointerRoot, CurrentTime);
  611. }
  612. void
  613. focusnext(const char *arg) {
  614. Client *c;
  615. if(!sel)
  616. return;
  617. for(c = sel->next; c && !isvisible(c); c = c->next);
  618. if(!c)
  619. for(c = clients; c && !isvisible(c); c = c->next);
  620. if(c) {
  621. focus(c);
  622. restack();
  623. }
  624. }
  625. void
  626. focusprev(const char *arg) {
  627. Client *c;
  628. if(!sel)
  629. return;
  630. for(c = sel->prev; c && !isvisible(c); c = c->prev);
  631. if(!c) {
  632. for(c = clients; c && c->next; c = c->next);
  633. for(; c && !isvisible(c); c = c->prev);
  634. }
  635. if(c) {
  636. focus(c);
  637. restack();
  638. }
  639. }
  640. Client *
  641. getclient(Window w) {
  642. Client *c;
  643. for(c = clients; c && c->win != w; c = c->next);
  644. return c;
  645. }
  646. unsigned long
  647. getcolor(const char *colstr) {
  648. Colormap cmap = DefaultColormap(dpy, screen);
  649. XColor color;
  650. if(!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
  651. eprint("error, cannot allocate color '%s'\n", colstr);
  652. return color.pixel;
  653. }
  654. long
  655. getstate(Window w) {
  656. int format, status;
  657. long result = -1;
  658. unsigned char *p = NULL;
  659. unsigned long n, extra;
  660. Atom real;
  661. status = XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState],
  662. &real, &format, &n, &extra, (unsigned char **)&p);
  663. if(status != Success)
  664. return -1;
  665. if(n != 0)
  666. result = *p;
  667. XFree(p);
  668. return result;
  669. }
  670. Bool
  671. gettextprop(Window w, Atom atom, char *text, unsigned int size) {
  672. char **list = NULL;
  673. int n;
  674. XTextProperty name;
  675. if(!text || size == 0)
  676. return False;
  677. text[0] = '\0';
  678. XGetTextProperty(dpy, w, &name, atom);
  679. if(!name.nitems)
  680. return False;
  681. if(name.encoding == XA_STRING)
  682. strncpy(text, (char *)name.value, size - 1);
  683. else {
  684. if(XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
  685. && n > 0 && *list) {
  686. strncpy(text, *list, size - 1);
  687. XFreeStringList(list);
  688. }
  689. }
  690. text[size - 1] = '\0';
  691. XFree(name.value);
  692. return True;
  693. }
  694. void
  695. grabbuttons(Client *c, Bool focused) {
  696. int i, j;
  697. unsigned int buttons[] = { Button1, Button2, Button3 };
  698. unsigned int modifiers[] = { MODKEY, MODKEY|LockMask, MODKEY|numlockmask,
  699. MODKEY|numlockmask|LockMask} ;
  700. XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
  701. if(focused)
  702. for(i = 0; i < LENGTH(buttons); i++)
  703. for(j = 0; j < LENGTH(modifiers); j++)
  704. XGrabButton(dpy, buttons[i], modifiers[j], c->win, False,
  705. BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
  706. else
  707. XGrabButton(dpy, AnyButton, AnyModifier, c->win, False,
  708. BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
  709. }
  710. void
  711. grabkeys(void) {
  712. unsigned int i, j;
  713. KeyCode code;
  714. XModifierKeymap *modmap;
  715. /* init modifier map */
  716. modmap = XGetModifierMapping(dpy);
  717. for(i = 0; i < 8; i++)
  718. for(j = 0; j < modmap->max_keypermod; j++) {
  719. if(modmap->modifiermap[i * modmap->max_keypermod + j] == XKeysymToKeycode(dpy, XK_Num_Lock))
  720. numlockmask = (1 << i);
  721. }
  722. XFreeModifiermap(modmap);
  723. XUngrabKey(dpy, AnyKey, AnyModifier, root);
  724. for(i = 0; i < LENGTH(keys); i++) {
  725. code = XKeysymToKeycode(dpy, keys[i].keysym);
  726. XGrabKey(dpy, code, keys[i].mod, root, True,
  727. GrabModeAsync, GrabModeAsync);
  728. XGrabKey(dpy, code, keys[i].mod|LockMask, root, True,
  729. GrabModeAsync, GrabModeAsync);
  730. XGrabKey(dpy, code, keys[i].mod|numlockmask, root, True,
  731. GrabModeAsync, GrabModeAsync);
  732. XGrabKey(dpy, code, keys[i].mod|numlockmask|LockMask, root, True,
  733. GrabModeAsync, GrabModeAsync);
  734. }
  735. }
  736. unsigned int
  737. idxoftag(const char *t) {
  738. unsigned int i;
  739. for(i = 0; (i < LENGTH(tags)) && t && strcmp(tags[i], t); i++);
  740. return (i < LENGTH(tags)) ? i : 0;
  741. }
  742. void
  743. initfont(const char *fontstr) {
  744. char *def, **missing;
  745. int i, n;
  746. missing = NULL;
  747. if(dc.font.set)
  748. XFreeFontSet(dpy, dc.font.set);
  749. dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
  750. if(missing) {
  751. while(n--)
  752. fprintf(stderr, "dwm: missing fontset: %s\n", missing[n]);
  753. XFreeStringList(missing);
  754. }
  755. if(dc.font.set) {
  756. XFontSetExtents *font_extents;
  757. XFontStruct **xfonts;
  758. char **font_names;
  759. dc.font.ascent = dc.font.descent = 0;
  760. font_extents = XExtentsOfFontSet(dc.font.set);
  761. n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
  762. for(i = 0, dc.font.ascent = 0, dc.font.descent = 0; i < n; i++) {
  763. dc.font.ascent = MAX(dc.font.ascent, (*xfonts)->ascent);
  764. dc.font.descent = MAX(dc.font.descent,(*xfonts)->descent);
  765. xfonts++;
  766. }
  767. }
  768. else {
  769. if(dc.font.xfont)
  770. XFreeFont(dpy, dc.font.xfont);
  771. dc.font.xfont = NULL;
  772. if(!(dc.font.xfont = XLoadQueryFont(dpy, fontstr))
  773. && !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
  774. eprint("error, cannot load font: '%s'\n", fontstr);
  775. dc.font.ascent = dc.font.xfont->ascent;
  776. dc.font.descent = dc.font.xfont->descent;
  777. }
  778. dc.font.height = dc.font.ascent + dc.font.descent;
  779. }
  780. Bool
  781. isoccupied(unsigned int t) {
  782. Client *c;
  783. for(c = clients; c; c = c->next)
  784. if(c->tags[t])
  785. return True;
  786. return False;
  787. }
  788. Bool
  789. isprotodel(Client *c) {
  790. int i, n;
  791. Atom *protocols;
  792. Bool ret = False;
  793. if(XGetWMProtocols(dpy, c->win, &protocols, &n)) {
  794. for(i = 0; !ret && i < n; i++)
  795. if(protocols[i] == wmatom[WMDelete])
  796. ret = True;
  797. XFree(protocols);
  798. }
  799. return ret;
  800. }
  801. Bool
  802. isurgent(unsigned int t) {
  803. Client *c;
  804. for(c = clients; c; c = c->next)
  805. if(c->isurgent && c->tags[t])
  806. return True;
  807. return False;
  808. }
  809. Bool
  810. isvisible(Client *c) {
  811. unsigned int i;
  812. for(i = 0; i < LENGTH(tags); i++)
  813. if(c->tags[i] && tagset[seltags][i])
  814. return True;
  815. return False;
  816. }
  817. void
  818. keypress(XEvent *e) {
  819. unsigned int i;
  820. KeySym keysym;
  821. XKeyEvent *ev;
  822. ev = &e->xkey;
  823. keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
  824. for(i = 0; i < LENGTH(keys); i++)
  825. if(keysym == keys[i].keysym
  826. && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state))
  827. {
  828. if(keys[i].func)
  829. keys[i].func(keys[i].arg);
  830. }
  831. }
  832. void
  833. killclient(const char *arg) {
  834. XEvent ev;
  835. if(!sel)
  836. return;
  837. if(isprotodel(sel)) {
  838. ev.type = ClientMessage;
  839. ev.xclient.window = sel->win;
  840. ev.xclient.message_type = wmatom[WMProtocols];
  841. ev.xclient.format = 32;
  842. ev.xclient.data.l[0] = wmatom[WMDelete];
  843. ev.xclient.data.l[1] = CurrentTime;
  844. XSendEvent(dpy, sel->win, False, NoEventMask, &ev);
  845. }
  846. else
  847. XKillClient(dpy, sel->win);
  848. }
  849. void
  850. manage(Window w, XWindowAttributes *wa) {
  851. Client *c, *t = NULL;
  852. Status rettrans;
  853. Window trans;
  854. XWindowChanges wc;
  855. c = emallocz(sizeof(Client));
  856. c->tags = emallocz(TAGSZ);
  857. c->win = w;
  858. /* geometry */
  859. c->x = wa->x;
  860. c->y = wa->y;
  861. c->w = wa->width;
  862. c->h = wa->height;
  863. c->oldbw = wa->border_width;
  864. if(c->w == sw && c->h == sh) {
  865. c->x = sx;
  866. c->y = sy;
  867. c->bw = wa->border_width;
  868. }
  869. else {
  870. if(c->x + c->w + 2 * c->bw > wx + ww)
  871. c->x = wx + ww - c->w - 2 * c->bw;
  872. if(c->y + c->h + 2 * c->bw > wy + wh)
  873. c->y = wy + wh - c->h - 2 * c->bw;
  874. c->x = MAX(c->x, wx);
  875. c->y = MAX(c->y, wy);
  876. c->bw = borderpx;
  877. }
  878. wc.border_width = c->bw;
  879. XConfigureWindow(dpy, w, CWBorderWidth, &wc);
  880. XSetWindowBorder(dpy, w, dc.norm[ColBorder]);
  881. configure(c); /* propagates border_width, if size doesn't change */
  882. updatesizehints(c);
  883. XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask);
  884. grabbuttons(c, False);
  885. updatetitle(c);
  886. if((rettrans = XGetTransientForHint(dpy, w, &trans) == Success))
  887. for(t = clients; t && t->win != trans; t = t->next);
  888. if(t)
  889. memcpy(c->tags, t->tags, TAGSZ);
  890. else
  891. applyrules(c);
  892. if(!c->isfloating)
  893. c->isfloating = (rettrans == Success) || c->isfixed;
  894. attach(c);
  895. attachstack(c);
  896. XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h); /* some windows require this */
  897. ban(c);
  898. XMapWindow(dpy, c->win);
  899. setclientstate(c, NormalState);
  900. arrange();
  901. }
  902. void
  903. mappingnotify(XEvent *e) {
  904. XMappingEvent *ev = &e->xmapping;
  905. XRefreshKeyboardMapping(ev);
  906. if(ev->request == MappingKeyboard)
  907. grabkeys();
  908. }
  909. void
  910. maprequest(XEvent *e) {
  911. static XWindowAttributes wa;
  912. XMapRequestEvent *ev = &e->xmaprequest;
  913. if(!XGetWindowAttributes(dpy, ev->window, &wa))
  914. return;
  915. if(wa.override_redirect)
  916. return;
  917. if(!getclient(ev->window))
  918. manage(ev->window, &wa);
  919. }
  920. void
  921. movemouse(Client *c) {
  922. int x1, y1, ocx, ocy, di, nx, ny;
  923. unsigned int dui;
  924. Window dummy;
  925. XEvent ev;
  926. ocx = nx = c->x;
  927. ocy = ny = c->y;
  928. if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
  929. None, cursor[CurMove], CurrentTime) != GrabSuccess)
  930. return;
  931. XQueryPointer(dpy, root, &dummy, &dummy, &x1, &y1, &di, &di, &dui);
  932. for(;;) {
  933. XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev);
  934. switch (ev.type) {
  935. case ButtonRelease:
  936. XUngrabPointer(dpy, CurrentTime);
  937. return;
  938. case ConfigureRequest:
  939. case Expose:
  940. case MapRequest:
  941. handler[ev.type](&ev);
  942. break;
  943. case MotionNotify:
  944. XSync(dpy, False);
  945. nx = ocx + (ev.xmotion.x - x1);
  946. ny = ocy + (ev.xmotion.y - y1);
  947. if(snap && nx >= wx && nx <= wx + ww
  948. && ny >= wy && ny <= wy + wh) {
  949. if(abs(wx - nx) < snap)
  950. nx = wx;
  951. else if(abs((wx + ww) - (nx + c->w + 2 * c->bw)) < snap)
  952. nx = wx + ww - c->w - 2 * c->bw;
  953. if(abs(wy - ny) < snap)
  954. ny = wy;
  955. else if(abs((wy + wh) - (ny + c->h + 2 * c->bw)) < snap)
  956. ny = wy + wh - c->h - 2 * c->bw;
  957. if(!c->isfloating && lt->arrange && (abs(nx - c->x) > snap || abs(ny - c->y) > snap))
  958. togglefloating(NULL);
  959. }
  960. if(!lt->arrange || c->isfloating)
  961. resize(c, nx, ny, c->w, c->h, False);
  962. break;
  963. }
  964. }
  965. }
  966. Client *
  967. nextunfloating(Client *c) {
  968. for(; c && (c->isfloating || !isvisible(c)); c = c->next);
  969. return c;
  970. }
  971. void
  972. propertynotify(XEvent *e) {
  973. Client *c;
  974. Window trans;
  975. XPropertyEvent *ev = &e->xproperty;
  976. if(ev->state == PropertyDelete)
  977. return; /* ignore */
  978. if((c = getclient(ev->window))) {
  979. switch (ev->atom) {
  980. default: break;
  981. case XA_WM_TRANSIENT_FOR:
  982. XGetTransientForHint(dpy, c->win, &trans);
  983. if(!c->isfloating && (c->isfloating = (getclient(trans) != NULL)))
  984. arrange();
  985. break;
  986. case XA_WM_NORMAL_HINTS:
  987. updatesizehints(c);
  988. break;
  989. case XA_WM_HINTS:
  990. updatewmhints(c);
  991. drawbar();
  992. break;
  993. }
  994. if(ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) {
  995. updatetitle(c);
  996. if(c == sel)
  997. drawbar();
  998. }
  999. }
  1000. }
  1001. void
  1002. quit(const char *arg) {
  1003. readin = running = False;
  1004. }
  1005. void
  1006. resize(Client *c, int x, int y, int w, int h, Bool sizehints) {
  1007. XWindowChanges wc;
  1008. if(sizehints) {
  1009. /* set minimum possible */
  1010. w = MAX(1, w);
  1011. h = MAX(1, h);
  1012. /* temporarily remove base dimensions */
  1013. w -= c->basew;
  1014. h -= c->baseh;
  1015. /* adjust for aspect limits */
  1016. if(c->minax != c->maxax && c->minay != c->maxay
  1017. && c->minax > 0 && c->maxax > 0 && c->minay > 0 && c->maxay > 0) {
  1018. if(w * c->maxay > h * c->maxax)
  1019. w = h * c->maxax / c->maxay;
  1020. else if(w * c->minay < h * c->minax)
  1021. h = w * c->minay / c->minax;
  1022. }
  1023. /* adjust for increment value */
  1024. if(c->incw)
  1025. w -= w % c->incw;
  1026. if(c->inch)
  1027. h -= h % c->inch;
  1028. /* restore base dimensions */
  1029. w += c->basew;
  1030. h += c->baseh;
  1031. w = MAX(w, c->minw);
  1032. h = MAX(h, c->minh);
  1033. if (c->maxw)
  1034. w = MIN(w, c->maxw);
  1035. if (c->maxh)
  1036. h = MIN(h, c->maxh);
  1037. }
  1038. if(w <= 0 || h <= 0)
  1039. return;
  1040. if(x > sx + sw)
  1041. x = sw - w - 2 * c->bw;
  1042. if(y > sy + sh)
  1043. y = sh - h - 2 * c->bw;
  1044. if(x + w + 2 * c->bw < sx)
  1045. x = sx;
  1046. if(y + h + 2 * c->bw < sy)
  1047. y = sy;
  1048. if(c->x != x || c->y != y || c->w != w || c->h != h) {
  1049. c->x = wc.x = x;
  1050. c->y = wc.y = y;
  1051. c->w = wc.width = w;
  1052. c->h = wc.height = h;
  1053. wc.border_width = c->bw;
  1054. XConfigureWindow(dpy, c->win,
  1055. CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc);
  1056. configure(c);
  1057. XSync(dpy, False);
  1058. }
  1059. }
  1060. void
  1061. resizemouse(Client *c) {
  1062. int ocx, ocy;
  1063. int nw, nh;
  1064. XEvent ev;
  1065. ocx = c->x;
  1066. ocy = c->y;
  1067. if(XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync,
  1068. None, cursor[CurResize], CurrentTime) != GrabSuccess)
  1069. return;
  1070. XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1);
  1071. for(;;) {
  1072. XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask , &ev);
  1073. switch(ev.type) {
  1074. case ButtonRelease:
  1075. XWarpPointer(dpy, None, c->win, 0, 0, 0, 0,
  1076. c->w + c->bw - 1, c->h + c->bw - 1);
  1077. XUngrabPointer(dpy, CurrentTime);
  1078. while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
  1079. return;
  1080. case ConfigureRequest:
  1081. case Expose:
  1082. case MapRequest:
  1083. handler[ev.type](&ev);
  1084. break;
  1085. case MotionNotify:
  1086. XSync(dpy, False);
  1087. nw = MAX(ev.xmotion.x - ocx - 2 * c->bw + 1, 1);
  1088. nh = MAX(ev.xmotion.y - ocy - 2 * c->bw + 1, 1);
  1089. if(snap && nw >= wx && nw <= wx + ww
  1090. && nh >= wy && nh <= wy + wh) {
  1091. if(!c->isfloating && lt->arrange
  1092. && (abs(nw - c->w) > snap || abs(nh - c->h) > snap))
  1093. togglefloating(NULL);
  1094. }
  1095. if(!lt->arrange || c->isfloating)
  1096. resize(c, c->x, c->y, nw, nh, True);
  1097. break;
  1098. }
  1099. }
  1100. }
  1101. void
  1102. restack(void) {
  1103. Client *c;
  1104. XEvent ev;
  1105. XWindowChanges wc;
  1106. drawbar();
  1107. if(!sel)
  1108. return;
  1109. if(sel->isfloating || !lt->arrange)
  1110. XRaiseWindow(dpy, sel->win);
  1111. if(lt->arrange) {
  1112. wc.stack_mode = Below;
  1113. wc.sibling = barwin;
  1114. for(c = stack; c; c = c->snext)
  1115. if(!c->isfloating && isvisible(c)) {
  1116. XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc);
  1117. wc.sibling = c->win;
  1118. }
  1119. }
  1120. XSync(dpy, False);
  1121. while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
  1122. }
  1123. void
  1124. run(void) {
  1125. char *p;
  1126. char sbuf[sizeof stext];
  1127. fd_set rd;
  1128. int r, xfd;
  1129. unsigned int len, offset;
  1130. XEvent ev;
  1131. /* main event loop, also reads status text from stdin */
  1132. XSync(dpy, False);
  1133. xfd = ConnectionNumber(dpy);
  1134. readin = True;
  1135. offset = 0;
  1136. len = sizeof stext - 1;
  1137. sbuf[len] = stext[len] = '\0'; /* 0-terminator is never touched */
  1138. while(running) {
  1139. FD_ZERO(&rd);
  1140. if(readin)
  1141. FD_SET(STDIN_FILENO, &rd);
  1142. FD_SET(xfd, &rd);
  1143. if(select(xfd + 1, &rd, NULL, NULL, NULL) == -1) {
  1144. if(errno == EINTR)
  1145. continue;
  1146. eprint("select failed\n");
  1147. }
  1148. if(FD_ISSET(STDIN_FILENO, &rd)) {
  1149. switch((r = read(STDIN_FILENO, sbuf + offset, len - offset))) {
  1150. case -1:
  1151. strncpy(stext, strerror(errno), len);
  1152. readin = False;
  1153. break;
  1154. case 0:
  1155. strncpy(stext, "EOF", 4);
  1156. readin = False;
  1157. break;
  1158. default:
  1159. for(p = sbuf + offset; r > 0; p++, r--, offset++)
  1160. if(*p == '\n' || *p == '\0') {
  1161. *p = '\0';
  1162. strncpy(stext, sbuf, len);
  1163. p += r - 1; /* p is sbuf + offset + r - 1 */
  1164. for(r = 0; *(p - r) && *(p - r) != '\n'; r++);
  1165. offset = r;
  1166. if(r)
  1167. memmove(sbuf, p - r + 1, r);
  1168. break;
  1169. }
  1170. break;
  1171. }
  1172. drawbar();
  1173. }
  1174. while(XPending(dpy)) {
  1175. XNextEvent(dpy, &ev);
  1176. if(handler[ev.type])
  1177. (handler[ev.type])(&ev); /* call handler */
  1178. }
  1179. }
  1180. }
  1181. void
  1182. scan(void) {
  1183. unsigned int i, num;
  1184. Window *wins, d1, d2;
  1185. XWindowAttributes wa;
  1186. wins = NULL;
  1187. if(XQueryTree(dpy, root, &d1, &d2, &wins, &num)) {
  1188. for(i = 0; i < num; i++) {
  1189. if(!XGetWindowAttributes(dpy, wins[i], &wa)
  1190. || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1))
  1191. continue;
  1192. if(wa.map_state == IsViewable || getstate(wins[i]) == IconicState)
  1193. manage(wins[i], &wa);
  1194. }
  1195. for(i = 0; i < num; i++) { /* now the transients */
  1196. if(!XGetWindowAttributes(dpy, wins[i], &wa))
  1197. continue;
  1198. if(XGetTransientForHint(dpy, wins[i], &d1)
  1199. && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState))
  1200. manage(wins[i], &wa);
  1201. }
  1202. }
  1203. if(wins)
  1204. XFree(wins);
  1205. }
  1206. void
  1207. setclientstate(Client *c, long state) {
  1208. long data[] = {state, None};
  1209. XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32,
  1210. PropModeReplace, (unsigned char *)data, 2);
  1211. }
  1212. void
  1213. setup(void) {
  1214. unsigned int i, w;
  1215. XSetWindowAttributes wa;
  1216. /* init screen */
  1217. screen = DefaultScreen(dpy);
  1218. root = RootWindow(dpy, screen);
  1219. initfont(FONT);
  1220. sx = 0;
  1221. sy = 0;
  1222. sw = DisplayWidth(dpy, screen);
  1223. sh = DisplayHeight(dpy, screen);
  1224. bh = dc.font.height + 2;
  1225. updategeom();
  1226. /* init atoms */
  1227. wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
  1228. wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
  1229. wmatom[WMName] = XInternAtom(dpy, "WM_NAME", False);
  1230. wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False);
  1231. netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False);
  1232. netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
  1233. /* init cursors */
  1234. wa.cursor = cursor[CurNormal] = XCreateFontCursor(dpy, XC_left_ptr);
  1235. cursor[CurResize] = XCreateFontCursor(dpy, XC_sizing);
  1236. cursor[CurMove] = XCreateFontCursor(dpy, XC_fleur);
  1237. /* init appearance */
  1238. dc.norm[ColBorder] = getcolor(NORMBORDERCOLOR);
  1239. dc.norm[ColBG] = getcolor(NORMBGCOLOR);
  1240. dc.norm[ColFG] = getcolor(NORMFGCOLOR);
  1241. dc.sel[ColBorder] = getcolor(SELBORDERCOLOR);
  1242. dc.sel[ColBG] = getcolor(SELBGCOLOR);
  1243. dc.sel[ColFG] = getcolor(SELFGCOLOR);
  1244. initfont(FONT);
  1245. dc.h = bh;
  1246. dc.drawable = XCreatePixmap(dpy, root, DisplayWidth(dpy, screen), bh, DefaultDepth(dpy, screen));
  1247. dc.gc = XCreateGC(dpy, root, 0, 0);
  1248. XSetLineAttributes(dpy, dc.gc, 1, LineSolid, CapButt, JoinMiter);
  1249. if(!dc.font.set)
  1250. XSetFont(dpy, dc.gc, dc.font.xfont->fid);
  1251. /* init tags */
  1252. tagset[0] = emallocz(TAGSZ);
  1253. tagset[1] = emallocz(TAGSZ);
  1254. tagset[0][0] = tagset[1][0] = True;
  1255. /* init bar */
  1256. for(blw = i = 0; LENGTH(layouts) > 1 && i < LENGTH(layouts); i++) {
  1257. w = textw(layouts[i].symbol);
  1258. blw = MAX(blw, w);
  1259. }
  1260. wa.override_redirect = 1;
  1261. wa.background_pixmap = ParentRelative;
  1262. wa.event_mask = ButtonPressMask|ExposureMask;
  1263. barwin = XCreateWindow(dpy, root, bx, by, bw, bh, 0, DefaultDepth(dpy, screen),
  1264. CopyFromParent, DefaultVisual(dpy, screen),
  1265. CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa);
  1266. XDefineCursor(dpy, barwin, cursor[CurNormal]);
  1267. XMapRaised(dpy, barwin);
  1268. strcpy(stext, "dwm-"VERSION);
  1269. drawbar();
  1270. /* EWMH support per view */
  1271. XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32,
  1272. PropModeReplace, (unsigned char *) netatom, NetLast);
  1273. /* select for events */
  1274. wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask
  1275. |EnterWindowMask|LeaveWindowMask|StructureNotifyMask;
  1276. XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa);
  1277. XSelectInput(dpy, root, wa.event_mask);
  1278. /* grab keys */
  1279. grabkeys();
  1280. }
  1281. void
  1282. spawn(const char *arg) {
  1283. static char *shell = NULL;
  1284. if(!shell && !(shell = getenv("SHELL")))
  1285. shell = "/bin/sh";
  1286. if(!arg)
  1287. return;
  1288. /* The double-fork construct avoids zombie processes and keeps the code
  1289. * clean from stupid signal handlers. */
  1290. if(fork() == 0) {
  1291. if(fork() == 0) {
  1292. if(dpy)
  1293. close(ConnectionNumber(dpy));
  1294. setsid();
  1295. execl(shell, shell, "-c", arg, (char *)NULL);
  1296. fprintf(stderr, "dwm: execl '%s -c %s'", shell, arg);
  1297. perror(" failed");
  1298. }
  1299. exit(0);
  1300. }
  1301. wait(0);
  1302. }
  1303. void
  1304. tag(const char *arg) {
  1305. unsigned int i;
  1306. if(!sel)
  1307. return;
  1308. for(i = 0; i < LENGTH(tags); i++)
  1309. sel->tags[i] = (arg == NULL);
  1310. sel->tags[idxoftag(arg)] = True;
  1311. arrange();
  1312. }
  1313. unsigned int
  1314. textnw(const char *text, unsigned int len) {
  1315. XRectangle r;
  1316. if(dc.font.set) {
  1317. XmbTextExtents(dc.font.set, text, len, NULL, &r);
  1318. return r.width;
  1319. }
  1320. return XTextWidth(dc.font.xfont, text, len);
  1321. }
  1322. unsigned int
  1323. textw(const char *text) {
  1324. return textnw(text, strlen(text)) + dc.font.height;
  1325. }
  1326. void
  1327. togglebar(const char *arg) {
  1328. showbar = !showbar;
  1329. updategeom();
  1330. updatebar();
  1331. arrange();
  1332. }
  1333. void
  1334. togglefloating(const char *arg) {
  1335. if(!sel)
  1336. return;
  1337. sel->isfloating = !sel->isfloating;
  1338. if(sel->isfloating)
  1339. resize(sel, sel->x, sel->y, sel->w, sel->h, True);
  1340. arrange();
  1341. }
  1342. void
  1343. togglelayout(const char *arg) {
  1344. unsigned int i;
  1345. if(!arg) {
  1346. if(++lt == &layouts[LENGTH(layouts)])
  1347. lt = &layouts[0];
  1348. }
  1349. else {
  1350. for(i = 0; i < LENGTH(layouts); i++)
  1351. if(!strcmp(arg, layouts[i].symbol))
  1352. break;
  1353. if(i == LENGTH(layouts))
  1354. return;
  1355. lt = &layouts[i];
  1356. }
  1357. if(sel)
  1358. arrange();
  1359. else
  1360. drawbar();
  1361. }
  1362. void
  1363. toggletag(const char *arg) {
  1364. unsigned int i, j;
  1365. if(!sel)
  1366. return;
  1367. i = idxoftag(arg);
  1368. sel->tags[i] = !sel->tags[i];
  1369. for(j = 0; j < LENGTH(tags) && !sel->tags[j]; j++);
  1370. if(j == LENGTH(tags))
  1371. sel->tags[i] = True; /* at least one tag must be enabled */
  1372. arrange();
  1373. }
  1374. void
  1375. toggleview(const char *arg) {
  1376. unsigned int i, j;
  1377. i = idxoftag(arg);
  1378. tagset[seltags][i] = !tagset[seltags][i];
  1379. for(j = 0; j < LENGTH(tags) && !tagset[seltags][j]; j++);
  1380. if(j == LENGTH(tags))
  1381. tagset[seltags][i] = True; /* at least one tag must be viewed */
  1382. arrange();
  1383. }
  1384. void
  1385. unban(Client *c) {
  1386. if(!c->isbanned)
  1387. return;
  1388. XMoveWindow(dpy, c->win, c->x, c->y);
  1389. c->isbanned = False;
  1390. }
  1391. void
  1392. unmanage(Client *c) {
  1393. XWindowChanges wc;
  1394. wc.border_width = c->oldbw;
  1395. /* The server grab construct avoids race conditions. */
  1396. XGrabServer(dpy);
  1397. XSetErrorHandler(xerrordummy);
  1398. XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */
  1399. detach(c);
  1400. detachstack(c);
  1401. if(sel == c)
  1402. focus(NULL);
  1403. XUngrabButton(dpy, AnyButton, AnyModifier, c->win);
  1404. setclientstate(c, WithdrawnState);
  1405. free(c->tags);
  1406. free(c);
  1407. XSync(dpy, False);
  1408. XSetErrorHandler(xerror);
  1409. XUngrabServer(dpy);
  1410. arrange();
  1411. }
  1412. void
  1413. unmapnotify(XEvent *e) {
  1414. Client *c;
  1415. XUnmapEvent *ev = &e->xunmap;
  1416. if((c = getclient(ev->window)))
  1417. unmanage(c);
  1418. }
  1419. void
  1420. updatebar(void) {
  1421. if(dc.drawable != 0)
  1422. XFreePixmap(dpy, dc.drawable);
  1423. dc.drawable = XCreatePixmap(dpy, root, bw, bh, DefaultDepth(dpy, screen));
  1424. XMoveResizeWindow(dpy, barwin, bx, by, bw, bh);
  1425. }
  1426. void
  1427. updategeom(void) {
  1428. unsigned int i;
  1429. #ifdef CUSTOMGEOM /* define your own if you are Xinerama user */
  1430. CUSTOMGEOM
  1431. #else
  1432. /* bar geometry*/
  1433. bx = 0;
  1434. by = showbar ? (topbar ? 0 : sh - bh) : -bh;
  1435. bw = sw;
  1436. /* window area geometry */
  1437. wx = sx;
  1438. wy = showbar && topbar ? sy + bh : sy;
  1439. ww = sw;
  1440. wh = showbar ? sh - bh : sh;
  1441. #endif
  1442. /* update layout geometries */
  1443. for(i = 0; i < LENGTH(layouts); i++)
  1444. if(layouts[i].updategeom)
  1445. layouts[i].updategeom();
  1446. }
  1447. void
  1448. updatesizehints(Client *c) {
  1449. long msize;
  1450. XSizeHints size;
  1451. if(!XGetWMNormalHints(dpy, c->win, &size, &msize) || !size.flags)
  1452. size.flags = PSize;
  1453. c->flags = size.flags;
  1454. if(c->flags & PBaseSize) {
  1455. c->basew = size.base_width;
  1456. c->baseh = size.base_height;
  1457. }
  1458. else if(c->flags & PMinSize) {
  1459. c->basew = size.min_width;
  1460. c->baseh = size.min_height;
  1461. }
  1462. else
  1463. c->basew = c->baseh = 0;
  1464. if(c->flags & PResizeInc) {
  1465. c->incw = size.width_inc;
  1466. c->inch = size.height_inc;
  1467. }
  1468. else
  1469. c->incw = c->inch = 0;
  1470. if(c->flags & PMaxSize) {
  1471. c->maxw = size.max_width;
  1472. c->maxh = size.max_height;
  1473. }
  1474. else
  1475. c->maxw = c->maxh = 0;
  1476. if(c->flags & PMinSize) {
  1477. c->minw = size.min_width;
  1478. c->minh = size.min_height;
  1479. }
  1480. else if(c->flags & PBaseSize) {
  1481. c->minw = size.base_width;
  1482. c->minh = size.base_height;
  1483. }
  1484. else
  1485. c->minw = c->minh = 0;
  1486. if(c->flags & PAspect) {
  1487. c->minax = size.min_aspect.x;
  1488. c->maxax = size.max_aspect.x;
  1489. c->minay = size.min_aspect.y;
  1490. c->maxay = size.max_aspect.y;
  1491. }
  1492. else
  1493. c->minax = c->maxax = c->minay = c->maxay = 0;
  1494. c->isfixed = (c->maxw && c->minw && c->maxh && c->minh
  1495. && c->maxw == c->minw && c->maxh == c->minh);
  1496. }
  1497. void
  1498. updatetitle(Client *c) {
  1499. if(!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name))
  1500. gettextprop(c->win, wmatom[WMName], c->name, sizeof c->name);
  1501. }
  1502. void
  1503. updatewmhints(Client *c) {
  1504. XWMHints *wmh;
  1505. if((wmh = XGetWMHints(dpy, c->win))) {
  1506. if(c == sel)
  1507. sel->isurgent = False;
  1508. else
  1509. c->isurgent = (wmh->flags & XUrgencyHint) ? True : False;
  1510. XFree(wmh);
  1511. }
  1512. }
  1513. void
  1514. view(const char *arg) {
  1515. seltags ^= 1; /* toggle sel tagset */
  1516. memset(tagset[seltags], (NULL == arg), TAGSZ);
  1517. tagset[seltags][idxoftag(arg)] = True;
  1518. arrange();
  1519. }
  1520. void
  1521. viewprevtag(const char *arg) {
  1522. seltags ^= 1; /* toggle sel tagset */
  1523. arrange();
  1524. }
  1525. /* There's no way to check accesses to destroyed windows, thus those cases are
  1526. * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
  1527. * default error handler, which may call exit. */
  1528. int
  1529. xerror(Display *dpy, XErrorEvent *ee) {
  1530. if(ee->error_code == BadWindow
  1531. || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch)
  1532. || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable)
  1533. || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable)
  1534. || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable)
  1535. || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch)
  1536. || (ee->request_code == X_GrabButton && ee->error_code == BadAccess)
  1537. || (ee->request_code == X_GrabKey && ee->error_code == BadAccess)
  1538. || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable))
  1539. return 0;
  1540. fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n",
  1541. ee->request_code, ee->error_code);
  1542. return xerrorxlib(dpy, ee); /* may call exit */
  1543. }
  1544. int
  1545. xerrordummy(Display *dpy, XErrorEvent *ee) {
  1546. return 0;
  1547. }
  1548. /* Startup Error handler to check if another window manager
  1549. * is already running. */
  1550. int
  1551. xerrorstart(Display *dpy, XErrorEvent *ee) {
  1552. otherwm = True;
  1553. return -1;
  1554. }
  1555. int
  1556. main(int argc, char *argv[]) {
  1557. if(argc == 2 && !strcmp("-v", argv[1]))
  1558. eprint("dwm-"VERSION", © 2006-2008 dwm engineers, see LICENSE for details\n");
  1559. else if(argc != 1)
  1560. eprint("usage: dwm [-v]\n");
  1561. setlocale(LC_CTYPE, "");
  1562. if(!(dpy = XOpenDisplay(0)))
  1563. eprint("dwm: cannot open display\n");
  1564. checkotherwm();
  1565. setup();
  1566. scan();
  1567. run();
  1568. cleanup();
  1569. XCloseDisplay(dpy);
  1570. return 0;
  1571. }