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.

1881 lines
43 KiB

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