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.

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