dwm.c 40 KB

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