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.

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