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.

1921 lines
44 KiB

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