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.

1886 lines
43 KiB

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