dwm.c 39 KB

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