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.

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