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.

1872 lines
44 KiB

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