dwm.c 41 KB

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