The forgotten half of the last patch.
[tabbed/julien_tabbed.git] / tabbed.c
blob9a447951d629603685d484a2ca71a7a45dcc8096
1 /*
2 * See LICENSE file for copyright and license details.
3 */
5 #include <sys/wait.h>
6 #include <locale.h>
7 #include <signal.h>
8 #include <stdarg.h>
9 #include <stdio.h>
10 #include <stdlib.h>
11 #include <string.h>
12 #include <unistd.h>
13 #include <X11/Xatom.h>
14 #include <X11/Xlib.h>
15 #include <X11/Xproto.h>
16 #include <X11/Xutil.h>
17 #include <X11/XKBlib.h>
18 #include <X11/Xft/Xft.h>
20 #include "arg.h"
22 /* XEMBED messages */
23 #define XEMBED_EMBEDDED_NOTIFY 0
24 #define XEMBED_WINDOW_ACTIVATE 1
25 #define XEMBED_WINDOW_DEACTIVATE 2
26 #define XEMBED_REQUEST_FOCUS 3
27 #define XEMBED_FOCUS_IN 4
28 #define XEMBED_FOCUS_OUT 5
29 #define XEMBED_FOCUS_NEXT 6
30 #define XEMBED_FOCUS_PREV 7
31 /* 8-9 were used for XEMBED_GRAB_KEY/XEMBED_UNGRAB_KEY */
32 #define XEMBED_MODALITY_ON 10
33 #define XEMBED_MODALITY_OFF 11
34 #define XEMBED_REGISTER_ACCELERATOR 12
35 #define XEMBED_UNREGISTER_ACCELERATOR 13
36 #define XEMBED_ACTIVATE_ACCELERATOR 14
38 /* Details for XEMBED_FOCUS_IN: */
39 #define XEMBED_FOCUS_CURRENT 0
40 #define XEMBED_FOCUS_FIRST 1
41 #define XEMBED_FOCUS_LAST 2
43 /* Macros */
44 #define MAX(a, b) ((a) > (b) ? (a) : (b))
45 #define MIN(a, b) ((a) < (b) ? (a) : (b))
46 #define LENGTH(x) (sizeof((x)) / sizeof(*(x)))
47 #define CLEANMASK(mask) (mask & ~(numlockmask | LockMask))
48 #define TEXTW(x) (textnw(x, strlen(x)) + dc.font.height)
50 enum { ColFG, ColBG, ColLast }; /* color */
51 enum { WMProtocols, WMDelete, WMName, WMState, WMFullscreen,
52 XEmbed, WMSelectTab, WMLast }; /* default atoms */
54 typedef union {
55 int i;
56 const void *v;
57 } Arg;
59 typedef struct {
60 unsigned int mod;
61 KeySym keysym;
62 void (*func)(const Arg *);
63 const Arg arg;
64 } Key;
66 typedef struct {
67 int x, y, w, h;
68 XftColor norm[ColLast];
69 XftColor sel[ColLast];
70 XftColor urg[ColLast];
71 Drawable drawable;
72 GC gc;
73 struct {
74 int ascent;
75 int descent;
76 int height;
77 XftFont *xfont;
78 } font;
79 } DC; /* draw context */
81 typedef struct {
82 char name[256];
83 Window win;
84 int tabx;
85 Bool urgent;
86 Bool closed;
87 } Client;
89 /* function declarations */
90 static void buttonpress(const XEvent *e);
91 static void cleanup(void);
92 static void clientmessage(const XEvent *e);
93 static void configurenotify(const XEvent *e);
94 static void configurerequest(const XEvent *e);
95 static void createnotify(const XEvent *e);
96 static void destroynotify(const XEvent *e);
97 static void die(const char *errstr, ...);
98 static void drawbar(void);
99 static void drawtext(const char *text, XftColor col[ColLast]);
100 static void *ecalloc(size_t n, size_t size);
101 static void *erealloc(void *o, size_t size);
102 static void expose(const XEvent *e);
103 static void focus(int c);
104 static void focusin(const XEvent *e);
105 static void focusonce(const Arg *arg);
106 static void focusurgent(const Arg *arg);
107 static void fullscreen(const Arg *arg);
108 static char *getatom(int a);
109 static int getclient(Window w);
110 static XftColor getcolor(const char *colstr);
111 static int getfirsttab(void);
112 static Bool gettextprop(Window w, Atom atom, char *text, unsigned int size);
113 static void initfont(const char *fontstr);
114 static Bool isprotodel(int c);
115 static void keypress(const XEvent *e);
116 static void killclient(const Arg *arg);
117 static void manage(Window win);
118 static void maprequest(const XEvent *e);
119 static void move(const Arg *arg);
120 static void movetab(const Arg *arg);
121 static void propertynotify(const XEvent *e);
122 static void resize(int c, int w, int h);
123 static void rotate(const Arg *arg);
124 static void run(void);
125 static void sendxembed(int c, long msg, long detail, long d1, long d2);
126 static void setcmd(int argc, char *argv[], int);
127 static void setup(void);
128 static void sigchld(int unused);
129 static void spawn(const Arg *arg);
130 static int textnw(const char *text, unsigned int len);
131 static void toggle(const Arg *arg);
132 static void unmanage(int c);
133 static void unmapnotify(const XEvent *e);
134 static void updatenumlockmask(void);
135 static void updatetitle(int c);
136 static int xerror(Display *dpy, XErrorEvent *ee);
137 static void xsettitle(Window w, const char *str);
139 /* variables */
140 static int screen;
141 static void (*handler[LASTEvent]) (const XEvent *) = {
142 [ButtonPress] = buttonpress,
143 [ClientMessage] = clientmessage,
144 [ConfigureNotify] = configurenotify,
145 [ConfigureRequest] = configurerequest,
146 [CreateNotify] = createnotify,
147 [UnmapNotify] = unmapnotify,
148 [DestroyNotify] = destroynotify,
149 [Expose] = expose,
150 [FocusIn] = focusin,
151 [KeyPress] = keypress,
152 [MapRequest] = maprequest,
153 [PropertyNotify] = propertynotify,
155 static int bh, wx, wy, ww, wh;
156 static unsigned int numlockmask;
157 static Bool running = True, nextfocus, doinitspawn = True,
158 fillagain = False, closelastclient = False,
159 killclientsfirst = False;
160 static Display *dpy;
161 static DC dc;
162 static Atom wmatom[WMLast];
163 static Window root, win;
164 static Client **clients;
165 static int nclients, sel = -1, lastsel = -1;
166 static int (*xerrorxlib)(Display *, XErrorEvent *);
167 static int cmd_append_pos;
168 static char winid[64];
169 static char **cmd;
170 static char *wmname = "tabbed";
171 static const char *geometry;
173 char *argv0;
175 /* configuration, allows nested code to access above variables */
176 #include "config.h"
178 void
179 buttonpress(const XEvent *e)
181 const XButtonPressedEvent *ev = &e->xbutton;
182 int i, fc;
183 Arg arg;
185 if (ev->y < 0 || ev->y > bh)
186 return;
188 if (((fc = getfirsttab()) > 0 && ev->x < TEXTW(before)) || ev->x < 0)
189 return;
191 for (i = fc; i < nclients; i++) {
192 if (clients[i]->tabx > ev->x) {
193 switch (ev->button) {
194 case Button1:
195 focus(i);
196 break;
197 case Button2:
198 focus(i);
199 killclient(NULL);
200 break;
201 case Button4: /* FALLTHROUGH */
202 case Button5:
203 arg.i = ev->button == Button4 ? -1 : 1;
204 rotate(&arg);
205 break;
207 break;
212 void
213 cleanup(void)
215 int i;
217 for (i = 0; i < nclients; i++) {
218 focus(i);
219 killclient(NULL);
220 killclient(NULL);
221 XReparentWindow(dpy, clients[i]->win, root, 0, 0);
222 unmanage(i);
224 free(clients);
225 clients = NULL;
227 XFreePixmap(dpy, dc.drawable);
228 XFreeGC(dpy, dc.gc);
229 XDestroyWindow(dpy, win);
230 XSync(dpy, False);
231 free(cmd);
234 void
235 clientmessage(const XEvent *e)
237 const XClientMessageEvent *ev = &e->xclient;
239 if (ev->message_type == wmatom[WMProtocols] &&
240 ev->data.l[0] == wmatom[WMDelete]) {
241 if (nclients > 1 && killclientsfirst) {
242 killclient(0);
243 return;
245 running = False;
249 void
250 configurenotify(const XEvent *e)
252 const XConfigureEvent *ev = &e->xconfigure;
254 if (ev->window == win && (ev->width != ww || ev->height != wh)) {
255 ww = ev->width;
256 wh = ev->height;
257 XFreePixmap(dpy, dc.drawable);
258 dc.drawable = XCreatePixmap(dpy, root, ww, wh,
259 DefaultDepth(dpy, screen));
260 if (sel > -1)
261 resize(sel, ww, wh - bh);
262 XSync(dpy, False);
266 void
267 configurerequest(const XEvent *e)
269 const XConfigureRequestEvent *ev = &e->xconfigurerequest;
270 XWindowChanges wc;
271 int c;
273 if ((c = getclient(ev->window)) > -1) {
274 wc.x = 0;
275 wc.y = bh;
276 wc.width = ww;
277 wc.height = wh - bh;
278 wc.border_width = 0;
279 wc.sibling = ev->above;
280 wc.stack_mode = ev->detail;
281 XConfigureWindow(dpy, clients[c]->win, ev->value_mask, &wc);
285 void
286 createnotify(const XEvent *e)
288 const XCreateWindowEvent *ev = &e->xcreatewindow;
290 if (ev->window != win && getclient(ev->window) < 0)
291 manage(ev->window);
294 void
295 destroynotify(const XEvent *e)
297 const XDestroyWindowEvent *ev = &e->xdestroywindow;
298 int c;
300 if ((c = getclient(ev->window)) > -1)
301 unmanage(c);
304 void
305 die(const char *errstr, ...)
307 va_list ap;
309 va_start(ap, errstr);
310 vfprintf(stderr, errstr, ap);
311 va_end(ap);
312 exit(EXIT_FAILURE);
315 void
316 drawbar(void)
318 XftColor *col;
319 int c, cc, fc, width;
320 char *name = NULL;
322 if (nclients == 0) {
323 dc.x = 0;
324 dc.w = ww;
325 XFetchName(dpy, win, &name);
326 drawtext(name ? name : "", dc.norm);
327 XCopyArea(dpy, dc.drawable, win, dc.gc, 0, 0, ww, bh, 0, 0);
328 XSync(dpy, False);
330 return;
333 width = ww;
334 cc = ww / tabwidth;
335 if (nclients > cc)
336 cc = (ww - TEXTW(before) - TEXTW(after)) / tabwidth;
338 if ((fc = getfirsttab()) + cc < nclients) {
339 dc.w = TEXTW(after);
340 dc.x = width - dc.w;
341 drawtext(after, dc.sel);
342 width -= dc.w;
344 dc.x = 0;
346 if (fc > 0) {
347 dc.w = TEXTW(before);
348 drawtext(before, dc.sel);
349 dc.x += dc.w;
350 width -= dc.w;
353 cc = MIN(cc, nclients);
354 for (c = fc; c < fc + cc; c++) {
355 dc.w = width / cc;
356 if (c == sel) {
357 col = dc.sel;
358 dc.w += width % cc;
359 } else {
360 col = clients[c]->urgent ? dc.urg : dc.norm;
362 drawtext(clients[c]->name, col);
363 dc.x += dc.w;
364 clients[c]->tabx = dc.x;
366 XCopyArea(dpy, dc.drawable, win, dc.gc, 0, 0, ww, bh, 0, 0);
367 XSync(dpy, False);
370 void
371 drawtext(const char *text, XftColor col[ColLast])
373 int i, j, x, y, h, len, olen;
374 char buf[256];
375 XftDraw *d;
376 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
378 XSetForeground(dpy, dc.gc, col[ColBG].pixel);
379 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
380 if (!text)
381 return;
383 olen = strlen(text);
384 h = dc.font.ascent + dc.font.descent;
385 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
386 x = dc.x + (h / 2);
388 /* shorten text if necessary */
389 for (len = MIN(olen, sizeof(buf));
390 len && textnw(text, len) > dc.w - h; len--);
392 if (!len)
393 return;
395 memcpy(buf, text, len);
396 if (len < olen) {
397 for (i = len, j = strlen(titletrim); j && i;
398 buf[--i] = titletrim[--j])
402 d = XftDrawCreate(dpy, dc.drawable, DefaultVisual(dpy, screen), DefaultColormap(dpy, screen));
403 XftDrawStringUtf8(d, &col[ColFG], dc.font.xfont, x, y, (XftChar8 *) buf, len);
404 XftDrawDestroy(d);
407 void *
408 ecalloc(size_t n, size_t size)
410 void *p;
412 if (!(p = calloc(n, size)))
413 die("%s: cannot calloc\n", argv0);
414 return p;
417 void *
418 erealloc(void *o, size_t size)
420 void *p;
422 if (!(p = realloc(o, size)))
423 die("%s: cannot realloc\n", argv0);
424 return p;
427 void
428 expose(const XEvent *e)
430 const XExposeEvent *ev = &e->xexpose;
432 if (ev->count == 0 && win == ev->window)
433 drawbar();
436 void
437 focus(int c)
439 char buf[BUFSIZ] = "tabbed-"VERSION" ::";
440 size_t i, n;
441 XWMHints* wmh;
443 /* If c, sel and clients are -1, raise tabbed-win itself */
444 if (nclients == 0) {
445 cmd[cmd_append_pos] = NULL;
446 for(i = 0, n = strlen(buf); cmd[i] && n < sizeof(buf); i++)
447 n += snprintf(&buf[n], sizeof(buf) - n, " %s", cmd[i]);
449 xsettitle(win, buf);
450 XRaiseWindow(dpy, win);
452 return;
455 if (c < 0 || c >= nclients)
456 return;
458 resize(c, ww, wh - bh);
459 XRaiseWindow(dpy, clients[c]->win);
460 XSetInputFocus(dpy, clients[c]->win, RevertToParent, CurrentTime);
461 sendxembed(c, XEMBED_FOCUS_IN, XEMBED_FOCUS_CURRENT, 0, 0);
462 sendxembed(c, XEMBED_WINDOW_ACTIVATE, 0, 0, 0);
463 xsettitle(win, clients[c]->name);
465 if (sel != c) {
466 lastsel = sel;
467 sel = c;
470 if (clients[c]->urgent && (wmh = XGetWMHints(dpy, clients[c]->win))) {
471 wmh->flags &= ~XUrgencyHint;
472 XSetWMHints(dpy, clients[c]->win, wmh);
473 clients[c]->urgent = False;
474 XFree(wmh);
477 drawbar();
478 XSync(dpy, False);
481 void
482 focusin(const XEvent *e)
484 const XFocusChangeEvent *ev = &e->xfocus;
485 int dummy;
486 Window focused;
488 if (ev->mode != NotifyUngrab) {
489 XGetInputFocus(dpy, &focused, &dummy);
490 if (focused == win)
491 focus(sel);
495 void
496 focusonce(const Arg *arg)
498 nextfocus = True;
501 void
502 focusurgent(const Arg *arg)
504 int c;
506 for (c = (sel + 1) % nclients; c != sel; c = (c + 1) % nclients) {
507 if (clients[c]->urgent) {
508 focus(c);
509 return;
514 void
515 fullscreen(const Arg *arg)
517 XEvent e;
519 e.type = ClientMessage;
520 e.xclient.window = win;
521 e.xclient.message_type = wmatom[WMState];
522 e.xclient.format = 32;
523 e.xclient.data.l[0] = 2;
524 e.xclient.data.l[1] = wmatom[WMFullscreen];
525 e.xclient.data.l[2] = 0;
526 XSendEvent(dpy, root, False, SubstructureNotifyMask, &e);
529 char *
530 getatom(int a)
532 static char buf[BUFSIZ];
533 Atom adummy;
534 int idummy;
535 unsigned long ldummy;
536 unsigned char *p = NULL;
538 XGetWindowProperty(dpy, win, wmatom[a], 0L, BUFSIZ, False, XA_STRING,
539 &adummy, &idummy, &ldummy, &ldummy, &p);
540 if (p)
541 strncpy(buf, (char *)p, LENGTH(buf)-1);
542 else
543 buf[0] = '\0';
544 XFree(p);
546 return buf;
550 getclient(Window w)
552 int i;
554 for (i = 0; i < nclients; i++) {
555 if (clients[i]->win == w)
556 return i;
559 return -1;
562 XftColor
563 getcolor(const char *colstr)
565 XftColor color;
567 if (!XftColorAllocName(dpy, DefaultVisual(dpy, screen), DefaultColormap(dpy, screen), colstr, &color))
568 die("%s: cannot allocate color '%s'\n", argv0, colstr);
570 return color;
574 getfirsttab(void)
576 int cc, ret;
578 if (sel < 0)
579 return 0;
581 cc = ww / tabwidth;
582 if (nclients > cc)
583 cc = (ww - TEXTW(before) - TEXTW(after)) / tabwidth;
585 ret = sel - cc / 2 + (cc + 1) % 2;
586 return ret < 0 ? 0 :
587 ret + cc > nclients ? MAX(0, nclients - cc) :
588 ret;
591 Bool
592 gettextprop(Window w, Atom atom, char *text, unsigned int size)
594 char **list = NULL;
595 int n;
596 XTextProperty name;
598 if (!text || size == 0)
599 return False;
601 text[0] = '\0';
602 XGetTextProperty(dpy, w, &name, atom);
603 if (!name.nitems)
604 return False;
606 if (name.encoding == XA_STRING) {
607 strncpy(text, (char *)name.value, size - 1);
608 } else if (XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
609 && n > 0 && *list) {
610 strncpy(text, *list, size - 1);
611 XFreeStringList(list);
613 text[size - 1] = '\0';
614 XFree(name.value);
616 return True;
619 void
620 initfont(const char *fontstr)
622 if (!(dc.font.xfont = XftFontOpenName(dpy, screen, fontstr))
623 && !(dc.font.xfont = XftFontOpenName(dpy, screen, "fixed")))
624 die("error, cannot load font: '%s'\n", fontstr);
626 dc.font.ascent = dc.font.xfont->ascent;
627 dc.font.descent = dc.font.xfont->descent;
628 dc.font.height = dc.font.ascent + dc.font.descent;
631 Bool
632 isprotodel(int c)
634 int i, n;
635 Atom *protocols;
636 Bool ret = False;
638 if (XGetWMProtocols(dpy, clients[c]->win, &protocols, &n)) {
639 for (i = 0; !ret && i < n; i++) {
640 if (protocols[i] == wmatom[WMDelete])
641 ret = True;
643 XFree(protocols);
646 return ret;
649 void
650 keypress(const XEvent *e)
652 const XKeyEvent *ev = &e->xkey;
653 unsigned int i;
654 KeySym keysym;
656 keysym = XkbKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0, 0);
657 for (i = 0; i < LENGTH(keys); i++) {
658 if (keysym == keys[i].keysym &&
659 CLEANMASK(keys[i].mod) == CLEANMASK(ev->state) &&
660 keys[i].func)
661 keys[i].func(&(keys[i].arg));
665 void
666 killclient(const Arg *arg)
668 XEvent ev;
670 if (sel < 0)
671 return;
673 if (isprotodel(sel) && !clients[sel]->closed) {
674 ev.type = ClientMessage;
675 ev.xclient.window = clients[sel]->win;
676 ev.xclient.message_type = wmatom[WMProtocols];
677 ev.xclient.format = 32;
678 ev.xclient.data.l[0] = wmatom[WMDelete];
679 ev.xclient.data.l[1] = CurrentTime;
680 XSendEvent(dpy, clients[sel]->win, False, NoEventMask, &ev);
681 clients[sel]->closed = True;
682 } else {
683 XKillClient(dpy, clients[sel]->win);
687 void
688 manage(Window w)
690 updatenumlockmask();
692 int i, j, nextpos;
693 unsigned int modifiers[] = { 0, LockMask, numlockmask,
694 numlockmask | LockMask };
695 KeyCode code;
696 Client *c;
697 XEvent e;
699 XWithdrawWindow(dpy, w, 0);
700 XReparentWindow(dpy, w, win, 0, bh);
701 XSelectInput(dpy, w, PropertyChangeMask |
702 StructureNotifyMask | EnterWindowMask);
703 XSync(dpy, False);
705 for (i = 0; i < LENGTH(keys); i++) {
706 if ((code = XKeysymToKeycode(dpy, keys[i].keysym))) {
707 for (j = 0; j < LENGTH(modifiers); j++) {
708 XGrabKey(dpy, code, keys[i].mod |
709 modifiers[j], w, True,
710 GrabModeAsync, GrabModeAsync);
715 c = ecalloc(1, sizeof *c);
716 c->win = w;
718 nclients++;
719 clients = erealloc(clients, sizeof(Client *) * nclients);
721 if(npisrelative) {
722 nextpos = sel + newposition;
723 } else {
724 if (newposition < 0)
725 nextpos = nclients - newposition;
726 else
727 nextpos = newposition;
729 if (nextpos >= nclients)
730 nextpos = nclients - 1;
731 if (nextpos < 0)
732 nextpos = 0;
734 if (nclients > 1 && nextpos < nclients - 1)
735 memmove(&clients[nextpos + 1], &clients[nextpos],
736 sizeof(Client *) * (nclients - nextpos - 1));
738 clients[nextpos] = c;
739 updatetitle(nextpos);
741 XLowerWindow(dpy, w);
742 XMapWindow(dpy, w);
744 e.xclient.window = w;
745 e.xclient.type = ClientMessage;
746 e.xclient.message_type = wmatom[XEmbed];
747 e.xclient.format = 32;
748 e.xclient.data.l[0] = CurrentTime;
749 e.xclient.data.l[1] = XEMBED_EMBEDDED_NOTIFY;
750 e.xclient.data.l[2] = 0;
751 e.xclient.data.l[3] = win;
752 e.xclient.data.l[4] = 0;
753 XSendEvent(dpy, root, False, NoEventMask, &e);
755 XSync(dpy, False);
757 /* Adjust sel before focus does set it to lastsel. */
758 if (sel >= nextpos)
759 sel++;
760 focus(nextfocus ? nextpos :
761 sel < 0 ? 0 :
762 sel);
763 nextfocus = foreground;
767 void
768 maprequest(const XEvent *e)
770 const XMapRequestEvent *ev = &e->xmaprequest;
772 if (getclient(ev->window) < 0)
773 manage(ev->window);
776 void
777 move(const Arg *arg)
779 if (arg->i >= 0 && arg->i < nclients)
780 focus(arg->i);
783 void
784 movetab(const Arg *arg)
786 int c;
787 Client *new;
789 c = (sel + arg->i) % nclients;
790 if (c < 0)
791 c += nclients;
793 if (sel < 0 || c == sel)
794 return;
796 new = clients[sel];
797 if (sel < c)
798 memmove(&clients[sel], &clients[sel+1],
799 sizeof(Client *) * (c - sel));
800 else
801 memmove(&clients[c+1], &clients[c],
802 sizeof(Client *) * (sel - c));
803 clients[c] = new;
804 sel = c;
806 drawbar();
809 void
810 propertynotify(const XEvent *e)
812 const XPropertyEvent *ev = &e->xproperty;
813 XWMHints *wmh;
814 int c;
815 char* selection = NULL;
816 Arg arg;
818 if (ev->state == PropertyNewValue && ev->atom == wmatom[WMSelectTab]) {
819 selection = getatom(WMSelectTab);
820 if (!strncmp(selection, "0x", 2)) {
821 arg.i = getclient(strtoul(selection, NULL, 0));
822 move(&arg);
823 } else {
824 cmd[cmd_append_pos] = selection;
825 arg.v = cmd;
826 spawn(&arg);
828 } else if (ev->state == PropertyNewValue && ev->atom == XA_WM_HINTS &&
829 (c = getclient(ev->window)) > -1 &&
830 (wmh = XGetWMHints(dpy, clients[c]->win))) {
831 if (wmh->flags & XUrgencyHint) {
832 XFree(wmh);
833 wmh = XGetWMHints(dpy, win);
834 if (c != sel) {
835 if (urgentswitch && wmh &&
836 !(wmh->flags & XUrgencyHint)) {
837 /* only switch, if tabbed was focused
838 * since last urgency hint if WMHints
839 * could not be received,
840 * default to no switch */
841 focus(c);
842 } else {
843 /* if no switch should be performed,
844 * mark tab as urgent */
845 clients[c]->urgent = True;
846 drawbar();
849 if (wmh && !(wmh->flags & XUrgencyHint)) {
850 /* update tabbed urgency hint
851 * if not set already */
852 wmh->flags |= XUrgencyHint;
853 XSetWMHints(dpy, win, wmh);
856 XFree(wmh);
857 } else if (ev->state != PropertyDelete && ev->atom == XA_WM_NAME &&
858 (c = getclient(ev->window)) > -1) {
859 updatetitle(c);
863 void
864 resize(int c, int w, int h)
866 XConfigureEvent ce;
867 XWindowChanges wc;
869 ce.x = 0;
870 ce.y = bh;
871 ce.width = wc.width = w;
872 ce.height = wc.height = h;
873 ce.type = ConfigureNotify;
874 ce.display = dpy;
875 ce.event = clients[c]->win;
876 ce.window = clients[c]->win;
877 ce.above = None;
878 ce.override_redirect = False;
879 ce.border_width = 0;
881 XConfigureWindow(dpy, clients[c]->win, CWWidth | CWHeight, &wc);
882 XSendEvent(dpy, clients[c]->win, False, StructureNotifyMask,
883 (XEvent *)&ce);
886 void
887 rotate(const Arg *arg)
889 int nsel = -1;
891 if (sel < 0)
892 return;
894 if (arg->i == 0) {
895 if (lastsel > -1)
896 focus(lastsel);
897 } else if (sel > -1) {
898 /* Rotating in an arg->i step around the clients. */
899 nsel = sel + arg->i;
900 while (nsel >= nclients)
901 nsel -= nclients;
902 while (nsel < 0)
903 nsel += nclients;
904 focus(nsel);
908 void
909 run(void)
911 XEvent ev;
913 /* main event loop */
914 XSync(dpy, False);
915 drawbar();
916 if (doinitspawn == True)
917 spawn(NULL);
919 while (running) {
920 XNextEvent(dpy, &ev);
921 if (handler[ev.type])
922 (handler[ev.type])(&ev); /* call handler */
926 void
927 sendxembed(int c, long msg, long detail, long d1, long d2)
929 XEvent e = { 0 };
931 e.xclient.window = clients[c]->win;
932 e.xclient.type = ClientMessage;
933 e.xclient.message_type = wmatom[XEmbed];
934 e.xclient.format = 32;
935 e.xclient.data.l[0] = CurrentTime;
936 e.xclient.data.l[1] = msg;
937 e.xclient.data.l[2] = detail;
938 e.xclient.data.l[3] = d1;
939 e.xclient.data.l[4] = d2;
940 XSendEvent(dpy, clients[c]->win, False, NoEventMask, &e);
943 void
944 setcmd(int argc, char *argv[], int replace)
946 int i;
948 cmd = ecalloc(argc + 3, sizeof(*cmd));
949 if (argc == 0)
950 return;
951 for (i = 0; i < argc; i++)
952 cmd[i] = argv[i];
953 cmd[replace > 0 ? replace : argc] = winid;
954 cmd_append_pos = argc + !replace;
955 cmd[cmd_append_pos] = cmd[cmd_append_pos + 1] = NULL;
958 void
959 setup(void)
961 int bitm, tx, ty, tw, th, dh, dw, isfixed;
962 XWMHints *wmh;
963 XClassHint class_hint;
964 XSizeHints *size_hint;
966 /* clean up any zombies immediately */
967 sigchld(0);
969 /* init screen */
970 screen = DefaultScreen(dpy);
971 root = RootWindow(dpy, screen);
972 initfont(font);
973 bh = dc.h = dc.font.height + 2;
975 /* init atoms */
976 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
977 wmatom[WMFullscreen] = XInternAtom(dpy, "_NET_WM_STATE_FULLSCREEN",
978 False);
979 wmatom[WMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
980 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
981 wmatom[WMSelectTab] = XInternAtom(dpy, "_TABBED_SELECT_TAB", False);
982 wmatom[WMState] = XInternAtom(dpy, "_NET_WM_STATE", False);
983 wmatom[XEmbed] = XInternAtom(dpy, "_XEMBED", False);
985 /* init appearance */
986 wx = 0;
987 wy = 0;
988 ww = 800;
989 wh = 600;
990 isfixed = 0;
992 if (geometry) {
993 tx = ty = tw = th = 0;
994 bitm = XParseGeometry(geometry, &tx, &ty, (unsigned *)&tw,
995 (unsigned *)&th);
996 if (bitm & XValue)
997 wx = tx;
998 if (bitm & YValue)
999 wy = ty;
1000 if (bitm & WidthValue)
1001 ww = tw;
1002 if (bitm & HeightValue)
1003 wh = th;
1004 if (bitm & XNegative && wx == 0)
1005 wx = -1;
1006 if (bitm & YNegative && wy == 0)
1007 wy = -1;
1008 if (bitm & (HeightValue | WidthValue))
1009 isfixed = 1;
1011 dw = DisplayWidth(dpy, screen);
1012 dh = DisplayHeight(dpy, screen);
1013 if (wx < 0)
1014 wx = dw + wx - ww - 1;
1015 if (wy < 0)
1016 wy = dh + wy - wh - 1;
1019 dc.norm[ColBG] = getcolor(normbgcolor);
1020 dc.norm[ColFG] = getcolor(normfgcolor);
1021 dc.sel[ColBG] = getcolor(selbgcolor);
1022 dc.sel[ColFG] = getcolor(selfgcolor);
1023 dc.urg[ColBG] = getcolor(urgbgcolor);
1024 dc.urg[ColFG] = getcolor(urgfgcolor);
1025 dc.drawable = XCreatePixmap(dpy, root, ww, wh,
1026 DefaultDepth(dpy, screen));
1027 dc.gc = XCreateGC(dpy, root, 0, 0);
1029 win = XCreateSimpleWindow(dpy, root, wx, wy, ww, wh, 0,
1030 dc.norm[ColFG].pixel, dc.norm[ColBG].pixel);
1031 XMapRaised(dpy, win);
1032 XSelectInput(dpy, win, SubstructureNotifyMask | FocusChangeMask |
1033 ButtonPressMask | ExposureMask | KeyPressMask |
1034 PropertyChangeMask | StructureNotifyMask |
1035 SubstructureRedirectMask);
1036 xerrorxlib = XSetErrorHandler(xerror);
1038 class_hint.res_name = wmname;
1039 class_hint.res_class = "tabbed";
1040 XSetClassHint(dpy, win, &class_hint);
1042 size_hint = XAllocSizeHints();
1043 if (!isfixed) {
1044 size_hint->flags = PSize;
1045 size_hint->height = wh;
1046 size_hint->width = ww;
1047 } else {
1048 size_hint->flags = PMaxSize | PMinSize;
1049 size_hint->min_width = size_hint->max_width = ww;
1050 size_hint->min_height = size_hint->max_height = wh;
1052 wmh = XAllocWMHints();
1053 XSetWMProperties(dpy, win, NULL, NULL, NULL, 0, size_hint, wmh, NULL);
1054 XFree(size_hint);
1055 XFree(wmh);
1057 XSetWMProtocols(dpy, win, &wmatom[WMDelete], 1);
1059 snprintf(winid, sizeof(winid), "%lu", win);
1060 setenv("XEMBED", winid, 1);
1062 nextfocus = foreground;
1063 focus(-1);
1066 void
1067 sigchld(int unused)
1069 if (signal(SIGCHLD, sigchld) == SIG_ERR)
1070 die("%s: cannot install SIGCHLD handler", argv0);
1072 while (0 < waitpid(-1, NULL, WNOHANG));
1075 void
1076 spawn(const Arg *arg)
1078 if (fork() == 0) {
1079 if(dpy)
1080 close(ConnectionNumber(dpy));
1082 setsid();
1083 if (arg && arg->v) {
1084 execvp(((char **)arg->v)[0], (char **)arg->v);
1085 fprintf(stderr, "%s: execvp %s", argv0,
1086 ((char **)arg->v)[0]);
1087 } else {
1088 cmd[cmd_append_pos] = NULL;
1089 execvp(cmd[0], cmd);
1090 fprintf(stderr, "%s: execvp %s", argv0, cmd[0]);
1092 perror(" failed");
1093 exit(0);
1098 textnw(const char *text, unsigned int len)
1100 XGlyphInfo ext;
1101 XftTextExtentsUtf8(dpy, dc.font.xfont, (XftChar8 *) text, len, &ext);
1102 return ext.xOff;
1105 void
1106 toggle(const Arg *arg)
1108 *(Bool*) arg->v = !*(Bool*) arg->v;
1111 void
1112 unmanage(int c)
1114 if (c < 0 || c >= nclients) {
1115 drawbar();
1116 XSync(dpy, False);
1117 return;
1120 if (!nclients)
1121 return;
1123 if (c == 0) {
1124 /* First client. */
1125 nclients--;
1126 free(clients[0]);
1127 memmove(&clients[0], &clients[1], sizeof(Client *) * nclients);
1128 } else if (c == nclients - 1) {
1129 /* Last client. */
1130 nclients--;
1131 free(clients[c]);
1132 clients = erealloc(clients, sizeof(Client *) * nclients);
1133 } else {
1134 /* Somewhere inbetween. */
1135 free(clients[c]);
1136 memmove(&clients[c], &clients[c+1],
1137 sizeof(Client *) * (nclients - (c + 1)));
1138 nclients--;
1141 if (nclients <= 0) {
1142 lastsel = sel = -1;
1144 if (closelastclient)
1145 running = False;
1146 else if (fillagain && running)
1147 spawn(NULL);
1148 } else {
1149 if (lastsel >= nclients)
1150 lastsel = nclients - 1;
1151 else if (lastsel > c)
1152 lastsel--;
1154 if (c == sel && lastsel >= 0) {
1155 focus(lastsel);
1156 } else {
1157 if (sel > c)
1158 sel--;
1159 if (sel >= nclients)
1160 sel = nclients - 1;
1162 focus(sel);
1166 drawbar();
1167 XSync(dpy, False);
1170 void
1171 unmapnotify(const XEvent *e)
1173 const XUnmapEvent *ev = &e->xunmap;
1174 int c;
1176 if ((c = getclient(ev->window)) > -1)
1177 unmanage(c);
1180 void
1181 updatenumlockmask(void)
1183 unsigned int i, j;
1184 XModifierKeymap *modmap;
1186 numlockmask = 0;
1187 modmap = XGetModifierMapping(dpy);
1188 for (i = 0; i < 8; i++) {
1189 for (j = 0; j < modmap->max_keypermod; j++) {
1190 if (modmap->modifiermap[i * modmap->max_keypermod + j]
1191 == XKeysymToKeycode(dpy, XK_Num_Lock))
1192 numlockmask = (1 << i);
1195 XFreeModifiermap(modmap);
1198 void
1199 updatetitle(int c)
1201 if (!gettextprop(clients[c]->win, wmatom[WMName], clients[c]->name,
1202 sizeof(clients[c]->name)))
1203 gettextprop(clients[c]->win, XA_WM_NAME, clients[c]->name,
1204 sizeof(clients[c]->name));
1205 if (sel == c)
1206 xsettitle(win, clients[c]->name);
1207 drawbar();
1210 /* There's no way to check accesses to destroyed windows, thus those cases are
1211 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1212 * default error handler, which may call exit. */
1214 xerror(Display *dpy, XErrorEvent *ee)
1216 if (ee->error_code == BadWindow
1217 || (ee->request_code == X_SetInputFocus &&
1218 ee->error_code == BadMatch)
1219 || (ee->request_code == X_PolyText8 &&
1220 ee->error_code == BadDrawable)
1221 || (ee->request_code == X_PolyFillRectangle &&
1222 ee->error_code == BadDrawable)
1223 || (ee->request_code == X_PolySegment &&
1224 ee->error_code == BadDrawable)
1225 || (ee->request_code == X_ConfigureWindow &&
1226 ee->error_code == BadMatch)
1227 || (ee->request_code == X_GrabButton &&
1228 ee->error_code == BadAccess)
1229 || (ee->request_code == X_GrabKey &&
1230 ee->error_code == BadAccess)
1231 || (ee->request_code == X_CopyArea &&
1232 ee->error_code == BadDrawable))
1233 return 0;
1235 fprintf(stderr, "%s: fatal error: request code=%d, error code=%d\n",
1236 argv0, ee->request_code, ee->error_code);
1237 return xerrorxlib(dpy, ee); /* may call exit */
1240 void
1241 xsettitle(Window w, const char *str)
1243 XTextProperty xtp;
1245 if (XmbTextListToTextProperty(dpy, (char **)&str, 1,
1246 XCompoundTextStyle, &xtp) == Success) {
1247 XSetTextProperty(dpy, w, &xtp, wmatom[WMName]);
1248 XSetTextProperty(dpy, w, &xtp, XA_WM_NAME);
1249 XFree(xtp.value);
1253 void
1254 usage(void)
1256 die("usage: %s [-dfksv] [-g geometry] [-n name] [-p [s+/-]pos]\n"
1257 " [-r narg] [-o color] [-O color] [-t color] [-T color]\n"
1258 " [-u color] [-U color] command...\n", argv0);
1262 main(int argc, char *argv[])
1264 Bool detach = False;
1265 int replace = 0;
1266 char *pstr;
1268 ARGBEGIN {
1269 case 'c':
1270 closelastclient = True;
1271 fillagain = False;
1272 break;
1273 case 'd':
1274 detach = True;
1275 break;
1276 case 'f':
1277 fillagain = True;
1278 break;
1279 case 'g':
1280 geometry = EARGF(usage());
1281 break;
1282 case 'k':
1283 killclientsfirst = True;
1284 break;
1285 case 'n':
1286 wmname = EARGF(usage());
1287 break;
1288 case 'O':
1289 normfgcolor = EARGF(usage());
1290 break;
1291 case 'o':
1292 normbgcolor = EARGF(usage());
1293 break;
1294 case 'p':
1295 pstr = EARGF(usage());
1296 if (pstr[0] == 's') {
1297 npisrelative = True;
1298 newposition = atoi(&pstr[1]);
1299 } else {
1300 newposition = atoi(pstr);
1302 break;
1303 case 'r':
1304 replace = atoi(EARGF(usage()));
1305 break;
1306 case 's':
1307 doinitspawn = False;
1308 break;
1309 case 'T':
1310 selfgcolor = EARGF(usage());
1311 break;
1312 case 't':
1313 selbgcolor = EARGF(usage());
1314 break;
1315 case 'U':
1316 urgfgcolor = EARGF(usage());
1317 break;
1318 case 'u':
1319 urgbgcolor = EARGF(usage());
1320 break;
1321 case 'v':
1322 die("tabbed-"VERSION", © 2009-2016 tabbed engineers, "
1323 "see LICENSE for details.\n");
1324 break;
1325 default:
1326 usage();
1327 break;
1328 } ARGEND;
1330 if (argc < 1) {
1331 doinitspawn = False;
1332 fillagain = False;
1335 setcmd(argc, argv, replace);
1337 if (!setlocale(LC_CTYPE, "") || !XSupportsLocale())
1338 fprintf(stderr, "%s: no locale support\n", argv0);
1339 if (!(dpy = XOpenDisplay(NULL)))
1340 die("%s: cannot open display\n", argv0);
1342 setup();
1343 printf("0x%lx\n", win);
1344 fflush(NULL);
1346 if (detach) {
1347 if (fork() == 0) {
1348 fclose(stdout);
1349 } else {
1350 if (dpy)
1351 close(ConnectionNumber(dpy));
1352 return EXIT_SUCCESS;
1356 run();
1357 cleanup();
1358 XCloseDisplay(dpy);
1360 return EXIT_SUCCESS;