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.

1914 lines
44 KiB

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