Remove h flag, put usage() in the default case
[tabbed/julien_tabbed.git] / tabbed.c
blob5f035c0ccb0e7eabd3cdd7bdbe2ed67510ae5d9a
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>
19 #include "arg.h"
21 /* XEMBED messages */
22 #define XEMBED_EMBEDDED_NOTIFY 0
23 #define XEMBED_WINDOW_ACTIVATE 1
24 #define XEMBED_WINDOW_DEACTIVATE 2
25 #define XEMBED_REQUEST_FOCUS 3
26 #define XEMBED_FOCUS_IN 4
27 #define XEMBED_FOCUS_OUT 5
28 #define XEMBED_FOCUS_NEXT 6
29 #define XEMBED_FOCUS_PREV 7
30 /* 8-9 were used for XEMBED_GRAB_KEY/XEMBED_UNGRAB_KEY */
31 #define XEMBED_MODALITY_ON 10
32 #define XEMBED_MODALITY_OFF 11
33 #define XEMBED_REGISTER_ACCELERATOR 12
34 #define XEMBED_UNREGISTER_ACCELERATOR 13
35 #define XEMBED_ACTIVATE_ACCELERATOR 14
37 /* Details for XEMBED_FOCUS_IN: */
38 #define XEMBED_FOCUS_CURRENT 0
39 #define XEMBED_FOCUS_FIRST 1
40 #define XEMBED_FOCUS_LAST 2
42 /* Macros */
43 #define MAX(a, b) ((a) > (b) ? (a) : (b))
44 #define MIN(a, b) ((a) < (b) ? (a) : (b))
45 #define LENGTH(x) (sizeof((x)) / sizeof(*(x)))
46 #define CLEANMASK(mask) (mask & ~(numlockmask | LockMask))
47 #define TEXTW(x) (textnw(x, strlen(x)) + dc.font.height)
49 enum { ColFG, ColBG, ColLast }; /* color */
50 enum { WMProtocols, WMDelete, WMName, WMState, WMFullscreen,
51 XEmbed, WMSelectTab, WMLast }; /* default atoms */
53 typedef union {
54 int i;
55 const void *v;
56 } Arg;
58 typedef struct {
59 unsigned int mod;
60 KeySym keysym;
61 void (*func)(const Arg *);
62 const Arg arg;
63 } Key;
65 typedef struct {
66 int x, y, w, h;
67 unsigned long norm[ColLast];
68 unsigned long sel[ColLast];
69 unsigned long urg[ColLast];
70 Drawable drawable;
71 GC gc;
72 struct {
73 int ascent;
74 int descent;
75 int height;
76 XFontSet set;
77 XFontStruct *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, unsigned long 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 unsigned long 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 static Display *dpy;
160 static DC dc;
161 static Atom wmatom[WMLast];
162 static Window root, win;
163 static Client **clients;
164 static int nclients, sel = -1, lastsel = -1;
165 static int (*xerrorxlib)(Display *, XErrorEvent *);
166 static int cmd_append_pos;
167 static char winid[64];
168 static char **cmd;
169 static char *wmname = "tabbed";
170 static const char *geometry;
172 char *argv0;
174 /* configuration, allows nested code to access above variables */
175 #include "config.h"
177 void
178 buttonpress(const XEvent *e)
180 const XButtonPressedEvent *ev = &e->xbutton;
181 int i, fc;
182 Arg arg;
184 if (ev->y < 0 || ev->y > bh)
185 return;
187 if (((fc = getfirsttab()) > 0 && ev->x < TEXTW(before)) || ev->x < 0)
188 return;
190 for (i = fc; i < nclients; i++) {
191 if (clients[i]->tabx > ev->x) {
192 switch (ev->button) {
193 case Button1:
194 focus(i);
195 break;
196 case Button2:
197 focus(i);
198 killclient(NULL);
199 break;
200 case Button4: /* FALLTHROUGH */
201 case Button5:
202 arg.i = ev->button == Button4 ? -1 : 1;
203 rotate(&arg);
204 break;
206 break;
211 void
212 cleanup(void)
214 int i;
216 for (i = 0; i < nclients; i++) {
217 focus(i);
218 killclient(NULL);
219 killclient(NULL);
220 XReparentWindow(dpy, clients[i]->win, root, 0, 0);
221 unmanage(i);
223 free(clients);
224 clients = NULL;
226 if (dc.font.set)
227 XFreeFontSet(dpy, dc.font.set);
228 else
229 XFreeFont(dpy, dc.font.xfont);
231 XFreePixmap(dpy, dc.drawable);
232 XFreeGC(dpy, dc.gc);
233 XDestroyWindow(dpy, win);
234 XSync(dpy, False);
235 free(cmd);
238 void
239 clientmessage(const XEvent *e)
241 const XClientMessageEvent *ev = &e->xclient;
243 if (ev->message_type == wmatom[WMProtocols] &&
244 ev->data.l[0] == wmatom[WMDelete])
245 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 unsigned long *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, unsigned long col[ColLast])
372 int i, x, y, h, len, olen;
373 char buf[256];
374 XRectangle r = { dc.x, dc.y, dc.w, dc.h };
376 XSetForeground(dpy, dc.gc, col[ColBG]);
377 XFillRectangles(dpy, dc.drawable, dc.gc, &r, 1);
378 if (!text)
379 return;
381 olen = strlen(text);
382 h = dc.font.ascent + dc.font.descent;
383 y = dc.y + (dc.h / 2) - (h / 2) + dc.font.ascent;
384 x = dc.x + (h / 2);
386 /* shorten text if necessary */
387 for (len = MIN(olen, sizeof(buf));
388 len && textnw(text, len) > dc.w - h; len--);
390 if (!len)
391 return;
393 memcpy(buf, text, len);
394 if (len < olen)
395 for(i = len; i && i > len - 3; buf[--i] = '.');
397 XSetForeground(dpy, dc.gc, col[ColFG]);
398 if (dc.font.set)
399 XmbDrawString(dpy, dc.drawable, dc.font.set,
400 dc.gc, x, y, buf, len);
401 else
402 XDrawString(dpy, dc.drawable, dc.gc, x, y, buf, len);
405 void *
406 ecalloc(size_t n, size_t size)
408 void *p;
410 if (!(p = calloc(n, size)))
411 die("%s: cannot calloc\n", argv0);
412 return p;
415 void *
416 erealloc(void *o, size_t size)
418 void *p;
420 if (!(p = realloc(o, size)))
421 die("%s: cannot realloc\n", argv0);
422 return p;
425 void
426 expose(const XEvent *e)
428 const XExposeEvent *ev = &e->xexpose;
430 if (ev->count == 0 && win == ev->window)
431 drawbar();
434 void
435 focus(int c)
437 char buf[BUFSIZ] = "tabbed-"VERSION" ::";
438 size_t i, n;
439 XWMHints* wmh;
441 /* If c, sel and clients are -1, raise tabbed-win itself */
442 if (nclients == 0) {
443 cmd[cmd_append_pos] = NULL;
444 for(i = 0, n = strlen(buf); cmd[i] && n < sizeof(buf); i++)
445 n += snprintf(&buf[n], sizeof(buf) - n, " %s", cmd[i]);
447 xsettitle(win, buf);
448 XRaiseWindow(dpy, win);
450 return;
453 if (c < 0 || c >= nclients)
454 return;
456 resize(c, ww, wh - bh);
457 XRaiseWindow(dpy, clients[c]->win);
458 XSetInputFocus(dpy, clients[c]->win, RevertToParent, CurrentTime);
459 sendxembed(c, XEMBED_FOCUS_IN, XEMBED_FOCUS_CURRENT, 0, 0);
460 sendxembed(c, XEMBED_WINDOW_ACTIVATE, 0, 0, 0);
461 xsettitle(win, clients[c]->name);
463 if (sel != c) {
464 lastsel = sel;
465 sel = c;
468 if (clients[c]->urgent && (wmh = XGetWMHints(dpy, clients[c]->win))) {
469 wmh->flags &= ~XUrgencyHint;
470 XSetWMHints(dpy, clients[c]->win, wmh);
471 clients[c]->urgent = False;
472 XFree(wmh);
475 drawbar();
476 XSync(dpy, False);
479 void
480 focusin(const XEvent *e)
482 const XFocusChangeEvent *ev = &e->xfocus;
483 int dummy;
484 Window focused;
486 if (ev->mode != NotifyUngrab) {
487 XGetInputFocus(dpy, &focused, &dummy);
488 if (focused == win)
489 focus(sel);
493 void
494 focusonce(const Arg *arg)
496 nextfocus = True;
499 void
500 focusurgent(const Arg *arg)
502 int c;
504 for (c = (sel + 1) % nclients; c != sel; c = (c + 1) % nclients) {
505 if (clients[c]->urgent) {
506 focus(c);
507 return;
512 void
513 fullscreen(const Arg *arg)
515 XEvent e;
517 e.type = ClientMessage;
518 e.xclient.window = win;
519 e.xclient.message_type = wmatom[WMState];
520 e.xclient.format = 32;
521 e.xclient.data.l[0] = 2;
522 e.xclient.data.l[1] = wmatom[WMFullscreen];
523 e.xclient.data.l[2] = 0;
524 XSendEvent(dpy, root, False, SubstructureNotifyMask, &e);
527 char *
528 getatom(int a)
530 static char buf[BUFSIZ];
531 Atom adummy;
532 int idummy;
533 unsigned long ldummy;
534 unsigned char *p = NULL;
536 XGetWindowProperty(dpy, win, wmatom[a], 0L, BUFSIZ, False, XA_STRING,
537 &adummy, &idummy, &ldummy, &ldummy, &p);
538 if (p)
539 strncpy(buf, (char *)p, LENGTH(buf)-1);
540 else
541 buf[0] = '\0';
542 XFree(p);
544 return buf;
548 getclient(Window w)
550 int i;
552 for (i = 0; i < nclients; i++) {
553 if (clients[i]->win == w)
554 return i;
557 return -1;
560 unsigned long
561 getcolor(const char *colstr)
563 Colormap cmap = DefaultColormap(dpy, screen);
564 XColor color;
566 if (!XAllocNamedColor(dpy, cmap, colstr, &color, &color))
567 die("%s: cannot allocate color '%s'\n", argv0, colstr);
569 return color.pixel;
573 getfirsttab(void)
575 int cc, ret;
577 if (sel < 0)
578 return 0;
580 cc = ww / tabwidth;
581 if (nclients > cc)
582 cc = (ww - TEXTW(before) - TEXTW(after)) / tabwidth;
584 ret = sel - cc / 2 + (cc + 1) % 2;
585 return ret < 0 ? 0 :
586 ret + cc > nclients ? MAX(0, nclients - cc) :
587 ret;
590 Bool
591 gettextprop(Window w, Atom atom, char *text, unsigned int size)
593 char **list = NULL;
594 int n;
595 XTextProperty name;
597 if (!text || size == 0)
598 return False;
600 text[0] = '\0';
601 XGetTextProperty(dpy, w, &name, atom);
602 if (!name.nitems)
603 return False;
605 if (name.encoding == XA_STRING) {
606 strncpy(text, (char *)name.value, size - 1);
607 } else if (XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success
608 && n > 0 && *list) {
609 strncpy(text, *list, size - 1);
610 XFreeStringList(list);
612 text[size - 1] = '\0';
613 XFree(name.value);
615 return True;
618 void
619 initfont(const char *fontstr)
621 char *def, **missing, **font_names;
622 XFontStruct **xfonts;
623 int i, n;
625 missing = NULL;
626 if (dc.font.set)
627 XFreeFontSet(dpy, dc.font.set);
629 dc.font.set = XCreateFontSet(dpy, fontstr, &missing, &n, &def);
630 if (missing) {
631 while (n--)
632 fprintf(stderr, "%s: missing fontset: %s\n",
633 argv0, missing[n]);
634 XFreeStringList(missing);
637 if (dc.font.set) {
638 dc.font.ascent = dc.font.descent = 0;
639 n = XFontsOfFontSet(dc.font.set, &xfonts, &font_names);
640 for (i = 0, dc.font.ascent = 0, dc.font.descent = 0;
641 i < n; i++) {
642 dc.font.ascent = MAX(dc.font.ascent, (*xfonts)->ascent);
643 dc.font.descent = MAX(dc.font.descent,(*xfonts)->descent);
644 xfonts++;
646 } else {
647 if (dc.font.xfont)
648 XFreeFont(dpy, dc.font.xfont);
649 dc.font.xfont = NULL;
650 if (!(dc.font.xfont = XLoadQueryFont(dpy, fontstr)) &&
651 !(dc.font.xfont = XLoadQueryFont(dpy, "fixed")))
652 die("%s: cannot load font: '%s'\n", argv0, fontstr);
654 dc.font.ascent = dc.font.xfont->ascent;
655 dc.font.descent = dc.font.xfont->descent;
657 dc.font.height = dc.font.ascent + dc.font.descent;
660 Bool
661 isprotodel(int c)
663 int i, n;
664 Atom *protocols;
665 Bool ret = False;
667 if (XGetWMProtocols(dpy, clients[c]->win, &protocols, &n)) {
668 for (i = 0; !ret && i < n; i++) {
669 if (protocols[i] == wmatom[WMDelete])
670 ret = True;
672 XFree(protocols);
675 return ret;
678 void
679 keypress(const XEvent *e)
681 const XKeyEvent *ev = &e->xkey;
682 unsigned int i;
683 KeySym keysym;
685 keysym = XkbKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0, 0);
686 for (i = 0; i < LENGTH(keys); i++) {
687 if (keysym == keys[i].keysym &&
688 CLEANMASK(keys[i].mod) == CLEANMASK(ev->state) &&
689 keys[i].func)
690 keys[i].func(&(keys[i].arg));
694 void
695 killclient(const Arg *arg)
697 XEvent ev;
699 if (sel < 0)
700 return;
702 if (isprotodel(sel) && !clients[sel]->closed) {
703 ev.type = ClientMessage;
704 ev.xclient.window = clients[sel]->win;
705 ev.xclient.message_type = wmatom[WMProtocols];
706 ev.xclient.format = 32;
707 ev.xclient.data.l[0] = wmatom[WMDelete];
708 ev.xclient.data.l[1] = CurrentTime;
709 XSendEvent(dpy, clients[sel]->win, False, NoEventMask, &ev);
710 clients[sel]->closed = True;
711 } else {
712 XKillClient(dpy, clients[sel]->win);
716 void
717 manage(Window w)
719 updatenumlockmask();
721 int i, j, nextpos;
722 unsigned int modifiers[] = { 0, LockMask, numlockmask,
723 numlockmask | LockMask };
724 KeyCode code;
725 Client *c;
726 XEvent e;
728 XWithdrawWindow(dpy, w, 0);
729 XReparentWindow(dpy, w, win, 0, bh);
730 XSelectInput(dpy, w, PropertyChangeMask |
731 StructureNotifyMask | EnterWindowMask);
732 XSync(dpy, False);
734 for (i = 0; i < LENGTH(keys); i++) {
735 if ((code = XKeysymToKeycode(dpy, keys[i].keysym))) {
736 for (j = 0; j < LENGTH(modifiers); j++) {
737 XGrabKey(dpy, code, keys[i].mod |
738 modifiers[j], w, True,
739 GrabModeAsync, GrabModeAsync);
744 c = ecalloc(1, sizeof *c);
745 c->win = w;
747 nclients++;
748 clients = erealloc(clients, sizeof(Client *) * nclients);
750 if(npisrelative) {
751 nextpos = sel + newposition;
752 } else {
753 if (newposition < 0)
754 nextpos = nclients - newposition;
755 else
756 nextpos = newposition;
758 if (nextpos >= nclients)
759 nextpos = nclients - 1;
760 if (nextpos < 0)
761 nextpos = 0;
763 if (nclients > 1 && nextpos < nclients - 1)
764 memmove(&clients[nextpos + 1], &clients[nextpos],
765 sizeof(Client *) * (nclients - nextpos - 1));
767 clients[nextpos] = c;
768 updatetitle(nextpos);
770 XLowerWindow(dpy, w);
771 XMapWindow(dpy, w);
773 e.xclient.window = w;
774 e.xclient.type = ClientMessage;
775 e.xclient.message_type = wmatom[XEmbed];
776 e.xclient.format = 32;
777 e.xclient.data.l[0] = CurrentTime;
778 e.xclient.data.l[1] = XEMBED_EMBEDDED_NOTIFY;
779 e.xclient.data.l[2] = 0;
780 e.xclient.data.l[3] = win;
781 e.xclient.data.l[4] = 0;
782 XSendEvent(dpy, root, False, NoEventMask, &e);
784 XSync(dpy, False);
786 /* Adjust sel before focus does set it to lastsel. */
787 if (sel >= nextpos)
788 sel++;
789 focus(nextfocus ? nextpos :
790 sel < 0 ? 0 :
791 sel);
792 nextfocus = foreground;
796 void
797 maprequest(const XEvent *e)
799 const XMapRequestEvent *ev = &e->xmaprequest;
801 if (getclient(ev->window) < 0)
802 manage(ev->window);
805 void
806 move(const Arg *arg)
808 if (arg->i >= 0 && arg->i < nclients)
809 focus(arg->i);
812 void
813 movetab(const Arg *arg)
815 int c;
816 Client *new;
818 c = (sel + arg->i) % nclients;
819 if (c < 0)
820 c += nclients;
822 if (sel < 0 || c == sel)
823 return;
825 new = clients[sel];
826 if (sel < c)
827 memmove(&clients[sel], &clients[sel+1],
828 sizeof(Client *) * (c - sel));
829 else
830 memmove(&clients[c+1], &clients[c],
831 sizeof(Client *) * (sel - c));
832 clients[c] = new;
833 sel = c;
835 drawbar();
838 void
839 propertynotify(const XEvent *e)
841 const XPropertyEvent *ev = &e->xproperty;
842 XWMHints *wmh;
843 int c;
844 char* selection = NULL;
845 Arg arg;
847 if (ev->state == PropertyNewValue && ev->atom == wmatom[WMSelectTab]) {
848 selection = getatom(WMSelectTab);
849 if (!strncmp(selection, "0x", 2)) {
850 arg.i = getclient(strtoul(selection, NULL, 0));
851 move(&arg);
852 } else {
853 cmd[cmd_append_pos] = selection;
854 arg.v = cmd;
855 spawn(&arg);
857 } else if (ev->state == PropertyNewValue && ev->atom == XA_WM_HINTS &&
858 (c = getclient(ev->window)) > -1 &&
859 (wmh = XGetWMHints(dpy, clients[c]->win))) {
860 if (wmh->flags & XUrgencyHint) {
861 XFree(wmh);
862 wmh = XGetWMHints(dpy, win);
863 if (c != sel) {
864 if (urgentswitch && wmh &&
865 !(wmh->flags & XUrgencyHint)) {
866 /* only switch, if tabbed was focused
867 * since last urgency hint if WMHints
868 * could not be received,
869 * default to no switch */
870 focus(c);
871 } else {
872 /* if no switch should be performed,
873 * mark tab as urgent */
874 clients[c]->urgent = True;
875 drawbar();
878 if (wmh && !(wmh->flags & XUrgencyHint)) {
879 /* update tabbed urgency hint
880 * if not set already */
881 wmh->flags |= XUrgencyHint;
882 XSetWMHints(dpy, win, wmh);
885 XFree(wmh);
886 } else if (ev->state != PropertyDelete && ev->atom == XA_WM_NAME &&
887 (c = getclient(ev->window)) > -1) {
888 updatetitle(c);
892 void
893 resize(int c, int w, int h)
895 XConfigureEvent ce;
896 XWindowChanges wc;
898 ce.x = 0;
899 ce.y = bh;
900 ce.width = wc.width = w;
901 ce.height = wc.height = h;
902 ce.type = ConfigureNotify;
903 ce.display = dpy;
904 ce.event = clients[c]->win;
905 ce.window = clients[c]->win;
906 ce.above = None;
907 ce.override_redirect = False;
908 ce.border_width = 0;
910 XConfigureWindow(dpy, clients[c]->win, CWWidth | CWHeight, &wc);
911 XSendEvent(dpy, clients[c]->win, False, StructureNotifyMask,
912 (XEvent *)&ce);
915 void
916 rotate(const Arg *arg)
918 int nsel = -1;
920 if (sel < 0)
921 return;
923 if (arg->i == 0) {
924 if (lastsel > -1)
925 focus(lastsel);
926 } else if (sel > -1) {
927 /* Rotating in an arg->i step around the clients. */
928 nsel = sel + arg->i;
929 while (nsel >= nclients)
930 nsel -= nclients;
931 while (nsel < 0)
932 nsel += nclients;
933 focus(nsel);
937 void
938 run(void)
940 XEvent ev;
942 /* main event loop */
943 XSync(dpy, False);
944 drawbar();
945 if (doinitspawn == True)
946 spawn(NULL);
948 while (running) {
949 XNextEvent(dpy, &ev);
950 if (handler[ev.type])
951 (handler[ev.type])(&ev); /* call handler */
955 void
956 sendxembed(int c, long msg, long detail, long d1, long d2)
958 XEvent e = { 0 };
960 e.xclient.window = clients[c]->win;
961 e.xclient.type = ClientMessage;
962 e.xclient.message_type = wmatom[XEmbed];
963 e.xclient.format = 32;
964 e.xclient.data.l[0] = CurrentTime;
965 e.xclient.data.l[1] = msg;
966 e.xclient.data.l[2] = detail;
967 e.xclient.data.l[3] = d1;
968 e.xclient.data.l[4] = d2;
969 XSendEvent(dpy, clients[c]->win, False, NoEventMask, &e);
972 void
973 setcmd(int argc, char *argv[], int replace)
975 int i;
977 cmd = ecalloc(argc + 3, sizeof(*cmd));
978 if (argc == 0)
979 return;
980 for (i = 0; i < argc; i++)
981 cmd[i] = argv[i];
982 cmd[replace > 0 ? replace : argc] = winid;
983 cmd_append_pos = argc + !replace;
984 cmd[cmd_append_pos] = cmd[cmd_append_pos + 1] = NULL;
987 void
988 setup(void)
990 int bitm, tx, ty, tw, th, dh, dw, isfixed;
991 XWMHints *wmh;
992 XClassHint class_hint;
993 XSizeHints *size_hint;
995 /* clean up any zombies immediately */
996 sigchld(0);
998 /* init screen */
999 screen = DefaultScreen(dpy);
1000 root = RootWindow(dpy, screen);
1001 initfont(font);
1002 bh = dc.h = dc.font.height + 2;
1004 /* init atoms */
1005 wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
1006 wmatom[WMFullscreen] = XInternAtom(dpy, "_NET_WM_STATE_FULLSCREEN",
1007 False);
1008 wmatom[WMName] = XInternAtom(dpy, "_NET_WM_NAME", False);
1009 wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False);
1010 wmatom[WMSelectTab] = XInternAtom(dpy, "_TABBED_SELECT_TAB", False);
1011 wmatom[WMState] = XInternAtom(dpy, "_NET_WM_STATE", False);
1012 wmatom[XEmbed] = XInternAtom(dpy, "_XEMBED", False);
1014 /* init appearance */
1015 wx = 0;
1016 wy = 0;
1017 ww = 800;
1018 wh = 600;
1019 isfixed = 0;
1021 if (geometry) {
1022 tx = ty = tw = th = 0;
1023 bitm = XParseGeometry(geometry, &tx, &ty, (unsigned *)&tw,
1024 (unsigned *)&th);
1025 if (bitm & XValue)
1026 wx = tx;
1027 if (bitm & YValue)
1028 wy = ty;
1029 if (bitm & WidthValue)
1030 ww = tw;
1031 if (bitm & HeightValue)
1032 wh = th;
1033 if (bitm & XNegative && wx == 0)
1034 wx = -1;
1035 if (bitm & YNegative && wy == 0)
1036 wy = -1;
1037 if (bitm & (HeightValue | WidthValue))
1038 isfixed = 1;
1040 dw = DisplayWidth(dpy, screen);
1041 dh = DisplayHeight(dpy, screen);
1042 if (wx < 0)
1043 wx = dw + wx - ww - 1;
1044 if (wy < 0)
1045 wy = dh + wy - wh - 1;
1048 dc.norm[ColBG] = getcolor(normbgcolor);
1049 dc.norm[ColFG] = getcolor(normfgcolor);
1050 dc.sel[ColBG] = getcolor(selbgcolor);
1051 dc.sel[ColFG] = getcolor(selfgcolor);
1052 dc.urg[ColBG] = getcolor(urgbgcolor);
1053 dc.urg[ColFG] = getcolor(urgfgcolor);
1054 dc.drawable = XCreatePixmap(dpy, root, ww, wh,
1055 DefaultDepth(dpy, screen));
1056 dc.gc = XCreateGC(dpy, root, 0, 0);
1057 if (!dc.font.set)
1058 XSetFont(dpy, dc.gc, dc.font.xfont->fid);
1060 win = XCreateSimpleWindow(dpy, root, wx, wy, ww, wh, 0,
1061 dc.norm[ColFG], dc.norm[ColBG]);
1062 XMapRaised(dpy, win);
1063 XSelectInput(dpy, win, SubstructureNotifyMask | FocusChangeMask |
1064 ButtonPressMask | ExposureMask | KeyPressMask |
1065 PropertyChangeMask | StructureNotifyMask |
1066 SubstructureRedirectMask);
1067 xerrorxlib = XSetErrorHandler(xerror);
1069 class_hint.res_name = wmname;
1070 class_hint.res_class = "tabbed";
1071 XSetClassHint(dpy, win, &class_hint);
1073 size_hint = XAllocSizeHints();
1074 if (!isfixed) {
1075 size_hint->flags = PSize;
1076 size_hint->height = wh;
1077 size_hint->width = ww;
1078 } else {
1079 size_hint->flags = PMaxSize | PMinSize;
1080 size_hint->min_width = size_hint->max_width = ww;
1081 size_hint->min_height = size_hint->max_height = wh;
1083 wmh = XAllocWMHints();
1084 XSetWMProperties(dpy, win, NULL, NULL, NULL, 0, size_hint, wmh, NULL);
1085 XFree(size_hint);
1086 XFree(wmh);
1088 XSetWMProtocols(dpy, win, &wmatom[WMDelete], 1);
1090 snprintf(winid, sizeof(winid), "%lu", win);
1091 setenv("XEMBED", winid, 1);
1093 nextfocus = foreground;
1094 focus(-1);
1097 void
1098 sigchld(int unused)
1100 if (signal(SIGCHLD, sigchld) == SIG_ERR)
1101 die("%s: cannot install SIGCHLD handler", argv0);
1103 while (0 < waitpid(-1, NULL, WNOHANG));
1106 void
1107 spawn(const Arg *arg)
1109 if (fork() == 0) {
1110 if(dpy)
1111 close(ConnectionNumber(dpy));
1113 setsid();
1114 if (arg && arg->v) {
1115 execvp(((char **)arg->v)[0], (char **)arg->v);
1116 fprintf(stderr, "%s: execvp %s", argv0,
1117 ((char **)arg->v)[0]);
1118 } else {
1119 cmd[cmd_append_pos] = NULL;
1120 execvp(cmd[0], cmd);
1121 fprintf(stderr, "%s: execvp %s", argv0, cmd[0]);
1123 perror(" failed");
1124 exit(0);
1129 textnw(const char *text, unsigned int len)
1131 XRectangle r;
1133 if (dc.font.set) {
1134 XmbTextExtents(dc.font.set, text, len, NULL, &r);
1135 return r.width;
1138 return XTextWidth(dc.font.xfont, text, len);
1141 void
1142 toggle(const Arg *arg)
1144 *(Bool*) arg->v = !*(Bool*) arg->v;
1147 void
1148 unmanage(int c)
1150 if (c < 0 || c >= nclients) {
1151 drawbar();
1152 XSync(dpy, False);
1153 return;
1156 if (!nclients)
1157 return;
1159 if (c == 0) {
1160 /* First client. */
1161 nclients--;
1162 free(clients[0]);
1163 memmove(&clients[0], &clients[1], sizeof(Client *) * nclients);
1164 } else if (c == nclients - 1) {
1165 /* Last client. */
1166 nclients--;
1167 free(clients[c]);
1168 clients = erealloc(clients, sizeof(Client *) * nclients);
1169 } else {
1170 /* Somewhere inbetween. */
1171 free(clients[c]);
1172 memmove(&clients[c], &clients[c+1],
1173 sizeof(Client *) * (nclients - (c + 1)));
1174 nclients--;
1177 if (nclients <= 0) {
1178 lastsel = sel = -1;
1180 if (closelastclient)
1181 running = False;
1182 else if (fillagain && running)
1183 spawn(NULL);
1184 } else {
1185 if (lastsel >= nclients)
1186 lastsel = nclients - 1;
1187 else if (lastsel > c)
1188 lastsel--;
1190 if (c == sel && lastsel >= 0) {
1191 focus(lastsel);
1192 } else {
1193 if (sel > c)
1194 sel--;
1195 if (sel >= nclients)
1196 sel = nclients - 1;
1198 focus(sel);
1202 drawbar();
1203 XSync(dpy, False);
1206 void
1207 unmapnotify(const XEvent *e)
1209 const XUnmapEvent *ev = &e->xunmap;
1210 int c;
1212 if ((c = getclient(ev->window)) > -1)
1213 unmanage(c);
1216 void
1217 updatenumlockmask(void)
1219 unsigned int i, j;
1220 XModifierKeymap *modmap;
1222 numlockmask = 0;
1223 modmap = XGetModifierMapping(dpy);
1224 for (i = 0; i < 8; i++) {
1225 for (j = 0; j < modmap->max_keypermod; j++) {
1226 if (modmap->modifiermap[i * modmap->max_keypermod + j]
1227 == XKeysymToKeycode(dpy, XK_Num_Lock))
1228 numlockmask = (1 << i);
1231 XFreeModifiermap(modmap);
1234 void
1235 updatetitle(int c)
1237 if (!gettextprop(clients[c]->win, wmatom[WMName], clients[c]->name,
1238 sizeof(clients[c]->name)))
1239 gettextprop(clients[c]->win, XA_WM_NAME, clients[c]->name,
1240 sizeof(clients[c]->name));
1241 if (sel == c)
1242 xsettitle(win, clients[c]->name);
1243 drawbar();
1246 /* There's no way to check accesses to destroyed windows, thus those cases are
1247 * ignored (especially on UnmapNotify's). Other types of errors call Xlibs
1248 * default error handler, which may call exit. */
1250 xerror(Display *dpy, XErrorEvent *ee)
1252 if (ee->error_code == BadWindow
1253 || (ee->request_code == X_SetInputFocus &&
1254 ee->error_code == BadMatch)
1255 || (ee->request_code == X_PolyText8 &&
1256 ee->error_code == BadDrawable)
1257 || (ee->request_code == X_PolyFillRectangle &&
1258 ee->error_code == BadDrawable)
1259 || (ee->request_code == X_PolySegment &&
1260 ee->error_code == BadDrawable)
1261 || (ee->request_code == X_ConfigureWindow &&
1262 ee->error_code == BadMatch)
1263 || (ee->request_code == X_GrabButton &&
1264 ee->error_code == BadAccess)
1265 || (ee->request_code == X_GrabKey &&
1266 ee->error_code == BadAccess)
1267 || (ee->request_code == X_CopyArea &&
1268 ee->error_code == BadDrawable))
1269 return 0;
1271 fprintf(stderr, "%s: fatal error: request code=%d, error code=%d\n",
1272 argv0, ee->request_code, ee->error_code);
1273 return xerrorxlib(dpy, ee); /* may call exit */
1276 void
1277 xsettitle(Window w, const char *str)
1279 XTextProperty xtp;
1281 if (XmbTextListToTextProperty(dpy, (char **)&str, 1,
1282 XCompoundTextStyle, &xtp) == Success) {
1283 XSetTextProperty(dpy, w, &xtp, wmatom[WMName]);
1284 XSetTextProperty(dpy, w, &xtp, XA_WM_NAME);
1285 XFree(xtp.value);
1289 void
1290 usage(void)
1292 die("usage: %s [-dfsv] [-g geometry] [-n name] [-p [s+/-]pos]\n"
1293 " [-r narg] [-o color] [-O color] [-t color] [-T color]\n"
1294 " [-u color] [-U color] command...\n", argv0);
1298 main(int argc, char *argv[])
1300 Bool detach = False;
1301 int replace = 0;
1302 char *pstr;
1304 ARGBEGIN {
1305 case 'c':
1306 closelastclient = True;
1307 fillagain = False;
1308 break;
1309 case 'd':
1310 detach = True;
1311 break;
1312 case 'f':
1313 fillagain = True;
1314 break;
1315 case 'g':
1316 geometry = EARGF(usage());
1317 break;
1318 case 'n':
1319 wmname = EARGF(usage());
1320 break;
1321 case 'O':
1322 normfgcolor = EARGF(usage());
1323 break;
1324 case 'o':
1325 normbgcolor = EARGF(usage());
1326 break;
1327 case 'p':
1328 pstr = EARGF(usage());
1329 if (pstr[0] == 's') {
1330 npisrelative = True;
1331 newposition = atoi(&pstr[1]);
1332 } else {
1333 newposition = atoi(pstr);
1335 break;
1336 case 'r':
1337 replace = atoi(EARGF(usage()));
1338 break;
1339 case 's':
1340 doinitspawn = False;
1341 break;
1342 case 'T':
1343 selfgcolor = EARGF(usage());
1344 break;
1345 case 't':
1346 selbgcolor = EARGF(usage());
1347 break;
1348 case 'U':
1349 urgfgcolor = EARGF(usage());
1350 break;
1351 case 'u':
1352 urgbgcolor = EARGF(usage());
1353 break;
1354 case 'v':
1355 die("tabbed-"VERSION", © 2009-2016 tabbed engineers, "
1356 "see LICENSE for details.\n");
1357 break;
1358 default:
1359 usage();
1360 break;
1361 } ARGEND;
1363 if (argc < 1) {
1364 doinitspawn = False;
1365 fillagain = False;
1368 setcmd(argc, argv, replace);
1370 if (!setlocale(LC_CTYPE, "") || !XSupportsLocale())
1371 fprintf(stderr, "%s: no locale support\n", argv0);
1372 if (!(dpy = XOpenDisplay(NULL)))
1373 die("%s: cannot open display\n", argv0);
1375 setup();
1376 printf("0x%lx\n", win);
1377 fflush(NULL);
1379 if (detach) {
1380 if (fork() == 0) {
1381 fclose(stdout);
1382 } else {
1383 if (dpy)
1384 close(ConnectionNumber(dpy));
1385 return EXIT_SUCCESS;
1389 run();
1390 cleanup();
1391 XCloseDisplay(dpy);
1393 return EXIT_SUCCESS;