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.

1767 lines
40 KiB

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