You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1949 lines
45 KiB

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