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.

1899 lines
44 KiB

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