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.

1886 lines
43 KiB

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