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.

1800 lines
41 KiB

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