Embed dmenu in tabbed own window
[tabbed/julien_tabbed.git] / tabbed.c
blobff3ada0fd6b078ef8ddbc51da6ad9c00fd0d97c9
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 XReparentWindow(dpy, clients[i]->win, root, 0, 0);
221 unmanage(i);
223 free(clients);
224 clients = NULL;
226 XFreePixmap(dpy, dc.drawable);
227 XFreeGC(dpy, dc.gc);
228 XDestroyWindow(dpy, win);
229 XSync(dpy, False);
230 free(cmd);
233 void
234 clientmessage(const XEvent *e)
236 const XClientMessageEvent *ev = &e->xclient;
238 if (ev->message_type == wmatom[WMProtocols] &&
239 ev->data.l[0] == wmatom[WMDelete]) {
240 if (nclients > 1 && killclientsfirst) {
241 killclient(0);
242 return;
244 running = False;
248 void
249 configurenotify(const XEvent *e)
251 const XConfigureEvent *ev = &e->xconfigure;
253 if (ev->window == win && (ev->width != ww || ev->height != wh)) {
254 ww = ev->width;
255 wh = ev->height;
256 XFreePixmap(dpy, dc.drawable);
257 dc.drawable = XCreatePixmap(dpy, root, ww, wh,
258 DefaultDepth(dpy, screen));
259 if (sel > -1)
260 resize(sel, ww, wh - bh);
261 XSync(dpy, False);
265 void
266 configurerequest(const XEvent *e)
268 const XConfigureRequestEvent *ev = &e->xconfigurerequest;
269 XWindowChanges wc;
270 int c;
272 if ((c = getclient(ev->window)) > -1) {
273 wc.x = 0;
274 wc.y = bh;
275 wc.width = ww;
276 wc.height = wh - bh;
277 wc.border_width = 0;
278 wc.sibling = ev->above;
279 wc.stack_mode = ev->detail;
280 XConfigureWindow(dpy, clients[c]->win, ev->value_mask, &wc);
284 void
285 createnotify(const XEvent *e)
287 const XCreateWindowEvent *ev = &e->xcreatewindow;
289 if (ev->window != win && getclient(ev->window) < 0)
290 manage(ev->window);
293 void
294 destroynotify(const XEvent *e)
296 const XDestroyWindowEvent *ev = &e->xdestroywindow;
297 int c;
299 if ((c = getclient(ev->window)) > -1)
300 unmanage(c);
303 void
304 die(const char *errstr, ...)
306 va_list ap;
308 va_start(ap, errstr);
309 vfprintf(stderr, errstr, ap);
310 va_end(ap);
311 exit(EXIT_FAILURE);
314 void
315 drawbar(void)
317 XftColor *col;
318 int c, cc, fc, width;
319 char *name = NULL;
321 if (nclients == 0) {
322 dc.x = 0;
323 dc.w = ww;
324 XFetchName(dpy, win, &name);
325 drawtext(name ? name : "", dc.norm);
326 XCopyArea(dpy, dc.drawable, win, dc.gc, 0, 0, ww, bh, 0, 0);
327 XSync(dpy, False);
329 return;
332 width = ww;
333 cc = ww / tabwidth;
334 if (nclients > cc)
335 cc = (ww - TEXTW(before) - TEXTW(after)) / tabwidth;
337 if ((fc = getfirsttab()) + cc < nclients) {
338 dc.w = TEXTW(after);
339 dc.x = width - dc.w;
340 drawtext(after, dc.sel);
341 width -= dc.w;
343 dc.x = 0;
345 if (fc > 0) {
346 dc.w = TEXTW(before);
347 drawtext(before, dc.sel);
348 dc.x += dc.w;
349 width -= dc.w;
352 cc = MIN(cc, nclients);
353 for (c = fc; c < fc + cc; c++) {
354 dc.w = width / cc;
355 if (c == sel) {
356 col = dc.sel;
357 dc.w += width % cc;
358 } else {
359 col = clients[c]->urgent ? dc.urg : dc.norm;
361 drawtext(clients[c]->name, col);
362 dc.x += dc.w;
363 clients[c]->tabx = dc.x;
365 XCopyArea(dpy, dc.drawable, win, dc.gc, 0, 0, ww, bh, 0, 0);
366 XSync(dpy, False);
369 void
370 drawtext(const char *text, XftColor col[ColLast])
372 int i, j, x, y, h, len, olen;
373 char buf[256];
374 XftDraw *d;
375 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
377 XSetForeground(dpy, dc.gc, col[ColBG].pixel);
378 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
379 if (!text)
380 return;
382 olen = strlen(text);
383 h = dc.font.ascent + dc.font.descent;
384 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
385 x = dc.x + (h / 2);
387 /* shorten text if necessary */
388 for (len = MIN(olen, sizeof(buf));
389 len && textnw(text, len) > dc.w - h; len--);
391 if (!len)
392 return;
394 memcpy(buf, text, len);
395 if (len < olen) {
396 for (i = len, j = strlen(titletrim); j && i;
397 buf[--i] = titletrim[--j])
401 d = XftDrawCreate(dpy, dc.drawable, DefaultVisual(dpy, screen), DefaultColormap(dpy, screen));
402 XftDrawStringUtf8(d, &col[ColFG], dc.font.xfont, x, y, (XftChar8 *) buf, len);
403 XftDrawDestroy(d);
406 void *
407 ecalloc(size_t n, size_t size)
409 void *p;
411 if (!(p = calloc(n, size)))
412 die("%s: cannot calloc\n", argv0);
413 return p;
416 void *
417 erealloc(void *o, size_t size)
419 void *p;
421 if (!(p = realloc(o, size)))
422 die("%s: cannot realloc\n", argv0);
423 return p;
426 void
427 expose(const XEvent *e)
429 const XExposeEvent *ev = &e->xexpose;
431 if (ev->count == 0 && win == ev->window)
432 drawbar();
435 void
436 focus(int c)
438 char buf[BUFSIZ] = "tabbed-"VERSION" ::";
439 size_t i, n;
440 XWMHints* wmh;
442 /* If c, sel and clients are -1, raise tabbed-win itself */
443 if (nclients == 0) {
444 cmd[cmd_append_pos] = NULL;
445 for(i = 0, n = strlen(buf); cmd[i] && n < sizeof(buf); i++)
446 n += snprintf(&buf[n], sizeof(buf) - n, " %s", cmd[i]);
448 xsettitle(win, buf);
449 XRaiseWindow(dpy, win);
451 return;
454 if (c < 0 || c >= nclients)
455 return;
457 resize(c, ww, wh - bh);
458 XRaiseWindow(dpy, clients[c]->win);
459 XSetInputFocus(dpy, clients[c]->win, RevertToParent, CurrentTime);
460 sendxembed(c, XEMBED_FOCUS_IN, XEMBED_FOCUS_CURRENT, 0, 0);
461 sendxembed(c, XEMBED_WINDOW_ACTIVATE, 0, 0, 0);
462 xsettitle(win, clients[c]->name);
464 if (sel != c) {
465 lastsel = sel;
466 sel = c;
469 if (clients[c]->urgent && (wmh = XGetWMHints(dpy, clients[c]->win))) {
470 wmh->flags &= ~XUrgencyHint;
471 XSetWMHints(dpy, clients[c]->win, wmh);
472 clients[c]->urgent = False;
473 XFree(wmh);
476 drawbar();
477 XSync(dpy, False);
480 void
481 focusin(const XEvent *e)
483 const XFocusChangeEvent *ev = &e->xfocus;
484 int dummy;
485 Window focused;
487 if (ev->mode != NotifyUngrab) {
488 XGetInputFocus(dpy, &focused, &dummy);
489 if (focused == win)
490 focus(sel);
494 void
495 focusonce(const Arg *arg)
497 nextfocus = True;
500 void
501 focusurgent(const Arg *arg)
503 int c;
505 if (sel < 0)
506 return;
508 for (c = (sel + 1) % nclients; c != sel; c = (c + 1) % nclients) {
509 if (clients[c]->urgent) {
510 focus(c);
511 return;
516 void
517 fullscreen(const Arg *arg)
519 XEvent e;
521 e.type = ClientMessage;
522 e.xclient.window = win;
523 e.xclient.message_type = wmatom[WMState];
524 e.xclient.format = 32;
525 e.xclient.data.l[0] = 2;
526 e.xclient.data.l[1] = wmatom[WMFullscreen];
527 e.xclient.data.l[2] = 0;
528 XSendEvent(dpy, root, False, SubstructureNotifyMask, &e);
531 char *
532 getatom(int a)
534 static char buf[BUFSIZ];
535 Atom adummy;
536 int idummy;
537 unsigned long ldummy;
538 unsigned char *p = NULL;
540 XGetWindowProperty(dpy, win, wmatom[a], 0L, BUFSIZ, False, XA_STRING,
541 &adummy, &idummy, &ldummy, &ldummy, &p);
542 if (p)
543 strncpy(buf, (char *)p, LENGTH(buf)-1);
544 else
545 buf[0] = '\0';
546 XFree(p);
548 return buf;
552 getclient(Window w)
554 int i;
556 for (i = 0; i < nclients; i++) {
557 if (clients[i]->win == w)
558 return i;
561 return -1;
564 XftColor
565 getcolor(const char *colstr)
567 XftColor color;
569 if (!XftColorAllocName(dpy, DefaultVisual(dpy, screen), DefaultColormap(dpy, screen), colstr, &color))
570 die("%s: cannot allocate color '%s'\n", argv0, colstr);
572 return color;
576 getfirsttab(void)
578 int cc, ret;
580 if (sel < 0)
581 return 0;
583 cc = ww / tabwidth;
584 if (nclients > cc)
585 cc = (ww - TEXTW(before) - TEXTW(after)) / tabwidth;
587 ret = sel - cc / 2 + (cc + 1) % 2;
588 return ret < 0 ? 0 :
589 ret + cc > nclients ? MAX(0, nclients - cc) :
590 ret;
593 Bool
594 gettextprop(Window w, Atom atom, char *text, unsigned int size)
596 char **list = NULL;
597 int n;
598 XTextProperty name;
600 if (!text || size == 0)
601 return False;
603 text[0] = '\0';
604 XGetTextProperty(dpy, w, &name, atom);
605 if (!name.nitems)
606 return False;
608 if (name.encoding == XA_STRING) {
609 strncpy(text, (char *)name.value, size - 1);
610 } else if (XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
611 && n > 0 && *list) {
612 strncpy(text, *list, size - 1);
613 XFreeStringList(list);
615 text[size - 1] = '\0';
616 XFree(name.value);
618 return True;
621 void
622 initfont(const char *fontstr)
624 if (!(dc.font.xfont = XftFontOpenName(dpy, screen, fontstr))
625 && !(dc.font.xfont = XftFontOpenName(dpy, screen, "fixed")))
626 die("error, cannot load font: '%s'\n", fontstr);
628 dc.font.ascent = dc.font.xfont->ascent;
629 dc.font.descent = dc.font.xfont->descent;
630 dc.font.height = dc.font.ascent + dc.font.descent;
633 Bool
634 isprotodel(int c)
636 int i, n;
637 Atom *protocols;
638 Bool ret = False;
640 if (XGetWMProtocols(dpy, clients[c]->win, &protocols, &n)) {
641 for (i = 0; !ret && i < n; i++) {
642 if (protocols[i] == wmatom[WMDelete])
643 ret = True;
645 XFree(protocols);
648 return ret;
651 void
652 keypress(const XEvent *e)
654 const XKeyEvent *ev = &e->xkey;
655 unsigned int i;
656 KeySym keysym;
658 keysym = XkbKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0, 0);
659 for (i = 0; i < LENGTH(keys); i++) {
660 if (keysym == keys[i].keysym &&
661 CLEANMASK(keys[i].mod) == CLEANMASK(ev->state) &&
662 keys[i].func)
663 keys[i].func(&(keys[i].arg));
667 void
668 killclient(const Arg *arg)
670 XEvent ev;
672 if (sel < 0)
673 return;
675 if (isprotodel(sel) && !clients[sel]->closed) {
676 ev.type = ClientMessage;
677 ev.xclient.window = clients[sel]->win;
678 ev.xclient.message_type = wmatom[WMProtocols];
679 ev.xclient.format = 32;
680 ev.xclient.data.l[0] = wmatom[WMDelete];
681 ev.xclient.data.l[1] = CurrentTime;
682 XSendEvent(dpy, clients[sel]->win, False, NoEventMask, &ev);
683 clients[sel]->closed = True;
684 } else {
685 XKillClient(dpy, clients[sel]->win);
689 void
690 manage(Window w)
692 updatenumlockmask();
694 int i, j, nextpos;
695 unsigned int modifiers[] = { 0, LockMask, numlockmask,
696 numlockmask | LockMask };
697 KeyCode code;
698 Client *c;
699 XEvent e;
701 XWithdrawWindow(dpy, w, 0);
702 XReparentWindow(dpy, w, win, 0, bh);
703 XSelectInput(dpy, w, PropertyChangeMask |
704 StructureNotifyMask | EnterWindowMask);
705 XSync(dpy, False);
707 for (i = 0; i < LENGTH(keys); i++) {
708 if ((code = XKeysymToKeycode(dpy, keys[i].keysym))) {
709 for (j = 0; j < LENGTH(modifiers); j++) {
710 XGrabKey(dpy, code, keys[i].mod |
711 modifiers[j], w, True,
712 GrabModeAsync, GrabModeAsync);
717 c = ecalloc(1, sizeof *c);
718 c->win = w;
720 nclients++;
721 clients = erealloc(clients, sizeof(Client *) * nclients);
723 if(npisrelative) {
724 nextpos = sel + newposition;
725 } else {
726 if (newposition < 0)
727 nextpos = nclients - newposition;
728 else
729 nextpos = newposition;
731 if (nextpos >= nclients)
732 nextpos = nclients - 1;
733 if (nextpos < 0)
734 nextpos = 0;
736 if (nclients > 1 && nextpos < nclients - 1)
737 memmove(&clients[nextpos + 1], &clients[nextpos],
738 sizeof(Client *) * (nclients - nextpos - 1));
740 clients[nextpos] = c;
741 updatetitle(nextpos);
743 XLowerWindow(dpy, w);
744 XMapWindow(dpy, w);
746 e.xclient.window = w;
747 e.xclient.type = ClientMessage;
748 e.xclient.message_type = wmatom[XEmbed];
749 e.xclient.format = 32;
750 e.xclient.data.l[0] = CurrentTime;
751 e.xclient.data.l[1] = XEMBED_EMBEDDED_NOTIFY;
752 e.xclient.data.l[2] = 0;
753 e.xclient.data.l[3] = win;
754 e.xclient.data.l[4] = 0;
755 XSendEvent(dpy, root, False, NoEventMask, &e);
757 XSync(dpy, False);
759 /* Adjust sel before focus does set it to lastsel. */
760 if (sel >= nextpos)
761 sel++;
762 focus(nextfocus ? nextpos :
763 sel < 0 ? 0 :
764 sel);
765 nextfocus = foreground;
769 void
770 maprequest(const XEvent *e)
772 const XMapRequestEvent *ev = &e->xmaprequest;
774 if (getclient(ev->window) < 0)
775 manage(ev->window);
778 void
779 move(const Arg *arg)
781 if (arg->i >= 0 && arg->i < nclients)
782 focus(arg->i);
785 void
786 movetab(const Arg *arg)
788 int c;
789 Client *new;
791 if (sel < 0)
792 return;
794 c = (sel + arg->i) % nclients;
795 if (c < 0)
796 c += nclients;
798 if (c == sel)
799 return;
801 new = clients[sel];
802 if (sel < c)
803 memmove(&clients[sel], &clients[sel+1],
804 sizeof(Client *) * (c - sel));
805 else
806 memmove(&clients[c+1], &clients[c],
807 sizeof(Client *) * (sel - c));
808 clients[c] = new;
809 sel = c;
811 drawbar();
814 void
815 propertynotify(const XEvent *e)
817 const XPropertyEvent *ev = &e->xproperty;
818 XWMHints *wmh;
819 int c;
820 char* selection = NULL;
821 Arg arg;
823 if (ev->state == PropertyNewValue && ev->atom == wmatom[WMSelectTab]) {
824 selection = getatom(WMSelectTab);
825 if (!strncmp(selection, "0x", 2)) {
826 arg.i = getclient(strtoul(selection, NULL, 0));
827 move(&arg);
828 } else {
829 cmd[cmd_append_pos] = selection;
830 arg.v = cmd;
831 spawn(&arg);
833 } else if (ev->state == PropertyNewValue && ev->atom == XA_WM_HINTS &&
834 (c = getclient(ev->window)) > -1 &&
835 (wmh = XGetWMHints(dpy, clients[c]->win))) {
836 if (wmh->flags & XUrgencyHint) {
837 XFree(wmh);
838 wmh = XGetWMHints(dpy, win);
839 if (c != sel) {
840 if (urgentswitch && wmh &&
841 !(wmh->flags & XUrgencyHint)) {
842 /* only switch, if tabbed was focused
843 * since last urgency hint if WMHints
844 * could not be received,
845 * default to no switch */
846 focus(c);
847 } else {
848 /* if no switch should be performed,
849 * mark tab as urgent */
850 clients[c]->urgent = True;
851 drawbar();
854 if (wmh && !(wmh->flags & XUrgencyHint)) {
855 /* update tabbed urgency hint
856 * if not set already */
857 wmh->flags |= XUrgencyHint;
858 XSetWMHints(dpy, win, wmh);
861 XFree(wmh);
862 } else if (ev->state != PropertyDelete && ev->atom == XA_WM_NAME &&
863 (c = getclient(ev->window)) > -1) {
864 updatetitle(c);
868 void
869 resize(int c, int w, int h)
871 XConfigureEvent ce;
872 XWindowChanges wc;
874 ce.x = 0;
875 ce.y = bh;
876 ce.width = wc.width = w;
877 ce.height = wc.height = h;
878 ce.type = ConfigureNotify;
879 ce.display = dpy;
880 ce.event = clients[c]->win;
881 ce.window = clients[c]->win;
882 ce.above = None;
883 ce.override_redirect = False;
884 ce.border_width = 0;
886 XConfigureWindow(dpy, clients[c]->win, CWWidth | CWHeight, &wc);
887 XSendEvent(dpy, clients[c]->win, False, StructureNotifyMask,
888 (XEvent *)&ce);
891 void
892 rotate(const Arg *arg)
894 int nsel = -1;
896 if (sel < 0)
897 return;
899 if (arg->i == 0) {
900 if (lastsel > -1)
901 focus(lastsel);
902 } else if (sel > -1) {
903 /* Rotating in an arg->i step around the clients. */
904 nsel = sel + arg->i;
905 while (nsel >= nclients)
906 nsel -= nclients;
907 while (nsel < 0)
908 nsel += nclients;
909 focus(nsel);
913 void
914 run(void)
916 XEvent ev;
918 /* main event loop */
919 XSync(dpy, False);
920 drawbar();
921 if (doinitspawn == True)
922 spawn(NULL);
924 while (running) {
925 XNextEvent(dpy, &ev);
926 if (handler[ev.type])
927 (handler[ev.type])(&ev); /* call handler */
931 void
932 sendxembed(int c, long msg, long detail, long d1, long d2)
934 XEvent e = { 0 };
936 e.xclient.window = clients[c]->win;
937 e.xclient.type = ClientMessage;
938 e.xclient.message_type = wmatom[XEmbed];
939 e.xclient.format = 32;
940 e.xclient.data.l[0] = CurrentTime;
941 e.xclient.data.l[1] = msg;
942 e.xclient.data.l[2] = detail;
943 e.xclient.data.l[3] = d1;
944 e.xclient.data.l[4] = d2;
945 XSendEvent(dpy, clients[c]->win, False, NoEventMask, &e);
948 void
949 setcmd(int argc, char *argv[], int replace)
951 int i;
953 cmd = ecalloc(argc + 3, sizeof(*cmd));
954 if (argc == 0)
955 return;
956 for (i = 0; i < argc; i++)
957 cmd[i] = argv[i];
958 cmd[replace > 0 ? replace : argc] = winid;
959 cmd_append_pos = argc + !replace;
960 cmd[cmd_append_pos] = cmd[cmd_append_pos + 1] = NULL;
963 void
964 setup(void)
966 int bitm, tx, ty, tw, th, dh, dw, isfixed;
967 XWMHints *wmh;
968 XClassHint class_hint;
969 XSizeHints *size_hint;
971 /* clean up any zombies immediately */
972 sigchld(0);
974 /* init screen */
975 screen = DefaultScreen(dpy);
976 root = RootWindow(dpy, screen);
977 initfont(font);
978 bh = dc.h = dc.font.height + 2;
980 /* init atoms */
981 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
982 wmatom[WMFullscreen] = XInternAtom(dpy, "_NET_WM_STATE_FULLSCREEN",
983 False);
984 wmatom[WMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
985 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
986 wmatom[WMSelectTab] = XInternAtom(dpy, "_TABBED_SELECT_TAB", False);
987 wmatom[WMState] = XInternAtom(dpy, "_NET_WM_STATE", False);
988 wmatom[XEmbed] = XInternAtom(dpy, "_XEMBED", False);
990 /* init appearance */
991 wx = 0;
992 wy = 0;
993 ww = 800;
994 wh = 600;
995 isfixed = 0;
997 if (geometry) {
998 tx = ty = tw = th = 0;
999 bitm = XParseGeometry(geometry, &tx, &ty, (unsigned *)&tw,
1000 (unsigned *)&th);
1001 if (bitm & XValue)
1002 wx = tx;
1003 if (bitm & YValue)
1004 wy = ty;
1005 if (bitm & WidthValue)
1006 ww = tw;
1007 if (bitm & HeightValue)
1008 wh = th;
1009 if (bitm & XNegative && wx == 0)
1010 wx = -1;
1011 if (bitm & YNegative && wy == 0)
1012 wy = -1;
1013 if (bitm & (HeightValue | WidthValue))
1014 isfixed = 1;
1016 dw = DisplayWidth(dpy, screen);
1017 dh = DisplayHeight(dpy, screen);
1018 if (wx < 0)
1019 wx = dw + wx - ww - 1;
1020 if (wy < 0)
1021 wy = dh + wy - wh - 1;
1024 dc.norm[ColBG] = getcolor(normbgcolor);
1025 dc.norm[ColFG] = getcolor(normfgcolor);
1026 dc.sel[ColBG] = getcolor(selbgcolor);
1027 dc.sel[ColFG] = getcolor(selfgcolor);
1028 dc.urg[ColBG] = getcolor(urgbgcolor);
1029 dc.urg[ColFG] = getcolor(urgfgcolor);
1030 dc.drawable = XCreatePixmap(dpy, root, ww, wh,
1031 DefaultDepth(dpy, screen));
1032 dc.gc = XCreateGC(dpy, root, 0, 0);
1034 win = XCreateSimpleWindow(dpy, root, wx, wy, ww, wh, 0,
1035 dc.norm[ColFG].pixel, dc.norm[ColBG].pixel);
1036 XMapRaised(dpy, win);
1037 XSelectInput(dpy, win, SubstructureNotifyMask | FocusChangeMask |
1038 ButtonPressMask | ExposureMask | KeyPressMask |
1039 PropertyChangeMask | StructureNotifyMask |
1040 SubstructureRedirectMask);
1041 xerrorxlib = XSetErrorHandler(xerror);
1043 class_hint.res_name = wmname;
1044 class_hint.res_class = "tabbed";
1045 XSetClassHint(dpy, win, &class_hint);
1047 size_hint = XAllocSizeHints();
1048 if (!isfixed) {
1049 size_hint->flags = PSize;
1050 size_hint->height = wh;
1051 size_hint->width = ww;
1052 } else {
1053 size_hint->flags = PMaxSize | PMinSize;
1054 size_hint->min_width = size_hint->max_width = ww;
1055 size_hint->min_height = size_hint->max_height = wh;
1057 wmh = XAllocWMHints();
1058 XSetWMProperties(dpy, win, NULL, NULL, NULL, 0, size_hint, wmh, NULL);
1059 XFree(size_hint);
1060 XFree(wmh);
1062 XSetWMProtocols(dpy, win, &wmatom[WMDelete], 1);
1064 snprintf(winid, sizeof(winid), "%lu", win);
1065 setenv("XEMBED", winid, 1);
1067 nextfocus = foreground;
1068 focus(-1);
1071 void
1072 sigchld(int unused)
1074 if (signal(SIGCHLD, sigchld) == SIG_ERR)
1075 die("%s: cannot install SIGCHLD handler", argv0);
1077 while (0 < waitpid(-1, NULL, WNOHANG));
1080 void
1081 spawn(const Arg *arg)
1083 if (fork() == 0) {
1084 if(dpy)
1085 close(ConnectionNumber(dpy));
1087 setsid();
1088 if (arg && arg->v) {
1089 execvp(((char **)arg->v)[0], (char **)arg->v);
1090 fprintf(stderr, "%s: execvp %s", argv0,
1091 ((char **)arg->v)[0]);
1092 } else {
1093 cmd[cmd_append_pos] = NULL;
1094 execvp(cmd[0], cmd);
1095 fprintf(stderr, "%s: execvp %s", argv0, cmd[0]);
1097 perror(" failed");
1098 exit(0);
1103 textnw(const char *text, unsigned int len)
1105 XGlyphInfo ext;
1106 XftTextExtentsUtf8(dpy, dc.font.xfont, (XftChar8 *) text, len, &ext);
1107 return ext.xOff;
1110 void
1111 toggle(const Arg *arg)
1113 *(Bool*) arg->v = !*(Bool*) arg->v;
1116 void
1117 unmanage(int c)
1119 if (c < 0 || c >= nclients) {
1120 drawbar();
1121 XSync(dpy, False);
1122 return;
1125 if (!nclients)
1126 return;
1128 if (c == 0) {
1129 /* First client. */
1130 nclients--;
1131 free(clients[0]);
1132 memmove(&clients[0], &clients[1], sizeof(Client *) * nclients);
1133 } else if (c == nclients - 1) {
1134 /* Last client. */
1135 nclients--;
1136 free(clients[c]);
1137 clients = erealloc(clients, sizeof(Client *) * nclients);
1138 } else {
1139 /* Somewhere inbetween. */
1140 free(clients[c]);
1141 memmove(&clients[c], &clients[c+1],
1142 sizeof(Client *) * (nclients - (c + 1)));
1143 nclients--;
1146 if (nclients <= 0) {
1147 lastsel = sel = -1;
1149 if (closelastclient)
1150 running = False;
1151 else if (fillagain && running)
1152 spawn(NULL);
1153 } else {
1154 if (lastsel >= nclients)
1155 lastsel = nclients - 1;
1156 else if (lastsel > c)
1157 lastsel--;
1159 if (c == sel && lastsel >= 0) {
1160 focus(lastsel);
1161 } else {
1162 if (sel > c)
1163 sel--;
1164 if (sel >= nclients)
1165 sel = nclients - 1;
1167 focus(sel);
1171 drawbar();
1172 XSync(dpy, False);
1175 void
1176 unmapnotify(const XEvent *e)
1178 const XUnmapEvent *ev = &e->xunmap;
1179 int c;
1181 if ((c = getclient(ev->window)) > -1)
1182 unmanage(c);
1185 void
1186 updatenumlockmask(void)
1188 unsigned int i, j;
1189 XModifierKeymap *modmap;
1191 numlockmask = 0;
1192 modmap = XGetModifierMapping(dpy);
1193 for (i = 0; i < 8; i++) {
1194 for (j = 0; j < modmap->max_keypermod; j++) {
1195 if (modmap->modifiermap[i * modmap->max_keypermod + j]
1196 == XKeysymToKeycode(dpy, XK_Num_Lock))
1197 numlockmask = (1 << i);
1200 XFreeModifiermap(modmap);
1203 void
1204 updatetitle(int c)
1206 if (!gettextprop(clients[c]->win, wmatom[WMName], clients[c]->name,
1207 sizeof(clients[c]->name)))
1208 gettextprop(clients[c]->win, XA_WM_NAME, clients[c]->name,
1209 sizeof(clients[c]->name));
1210 if (sel == c)
1211 xsettitle(win, clients[c]->name);
1212 drawbar();
1215 /* There's no way to check accesses to destroyed windows, thus those cases are
1216 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1217 * default error handler, which may call exit. */
1219 xerror(Display *dpy, XErrorEvent *ee)
1221 if (ee->error_code == BadWindow
1222 || (ee->request_code == X_SetInputFocus &&
1223 ee->error_code == BadMatch)
1224 || (ee->request_code == X_PolyText8 &&
1225 ee->error_code == BadDrawable)
1226 || (ee->request_code == X_PolyFillRectangle &&
1227 ee->error_code == BadDrawable)
1228 || (ee->request_code == X_PolySegment &&
1229 ee->error_code == BadDrawable)
1230 || (ee->request_code == X_ConfigureWindow &&
1231 ee->error_code == BadMatch)
1232 || (ee->request_code == X_GrabButton &&
1233 ee->error_code == BadAccess)
1234 || (ee->request_code == X_GrabKey &&
1235 ee->error_code == BadAccess)
1236 || (ee->request_code == X_CopyArea &&
1237 ee->error_code == BadDrawable))
1238 return 0;
1240 fprintf(stderr, "%s: fatal error: request code=%d, error code=%d\n",
1241 argv0, ee->request_code, ee->error_code);
1242 return xerrorxlib(dpy, ee); /* may call exit */
1245 void
1246 xsettitle(Window w, const char *str)
1248 XTextProperty xtp;
1250 if (XmbTextListToTextProperty(dpy, (char **)&str, 1,
1251 XCompoundTextStyle, &xtp) == Success) {
1252 XSetTextProperty(dpy, w, &xtp, wmatom[WMName]);
1253 XSetTextProperty(dpy, w, &xtp, XA_WM_NAME);
1254 XFree(xtp.value);
1258 void
1259 usage(void)
1261 die("usage: %s [-dfksv] [-g geometry] [-n name] [-p [s+/-]pos]\n"
1262 " [-r narg] [-o color] [-O color] [-t color] [-T color]\n"
1263 " [-u color] [-U color] command...\n", argv0);
1267 main(int argc, char *argv[])
1269 Bool detach = False;
1270 int replace = 0;
1271 char *pstr;
1273 ARGBEGIN {
1274 case 'c':
1275 closelastclient = True;
1276 fillagain = False;
1277 break;
1278 case 'd':
1279 detach = True;
1280 break;
1281 case 'f':
1282 fillagain = True;
1283 break;
1284 case 'g':
1285 geometry = EARGF(usage());
1286 break;
1287 case 'k':
1288 killclientsfirst = True;
1289 break;
1290 case 'n':
1291 wmname = EARGF(usage());
1292 break;
1293 case 'O':
1294 normfgcolor = EARGF(usage());
1295 break;
1296 case 'o':
1297 normbgcolor = EARGF(usage());
1298 break;
1299 case 'p':
1300 pstr = EARGF(usage());
1301 if (pstr[0] == 's') {
1302 npisrelative = True;
1303 newposition = atoi(&pstr[1]);
1304 } else {
1305 newposition = atoi(pstr);
1307 break;
1308 case 'r':
1309 replace = atoi(EARGF(usage()));
1310 break;
1311 case 's':
1312 doinitspawn = False;
1313 break;
1314 case 'T':
1315 selfgcolor = EARGF(usage());
1316 break;
1317 case 't':
1318 selbgcolor = EARGF(usage());
1319 break;
1320 case 'U':
1321 urgfgcolor = EARGF(usage());
1322 break;
1323 case 'u':
1324 urgbgcolor = EARGF(usage());
1325 break;
1326 case 'v':
1327 die("tabbed-"VERSION", © 2009-2016 tabbed engineers, "
1328 "see LICENSE for details.\n");
1329 break;
1330 default:
1331 usage();
1332 break;
1333 } ARGEND;
1335 if (argc < 1) {
1336 doinitspawn = False;
1337 fillagain = False;
1340 setcmd(argc, argv, replace);
1342 if (!setlocale(LC_CTYPE, "") || !XSupportsLocale())
1343 fprintf(stderr, "%s: no locale support\n", argv0);
1344 if (!(dpy = XOpenDisplay(NULL)))
1345 die("%s: cannot open display\n", argv0);
1347 setup();
1348 printf("0x%lx\n", win);
1349 fflush(NULL);
1351 if (detach) {
1352 if (fork() == 0) {
1353 fclose(stdout);
1354 } else {
1355 if (dpy)
1356 close(ConnectionNumber(dpy));
1357 return EXIT_SUCCESS;
1361 run();
1362 cleanup();
1363 XCloseDisplay(dpy);
1365 return EXIT_SUCCESS;