dwm.c 40 KB

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