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.

1897 lines
44 KiB

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