1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
|
/* see license for copyright and license */
#include <stdlib.h>
#include <stdio.h>
#include <stdarg.h>
#include <unistd.h>
#include <string.h>
#include <signal.h>
#include <sys/wait.h>
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/keysym.h>
#include <X11/Xproto.h>
#include <X11/Xatom.h>
#define LENGTH(x) (sizeof(x)/sizeof(*x))
#define CLEANMASK(mask) (mask & ~(numlockmask | LockMask))
#define BUTTONMASK ButtonPressMask|ButtonReleaseMask
/* mouse motion actions */
enum { RESIZE, MOVE, };
/* tiling layout modes */
enum { TILE, MONOCLE, BSTACK, GRID, };
/* wm and net atoms selected through wmatoms and netatoms arrays */
enum { WM_PROTOCOLS, WM_DELETE_WINDOW, WM_COUNT };
enum { NET_SUPPORTED, NET_FULLSCREEN, NET_WM_STATE, NET_ACTIVE, NET_COUNT };
/* argument structure to be passed to function by config.h
* com - a command to run
* i - an integer to indicate different states
*/
typedef union {
const char** com;
const int i;
} Arg;
/* a key struct represents a combination of
* mod - a modifier mask
* keysym - and the key pressed
* func - the function to be triggered because of the above combo
* arg - the argument to the function
*/
typedef struct {
unsigned int mod;
KeySym keysym;
void (*func)(const Arg *);
const Arg arg;
} key;
/* a button struct represents a combination of
* mask - a modifier mask
* button - and the mouse button pressed
* func - the function to be triggered because of the above combo
* arg - the argument to the function
*/
typedef struct {
unsigned int mask;
unsigned int button;
void (*func)(const Arg *);
const Arg arg;
} Button;
/* a client is a wrapper to a window that additionally
* holds some properties for that window
*
* next - the client after this one, or NULL if the current is the only or last client
* isurgent - the window received an urgent hint
* istransient - the window is transient
* isfullscreen - the window is fullscreen
* isfloating - the window is floating
* win - the window
*
* istransient is separate from isfloating as floating window can be reset
* to their tiling positions, while the transients will always be floating
*/
typedef struct client {
struct client *next;
Bool isurgent, istransient, isfullscreen, isfloating;
Window win;
} client;
/* properties of each desktop
* master_size - the size of the master window
* mode - the desktop's tiling layout mode
* growth - growth factor of the first stack window
* head - the start of the client list
* current - the currently highlighted window
* prevfocus - the client that previously had focus
* showpanel - the visibility status of the panel
*/
typedef struct {
int master_size;
int mode;
int growth;
client *head;
client *current;
client *prevfocus;
Bool showpanel;
} desktop;
/* define behavior of certain applications
* configured in config.h
* class - the class or name of the instance
* desktop - what desktop it should be spawned at
* follow - whether to change desktop focus to the specified desktop
*/
typedef struct {
const char *class;
const int desktop;
const Bool follow;
} AppRule;
/* Functions */
static void addwindow(Window w);
static void buttonpress(XEvent *e);
static void change_desktop(const Arg *arg);
static void cleanup(void);
static void client_to_desktop(const Arg *arg);
static void clientmessage(XEvent *e);
static void configurerequest(XEvent *e);
static void desktopinfo(void);
static void destroynotify(XEvent *e);
static void die(const char* errstr, ...);
static void enternotify(XEvent *e);
static void focusurgent();
static unsigned long getcolor(const char* color);
static void grabbuttons(client *c);
static void grabkeys(void);
static void keypress(XEvent *e);
static void killclient();
static void last_desktop();
static void maprequest(XEvent *e);
static void move_down();
static void move_up();
static void mousemotion(const Arg *arg);
static void next_win();
static void prev_win();
static void propertynotify(XEvent *e);
static void quit(const Arg *arg);
static void removeclient(client *c);
static void resize_master(const Arg *arg);
static void resize_stack(const Arg *arg);
static void rotate_desktop(const Arg *arg);
static void run(void);
static void save_desktop(int i);
static void select_desktop(int i);
static void sendevent(Window w, int atom);
static void setfullscreen(client *c, Bool fullscreen);
static void setup(void);
static void sigchld();
static void spawn(const Arg *arg);
static void swap_master();
static void switch_mode(const Arg *arg);
static void tile(void);
static void togglepanel();
static void update_current(client *c);
static void unmapnotify(XEvent *e);
static client* wintoclient(Window w);
static int xerrorstart();
#include "config.h"
/* variables */
static Bool running = True;
static Bool showpanel = SHOW_PANEL;
static int retval = 0;
static int current_desktop = 0;
static int previous_desktop = 0;
static int growth = 0;
static int mode = DEFAULT_MODE;
static int master_size;
static int wh; /* window area height - screen height minus the border size and panel height */
static int ww; /* window area width - screen width minus the border size */
static int screen;
static int xerror(Display *dis, XErrorEvent *ee);
static int (*xerrorxlib)(Display *, XErrorEvent *);
static unsigned int win_focus;
static unsigned int win_unfocus;
static unsigned int numlockmask = 0; /* dynamic key lock mask */
static Display *dis;
static Window root;
static client *head, *prevfocus, *current;
static Atom wmatoms[WM_COUNT], netatoms[NET_COUNT];
static desktop desktops[DESKTOPS];
/* events array
* on receival of a new event, call the appropriate function to handle it
*/
static void (*events[LASTEvent])(XEvent *e) = {
[ButtonPress] = buttonpress,
[ClientMessage] = clientmessage,
[ConfigureRequest] = configurerequest,
[DestroyNotify] = destroynotify,
[EnterNotify] = enternotify,
[KeyPress] = keypress,
[MapRequest] = maprequest,
[PropertyNotify] = propertynotify,
[UnmapNotify] = unmapnotify,
};
/* create a new client and add the new window
* window should notify of property change events
*/
void addwindow(Window w) {
client *c, *t;
if (!(c = (client *)calloc(1, sizeof(client))))
die("error: could not calloc() %u bytes\n", sizeof(client));
if (!head) head = c;
else if (ATTACH_ASIDE) {
for(t=head; t->next; t=t->next); /* get the last client */
t->next = c;
} else {
c->next = (t = head);
head = c;
}
prevfocus = current;
XSelectInput(dis, ((current = c)->win = w), PropertyChangeMask|(FOLLOW_MOUSE?EnterWindowMask:0));
}
/* on the press of a button check to see if there's a binded function to call */
void buttonpress(XEvent *e) {
client *c = wintoclient(e->xbutton.window);
if (!c) return;
if (CLICK_TO_FOCUS && current != c && e->xbutton.button == Button1) update_current(c);
for (unsigned int i=0; i<LENGTH(buttons); i++)
if (buttons[i].func && buttons[i].button == e->xbutton.button &&
CLEANMASK(buttons[i].mask) == CLEANMASK(e->xbutton.state)) {
update_current(c);
buttons[i].func(&(buttons[i].arg));
}
}
/* focus another desktop
* to avoid flickering
* first map the new windows
* if the layout mode is fullscreen map only one window
* then unmap previous windows
*/
void change_desktop(const Arg *arg) {
if (arg->i == current_desktop) return;
previous_desktop = current_desktop;
select_desktop(arg->i);
tile();
if (mode == MONOCLE && current) XMapWindow(dis, current->win);
else for (client *c=head; c; c=c->next) XMapWindow(dis, c->win);
update_current(NULL);
select_desktop(previous_desktop);
for (client *c=head; c; c=c->next) XUnmapWindow(dis, c->win);
select_desktop(arg->i);
desktopinfo();
}
/* remove all windows in all desktops
* get the all windows and send a delete message
*/
void cleanup(void) {
Window root_return;
Window parent_return;
Window *children;
unsigned int nchildren;
XUngrabKey(dis, AnyKey, AnyModifier, root);
XQueryTree(dis, root, &root_return, &parent_return, &children, &nchildren);
for (unsigned int i = 0; i<nchildren; i++) sendevent(children[i], WM_DELETE_WINDOW);
if (children) XFree(children);
XSync(dis, False);
XSetInputFocus(dis, PointerRoot, RevertToPointerRoot, CurrentTime);
}
/* move a client to another desktop
* store the client's window
* remove the client
* add the window to the new desktop
* if defined change focus to the new desktop
*/
void client_to_desktop(const Arg *arg) {
if (arg->i == current_desktop || !current) return;
Window w = current->win;
int cd = current_desktop;
XUnmapWindow(dis, current->win);
if (current->isfullscreen) setfullscreen(current, False);
removeclient(current);
select_desktop(arg->i);
addwindow(w);
select_desktop(cd);
tile();
update_current(NULL);
if (FOLLOW_WINDOW) change_desktop(arg);
desktopinfo();
}
/* check if window requested fullscreen or activation
* To change the state of a mapped window, a client MUST
* send a _NET_WM_STATE client message to the root window
* message_type must be _NET_WM_STATE
* data.l[0] is the action to be taken
* data.l[1] is the property to alter three actions:
* remove/unset _NET_WM_STATE_REMOVE=0
* add/set _NET_WM_STATE_ADD=1,
* toggle _NET_WM_STATE_TOGGLE=2
*/
void clientmessage(XEvent *e) {
client *c = wintoclient(e->xclient.window);
if (c && e->xclient.message_type == netatoms[NET_WM_STATE] && ((unsigned)e->xclient.data.l[1]
== netatoms[NET_FULLSCREEN] || (unsigned)e->xclient.data.l[2] == netatoms[NET_FULLSCREEN]))
setfullscreen(c, (e->xclient.data.l[0] == 1 || (e->xclient.data.l[0] == 2 && !c->isfullscreen)));
else if (c && e->xclient.message_type == netatoms[NET_ACTIVE]) current = c;
tile();
update_current(NULL);
}
/* a configure request means that the window requested changes in its geometry
* state. if the window is fullscreen discard and fill the screen, else set the
* appropriate values as requested, and tile the window again so that it fills
* the gaps that otherwise could have been created
*/
void configurerequest(XEvent *e) {
client *c = wintoclient(e->xconfigurerequest.window);
if (c && c->isfullscreen)
XMoveResizeWindow(dis, c->win, 0, 0, ww + BORDER_WIDTH, wh + BORDER_WIDTH + PANEL_HEIGHT);
else {
XWindowChanges wc;
wc.x = e->xconfigurerequest.x;
wc.y = e->xconfigurerequest.y + (showpanel && TOP_PANEL) ? PANEL_HEIGHT : 0;
wc.width = (e->xconfigurerequest.width < ww - BORDER_WIDTH) ? e->xconfigurerequest.width : ww + BORDER_WIDTH;
wc.height = (e->xconfigurerequest.height < wh - BORDER_WIDTH) ? e->xconfigurerequest.height : wh + BORDER_WIDTH;
wc.border_width = e->xconfigurerequest.border_width;
wc.sibling = e->xconfigurerequest.above;
wc.stack_mode = e->xconfigurerequest.detail;
XConfigureWindow(dis, e->xconfigurerequest.window, e->xconfigurerequest.value_mask, &wc);
XSync(dis, False);
}
tile();
}
/* output info about the desktops on standard output stream
*
* the info is a list of ':' separated values for each desktop
* desktop to desktop info is separated by ' ' single spaces
* the info values are
* the desktop number/id
* the desktop's client count
* the desktop's tiling layout mode/id
* whether the desktop is the current focused (1) or not (0)
* whether any client in that desktop has received an urgent hint
*
* once the info is collected, immediately flush the stream
*/
void desktopinfo(void) {
Bool urgent = False;
int cd = current_desktop, n=0, d=0;
for (client *c; d<DESKTOPS; d++) {
for (select_desktop(d), c=head, n=0, urgent=False; c; c=c->next, ++n) if (c->isurgent) urgent = True;
fprintf(stdout, "%d:%d:%d:%d:%d%c", d, n, mode, current_desktop == cd, urgent, d+1==DESKTOPS?'\n':' ');
}
fflush(stdout);
select_desktop(cd);
}
/* a destroy notification is received when a window is being closed
* on receival, remove the appropriate client that held that window
*/
void destroynotify(XEvent *e) {
client *c = wintoclient(e->xdestroywindow.window);
if (c) removeclient(c);
desktopinfo();
}
/* print a message on standard error stream
* and exit with failure exit code
*/
void die(const char *errstr, ...) {
va_list ap;
va_start(ap, errstr);
vfprintf(stderr, errstr, ap);
va_end(ap);
exit(EXIT_FAILURE);
}
/* when the mouse enters a window's borders
* the window, if notifying of such events (EnterWindowMask)
* will notify the wm and will get focus
*/
void enternotify(XEvent *e) {
if (!FOLLOW_MOUSE) return;
client *c = wintoclient(e->xcrossing.window);
if (!c) return;
if (e->xcrossing.mode == NotifyNormal && e->xcrossing.detail != NotifyInferior) update_current(c);
}
/* find and focus the client which received
* the urgent hint in the current desktop
*/
void focusurgent() {
for (client *c=head; c; c=c->next) if (c->isurgent) update_current(c);
}
/* get a pixel with the requested color
* to fill some window area - borders
*/
unsigned long getcolor(const char* color) {
Colormap map = DefaultColormap(dis, screen);
XColor c;
if (!XAllocNamedColor(dis, map, color, &c, &c))
die("error: cannot allocate color '%s'\n", c);
return c.pixel;
}
/* set the given client to listen to button events (presses / releases) */
void grabbuttons(client *c) {
unsigned int modifiers[] = { 0, LockMask, numlockmask, numlockmask|LockMask };
for (unsigned int b=0; b<LENGTH(buttons); b++)
for (unsigned int m=0; m<LENGTH(modifiers); m++)
XGrabButton(dis, buttons[b].button, buttons[b].mask|modifiers[m], c->win,
False, BUTTONMASK, GrabModeAsync, GrabModeAsync, None, None);
}
/* the wm should listen to key presses */
void grabkeys(void) {
KeyCode code;
XUngrabKey(dis, AnyKey, AnyModifier, root);
unsigned int modifiers[] = { 0, LockMask, numlockmask, numlockmask|LockMask };
for (unsigned int k=0; k<LENGTH(keys); k++)
if ((code = XKeysymToKeycode(dis, keys[k].keysym)))
for (unsigned int m=0; m<LENGTH(modifiers); m++)
XGrabKey(dis, code, keys[k].mod|modifiers[m], root, True, GrabModeAsync, GrabModeAsync);
}
/* on the press of a key check to see if there's a binded function to call */
void keypress(XEvent *e) {
KeySym keysym;
keysym = XKeycodeToKeysym(dis, (KeyCode)e->xkey.keycode, 0);
for (unsigned int i=0; i<LENGTH(keys); i++)
if (keysym == keys[i].keysym && CLEANMASK(keys[i].mod) == CLEANMASK(e->xkey.state) && keys[i].func)
keys[i].func(&keys[i].arg);
}
/* explicitly kill a client - close the highlighted window
* send a delete message and remove the client
*/
void killclient() {
if (!current) return;
sendevent(current->win, WM_DELETE_WINDOW);
removeclient(current);
}
/* focus the previously focused desktop */
void last_desktop() {
change_desktop(&(Arg){.i = previous_desktop});
}
/* a map request is received when a window wants to display itself
* if the window has override_redirect flag set then it should not be handled
* by the wm. if the window already has a client then there is nothing to do.
*
* get the window class and name instance and try to match against an app rule.
* create a client for the window, that client will always be current.
* check for transient state, and fullscreen state and the appropriate values.
* if the desktop in which the window was spawned is the current desktop then
* display the window, else, if set, focus the new desktop.
*/
void maprequest(XEvent *e) {
static XWindowAttributes wa;
if (XGetWindowAttributes(dis, e->xmaprequest.window, &wa) && wa.override_redirect) return;
if (wintoclient(e->xmaprequest.window)) return;
Bool follow = False;
int cd = current_desktop, newdsk = current_desktop;
XClassHint ch = {0, 0};
if (XGetClassHint(dis, e->xmaprequest.window, &ch))
for (unsigned int i=0; i<LENGTH(rules); i++)
if (!strcmp(ch.res_class, rules[i].class) || !strcmp(ch.res_name, rules[i].class)) {
follow = rules[i].follow;
newdsk = rules[i].desktop;
break;
}
if (ch.res_class) XFree(ch.res_class);
if (ch.res_name) XFree(ch.res_name);
select_desktop(newdsk);
addwindow(e->xmaprequest.window);
Window w;
current->istransient = XGetTransientForHint(dis, e->xmaprequest.window, &w);
int di; unsigned long dl; unsigned char *state = NULL; Atom da;
if (XGetWindowProperty(dis, current->win, netatoms[NET_WM_STATE], 0L, sizeof da,
False, XA_ATOM, &da, &di, &dl, &dl, &state) == Success && state)
setfullscreen(current, (*(Atom *)state == netatoms[NET_FULLSCREEN]));
if (state) XFree(state);
select_desktop(cd);
if (cd == newdsk) {
tile();
XMapWindow(dis, current->win);
update_current(NULL);
grabbuttons(current);
} else if (follow) change_desktop(&(Arg){.i = newdsk});
desktopinfo();
}
/* grab the pointer and get it's current position
* all pointer movement events will be reported until it's ungrabbed
* until the mouse button has not been released,
* grab the interesting events - button press/release and pointer motion
* and on on pointer movement resize or move the window under the curson.
* if the received event is a map request or a configure request call the
* appropriate handler, and stop listening for other events.
* Ungrab the poitner and event handling is passed back to run() function.
* Once a window has been moved or resized, it's marked as floating.
*/
void mousemotion(const Arg *arg) {
if (!current) return;
static XWindowAttributes wa;
XGetWindowAttributes(dis, current->win, &wa);
if (XGrabPointer(dis, root, False, BUTTONMASK|PointerMotionMask, GrabModeAsync,
GrabModeAsync, None, None, CurrentTime) != GrabSuccess) return;
int x, y, z; unsigned int v; Window w;
XQueryPointer(dis, root, &w, &w, &x, &y, &z, &z, &v);
XEvent ev;
do {
XMaskEvent(dis, BUTTONMASK|PointerMotionMask|SubstructureRedirectMask, &ev);
switch (ev.type) {
case ConfigureRequest:
case MapRequest:
events[ev.type](&ev);
break;
case MotionNotify:
if (arg->i == MOVE) XMoveWindow(dis, current->win, wa.x + ev.xmotion.x - x, wa.y + ev.xmotion.y - y);
else XResizeWindow(dis, current->win, wa.width + ev.xmotion.x - x, wa.height + ev.xmotion.y - y);
break;
}
current->isfloating = True;
} while(ev.type != ButtonRelease);
XUngrabPointer(dis, CurrentTime);
tile();
}
/* move the current client, to current->next
* and current->next to current client's position
*/
void move_down() {
if (!current || !head->next) return;
for (client *t=head; t; t=t->next) if (t->isfullscreen) return;
/* p is previous, n is next, if current is head n is last, c is current */
client *p = NULL, *n = (current->next) ? current->next : head;
for (p=head; p && p->next != current; p=p->next);
/* if there's a previous client then p->next should be what's after c
* ..->[p]->[c]->[n]->.. ==> ..->[p]->[n]->[c]->..
*/
if (p) p->next = current->next;
/* else if no p client, then c is head, swapping with n should update head
* [c]->[n]->.. ==> [n]->[c]->..
* ^head ^head
*/
else head = n;
/* if c is the last client, c will be the current head
* [n]->..->[p]->[c]->NULL ==> [c]->[n]->..->[p]->NULL
* ^head ^head
* else c will take the place of n, so c-next will be n->next
* ..->[p]->[c]->[n]->.. ==> ..->[p]->[n]->[c]->..
*/
current->next = (current->next) ? n->next : n;
/* if c was swapped with n then they now point to the same ->next. n->next should be c
* ..->[p]->[c]->[n]->.. ==> ..->[p]->[n]->.. ==> ..->[p]->[n]->[c]->..
* [c]-^
*/
if (current->next == n->next) n->next = current;
/* else c is the last client and n is head,
* so c will be move to be head, no need to update n->next
* [n]->..->[p]->[c]->NULL ==> [c]->[n]->..->[p]->NULL
* ^head ^head
*/
else head = current;
tile();
update_current(NULL);
}
/* move the current client, to the previous from current
* and the previous from current to current client's position
*/
void move_up() {
if (!current || !head->next) return;
for (client *t=head; t; t=t->next) if (t->isfullscreen) return;
client *pp = NULL, *p;
/* p is previous from current or last if current is head */
for (p=head; p->next && p->next != current; p=p->next);
/* pp is previous from p, or null if current is head and thus p is last */
if (p->next) for (pp=head; pp; pp=pp->next) if (pp->next == p) break;
/* if p has a previous client then the next client should be current (current is c)
* ..->[pp]->[p]->[c]->.. ==> ..->[pp]->[c]->[p]->..
*/
if (pp) pp->next = current;
/* if p doesn't have a previous client, then p might be head, so head must change to c
* [p]->[c]->.. ==> [c]->[p]->..
* ^head ^head
* if p is not head, then c is head (and p is last), so the new head is next of c
* [c]->[n]->..->[p]->NULL ==> [n]->..->[p]->[c]->NULL
* ^head ^last ^head ^last
*/
else head = (current == head) ? current->next : current;
/* next of p should be next of c
* ..->[pp]->[p]->[c]->[n]->.. ==> ..->[pp]->[c]->[p]->[n]->..
* except if c was head (now c->next is head), so next of p should be c
* [c]->[n]->..->[p]->NULL ==> [n]->..->[p]->[c]->NULL
* ^head ^last ^head ^last
*/
p->next = (current->next == head) ? current : current->next;
/* next of c should be p
* ..->[pp]->[p]->[c]->[n]->.. ==> ..->[pp]->[c]->[p]->[n]->..
* except if c was head (now c->next is head), so c is must be last
* [c]->[n]->..->[p]->NULL ==> [n]->..->[p]->[c]->NULL
* ^head ^last ^head ^last
*/
current->next = (current->next == head) ? NULL : p;
tile();
update_current(NULL);
}
/* cyclic focus the next window
* if the window is the last on stack, focus head
*/
void next_win() {
if (!current || !head->next) return;
update_current((prevfocus = current)->next ? current->next : head);
if (mode == MONOCLE) XMapWindow(dis, current->win);
}
/* cyclic focus the previous window
* if the window is the head, focus the last stack window
*/
void prev_win() {
if (!current || !head->next) return;
if (head == (prevfocus = current)) while (current->next) current=current->next;
else for (client *t=head; t; t=t->next) if (t->next == current) { current = t; break; }
if (mode == MONOCLE) XMapWindow(dis, current->win);
update_current(NULL);
}
/* property notify is called when one of the window's properties
* is changed, such as an urgent hint is received
*/
void propertynotify(XEvent *e) {
client *c;
if ((c = wintoclient(e->xproperty.window)))
if (e->xproperty.atom == XA_WM_HINTS) {
XWMHints *wmh = XGetWMHints(dis, e->xproperty.window);
c->isurgent = wmh && (wmh->flags & XUrgencyHint);
XFree(wmh);
desktopinfo();
}
}
/* to quit just stop receiving events
* run() is stopped and control is back to main()
*/
void quit(const Arg *arg) {
retval = arg->i;
running = False;
}
/* remove the specified client
* the previous client must point to the next client of the given
* the removing client can be on any desktop, so we must return
* back the current focused desktop
*/
void removeclient(client *c) {
client **p = NULL;
int nd = 0, cd = current_desktop;
for (Bool found = False; nd<DESKTOPS && !found; nd++)
for (select_desktop(nd), p = &head; *p && !(found = *p == c); p = &(*p)->next);
*p = c->next;
current = (prevfocus && prevfocus != current) ? prevfocus : (*p) ? (prevfocus = *p) : (prevfocus = head);
select_desktop(cd);
tile();
if (mode == MONOCLE && cd == --nd && current) XMapWindow(dis, current->win);
update_current(NULL);
free(c);
}
/* resize the master window - check for boundary size limits
* the size of a window can't be less than MINWSZ
*/
void resize_master(const Arg *arg) {
int msz = master_size + arg->i;
if ((mode == BSTACK ? wh : ww) - msz <= MINWSZ || msz <= MINWSZ) return;
master_size = msz;
tile();
}
/* resize the first stack window - no boundary checks */
void resize_stack(const Arg *arg) {
growth += arg->i;
tile();
}
/* jump and focus the 'current + n' desktop */
void rotate_desktop(const Arg *arg) {
change_desktop(&(Arg){.i = (current_desktop + DESKTOPS + arg->i) % DESKTOPS});
}
/* main event loop - on receival of an event call the appropriate event handler */
void run(void) {
XEvent ev;
while(running && !XNextEvent(dis, &ev)) if (events[ev.type]) events[ev.type](&ev);
}
/* save specified desktop's properties */
void save_desktop(int i) {
if (i >= DESKTOPS) return;
desktops[i].master_size = master_size;
desktops[i].mode = mode;
desktops[i].growth = growth;
desktops[i].head = head;
desktops[i].current = current;
desktops[i].showpanel = showpanel;
desktops[i].prevfocus = prevfocus;
}
/* set the specified desktop's properties */
void select_desktop(int i) {
if (i >= DESKTOPS || i == current_desktop) return;
save_desktop(current_desktop);
master_size = desktops[i].master_size;
mode = desktops[i].mode;
growth = desktops[i].growth;
head = desktops[i].head;
current = desktops[i].current;
showpanel = desktops[i].showpanel;
prevfocus = desktops[i].prevfocus;
current_desktop = i;
}
/* send the given event - WM_DELETE_WINDOW for now */
void sendevent(Window w, int atom) {
if (atom >= WM_COUNT) return;
XEvent ev;
ev.type = ClientMessage;
ev.xclient.window = w;
ev.xclient.message_type = wmatoms[WM_PROTOCOLS];
ev.xclient.format = 32;
ev.xclient.data.l[0] = wmatoms[atom];
ev.xclient.data.l[1] = CurrentTime;
XSendEvent(dis, w, False, NoEventMask, &ev);
}
/* set or unset fullscreen state of client */
void setfullscreen(client *c, Bool fullscreen) {
XChangeProperty(dis, c->win, netatoms[NET_WM_STATE], XA_ATOM, 32, PropModeReplace, (unsigned char*)
((c->isfullscreen = fullscreen) ? &netatoms[NET_FULLSCREEN] : 0), fullscreen);
if (c->isfullscreen) XMoveResizeWindow(dis, c->win, 0, 0, ww + BORDER_WIDTH, wh + BORDER_WIDTH + PANEL_HEIGHT);
}
/* set initial values
* root window - screen height/width - atoms - xerror handler
* set masks for reporting events handled by the wm
* and propagate the suported net atoms
*/
void setup(void) {
sigchld();
screen = DefaultScreen(dis);
root = RootWindow(dis, screen);
ww = XDisplayWidth(dis, screen) - BORDER_WIDTH;
wh = XDisplayHeight(dis, screen) - (SHOW_PANEL ? PANEL_HEIGHT : 0) - BORDER_WIDTH;
master_size = ((mode == BSTACK) ? wh : ww) * MASTER_SIZE;
for (unsigned int i=0; i<DESKTOPS; i++) save_desktop(i);
change_desktop(&(Arg){.i = DEFAULT_DESKTOP});
win_focus = getcolor(FOCUS);
win_unfocus = getcolor(UNFOCUS);
XModifierKeymap *modmap = XGetModifierMapping(dis);
for (int k=0; k<8; k++)
for (int j=0; j<modmap->max_keypermod; j++)
if (modmap->modifiermap[modmap->max_keypermod*k + j] == XKeysymToKeycode(dis, XK_Num_Lock))
numlockmask = (1 << k);
XFreeModifiermap(modmap);
/* set up atoms for dialog/notification windows */
wmatoms[WM_PROTOCOLS] = XInternAtom(dis, "WM_PROTOCOLS", False);
wmatoms[WM_DELETE_WINDOW] = XInternAtom(dis, "WM_DELETE_WINDOW", False);
netatoms[NET_SUPPORTED] = XInternAtom(dis, "_NET_SUPPORTED", False);
netatoms[NET_WM_STATE] = XInternAtom(dis, "_NET_WM_STATE", False);
netatoms[NET_ACTIVE] = XInternAtom(dis, "_NET_ACTIVE_WINDOW", False);
netatoms[NET_FULLSCREEN] = XInternAtom(dis, "_NET_WM_STATE_FULLSCREEN", False);
/* check if another window manager is running */
xerrorxlib = XSetErrorHandler(xerrorstart);
XSelectInput(dis, DefaultRootWindow(dis), SubstructureRedirectMask|SubstructureNotifyMask|PropertyChangeMask|ButtonPressMask);
XSync(dis, False);
XSetErrorHandler(xerror);
XSync(dis, False);
XChangeProperty(dis, root, netatoms[NET_SUPPORTED], XA_ATOM, 32, PropModeReplace, (unsigned char *)netatoms, NET_COUNT);
grabkeys();
}
void sigchld() {
if (signal(SIGCHLD, sigchld) == SIG_ERR)
die("error: can't install SIGCHLD handler\n");
while(0 < waitpid(-1, NULL, WNOHANG));
}
/* execute a command */
void spawn(const Arg *arg) {
if (fork() == 0) {
if (dis) close(ConnectionNumber(dis));
setsid();
execvp((char*)arg->com[0], (char**)arg->com);
fprintf(stderr, "error: execvp %s", (char *)arg->com[0]);
perror(" failed"); /* also prints the err msg */
exit(EXIT_SUCCESS);
}
}
/* swap master window with current or
* if current is master with the next
* if current is not head, then head is
* behind us, so move_up until is head
*/
void swap_master() {
if (!current || !head->next || mode == MONOCLE) return;
for (client *t=head; t; t=t->next) if (t->isfullscreen) return;
/* if current is head swap with next window */
if (current == head) move_down();
else while (current != head) move_up();
update_current(head);
tile();
}
/* switch the tiling mode and reset all floating windows */
void switch_mode(const Arg *arg) {
if (mode == MONOCLE) for (client *c=head; c; c=c->next) XMapWindow(dis, c->win);
for (client *c=head; c; c=c->next) c->isfloating = False;
mode = arg->i;
master_size = (mode == BSTACK ? wh : ww) * MASTER_SIZE;
tile();
update_current(NULL);
desktopinfo();
}
/* tile all windows of current desktop to the set tiling mode */
void tile(void) {
if (!head) return; /* nothing to arange */
client *c;
/* n:number of windows, d:difference, h:available height, z:client height */
int n = 0, d = 0, h = wh + (showpanel ? 0 : PANEL_HEIGHT), z = mode == BSTACK ? ww : h;
/* client's x,y coordinates, width and height */
int cx = 0, cy = (TOP_PANEL && showpanel ? PANEL_HEIGHT : 0), cw = 0, ch = 0;
/* count stack windows -- do not consider fullscreen or transient clients */
for (n=0, c=head->next; c; c=c->next) if (!c->istransient && !c->isfullscreen && !c->isfloating) ++n;
if (!head->next || (head->next->istransient && !head->next->next) || mode == MONOCLE) {
for (c=head; c; c=c->next) if (!c->isfullscreen && !c->istransient && !c->isfloating)
XMoveResizeWindow(dis, c->win, cx, cy, ww + BORDER_WIDTH, h + BORDER_WIDTH);
} else if (mode == TILE || mode == BSTACK) {
d = (z - growth)%n + growth; /* n should be greater than one */
z = (z - growth)/n; /* adjust to match screen height/width */
if (!head->isfullscreen && !head->istransient && !head->isfloating)
(mode == BSTACK) ? XMoveResizeWindow(dis, head->win, cx, cy, ww - BORDER_WIDTH, master_size - BORDER_WIDTH)
: XMoveResizeWindow(dis, head->win, cx, cy, master_size - BORDER_WIDTH, h - BORDER_WIDTH);
for (c=head->next; c && (c->isfullscreen || c->istransient || c->isfloating); c=c->next);
if (c) (mode == BSTACK) ? XMoveResizeWindow(dis, c->win, cx, (cy += master_size),
(cw = z - BORDER_WIDTH) + d, (ch = h - master_size - BORDER_WIDTH))
: XMoveResizeWindow(dis, c->win, (cx += master_size), cy,
(cw = ww - master_size - BORDER_WIDTH), (ch = z - BORDER_WIDTH) + d);
if (c) for (mode==BSTACK?(cx+=z+d):(cy+=z+d), c=c->next; c; c=c->next)
if (!c->isfullscreen && !c->istransient && !c->isfloating) {
XMoveResizeWindow(dis, c->win, cx, cy, cw, ch);
mode==BSTACK?(cx+=z):(cy+=z);
}
} else if (mode == GRID) {
++n; /* include head on window count */
int cols, rows, cn=0, rn=0, i=0; /* columns, rows, and current column and row number */
for (cols=0; cols <= n/2; cols++) if (cols*cols >= n) break; /* emulate square root */
if (n == 5) cols = 2;
rows = n/cols;
cw = cols ? ww/cols : ww;
for (i=0, c=head; c; c=c->next, i++) {
if (i/rows + 1 > cols - n%cols) rows = n/cols + 1;
ch = h/rows;
cx = cn*cw;
cy = (TOP_PANEL && showpanel ? PANEL_HEIGHT : 0) + rn*ch;
if (!c->isfullscreen && !c->istransient && !c->isfloating)
XMoveResizeWindow(dis, c->win, cx, cy, cw - BORDER_WIDTH, ch - BORDER_WIDTH);
if (++rn >= rows) { rn = 0; cn++; }
}
} else fprintf(stderr, "error: no such layout mode: %d\n", mode);
free(c);
}
/* toggle visibility state of the panel */
void togglepanel() {
showpanel = !showpanel;
tile();
}
/* windows that request to unmap should lose their
* client, so no invisible windows exist on screen
*/
void unmapnotify(XEvent *e) {
client *c = wintoclient(e->xunmap.window);
if (c && e->xunmap.send_event) removeclient(c);
desktopinfo();
}
/* update client - set highlighted borders and active window
* if no client is given update current
* if current is NULL then delete the active window property
*/
void update_current(client *c) {
if (!current && !c) {
XDeleteProperty(dis, root, netatoms[NET_ACTIVE]);
return;
} else if(c) current = c;
int border_width = (!head->next || (head->next->istransient &&
!head->next->next) || mode == MONOCLE) ? 0 : BORDER_WIDTH;
for (client *c=head; c; c=c->next) {
XSetWindowBorderWidth(dis, c->win, (c->isfullscreen ? 0 : border_width));
XSetWindowBorder(dis, c->win, (current == c ? win_focus : win_unfocus));
}
XChangeProperty(dis, root, netatoms[NET_ACTIVE], XA_WINDOW, 32, PropModeReplace, (unsigned char *)¤t->win, 1);
XSetInputFocus(dis, current->win, RevertToPointerRoot, CurrentTime);
XRaiseWindow(dis, current->win);
XSync(dis, False);
}
/* find to which client the given window belongs to */
client* wintoclient(Window w) {
client *c = NULL;
int d = 0, cd = current_desktop;
for (Bool found = False; d<DESKTOPS && !found; ++d)
for (select_desktop(d), c=head; c && !(found = (w == c->win)); c=c->next);
select_desktop(cd);
return c;
}
/* There's no way to check accesses to destroyed windows, thus those cases are
* ignored (especially on UnmapNotify's). Other types of errors call Xlibs
* default error handler, which may call exit through xerrorlib. */
int xerror(Display *dis, XErrorEvent *ee) {
if (ee->error_code == BadWindow
|| (ee->error_code == BadMatch && (ee->request_code == X_SetInputFocus || ee->request_code == X_ConfigureWindow))
|| (ee->error_code == BadDrawable && (ee->request_code == X_PolyText8 || ee->request_code == X_PolyFillRectangle
|| ee->request_code == X_PolySegment || ee->request_code == X_CopyArea))
|| (ee->error_code == BadAccess && ee->request_code == X_GrabKey))
return 0;
fprintf(stderr, "error: xerror: request code: %d, error code: %d\n", ee->request_code, ee->error_code);
return xerrorxlib(dis, ee);
}
int xerrorstart() {
die("error: another window manager is already running\n");
return -1;
}
int main(int argc, char *argv[]) {
if (argc == 2 && strcmp("-v", argv[1]) == 0) {
fprintf(stdout, "%s-%s\n", WMNAME, VERSION);
return EXIT_SUCCESS;
} else if (argc != 1) die("usage: %s [-v]\n", WMNAME);
if (!(dis = XOpenDisplay(NULL))) die("error: cannot open display\n");
setup();
desktopinfo(); /* zero out every desktop on (re)start */
run();
cleanup();
XCloseDisplay(dis);
return retval;
}
|