dwm.c 40 KB

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