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.

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