dwm.c 41 KB

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