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.

1719 lines
40 KiB

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