dwm.c 40 KB

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