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.

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