]> code.delx.au - spectrwm/blob - spectrwm.c
Limit window name to 64 characters by default.
[spectrwm] / spectrwm.c
1 /*
2 * Copyright (c) 2009-2012 Marco Peereboom <marco@peereboom.us>
3 * Copyright (c) 2009-2011 Ryan McBride <mcbride@countersiege.com>
4 * Copyright (c) 2009 Darrin Chandler <dwchandler@stilyagin.com>
5 * Copyright (c) 2009 Pierre-Yves Ritschard <pyr@spootnik.org>
6 * Copyright (c) 2010 Tuukka Kataja <stuge@xor.fi>
7 * Copyright (c) 2011 Jason L. Wright <jason@thought.net>
8 * Copyright (c) 2011-2012 Reginald Kennedy <rk@rejii.com>
9 * Copyright (c) 2011-2012 Lawrence Teo <lteo@lteo.net>
10 * Copyright (c) 2011-2012 Tiago Cunha <tcunha@gmx.com>
11 *
12 * Permission to use, copy, modify, and distribute this software for any
13 * purpose with or without fee is hereby granted, provided that the above
14 * copyright notice and this permission notice appear in all copies.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
17 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
18 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
19 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
20 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
21 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
22 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
23 */
24 /*
25 * Much code and ideas taken from dwm under the following license:
26 * MIT/X Consortium License
27 *
28 * 2006-2008 Anselm R Garbe <garbeam at gmail dot com>
29 * 2006-2007 Sander van Dijk <a dot h dot vandijk at gmail dot com>
30 * 2006-2007 Jukka Salmi <jukka at salmi dot ch>
31 * 2007 Premysl Hruby <dfenze at gmail dot com>
32 * 2007 Szabolcs Nagy <nszabolcs at gmail dot com>
33 * 2007 Christof Musik <christof at sendfax dot de>
34 * 2007-2008 Enno Gottox Boland <gottox at s01 dot de>
35 * 2007-2008 Peter Hartlich <sgkkr at hartlich dot com>
36 * 2008 Martin Hurton <martin dot hurton at gmail dot com>
37 *
38 * Permission is hereby granted, free of charge, to any person obtaining a
39 * copy of this software and associated documentation files (the "Software"),
40 * to deal in the Software without restriction, including without limitation
41 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
42 * and/or sell copies of the Software, and to permit persons to whom the
43 * Software is furnished to do so, subject to the following conditions:
44 *
45 * The above copyright notice and this permission notice shall be included in
46 * all copies or substantial portions of the Software.
47 *
48 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
49 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
50 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
51 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
52 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
53 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
54 * DEALINGS IN THE SOFTWARE.
55 */
56
57 #include <stdio.h>
58 #include <stdlib.h>
59 #include <err.h>
60 #include <errno.h>
61 #include <fcntl.h>
62 #include <locale.h>
63 #include <unistd.h>
64 #include <time.h>
65 #include <signal.h>
66 #include <string.h>
67 #include <util.h>
68 #include <pwd.h>
69 #include <paths.h>
70 #include <ctype.h>
71
72 #include <sys/types.h>
73 #include <sys/time.h>
74 #include <sys/stat.h>
75 #include <sys/wait.h>
76 #include <sys/queue.h>
77 #include <sys/param.h>
78 #include <sys/select.h>
79 #if defined(__linux__)
80 #include "tree.h"
81 #elif defined(__OpenBSD__)
82 #include <sys/tree.h>
83 #elif defined(__FreeBSD__)
84 #include <sys/tree.h>
85 #else
86 #include "tree.h"
87 #endif
88
89 #include <X11/cursorfont.h>
90 #include <X11/keysym.h>
91 #include <X11/XKBlib.h>
92 #include <X11/Xatom.h>
93 #include <X11/Xlib.h>
94 #include <X11/Xproto.h>
95 #include <X11/Xutil.h>
96 #include <X11/extensions/Xrandr.h>
97 #include <X11/extensions/XTest.h>
98
99 #ifdef __OSX__
100 #include <osx.h>
101 #endif
102
103 #include "version.h"
104
105 #ifdef SPECTRWM_BUILDSTR
106 static const char *buildstr = SPECTRWM_BUILDSTR;
107 #else
108 static const char *buildstr = SPECTRWM_VERSION;
109 #endif
110
111 #if RANDR_MAJOR < 1
112 # error XRandR versions less than 1.0 are not supported
113 #endif
114
115 #if RANDR_MAJOR >= 1
116 #if RANDR_MINOR >= 2
117 #define SWM_XRR_HAS_CRTC
118 #endif
119 #endif
120
121 /*#define SWM_DEBUG*/
122 #ifdef SWM_DEBUG
123 #define DPRINTF(x...) do { if (swm_debug) fprintf(stderr, x); } while (0)
124 #define DNPRINTF(n,x...) do { if (swm_debug & n) fprintf(stderr, x); } while (0)
125 #define SWM_D_MISC 0x0001
126 #define SWM_D_EVENT 0x0002
127 #define SWM_D_WS 0x0004
128 #define SWM_D_FOCUS 0x0008
129 #define SWM_D_MOVE 0x0010
130 #define SWM_D_STACK 0x0020
131 #define SWM_D_MOUSE 0x0040
132 #define SWM_D_PROP 0x0080
133 #define SWM_D_CLASS 0x0100
134 #define SWM_D_KEY 0x0200
135 #define SWM_D_QUIRK 0x0400
136 #define SWM_D_SPAWN 0x0800
137 #define SWM_D_EVENTQ 0x1000
138 #define SWM_D_CONF 0x2000
139 #define SWM_D_BAR 0x4000
140
141 u_int32_t swm_debug = 0
142 | SWM_D_MISC
143 | SWM_D_EVENT
144 | SWM_D_WS
145 | SWM_D_FOCUS
146 | SWM_D_MOVE
147 | SWM_D_STACK
148 | SWM_D_MOUSE
149 | SWM_D_PROP
150 | SWM_D_CLASS
151 | SWM_D_KEY
152 | SWM_D_QUIRK
153 | SWM_D_SPAWN
154 | SWM_D_EVENTQ
155 | SWM_D_CONF
156 | SWM_D_BAR
157 ;
158 #else
159 #define DPRINTF(x...)
160 #define DNPRINTF(n,x...)
161 #endif
162
163 #define LENGTH(x) (sizeof x / sizeof x[0])
164 #define MODKEY Mod1Mask
165 #define CLEANMASK(mask) (mask & ~(numlockmask | LockMask))
166 #define BUTTONMASK (ButtonPressMask|ButtonReleaseMask)
167 #define MOUSEMASK (BUTTONMASK|PointerMotionMask)
168 #define SWM_PROPLEN (16)
169 #define SWM_FUNCNAME_LEN (32)
170 #define SWM_KEYS_LEN (255)
171 #define SWM_QUIRK_LEN (64)
172 #define X(r) (r)->g.x
173 #define Y(r) (r)->g.y
174 #define WIDTH(r) (r)->g.w
175 #define HEIGHT(r) (r)->g.h
176 #define SH_MIN(w) (w)->sh_mask & PMinSize
177 #define SH_MIN_W(w) (w)->sh.min_width
178 #define SH_MIN_H(w) (w)->sh.min_height
179 #define SH_MAX(w) (w)->sh_mask & PMaxSize
180 #define SH_MAX_W(w) (w)->sh.max_width
181 #define SH_MAX_H(w) (w)->sh.max_height
182 #define SH_INC(w) (w)->sh_mask & PResizeInc
183 #define SH_INC_W(w) (w)->sh.width_inc
184 #define SH_INC_H(w) (w)->sh.height_inc
185 #define SWM_MAX_FONT_STEPS (3)
186 #define WINID(w) ((w) ? (w)->id : 0)
187 #define YESNO(x) ((x) ? "yes" : "no")
188
189 #define SWM_FOCUS_DEFAULT (0)
190 #define SWM_FOCUS_SYNERGY (1)
191 #define SWM_FOCUS_FOLLOW (2)
192
193 #define SWM_CONF_DEFAULT (0)
194 #define SWM_CONF_KEYMAPPING (1)
195
196 #ifndef SWM_LIB
197 #define SWM_LIB "/usr/local/lib/libswmhack.so"
198 #endif
199
200 char **start_argv;
201 Atom astate;
202 Atom aprot;
203 Atom adelete;
204 Atom takefocus;
205 Atom a_wmname;
206 Atom a_netwmname;
207 Atom a_utf8_string;
208 Atom a_string;
209 Atom a_swm_iconic;
210 volatile sig_atomic_t running = 1;
211 volatile sig_atomic_t restart_wm = 0;
212 int outputs = 0;
213 int last_focus_event = FocusOut;
214 int (*xerrorxlib)(Display *, XErrorEvent *);
215 int other_wm;
216 int ss_enabled = 0;
217 int xrandr_support;
218 int xrandr_eventbase;
219 unsigned int numlockmask = 0;
220 Display *display;
221
222 int cycle_empty = 0;
223 int cycle_visible = 0;
224 int term_width = 0;
225 int font_adjusted = 0;
226 unsigned int mod_key = MODKEY;
227
228 /* dmenu search */
229 struct swm_region *search_r;
230 int select_list_pipe[2];
231 int select_resp_pipe[2];
232 pid_t searchpid;
233 volatile sig_atomic_t search_resp;
234 int search_resp_action;
235
236 struct search_window {
237 TAILQ_ENTRY(search_window) entry;
238 int idx;
239 struct ws_win *win;
240 GC gc;
241 Window indicator;
242 };
243 TAILQ_HEAD(search_winlist, search_window);
244 struct search_winlist search_wl;
245
246 /* search actions */
247 enum {
248 SWM_SEARCH_NONE,
249 SWM_SEARCH_UNICONIFY,
250 SWM_SEARCH_NAME_WORKSPACE,
251 SWM_SEARCH_SEARCH_WORKSPACE,
252 SWM_SEARCH_SEARCH_WINDOW
253 };
254
255 #define SWM_STACK_TOP (0)
256 #define SWM_STACK_BOTTOM (1)
257 #define SWM_STACK_ABOVE (2)
258 #define SWM_STACK_BELOW (3)
259
260 /* dialog windows */
261 double dialog_ratio = 0.6;
262 /* status bar */
263 #define SWM_BAR_MAX (256)
264 #define SWM_BAR_JUSTIFY_LEFT (0)
265 #define SWM_BAR_JUSTIFY_CENTER (1)
266 #define SWM_BAR_JUSTIFY_RIGHT (2)
267 #define SWM_BAR_OFFSET (4)
268 #define SWM_BAR_FONTS "-*-terminus-medium-*-*-*-*-*-*-*-*-*-*-*," \
269 "-*-profont-*-*-*-*-*-*-*-*-*-*-*-*," \
270 "-*-times-medium-r-*-*-*-*-*-*-*-*-*-*," \
271 "-misc-fixed-medium-r-*-*-*-*-*-*-*-*-*-*," \
272 "-*-*-*-r-*--*-*-*-*-*-*-*-*"
273
274 #ifdef X_HAVE_UTF8_STRING
275 #define DRAWSTRING(x...) Xutf8DrawString(x)
276 #else
277 #define DRAWSTRING(x...) XmbDrawString(x)
278 #endif
279
280 char *bar_argv[] = { NULL, NULL };
281 int bar_pipe[2];
282 unsigned char bar_ext[SWM_BAR_MAX];
283 char bar_vertext[SWM_BAR_MAX];
284 int bar_version = 0;
285 sig_atomic_t bar_alarm = 0;
286 int bar_delay = 30;
287 int bar_enabled = 1;
288 int bar_border_width = 1;
289 int bar_at_bottom = 0;
290 int bar_extra = 1;
291 int bar_extra_running = 0;
292 int bar_verbose = 1;
293 int bar_height = 0;
294 int bar_justify = SWM_BAR_JUSTIFY_LEFT;
295 char *bar_format = NULL;
296 int stack_enabled = 1;
297 int clock_enabled = 1;
298 int urgent_enabled = 0;
299 char *clock_format = NULL;
300 int title_name_enabled = 0;
301 int title_class_enabled = 0;
302 int window_name_enabled = 0;
303 int focus_mode = SWM_FOCUS_DEFAULT;
304 int focus_close = SWM_STACK_BELOW;
305 int focus_close_wrap = 1;
306 int focus_default = SWM_STACK_TOP;
307 int spawn_position = SWM_STACK_TOP;
308 int disable_border = 0;
309 int border_width = 1;
310 int verbose_layout = 0;
311 pid_t bar_pid;
312 XFontSet bar_fs;
313 XFontSetExtents *bar_fs_extents;
314 char *bar_fonts;
315 char *spawn_term[] = { NULL, NULL }; /* XXX fully dynamic */
316 struct passwd *pwd;
317
318 #define SWM_MENU_FN (2)
319 #define SWM_MENU_NB (4)
320 #define SWM_MENU_NF (6)
321 #define SWM_MENU_SB (8)
322 #define SWM_MENU_SF (10)
323
324 /* layout manager data */
325 struct swm_geometry {
326 int x;
327 int y;
328 int w;
329 int h;
330 };
331
332 struct swm_screen;
333 struct workspace;
334
335 /* virtual "screens" */
336 struct swm_region {
337 TAILQ_ENTRY(swm_region) entry;
338 struct swm_geometry g;
339 struct workspace *ws; /* current workspace on this region */
340 struct workspace *ws_prior; /* prior workspace on this region */
341 struct swm_screen *s; /* screen idx */
342 Window bar_window;
343 };
344 TAILQ_HEAD(swm_region_list, swm_region);
345
346 struct ws_win {
347 TAILQ_ENTRY(ws_win) entry;
348 Window id;
349 Window transient;
350 struct ws_win *child_trans; /* transient child window */
351 struct swm_geometry g; /* current geometry */
352 struct swm_geometry g_float; /* geometry when floating */
353 struct swm_geometry rg_float; /* region geom when floating */
354 int g_floatvalid; /* g_float geometry validity */
355 int floatmaxed; /* whether maxed by max_stack */
356 int floating;
357 int manual;
358 int iconic;
359 unsigned int ewmh_flags;
360 int font_size_boundary[SWM_MAX_FONT_STEPS];
361 int font_steps;
362 int last_inc;
363 int can_delete;
364 int take_focus;
365 int java;
366 unsigned long quirks;
367 struct workspace *ws; /* always valid */
368 struct swm_screen *s; /* always valid, never changes */
369 XWindowAttributes wa;
370 XSizeHints sh;
371 long sh_mask;
372 XClassHint ch;
373 XWMHints *hints;
374 };
375 TAILQ_HEAD(ws_win_list, ws_win);
376
377 /* pid goo */
378 struct pid_e {
379 TAILQ_ENTRY(pid_e) entry;
380 long pid;
381 int ws;
382 };
383 TAILQ_HEAD(pid_list, pid_e);
384 struct pid_list pidlist = TAILQ_HEAD_INITIALIZER(pidlist);
385
386 /* layout handlers */
387 void stack(void);
388 void vertical_config(struct workspace *, int);
389 void vertical_stack(struct workspace *, struct swm_geometry *);
390 void horizontal_config(struct workspace *, int);
391 void horizontal_stack(struct workspace *, struct swm_geometry *);
392 void max_stack(struct workspace *, struct swm_geometry *);
393 void plain_stacker(struct workspace *);
394 void fancy_stacker(struct workspace *);
395
396 struct ws_win *find_window(Window);
397
398 void grabbuttons(struct ws_win *, int);
399 void new_region(struct swm_screen *, int, int, int, int);
400 void unmanage_window(struct ws_win *);
401 long getstate(Window);
402
403 int conf_load(char *, int);
404
405 struct layout {
406 void (*l_stack)(struct workspace *, struct swm_geometry *);
407 void (*l_config)(struct workspace *, int);
408 u_int32_t flags;
409 #define SWM_L_FOCUSPREV (1<<0)
410 #define SWM_L_MAPONFOCUS (1<<1)
411 void (*l_string)(struct workspace *);
412 } layouts[] = {
413 /* stack, configure */
414 { vertical_stack, vertical_config, 0, plain_stacker },
415 { horizontal_stack, horizontal_config, 0, plain_stacker },
416 { max_stack, NULL,
417 SWM_L_MAPONFOCUS | SWM_L_FOCUSPREV, plain_stacker },
418 { NULL, NULL, 0, NULL },
419 };
420
421 /* position of max_stack mode in the layouts array, index into layouts! */
422 #define SWM_V_STACK (0)
423 #define SWM_H_STACK (1)
424 #define SWM_MAX_STACK (2)
425
426 #define SWM_H_SLICE (32)
427 #define SWM_V_SLICE (32)
428
429 /* define work spaces */
430 struct workspace {
431 int idx; /* workspace index */
432 char *name; /* workspace name */
433 int always_raise; /* raise windows on focus */
434 struct layout *cur_layout; /* current layout handlers */
435 struct ws_win *focus; /* may be NULL */
436 struct ws_win *focus_prev; /* may be NULL */
437 struct swm_region *r; /* may be NULL */
438 struct swm_region *old_r; /* may be NULL */
439 struct ws_win_list winlist; /* list of windows in ws */
440 struct ws_win_list unmanagedlist; /* list of dead windows in ws */
441 char stacker[10]; /* display stacker and layout */
442
443 /* stacker state */
444 struct {
445 int horizontal_msize;
446 int horizontal_mwin;
447 int horizontal_stacks;
448 int horizontal_flip;
449 int vertical_msize;
450 int vertical_mwin;
451 int vertical_stacks;
452 int vertical_flip;
453 } l_state;
454 };
455
456 enum { SWM_S_COLOR_BAR, SWM_S_COLOR_BAR_BORDER, SWM_S_COLOR_BAR_FONT,
457 SWM_S_COLOR_FOCUS, SWM_S_COLOR_UNFOCUS, SWM_S_COLOR_MAX };
458
459 /* physical screen mapping */
460 #define SWM_WS_MAX (22) /* hard limit */
461 int workspace_limit = 10; /* soft limit */
462
463 struct swm_screen {
464 int idx; /* screen index */
465 struct swm_region_list rl; /* list of regions on this screen */
466 struct swm_region_list orl; /* list of old regions */
467 Window root;
468 struct workspace ws[SWM_WS_MAX];
469
470 /* colors */
471 struct {
472 unsigned long color;
473 char *name;
474 } c[SWM_S_COLOR_MAX];
475
476 GC bar_gc;
477 };
478 struct swm_screen *screens;
479
480 /* args to functions */
481 union arg {
482 int id;
483 #define SWM_ARG_ID_FOCUSNEXT (0)
484 #define SWM_ARG_ID_FOCUSPREV (1)
485 #define SWM_ARG_ID_FOCUSMAIN (2)
486 #define SWM_ARG_ID_FOCUSCUR (4)
487 #define SWM_ARG_ID_SWAPNEXT (10)
488 #define SWM_ARG_ID_SWAPPREV (11)
489 #define SWM_ARG_ID_SWAPMAIN (12)
490 #define SWM_ARG_ID_MOVELAST (13)
491 #define SWM_ARG_ID_MASTERSHRINK (20)
492 #define SWM_ARG_ID_MASTERGROW (21)
493 #define SWM_ARG_ID_MASTERADD (22)
494 #define SWM_ARG_ID_MASTERDEL (23)
495 #define SWM_ARG_ID_FLIPLAYOUT (24)
496 #define SWM_ARG_ID_STACKRESET (30)
497 #define SWM_ARG_ID_STACKINIT (31)
498 #define SWM_ARG_ID_CYCLEWS_UP (40)
499 #define SWM_ARG_ID_CYCLEWS_DOWN (41)
500 #define SWM_ARG_ID_CYCLESC_UP (42)
501 #define SWM_ARG_ID_CYCLESC_DOWN (43)
502 #define SWM_ARG_ID_CYCLEWS_UP_ALL (44)
503 #define SWM_ARG_ID_CYCLEWS_DOWN_ALL (45)
504 #define SWM_ARG_ID_STACKINC (50)
505 #define SWM_ARG_ID_STACKDEC (51)
506 #define SWM_ARG_ID_SS_ALL (60)
507 #define SWM_ARG_ID_SS_WINDOW (61)
508 #define SWM_ARG_ID_DONTCENTER (70)
509 #define SWM_ARG_ID_CENTER (71)
510 #define SWM_ARG_ID_KILLWINDOW (80)
511 #define SWM_ARG_ID_DELETEWINDOW (81)
512 #define SWM_ARG_ID_WIDTHGROW (90)
513 #define SWM_ARG_ID_WIDTHSHRINK (91)
514 #define SWM_ARG_ID_HEIGHTGROW (92)
515 #define SWM_ARG_ID_HEIGHTSHRINK (93)
516 #define SWM_ARG_ID_MOVEUP (100)
517 #define SWM_ARG_ID_MOVEDOWN (101)
518 #define SWM_ARG_ID_MOVELEFT (102)
519 #define SWM_ARG_ID_MOVERIGHT (103)
520 char **argv;
521 };
522
523 void focus(struct swm_region *, union arg *);
524 void focus_magic(struct ws_win *);
525
526 /* quirks */
527 struct quirk {
528 TAILQ_ENTRY(quirk) entry;
529 char *class;
530 char *name;
531 unsigned long quirk;
532 #define SWM_Q_FLOAT (1<<0) /* float this window */
533 #define SWM_Q_TRANSSZ (1<<1) /* transiend window size too small */
534 #define SWM_Q_ANYWHERE (1<<2) /* don't position this window */
535 #define SWM_Q_XTERM_FONTADJ (1<<3) /* adjust xterm fonts when resizing */
536 #define SWM_Q_FULLSCREEN (1<<4) /* remove border */
537 #define SWM_Q_FOCUSPREV (1<<5) /* focus on caller */
538 };
539 TAILQ_HEAD(quirk_list, quirk);
540 struct quirk_list quirks = TAILQ_HEAD_INITIALIZER(quirks);
541
542 /*
543 * Supported EWMH hints should be added to
544 * both the enum and the ewmh array
545 */
546 enum { _NET_ACTIVE_WINDOW, _NET_MOVERESIZE_WINDOW, _NET_CLOSE_WINDOW,
547 _NET_WM_WINDOW_TYPE, _NET_WM_WINDOW_TYPE_DOCK,
548 _NET_WM_WINDOW_TYPE_TOOLBAR, _NET_WM_WINDOW_TYPE_UTILITY,
549 _NET_WM_WINDOW_TYPE_SPLASH, _NET_WM_WINDOW_TYPE_DIALOG,
550 _NET_WM_WINDOW_TYPE_NORMAL, _NET_WM_STATE,
551 _NET_WM_STATE_MAXIMIZED_HORZ, _NET_WM_STATE_MAXIMIZED_VERT,
552 _NET_WM_STATE_SKIP_TASKBAR, _NET_WM_STATE_SKIP_PAGER,
553 _NET_WM_STATE_HIDDEN, _NET_WM_STATE_ABOVE, _SWM_WM_STATE_MANUAL,
554 _NET_WM_STATE_FULLSCREEN, _NET_WM_ALLOWED_ACTIONS, _NET_WM_ACTION_MOVE,
555 _NET_WM_ACTION_RESIZE, _NET_WM_ACTION_FULLSCREEN, _NET_WM_ACTION_CLOSE,
556 SWM_EWMH_HINT_MAX };
557
558 struct ewmh_hint {
559 char *name;
560 Atom atom;
561 } ewmh[SWM_EWMH_HINT_MAX] = {
562 /* must be in same order as in the enum */
563 {"_NET_ACTIVE_WINDOW", None},
564 {"_NET_MOVERESIZE_WINDOW", None},
565 {"_NET_CLOSE_WINDOW", None},
566 {"_NET_WM_WINDOW_TYPE", None},
567 {"_NET_WM_WINDOW_TYPE_DOCK", None},
568 {"_NET_WM_WINDOW_TYPE_TOOLBAR", None},
569 {"_NET_WM_WINDOW_TYPE_UTILITY", None},
570 {"_NET_WM_WINDOW_TYPE_SPLASH", None},
571 {"_NET_WM_WINDOW_TYPE_DIALOG", None},
572 {"_NET_WM_WINDOW_TYPE_NORMAL", None},
573 {"_NET_WM_STATE", None},
574 {"_NET_WM_STATE_MAXIMIZED_HORZ", None},
575 {"_NET_WM_STATE_MAXIMIZED_VERT", None},
576 {"_NET_WM_STATE_SKIP_TASKBAR", None},
577 {"_NET_WM_STATE_SKIP_PAGER", None},
578 {"_NET_WM_STATE_HIDDEN", None},
579 {"_NET_WM_STATE_ABOVE", None},
580 {"_SWM_WM_STATE_MANUAL", None},
581 {"_NET_WM_STATE_FULLSCREEN", None},
582 {"_NET_WM_ALLOWED_ACTIONS", None},
583 {"_NET_WM_ACTION_MOVE", None},
584 {"_NET_WM_ACTION_RESIZE", None},
585 {"_NET_WM_ACTION_FULLSCREEN", None},
586 {"_NET_WM_ACTION_CLOSE", None},
587 };
588
589 void store_float_geom(struct ws_win *, struct swm_region *);
590 int floating_toggle_win(struct ws_win *);
591 void spawn_select(struct swm_region *, union arg *, char *, int *);
592 unsigned char *get_win_name(Window);
593
594 int
595 get_property(Window id, Atom atom, long count, Atom type, unsigned long *nitems,
596 unsigned long *nbytes, unsigned char **data)
597 {
598 int format, status;
599 unsigned long *nbytes_ret, *nitems_ret;
600 unsigned long nbytes_tmp, nitems_tmp;
601 Atom real;
602
603 nbytes_ret = nbytes != NULL ? nbytes : &nbytes_tmp;
604 nitems_ret = nitems != NULL ? nitems : &nitems_tmp;
605
606 status = XGetWindowProperty(display, id, atom, 0L, count, False, type,
607 &real, &format, nitems_ret, nbytes_ret, data);
608
609 if (status != Success)
610 return (False);
611 if (real != type)
612 return (False);
613
614 return (True);
615 }
616
617 void
618 update_iconic(struct ws_win *win, int newv)
619 {
620 int32_t v = newv;
621 Atom iprop;
622
623 win->iconic = newv;
624
625 iprop = XInternAtom(display, "_SWM_ICONIC", False);
626 if (!iprop)
627 return;
628 if (newv)
629 XChangeProperty(display, win->id, iprop, XA_INTEGER, 32,
630 PropModeReplace, (unsigned char *)&v, 1);
631 else
632 XDeleteProperty(display, win->id, iprop);
633 }
634
635 int
636 get_iconic(struct ws_win *win)
637 {
638 int32_t v = 0;
639 int retfmt, status;
640 Atom iprop, rettype;
641 unsigned long nitems, extra;
642 unsigned char *prop = NULL;
643
644 iprop = XInternAtom(display, "_SWM_ICONIC", False);
645 if (!iprop)
646 goto out;
647 status = XGetWindowProperty(display, win->id, iprop, 0L, 1L,
648 False, XA_INTEGER, &rettype, &retfmt, &nitems, &extra, &prop);
649 if (status != Success)
650 goto out;
651 if (rettype != XA_INTEGER || retfmt != 32)
652 goto out;
653 if (nitems != 1)
654 goto out;
655 v = *((int32_t *)prop);
656
657 out:
658 if (prop != NULL)
659 XFree(prop);
660 return (v);
661 }
662
663 void
664 setup_ewmh(void)
665 {
666 int i,j;
667 Atom sup_list;
668
669 sup_list = XInternAtom(display, "_NET_SUPPORTED", False);
670
671 for (i = 0; i < LENGTH(ewmh); i++)
672 ewmh[i].atom = XInternAtom(display, ewmh[i].name, False);
673
674 for (i = 0; i < ScreenCount(display); i++) {
675 /* Support check window will be created by workaround(). */
676
677 /* Report supported atoms */
678 XDeleteProperty(display, screens[i].root, sup_list);
679 for (j = 0; j < LENGTH(ewmh); j++)
680 XChangeProperty(display, screens[i].root,
681 sup_list, XA_ATOM, 32,
682 PropModeAppend, (unsigned char *)&ewmh[j].atom, 1);
683 }
684 }
685
686 void
687 teardown_ewmh(void)
688 {
689 int i, success;
690 unsigned char *data = NULL;
691 unsigned long n;
692 Atom sup_check, sup_list;
693 Window id;
694
695 sup_check = XInternAtom(display, "_NET_SUPPORTING_WM_CHECK", False);
696 sup_list = XInternAtom(display, "_NET_SUPPORTED", False);
697
698 for (i = 0; i < ScreenCount(display); i++) {
699 /* Get the support check window and destroy it */
700 success = get_property(screens[i].root, sup_check, 1, XA_WINDOW,
701 &n, NULL, &data);
702
703 if (success) {
704 id = data[0];
705 XDestroyWindow(display, id);
706 XDeleteProperty(display, screens[i].root, sup_check);
707 XDeleteProperty(display, screens[i].root, sup_list);
708 }
709
710 XFree(data);
711 }
712 }
713
714 void
715 ewmh_autoquirk(struct ws_win *win)
716 {
717 int success, i;
718 unsigned long *data = NULL, n;
719 Atom type;
720
721 success = get_property(win->id, ewmh[_NET_WM_WINDOW_TYPE].atom, (~0L),
722 XA_ATOM, &n, NULL, (void *)&data);
723
724 if (!success) {
725 XFree(data);
726 return;
727 }
728
729 for (i = 0; i < n; i++) {
730 type = data[i];
731 if (type == ewmh[_NET_WM_WINDOW_TYPE_NORMAL].atom)
732 break;
733 if (type == ewmh[_NET_WM_WINDOW_TYPE_DOCK].atom ||
734 type == ewmh[_NET_WM_WINDOW_TYPE_TOOLBAR].atom ||
735 type == ewmh[_NET_WM_WINDOW_TYPE_UTILITY].atom) {
736 win->floating = 1;
737 win->quirks = SWM_Q_FLOAT | SWM_Q_ANYWHERE;
738 break;
739 }
740 if (type == ewmh[_NET_WM_WINDOW_TYPE_SPLASH].atom ||
741 type == ewmh[_NET_WM_WINDOW_TYPE_DIALOG].atom) {
742 win->floating = 1;
743 win->quirks = SWM_Q_FLOAT;
744 break;
745 }
746 }
747
748 XFree(data);
749 }
750
751 #define SWM_EWMH_ACTION_COUNT_MAX (6)
752 #define EWMH_F_FULLSCREEN (1<<0)
753 #define EWMH_F_ABOVE (1<<1)
754 #define EWMH_F_HIDDEN (1<<2)
755 #define EWMH_F_SKIP_PAGER (1<<3)
756 #define EWMH_F_SKIP_TASKBAR (1<<4)
757 #define SWM_F_MANUAL (1<<5)
758
759 int
760 ewmh_set_win_fullscreen(struct ws_win *win, int fs)
761 {
762 struct swm_geometry rg;
763
764 if (!win->ws->r)
765 return (0);
766
767 if (!win->floating)
768 return (0);
769
770 DNPRINTF(SWM_D_MISC, "ewmh_set_win_fullscreen: window: 0x%lx, "
771 "fullscreen %s\n", win->id, YESNO(fs));
772
773 rg = win->ws->r->g;
774
775 if (fs) {
776 store_float_geom(win, win->ws->r);
777
778 win->g = rg;
779 } else {
780 if (win->g_floatvalid) {
781 /* refloat at last floating relative position */
782 X(win) = win->g_float.x - win->rg_float.x + rg.x;
783 Y(win) = win->g_float.y - win->rg_float.y + rg.y;
784 WIDTH(win) = win->g_float.w;
785 HEIGHT(win) = win->g_float.h;
786 }
787 }
788
789 return (1);
790 }
791
792 void
793 ewmh_update_actions(struct ws_win *win)
794 {
795 Atom actions[SWM_EWMH_ACTION_COUNT_MAX];
796 int n = 0;
797
798 if (win == NULL)
799 return;
800
801 actions[n++] = ewmh[_NET_WM_ACTION_CLOSE].atom;
802
803 if (win->floating) {
804 actions[n++] = ewmh[_NET_WM_ACTION_MOVE].atom;
805 actions[n++] = ewmh[_NET_WM_ACTION_RESIZE].atom;
806 }
807
808 XChangeProperty(display, win->id, ewmh[_NET_WM_ALLOWED_ACTIONS].atom,
809 XA_ATOM, 32, PropModeReplace, (unsigned char *)actions, n);
810 }
811
812 #define _NET_WM_STATE_REMOVE 0 /* remove/unset property */
813 #define _NET_WM_STATE_ADD 1 /* add/set property */
814 #define _NET_WM_STATE_TOGGLE 2 /* toggle property */
815
816 void
817 ewmh_update_win_state(struct ws_win *win, long state, long action)
818 {
819 unsigned int mask = 0;
820 unsigned int changed = 0;
821 unsigned int orig_flags;
822
823 if (win == NULL)
824 return;
825
826 if (state == ewmh[_NET_WM_STATE_FULLSCREEN].atom)
827 mask = EWMH_F_FULLSCREEN;
828 if (state == ewmh[_NET_WM_STATE_ABOVE].atom)
829 mask = EWMH_F_ABOVE;
830 if (state == ewmh[_SWM_WM_STATE_MANUAL].atom)
831 mask = SWM_F_MANUAL;
832 if (state == ewmh[_NET_WM_STATE_SKIP_PAGER].atom)
833 mask = EWMH_F_SKIP_PAGER;
834 if (state == ewmh[_NET_WM_STATE_SKIP_TASKBAR].atom)
835 mask = EWMH_F_SKIP_TASKBAR;
836
837
838 orig_flags = win->ewmh_flags;
839
840 switch (action) {
841 case _NET_WM_STATE_REMOVE:
842 win->ewmh_flags &= ~mask;
843 break;
844 case _NET_WM_STATE_ADD:
845 win->ewmh_flags |= mask;
846 break;
847 case _NET_WM_STATE_TOGGLE:
848 win->ewmh_flags ^= mask;
849 break;
850 }
851
852 changed = (win->ewmh_flags & mask) ^ (orig_flags & mask) ? 1 : 0;
853
854 if (state == ewmh[_NET_WM_STATE_ABOVE].atom)
855 if (changed)
856 if (!floating_toggle_win(win))
857 win->ewmh_flags = orig_flags; /* revert */
858 if (state == ewmh[_SWM_WM_STATE_MANUAL].atom)
859 if (changed)
860 win->manual = (win->ewmh_flags & SWM_F_MANUAL) != 0;
861 if (state == ewmh[_NET_WM_STATE_FULLSCREEN].atom)
862 if (changed)
863 if (!ewmh_set_win_fullscreen(win,
864 win->ewmh_flags & EWMH_F_FULLSCREEN))
865 win->ewmh_flags = orig_flags; /* revert */
866
867 XDeleteProperty(display, win->id, ewmh[_NET_WM_STATE].atom);
868
869 if (win->ewmh_flags & EWMH_F_FULLSCREEN)
870 XChangeProperty(display, win->id, ewmh[_NET_WM_STATE].atom,
871 XA_ATOM, 32, PropModeAppend,
872 (unsigned char *)&ewmh[_NET_WM_STATE_FULLSCREEN].atom, 1);
873 if (win->ewmh_flags & EWMH_F_SKIP_PAGER)
874 XChangeProperty(display, win->id, ewmh[_NET_WM_STATE].atom,
875 XA_ATOM, 32, PropModeAppend,
876 (unsigned char *)&ewmh[_NET_WM_STATE_SKIP_PAGER].atom, 1);
877 if (win->ewmh_flags & EWMH_F_SKIP_TASKBAR)
878 XChangeProperty(display, win->id, ewmh[_NET_WM_STATE].atom,
879 XA_ATOM, 32, PropModeAppend,
880 (unsigned char *)&ewmh[_NET_WM_STATE_SKIP_TASKBAR].atom, 1);
881 if (win->ewmh_flags & EWMH_F_ABOVE)
882 XChangeProperty(display, win->id, ewmh[_NET_WM_STATE].atom,
883 XA_ATOM, 32, PropModeAppend,
884 (unsigned char *)&ewmh[_NET_WM_STATE_ABOVE].atom, 1);
885 if (win->ewmh_flags & SWM_F_MANUAL)
886 XChangeProperty(display, win->id, ewmh[_NET_WM_STATE].atom,
887 XA_ATOM, 32, PropModeAppend,
888 (unsigned char *)&ewmh[_SWM_WM_STATE_MANUAL].atom, 1);
889 }
890
891 void
892 ewmh_get_win_state(struct ws_win *win)
893 {
894 int success, i;
895 unsigned long n;
896 Atom *states;
897
898 if (win == NULL)
899 return;
900
901 win->ewmh_flags = 0;
902 if (win->floating)
903 win->ewmh_flags |= EWMH_F_ABOVE;
904 if (win->manual)
905 win->ewmh_flags |= SWM_F_MANUAL;
906
907 success = get_property(win->id, ewmh[_NET_WM_STATE].atom,
908 (~0L), XA_ATOM, &n, NULL, (void *)&states);
909
910 if (!success)
911 return;
912
913 for (i = 0; i < n; i++)
914 ewmh_update_win_state(win, states[i], _NET_WM_STATE_ADD);
915
916 XFree(states);
917 }
918
919 /* events */
920 #ifdef SWM_DEBUG
921 char *
922 geteventname(XEvent *e)
923 {
924 char *name = NULL;
925
926 switch (e->type) {
927 case KeyPress:
928 name = "KeyPress";
929 break;
930 case KeyRelease:
931 name = "KeyRelease";
932 break;
933 case ButtonPress:
934 name = "ButtonPress";
935 break;
936 case ButtonRelease:
937 name = "ButtonRelease";
938 break;
939 case MotionNotify:
940 name = "MotionNotify";
941 break;
942 case EnterNotify:
943 name = "EnterNotify";
944 break;
945 case LeaveNotify:
946 name = "LeaveNotify";
947 break;
948 case FocusIn:
949 name = "FocusIn";
950 break;
951 case FocusOut:
952 name = "FocusOut";
953 break;
954 case KeymapNotify:
955 name = "KeymapNotify";
956 break;
957 case Expose:
958 name = "Expose";
959 break;
960 case GraphicsExpose:
961 name = "GraphicsExpose";
962 break;
963 case NoExpose:
964 name = "NoExpose";
965 break;
966 case VisibilityNotify:
967 name = "VisibilityNotify";
968 break;
969 case CreateNotify:
970 name = "CreateNotify";
971 break;
972 case DestroyNotify:
973 name = "DestroyNotify";
974 break;
975 case UnmapNotify:
976 name = "UnmapNotify";
977 break;
978 case MapNotify:
979 name = "MapNotify";
980 break;
981 case MapRequest:
982 name = "MapRequest";
983 break;
984 case ReparentNotify:
985 name = "ReparentNotify";
986 break;
987 case ConfigureNotify:
988 name = "ConfigureNotify";
989 break;
990 case ConfigureRequest:
991 name = "ConfigureRequest";
992 break;
993 case GravityNotify:
994 name = "GravityNotify";
995 break;
996 case ResizeRequest:
997 name = "ResizeRequest";
998 break;
999 case CirculateNotify:
1000 name = "CirculateNotify";
1001 break;
1002 case CirculateRequest:
1003 name = "CirculateRequest";
1004 break;
1005 case PropertyNotify:
1006 name = "PropertyNotify";
1007 break;
1008 case SelectionClear:
1009 name = "SelectionClear";
1010 break;
1011 case SelectionRequest:
1012 name = "SelectionRequest";
1013 break;
1014 case SelectionNotify:
1015 name = "SelectionNotify";
1016 break;
1017 case ColormapNotify:
1018 name = "ColormapNotify";
1019 break;
1020 case ClientMessage:
1021 name = "ClientMessage";
1022 break;
1023 case MappingNotify:
1024 name = "MappingNotify";
1025 break;
1026 default:
1027 name = "Unknown";
1028 }
1029
1030 return (name);
1031 }
1032
1033 char *
1034 xrandr_geteventname(XEvent *e)
1035 {
1036 char *name = NULL;
1037
1038 switch(e->type - xrandr_eventbase) {
1039 case RRScreenChangeNotify:
1040 name = "RRScreenChangeNotify";
1041 break;
1042 default:
1043 name = "Unknown";
1044 }
1045
1046 return (name);
1047 }
1048
1049 void
1050 dumpwins(struct swm_region *r, union arg *args)
1051 {
1052 struct ws_win *win;
1053 unsigned int state;
1054 XWindowAttributes wa;
1055
1056 if (r->ws == NULL) {
1057 warnx("dumpwins: invalid workspace");
1058 return;
1059 }
1060
1061 warnx("=== managed window list ws %02d ===", r->ws->idx);
1062
1063 TAILQ_FOREACH(win, &r->ws->winlist, entry) {
1064 state = getstate(win->id);
1065 if (!XGetWindowAttributes(display, win->id, &wa))
1066 warnx("window: 0x%lx, failed XGetWindowAttributes",
1067 win->id);
1068 warnx("window: 0x%lx, map_state: %d, state: %d, "
1069 "transient: 0x%lx", win->id, wa.map_state, state,
1070 win->transient);
1071 }
1072
1073 warnx("===== unmanaged window list =====");
1074 TAILQ_FOREACH(win, &r->ws->unmanagedlist, entry) {
1075 state = getstate(win->id);
1076 if (!XGetWindowAttributes(display, win->id, &wa))
1077 warnx("window: 0x%lx, failed XGetWindowAttributes",
1078 win->id);
1079 warnx("window: 0x%lx, map_state: %d, state: %d, "
1080 "transient: 0x%lx", win->id, wa.map_state, state,
1081 win->transient);
1082 }
1083
1084 warnx("=================================");
1085 }
1086 #else
1087 void
1088 dumpwins(struct swm_region *r, union arg *args)
1089 {
1090 }
1091 #endif /* SWM_DEBUG */
1092
1093 void expose(XEvent *);
1094 void keypress(XEvent *);
1095 void buttonpress(XEvent *);
1096 void configurerequest(XEvent *);
1097 void configurenotify(XEvent *);
1098 void destroynotify(XEvent *);
1099 void enternotify(XEvent *);
1100 void focusevent(XEvent *);
1101 void mapnotify(XEvent *);
1102 void mappingnotify(XEvent *);
1103 void maprequest(XEvent *);
1104 void propertynotify(XEvent *);
1105 void unmapnotify(XEvent *);
1106 void visibilitynotify(XEvent *);
1107 void clientmessage(XEvent *);
1108
1109 void (*handler[LASTEvent])(XEvent *) = {
1110 [Expose] = expose,
1111 [KeyPress] = keypress,
1112 [ButtonPress] = buttonpress,
1113 [ConfigureRequest] = configurerequest,
1114 [ConfigureNotify] = configurenotify,
1115 [DestroyNotify] = destroynotify,
1116 [EnterNotify] = enternotify,
1117 [FocusIn] = focusevent,
1118 [FocusOut] = focusevent,
1119 [MapNotify] = mapnotify,
1120 [MappingNotify] = mappingnotify,
1121 [MapRequest] = maprequest,
1122 [PropertyNotify] = propertynotify,
1123 [UnmapNotify] = unmapnotify,
1124 [VisibilityNotify] = visibilitynotify,
1125 [ClientMessage] = clientmessage,
1126 };
1127
1128 void
1129 sighdlr(int sig)
1130 {
1131 int saved_errno, status;
1132 pid_t pid;
1133
1134 saved_errno = errno;
1135
1136 switch (sig) {
1137 case SIGCHLD:
1138 while ((pid = waitpid(WAIT_ANY, &status, WNOHANG)) != 0) {
1139 if (pid == -1) {
1140 if (errno == EINTR)
1141 continue;
1142 #ifdef SWM_DEBUG
1143 if (errno != ECHILD)
1144 warn("sighdlr: waitpid");
1145 #endif /* SWM_DEBUG */
1146 break;
1147 }
1148 if (pid == searchpid)
1149 search_resp = 1;
1150
1151 #ifdef SWM_DEBUG
1152 if (WIFEXITED(status)) {
1153 if (WEXITSTATUS(status) != 0)
1154 warnx("sighdlr: child exit status: %d",
1155 WEXITSTATUS(status));
1156 } else
1157 warnx("sighdlr: child is terminated "
1158 "abnormally");
1159 #endif /* SWM_DEBUG */
1160 }
1161 break;
1162
1163 case SIGHUP:
1164 restart_wm = 1;
1165 break;
1166 case SIGINT:
1167 case SIGTERM:
1168 case SIGQUIT:
1169 running = 0;
1170 break;
1171 }
1172
1173 errno = saved_errno;
1174 }
1175
1176 struct pid_e *
1177 find_pid(long pid)
1178 {
1179 struct pid_e *p = NULL;
1180
1181 DNPRINTF(SWM_D_MISC, "find_pid: %lu\n", pid);
1182
1183 if (pid == 0)
1184 return (NULL);
1185
1186 TAILQ_FOREACH(p, &pidlist, entry) {
1187 if (p->pid == pid)
1188 return (p);
1189 }
1190
1191 return (NULL);
1192 }
1193
1194 unsigned long
1195 name_to_color(char *colorname)
1196 {
1197 Colormap cmap;
1198 Status status;
1199 XColor screen_def, exact_def;
1200 unsigned long result = 0;
1201 char cname[32] = "#";
1202
1203 cmap = DefaultColormap(display, screens[0].idx);
1204 status = XAllocNamedColor(display, cmap, colorname,
1205 &screen_def, &exact_def);
1206 if (!status) {
1207 strlcat(cname, colorname + 2, sizeof cname - 1);
1208 status = XAllocNamedColor(display, cmap, cname, &screen_def,
1209 &exact_def);
1210 }
1211 if (status)
1212 result = screen_def.pixel;
1213 else
1214 warnx("color '%s' not found", colorname);
1215
1216 return (result);
1217 }
1218
1219 void
1220 setscreencolor(char *val, int i, int c)
1221 {
1222 if (i > 0 && i <= ScreenCount(display)) {
1223 screens[i - 1].c[c].color = name_to_color(val);
1224 free(screens[i - 1].c[c].name);
1225 if ((screens[i - 1].c[c].name = strdup(val)) == NULL)
1226 err(1, "strdup");
1227 } else if (i == -1) {
1228 for (i = 0; i < ScreenCount(display); i++) {
1229 screens[i].c[c].color = name_to_color(val);
1230 free(screens[i].c[c].name);
1231 if ((screens[i].c[c].name = strdup(val)) == NULL)
1232 err(1, "strdup");
1233 }
1234 } else
1235 errx(1, "invalid screen index: %d out of bounds (maximum %d)",
1236 i, ScreenCount(display));
1237 }
1238
1239 void
1240 fancy_stacker(struct workspace *ws)
1241 {
1242 strlcpy(ws->stacker, "[ ]", sizeof ws->stacker);
1243 if (ws->cur_layout->l_stack == vertical_stack)
1244 snprintf(ws->stacker, sizeof ws->stacker,
1245 ws->l_state.vertical_flip ? "[%d>%d]" : "[%d|%d]",
1246 ws->l_state.vertical_mwin, ws->l_state.vertical_stacks);
1247 if (ws->cur_layout->l_stack == horizontal_stack)
1248 snprintf(ws->stacker, sizeof ws->stacker,
1249 ws->l_state.horizontal_flip ? "[%dv%d]" : "[%d-%d]",
1250 ws->l_state.horizontal_mwin, ws->l_state.horizontal_stacks);
1251 }
1252
1253 void
1254 plain_stacker(struct workspace *ws)
1255 {
1256 strlcpy(ws->stacker, "[ ]", sizeof ws->stacker);
1257 if (ws->cur_layout->l_stack == vertical_stack)
1258 strlcpy(ws->stacker, ws->l_state.vertical_flip ? "[>]" : "[|]",
1259 sizeof ws->stacker);
1260 if (ws->cur_layout->l_stack == horizontal_stack)
1261 strlcpy(ws->stacker, ws->l_state.horizontal_flip ? "[v]" : "[-]",
1262 sizeof ws->stacker);
1263 }
1264
1265 void
1266 custom_region(char *val)
1267 {
1268 unsigned int sidx, x, y, w, h;
1269
1270 if (sscanf(val, "screen[%u]:%ux%u+%u+%u", &sidx, &w, &h, &x, &y) != 5)
1271 errx(1, "invalid custom region, "
1272 "should be 'screen[<n>]:<n>x<n>+<n>+<n>");
1273 if (sidx < 1 || sidx > ScreenCount(display))
1274 errx(1, "invalid screen index: %d out of bounds (maximum %d)",
1275 sidx, ScreenCount(display));
1276 sidx--;
1277
1278 if (w < 1 || h < 1)
1279 errx(1, "region %ux%u+%u+%u too small", w, h, x, y);
1280
1281 if (x > DisplayWidth(display, sidx) ||
1282 y > DisplayHeight(display, sidx) ||
1283 w + x > DisplayWidth(display, sidx) ||
1284 h + y > DisplayHeight(display, sidx)) {
1285 warnx("ignoring region %ux%u+%u+%u - not within screen "
1286 "boundaries (%ux%u)", w, h, x, y,
1287 DisplayWidth(display, sidx), DisplayHeight(display, sidx));
1288 return;
1289 }
1290
1291 new_region(&screens[sidx], x, y, w, h);
1292 }
1293
1294 void
1295 socket_setnonblock(int fd)
1296 {
1297 int flags;
1298
1299 if ((flags = fcntl(fd, F_GETFL, 0)) == -1)
1300 err(1, "fcntl F_GETFL");
1301 flags |= O_NONBLOCK;
1302 if ((flags = fcntl(fd, F_SETFL, flags)) == -1)
1303 err(1, "fcntl F_SETFL");
1304 }
1305
1306 void
1307 bar_print(struct swm_region *r, char *s)
1308 {
1309 int x = 0;
1310 size_t len;
1311 XRectangle ibox, lbox;
1312
1313 XClearWindow(display, r->bar_window);
1314
1315 len = strlen(s);
1316 XmbTextExtents(bar_fs, s, len, &ibox, &lbox);
1317
1318 switch (bar_justify) {
1319 case SWM_BAR_JUSTIFY_LEFT:
1320 x = SWM_BAR_OFFSET;
1321 break;
1322 case SWM_BAR_JUSTIFY_CENTER:
1323 x = (WIDTH(r) - lbox.width) / 2;
1324 break;
1325 case SWM_BAR_JUSTIFY_RIGHT:
1326 x = WIDTH(r) - lbox.width - SWM_BAR_OFFSET;
1327 break;
1328 }
1329
1330 if (x < SWM_BAR_OFFSET)
1331 x = SWM_BAR_OFFSET;
1332
1333 DRAWSTRING(display, r->bar_window, bar_fs, r->s->bar_gc,
1334 x, (bar_fs_extents->max_logical_extent.height - lbox.height) / 2 -
1335 lbox.y, s, len);
1336 }
1337
1338 void
1339 bar_extra_stop(void)
1340 {
1341 if (bar_pipe[0]) {
1342 close(bar_pipe[0]);
1343 bzero(bar_pipe, sizeof bar_pipe);
1344 }
1345 if (bar_pid) {
1346 kill(bar_pid, SIGTERM);
1347 bar_pid = 0;
1348 }
1349 strlcpy((char *)bar_ext, "", sizeof bar_ext);
1350 bar_extra = 0;
1351 }
1352
1353 void
1354 bar_class_name(char *s, size_t sz, struct swm_region *r)
1355 {
1356 if (r == NULL || r->ws == NULL || r->ws->focus == NULL)
1357 return;
1358 if (r->ws->focus->ch.res_class != NULL)
1359 strlcat(s, r->ws->focus->ch.res_class, sz);
1360 }
1361
1362 void
1363 bar_title_name(char *s, size_t sz, struct swm_region *r)
1364 {
1365 if (r == NULL || r->ws == NULL || r->ws->focus == NULL)
1366 return;
1367 if (r->ws->focus->ch.res_name != NULL)
1368 strlcat(s, r->ws->focus->ch.res_name, sz);
1369 }
1370
1371 void
1372 bar_window_name(char *s, size_t sz, struct swm_region *r)
1373 {
1374 unsigned char *title;
1375
1376 if (r == NULL || r->ws == NULL || r->ws->focus == NULL)
1377 return;
1378 if ((title = get_win_name(r->ws->focus->id)) == NULL)
1379 return;
1380
1381 if (r->ws->focus->floating)
1382 strlcat(s, "(f) ", sz);
1383 strlcat(s, (char *)title, sz);
1384 strlcat(s, " ", sz);
1385
1386 XFree(title);
1387 }
1388
1389 int urgent[SWM_WS_MAX];
1390 void
1391 bar_urgent(char *s, size_t sz)
1392 {
1393 XWMHints *wmh = NULL;
1394 struct ws_win *win;
1395 int i, j;
1396 char b[8];
1397
1398 for (i = 0; i < workspace_limit; i++)
1399 urgent[i] = 0;
1400
1401 for (i = 0; i < ScreenCount(display); i++)
1402 for (j = 0; j < workspace_limit; j++)
1403 TAILQ_FOREACH(win, &screens[i].ws[j].winlist, entry) {
1404 wmh = XGetWMHints(display, win->id);
1405 if (wmh == NULL)
1406 continue;
1407
1408 if (wmh->flags & XUrgencyHint)
1409 urgent[j] = 1;
1410 XFree(wmh);
1411 }
1412
1413 for (i = 0; i < workspace_limit; i++) {
1414 if (urgent[i])
1415 snprintf(b, sizeof b, "%d ", i + 1);
1416 else
1417 snprintf(b, sizeof b, "- ");
1418 strlcat(s, b, sz);
1419 }
1420 }
1421
1422 void
1423 bar_workspace_name(char *s, size_t sz, struct swm_region *r)
1424 {
1425 if (r == NULL || r->ws == NULL)
1426 return;
1427 if (r->ws->name != NULL)
1428 strlcat(s, r->ws->name, sz);
1429 }
1430
1431 /* build the default bar format according to the defined enabled options */
1432 void
1433 bar_fmt(char *fmtexp, char *fmtnew, struct swm_region *r, size_t sz)
1434 {
1435 /* if format provided, just copy the buffers */
1436 if (bar_format != NULL) {
1437 strlcpy(fmtnew, fmtexp, sz);
1438 return;
1439 }
1440
1441 /* reset the output buffer */
1442 *fmtnew = '\0';
1443
1444 strlcat(fmtnew, "+N:+I ", sz);
1445 if (stack_enabled)
1446 strlcat(fmtnew, "+S", sz);
1447 strlcat(fmtnew, " ", sz);
1448
1449 /* only show the workspace name if there's actually one */
1450 if (r != NULL && r->ws != NULL && r->ws->name != NULL)
1451 strlcat(fmtnew, "<+D>", sz);
1452 strlcat(fmtnew, " ", sz);
1453
1454 if (clock_enabled) {
1455 strlcat(fmtnew, fmtexp, sz);
1456 strlcat(fmtnew, " ", sz);
1457 }
1458
1459 /* bar_urgent already adds the space before the last asterisk */
1460 if (urgent_enabled)
1461 strlcat(fmtnew, "* +U* ", sz);
1462
1463 if (title_class_enabled)
1464 strlcat(fmtnew, "+C", sz);
1465 if (title_name_enabled) {
1466 /* add a colon if showing the class and something is focused */
1467 if (title_class_enabled && r != NULL && r->ws != NULL &&
1468 r->ws->focus != NULL)
1469 strlcat(fmtnew, ":", sz);
1470 strlcat(fmtnew, "+T", sz);
1471 }
1472
1473 strlcat(fmtnew, " ", sz);
1474 if (window_name_enabled)
1475 strlcat(fmtnew, "+64W", sz);
1476
1477 /* finally add the action script output and the version */
1478 strlcat(fmtnew, " +A +V", sz);
1479 }
1480
1481 /* replaces the bar format character sequences (like in tmux(1)) */
1482 char *
1483 bar_replace_seq(char *fmt, char *fmtrep, struct swm_region *r, size_t *offrep,
1484 size_t sz)
1485 {
1486 char *ptr;
1487 char num[8], tmp[SWM_BAR_MAX];
1488 int limit;
1489 size_t len, numoff = 0;
1490
1491 /* reset strlcat(3) buffer */
1492 *tmp = '\0';
1493
1494 /* get number, if any */
1495 fmt++;
1496 while (*fmt != '\0' && isdigit((unsigned char) *fmt)) {
1497 if (numoff >= sizeof num - 1)
1498 break;
1499 num[numoff++] = *fmt++;
1500 }
1501 num[numoff] = '\0';
1502
1503 if ((limit = strtonum(num, 1, sizeof tmp - 1, NULL)) == 0)
1504 limit = sizeof tmp - 1;
1505
1506 /* if number is too big, skip to the first non-digit */
1507 if (numoff >= sizeof num - 1) {
1508 while (*fmt != '\0' && isdigit((unsigned char) *fmt))
1509 fmt++;
1510 }
1511 /* there is nothing to replace (ie EOL) */
1512 if (*fmt == '\0')
1513 return (fmt);
1514
1515 switch (*fmt) {
1516 case 'A':
1517 snprintf(tmp, sizeof tmp, "%s", bar_ext);
1518 break;
1519 case 'C':
1520 bar_class_name(tmp, sizeof tmp, r);
1521 break;
1522 case 'D':
1523 bar_workspace_name(tmp, sizeof tmp, r);
1524 break;
1525 case 'I':
1526 snprintf(tmp, sizeof tmp, "%d", r->ws->idx + 1);
1527 break;
1528 case 'N':
1529 snprintf(tmp, sizeof tmp, "%d", r->s->idx + 1);
1530 break;
1531 case 'S':
1532 snprintf(tmp, sizeof tmp, "%s", r->ws->stacker);
1533 break;
1534 case 'T':
1535 bar_title_name(tmp, sizeof tmp, r);
1536 break;
1537 case 'U':
1538 bar_urgent(tmp, sizeof tmp);
1539 break;
1540 case 'V':
1541 snprintf(tmp, sizeof tmp, "%s", bar_vertext);
1542 break;
1543 case 'W':
1544 bar_window_name(tmp, sizeof tmp, r);
1545 break;
1546 default:
1547 /* unknown character sequence; copy as-is */
1548 snprintf(tmp, sizeof tmp, "+%c", *fmt);
1549 break;
1550 }
1551
1552 len = strlen(tmp);
1553 ptr = tmp;
1554 if (len < limit)
1555 limit = len;
1556 while (limit-- > 0) {
1557 if (*offrep >= sz - 1)
1558 break;
1559 fmtrep[(*offrep)++] = *ptr++;
1560 }
1561
1562 fmt++;
1563 return (fmt);
1564 }
1565
1566 void
1567 bar_replace(char *fmt, char *fmtrep, struct swm_region *r, size_t sz)
1568 {
1569 size_t off;
1570
1571 off = 0;
1572 while (*fmt != '\0') {
1573 if (*fmt != '+') {
1574 /* skip ordinary characters */
1575 if (off >= sz - 1)
1576 break;
1577 fmtrep[off++] = *fmt++;
1578 continue;
1579 }
1580
1581 /* character sequence found; replace it */
1582 fmt = bar_replace_seq(fmt, fmtrep, r, &off, sz);
1583 if (off >= sz - 1)
1584 break;
1585 }
1586
1587 fmtrep[off] = '\0';
1588 }
1589
1590 void
1591 bar_fmt_expand(char *fmtexp, size_t sz)
1592 {
1593 char *fmt = NULL;
1594 size_t len;
1595 struct tm tm;
1596 time_t tmt;
1597
1598 /* start by grabbing the current time and date */
1599 time(&tmt);
1600 localtime_r(&tmt, &tm);
1601
1602 /* figure out what to expand */
1603 if (bar_format != NULL)
1604 fmt = bar_format;
1605 else if (bar_format == NULL && clock_enabled)
1606 fmt = clock_format;
1607 /* if nothing to expand bail out */
1608 if (fmt == NULL) {
1609 *fmtexp = '\0';
1610 return;
1611 }
1612
1613 /* copy as-is, just in case the format shouldn't be expanded below */
1614 strlcpy(fmtexp, fmt, sz);
1615 /* finally pass the string through strftime(3) */
1616 #ifndef SWM_DENY_CLOCK_FORMAT
1617 if ((len = strftime(fmtexp, sz, fmt, &tm)) == 0)
1618 warnx("format too long");
1619 fmtexp[len] = '\0';
1620 #endif
1621 }
1622
1623 void
1624 bar_fmt_print(void)
1625 {
1626 char fmtexp[SWM_BAR_MAX], fmtnew[SWM_BAR_MAX];
1627 char fmtrep[SWM_BAR_MAX];
1628 int i;
1629 struct swm_region *r;
1630
1631 /* expand the format by first passing it through strftime(3) */
1632 bar_fmt_expand(fmtexp, sizeof fmtexp);
1633
1634 for (i = 0; i < ScreenCount(display); i++) {
1635 TAILQ_FOREACH(r, &screens[i].rl, entry) {
1636 bar_fmt(fmtexp, fmtnew, r, sizeof fmtnew);
1637 bar_replace(fmtnew, fmtrep, r, sizeof fmtrep);
1638 bar_print(r, fmtrep);
1639 }
1640 }
1641 }
1642
1643 void
1644 bar_update(void)
1645 {
1646 size_t len;
1647 char *b;
1648
1649 if (bar_enabled == 0)
1650 return;
1651 if (bar_extra && bar_extra_running) {
1652 /* ignore short reads; it'll correct itself */
1653 while ((b = fgetln(stdin, &len)) != NULL)
1654 if (b && b[len - 1] == '\n') {
1655 b[len - 1] = '\0';
1656 strlcpy((char *)bar_ext, b, sizeof bar_ext);
1657 }
1658 if (b == NULL && errno != EAGAIN) {
1659 warn("bar_update: bar_extra failed");
1660 bar_extra_stop();
1661 }
1662 } else
1663 strlcpy((char *)bar_ext, "", sizeof bar_ext);
1664
1665 bar_fmt_print();
1666 alarm(bar_delay);
1667 }
1668
1669 void
1670 bar_signal(int sig)
1671 {
1672 bar_alarm = 1;
1673 }
1674
1675 void
1676 bar_toggle(struct swm_region *r, union arg *args)
1677 {
1678 struct swm_region *tmpr;
1679 int i, sc = ScreenCount(display);
1680
1681 DNPRINTF(SWM_D_BAR, "bar_toggle\n");
1682
1683 if (bar_enabled)
1684 for (i = 0; i < sc; i++)
1685 TAILQ_FOREACH(tmpr, &screens[i].rl, entry)
1686 XUnmapWindow(display, tmpr->bar_window);
1687 else
1688 for (i = 0; i < sc; i++)
1689 TAILQ_FOREACH(tmpr, &screens[i].rl, entry)
1690 XMapRaised(display, tmpr->bar_window);
1691
1692 bar_enabled = !bar_enabled;
1693
1694 stack();
1695 /* must be after stack */
1696 bar_update();
1697 }
1698
1699 void
1700 bar_refresh(void)
1701 {
1702 XSetWindowAttributes wa;
1703 struct swm_region *r;
1704 int i;
1705
1706 /* do this here because the conf file is in memory */
1707 if (bar_extra && bar_extra_running == 0 && bar_argv[0]) {
1708 /* launch external status app */
1709 bar_extra_running = 1;
1710 if (pipe(bar_pipe) == -1)
1711 err(1, "pipe error");
1712 socket_setnonblock(bar_pipe[0]);
1713 socket_setnonblock(bar_pipe[1]); /* XXX hmmm, really? */
1714 if (dup2(bar_pipe[0], 0) == -1)
1715 err(1, "dup2");
1716 if (dup2(bar_pipe[1], 1) == -1)
1717 err(1, "dup2");
1718 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
1719 err(1, "could not disable SIGPIPE");
1720 switch (bar_pid = fork()) {
1721 case -1:
1722 err(1, "cannot fork");
1723 break;
1724 case 0: /* child */
1725 close(bar_pipe[0]);
1726 execvp(bar_argv[0], bar_argv);
1727 err(1, "%s external app failed", bar_argv[0]);
1728 break;
1729 default: /* parent */
1730 close(bar_pipe[1]);
1731 break;
1732 }
1733 }
1734
1735 bzero(&wa, sizeof wa);
1736 for (i = 0; i < ScreenCount(display); i++)
1737 TAILQ_FOREACH(r, &screens[i].rl, entry) {
1738 wa.border_pixel =
1739 screens[i].c[SWM_S_COLOR_BAR_BORDER].color;
1740 wa.background_pixel =
1741 screens[i].c[SWM_S_COLOR_BAR].color;
1742 XChangeWindowAttributes(display, r->bar_window,
1743 CWBackPixel | CWBorderPixel, &wa);
1744 }
1745 bar_update();
1746 }
1747
1748 void
1749 bar_setup(struct swm_region *r)
1750 {
1751 char *default_string;
1752 char **missing_charsets;
1753 int num_missing_charsets = 0;
1754 int i, x, y;
1755
1756 if (bar_fs) {
1757 XFreeFontSet(display, bar_fs);
1758 bar_fs = NULL;
1759 }
1760
1761
1762 DNPRINTF(SWM_D_BAR, "bar_setup: loading bar_fonts: %s\n", bar_fonts);
1763
1764 bar_fs = XCreateFontSet(display, bar_fonts, &missing_charsets,
1765 &num_missing_charsets, &default_string);
1766
1767 if (num_missing_charsets > 0) {
1768 warnx("Unable to load charset(s):");
1769
1770 for (i = 0; i < num_missing_charsets; ++i)
1771 warnx("%s", missing_charsets[i]);
1772
1773 XFreeStringList(missing_charsets);
1774
1775 if (strcmp(default_string, ""))
1776 warnx("Glyphs from those sets will be replaced "
1777 "by '%s'.", default_string);
1778 else
1779 warnx("Glyphs from those sets won't be drawn.");
1780 }
1781
1782 if (bar_fs == NULL)
1783 errx(1, "Error creating font set structure.");
1784
1785 bar_fs_extents = XExtentsOfFontSet(bar_fs);
1786
1787 bar_height = bar_fs_extents->max_logical_extent.height +
1788 2 * bar_border_width;
1789
1790 if (bar_height < 1)
1791 bar_height = 1;
1792
1793 x = X(r);
1794 y = bar_at_bottom ? (Y(r) + HEIGHT(r) - bar_height) : Y(r);
1795
1796 r->bar_window = XCreateSimpleWindow(display,
1797 r->s->root, x, y, WIDTH(r) - 2 * bar_border_width,
1798 bar_height - 2 * bar_border_width,
1799 bar_border_width, r->s->c[SWM_S_COLOR_BAR_BORDER].color,
1800 r->s->c[SWM_S_COLOR_BAR].color);
1801 XSelectInput(display, r->bar_window, VisibilityChangeMask);
1802 if (bar_enabled)
1803 XMapRaised(display, r->bar_window);
1804 DNPRINTF(SWM_D_BAR, "bar_setup: bar_window: 0x%lx\n", r->bar_window);
1805
1806 if (signal(SIGALRM, bar_signal) == SIG_ERR)
1807 err(1, "could not install bar_signal");
1808 bar_refresh();
1809 }
1810
1811 void
1812 drain_enter_notify(void)
1813 {
1814 int i = 0;
1815 XEvent cne;
1816
1817 while (XCheckMaskEvent(display, EnterWindowMask, &cne))
1818 i++;
1819
1820 DNPRINTF(SWM_D_MISC, "drain_enter_notify: drained: %d\n", i);
1821 }
1822
1823 void
1824 set_win_state(struct ws_win *win, long state)
1825 {
1826 long data[] = {state, None};
1827
1828 DNPRINTF(SWM_D_EVENT, "set_win_state: window: 0x%lx\n", win->id);
1829
1830 if (win == NULL)
1831 return;
1832
1833 XChangeProperty(display, win->id, astate, astate, 32, PropModeReplace,
1834 (unsigned char *)data, 2);
1835 }
1836
1837 long
1838 getstate(Window w)
1839 {
1840 long result = -1;
1841 unsigned char *p = NULL;
1842 unsigned long n;
1843
1844 if (!get_property(w, astate, 2L, astate, &n, NULL, &p))
1845 return (-1);
1846 if (n != 0)
1847 result = *((long *)p);
1848 XFree(p);
1849 return (result);
1850 }
1851
1852 void
1853 version(struct swm_region *r, union arg *args)
1854 {
1855 bar_version = !bar_version;
1856 if (bar_version)
1857 snprintf(bar_vertext, sizeof bar_vertext,
1858 "Version: %s Build: %s", SPECTRWM_VERSION, buildstr);
1859 else
1860 strlcpy(bar_vertext, "", sizeof bar_vertext);
1861 bar_update();
1862 }
1863
1864 void
1865 client_msg(struct ws_win *win, Atom a)
1866 {
1867 XClientMessageEvent cm;
1868
1869 if (win == NULL)
1870 return;
1871
1872 bzero(&cm, sizeof cm);
1873 cm.type = ClientMessage;
1874 cm.window = win->id;
1875 cm.message_type = aprot;
1876 cm.format = 32;
1877 cm.data.l[0] = a;
1878 cm.data.l[1] = CurrentTime;
1879 XSendEvent(display, win->id, False, 0L, (XEvent *)&cm);
1880 }
1881
1882 /* synthetic response to a ConfigureRequest when not making a change */
1883 void
1884 config_win(struct ws_win *win, XConfigureRequestEvent *ev)
1885 {
1886 XConfigureEvent ce;
1887
1888 if (win == NULL)
1889 return;
1890
1891 /* send notification of unchanged state. */
1892 ce.type = ConfigureNotify;
1893 ce.x = X(win);
1894 ce.y = Y(win);
1895 ce.width = WIDTH(win);
1896 ce.height = HEIGHT(win);
1897 ce.override_redirect = False;
1898
1899 if (ev == NULL) {
1900 /* EWMH */
1901 ce.display = display;
1902 ce.event = win->id;
1903 ce.window = win->id;
1904 ce.border_width = border_width;
1905 ce.above = None;
1906 } else {
1907 /* normal */
1908 ce.display = ev->display;
1909 ce.event = ev->window;
1910 ce.window = ev->window;
1911
1912 /* make response appear more WM_SIZE_HINTS-compliant */
1913 if (win->sh_mask)
1914 DNPRINTF(SWM_D_MISC, "config_win: hints: window: 0x%lx,"
1915 " sh_mask: %ld, min: %d x %d, max: %d x %d, inc: "
1916 "%d x %d\n", win->id, win->sh_mask, SH_MIN_W(win),
1917 SH_MIN_H(win), SH_MAX_W(win), SH_MAX_H(win),
1918 SH_INC_W(win), SH_INC_H(win));
1919
1920 /* min size */
1921 if (SH_MIN(win)) {
1922 /* the hint may be set... to 0! */
1923 if (SH_MIN_W(win) > 0 && ce.width < SH_MIN_W(win))
1924 ce.width = SH_MIN_W(win);
1925 if (SH_MIN_H(win) > 0 && ce.height < SH_MIN_H(win))
1926 ce.height = SH_MIN_H(win);
1927 }
1928
1929 /* max size */
1930 if (SH_MAX(win)) {
1931 /* may also be advertized as 0 */
1932 if (SH_MAX_W(win) > 0 && ce.width > SH_MAX_W(win))
1933 ce.width = SH_MAX_W(win);
1934 if (SH_MAX_H(win) > 0 && ce.height > SH_MAX_H(win))
1935 ce.height = SH_MAX_H(win);
1936 }
1937
1938 /* resize increment. */
1939 if (SH_INC(win)) {
1940 if (SH_INC_W(win) > 1 && ce.width > SH_INC_W(win))
1941 ce.width -= (ce.width - SH_MIN_W(win)) %
1942 SH_INC_W(win);
1943 if (SH_INC_H(win) > 1 && ce.height > SH_INC_H(win))
1944 ce.height -= (ce.height - SH_MIN_H(win)) %
1945 SH_INC_H(win);
1946 }
1947
1948 /* adjust x and y for requested border_width. */
1949 ce.x += border_width - ev->border_width;
1950 ce.y += border_width - ev->border_width;
1951 ce.border_width = ev->border_width;
1952 ce.above = ev->above;
1953 }
1954
1955 DNPRINTF(SWM_D_MISC, "config_win: ewmh: %s, window: 0x%lx, (x,y) w x h: "
1956 "(%d,%d) %d x %d, border: %d\n", YESNO(ev == NULL), win->id, ce.x,
1957 ce.y, ce.width, ce.height, ce.border_width);
1958
1959 XSendEvent(display, win->id, False, StructureNotifyMask, (XEvent *)&ce);
1960 }
1961
1962 int
1963 count_win(struct workspace *ws, int count_transient)
1964 {
1965 struct ws_win *win;
1966 int count = 0;
1967
1968 TAILQ_FOREACH(win, &ws->winlist, entry) {
1969 if (count_transient == 0 && win->floating)
1970 continue;
1971 if (count_transient == 0 && win->transient)
1972 continue;
1973 if (win->iconic)
1974 continue;
1975 count++;
1976 }
1977 DNPRINTF(SWM_D_MISC, "count_win: %d\n", count);
1978
1979 return (count);
1980 }
1981
1982 void
1983 quit(struct swm_region *r, union arg *args)
1984 {
1985 DNPRINTF(SWM_D_MISC, "quit\n");
1986 running = 0;
1987 }
1988
1989 void
1990 unmap_window(struct ws_win *win)
1991 {
1992 if (win == NULL)
1993 return;
1994
1995 /* don't unmap again */
1996 if (getstate(win->id) == IconicState)
1997 return;
1998
1999 set_win_state(win, IconicState);
2000
2001 XUnmapWindow(display, win->id);
2002 XSetWindowBorder(display, win->id,
2003 win->s->c[SWM_S_COLOR_UNFOCUS].color);
2004 }
2005
2006 void
2007 unmap_all(void)
2008 {
2009 struct ws_win *win;
2010 int i, j;
2011
2012 for (i = 0; i < ScreenCount(display); i++)
2013 for (j = 0; j < workspace_limit; j++)
2014 TAILQ_FOREACH(win, &screens[i].ws[j].winlist, entry)
2015 unmap_window(win);
2016 }
2017
2018 void
2019 fake_keypress(struct ws_win *win, int keysym, int modifiers)
2020 {
2021 XKeyEvent event;
2022
2023 if (win == NULL)
2024 return;
2025
2026 event.display = display; /* Ignored, but what the hell */
2027 event.window = win->id;
2028 event.root = win->s->root;
2029 event.subwindow = None;
2030 event.time = CurrentTime;
2031 event.x = X(win);
2032 event.y = Y(win);
2033 event.x_root = 1;
2034 event.y_root = 1;
2035 event.same_screen = True;
2036 event.keycode = XKeysymToKeycode(display, keysym);
2037 event.state = modifiers;
2038
2039 event.type = KeyPress;
2040 XSendEvent(event.display, event.window, True,
2041 KeyPressMask, (XEvent *)&event);
2042
2043 event.type = KeyRelease;
2044 XSendEvent(event.display, event.window, True,
2045 KeyPressMask, (XEvent *)&event);
2046
2047 }
2048
2049 void
2050 restart(struct swm_region *r, union arg *args)
2051 {
2052 DNPRINTF(SWM_D_MISC, "restart: %s\n", start_argv[0]);
2053
2054 /* disable alarm because the following code may not be interrupted */
2055 alarm(0);
2056 if (signal(SIGALRM, SIG_IGN) == SIG_ERR)
2057 err(1, "can't disable alarm");
2058
2059 bar_extra_stop();
2060 bar_extra = 1;
2061 unmap_all();
2062 XCloseDisplay(display);
2063 execvp(start_argv[0], start_argv);
2064 warn("execvp failed");
2065 quit(NULL, NULL);
2066 }
2067
2068 struct swm_region *
2069 root_to_region(Window root)
2070 {
2071 struct swm_region *r = NULL;
2072 Window rr, cr;
2073 int i, x, y, wx, wy;
2074 unsigned int mask;
2075
2076 for (i = 0; i < ScreenCount(display); i++)
2077 if (screens[i].root == root)
2078 break;
2079
2080 if (XQueryPointer(display, screens[i].root,
2081 &rr, &cr, &x, &y, &wx, &wy, &mask) != False) {
2082 /* choose a region based on pointer location */
2083 TAILQ_FOREACH(r, &screens[i].rl, entry)
2084 if (x >= X(r) && x <= X(r) + WIDTH(r) &&
2085 y >= Y(r) && y <= Y(r) + HEIGHT(r))
2086 break;
2087 }
2088
2089 if (r == NULL)
2090 r = TAILQ_FIRST(&screens[i].rl);
2091
2092 return (r);
2093 }
2094
2095 struct ws_win *
2096 find_unmanaged_window(Window id)
2097 {
2098 struct ws_win *win;
2099 int i, j;
2100
2101 for (i = 0; i < ScreenCount(display); i++)
2102 for (j = 0; j < workspace_limit; j++)
2103 TAILQ_FOREACH(win, &screens[i].ws[j].unmanagedlist,
2104 entry)
2105 if (id == win->id)
2106 return (win);
2107 return (NULL);
2108 }
2109
2110 struct ws_win *
2111 find_window(Window id)
2112 {
2113 struct ws_win *win;
2114 Window wrr, wpr, *wcr = NULL;
2115 int i, j;
2116 unsigned int nc;
2117
2118 for (i = 0; i < ScreenCount(display); i++)
2119 for (j = 0; j < workspace_limit; j++)
2120 TAILQ_FOREACH(win, &screens[i].ws[j].winlist, entry)
2121 if (id == win->id)
2122 return (win);
2123
2124 /* if we were looking for the parent return that window instead */
2125 if (XQueryTree(display, id, &wrr, &wpr, &wcr, &nc) == 0)
2126 return (NULL);
2127 if (wcr)
2128 XFree(wcr);
2129
2130 /* ignore not found and root */
2131 if (wpr == 0 || wrr == wpr)
2132 return (NULL);
2133
2134 /* look for parent */
2135 for (i = 0; i < ScreenCount(display); i++)
2136 for (j = 0; j < workspace_limit; j++)
2137 TAILQ_FOREACH(win, &screens[i].ws[j].winlist, entry)
2138 if (wpr == win->id)
2139 return (win);
2140
2141 return (NULL);
2142 }
2143
2144 void
2145 spawn(int ws_idx, union arg *args, int close_fd)
2146 {
2147 int fd;
2148 char *ret = NULL;
2149
2150 DNPRINTF(SWM_D_MISC, "spawn: %s\n", args->argv[0]);
2151
2152 if (display)
2153 close(ConnectionNumber(display));
2154
2155 setenv("LD_PRELOAD", SWM_LIB, 1);
2156
2157 if (asprintf(&ret, "%d", ws_idx) == -1) {
2158 warn("spawn: asprintf SWM_WS");
2159 _exit(1);
2160 }
2161 setenv("_SWM_WS", ret, 1);
2162 free(ret);
2163 ret = NULL;
2164
2165 if (asprintf(&ret, "%d", getpid()) == -1) {
2166 warn("spawn: asprintf _SWM_PID");
2167 _exit(1);
2168 }
2169 setenv("_SWM_PID", ret, 1);
2170 free(ret);
2171 ret = NULL;
2172
2173 if (setsid() == -1) {
2174 warn("spawn: setsid");
2175 _exit(1);
2176 }
2177
2178 if (close_fd) {
2179 /*
2180 * close stdin and stdout to prevent interaction between apps
2181 * and the baraction script
2182 * leave stderr open to record errors
2183 */
2184 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) == -1) {
2185 warn("spawn: open");
2186 _exit(1);
2187 }
2188 dup2(fd, STDIN_FILENO);
2189 dup2(fd, STDOUT_FILENO);
2190 if (fd > 2)
2191 close(fd);
2192 }
2193
2194 execvp(args->argv[0], args->argv);
2195
2196 warn("spawn: execvp");
2197 _exit(1);
2198 }
2199
2200 void
2201 spawnterm(struct swm_region *r, union arg *args)
2202 {
2203 DNPRINTF(SWM_D_MISC, "spawnterm\n");
2204
2205 if (fork() == 0) {
2206 if (term_width)
2207 setenv("_SWM_XTERM_FONTADJ", "", 1);
2208 spawn(r->ws->idx, args, 1);
2209 }
2210 }
2211
2212 void
2213 kill_refs(struct ws_win *win)
2214 {
2215 int i, x;
2216 struct swm_region *r;
2217 struct workspace *ws;
2218
2219 if (win == NULL)
2220 return;
2221
2222 for (i = 0; i < ScreenCount(display); i++)
2223 TAILQ_FOREACH(r, &screens[i].rl, entry)
2224 for (x = 0; x < workspace_limit; x++) {
2225 ws = &r->s->ws[x];
2226 if (win == ws->focus)
2227 ws->focus = NULL;
2228 if (win == ws->focus_prev)
2229 ws->focus_prev = NULL;
2230 }
2231 }
2232
2233 int
2234 validate_win(struct ws_win *testwin)
2235 {
2236 struct ws_win *win;
2237 struct workspace *ws;
2238 struct swm_region *r;
2239 int i, x;
2240
2241 if (testwin == NULL)
2242 return (0);
2243
2244 for (i = 0; i < ScreenCount(display); i++)
2245 TAILQ_FOREACH(r, &screens[i].rl, entry)
2246 for (x = 0; x < workspace_limit; x++) {
2247 ws = &r->s->ws[x];
2248 TAILQ_FOREACH(win, &ws->winlist, entry)
2249 if (win == testwin)
2250 return (0);
2251 }
2252 return (1);
2253 }
2254
2255 int
2256 validate_ws(struct workspace *testws)
2257 {
2258 struct swm_region *r;
2259 struct workspace *ws;
2260 int i, x;
2261
2262 /* validate all ws */
2263 for (i = 0; i < ScreenCount(display); i++)
2264 TAILQ_FOREACH(r, &screens[i].rl, entry)
2265 for (x = 0; x < workspace_limit; x++) {
2266 ws = &r->s->ws[x];
2267 if (ws == testws)
2268 return (0);
2269 }
2270 return (1);
2271 }
2272
2273 void
2274 unfocus_win(struct ws_win *win)
2275 {
2276 XEvent cne;
2277 Window none = None;
2278
2279 DNPRINTF(SWM_D_FOCUS, "unfocus_win: window: 0x%lx\n", WINID(win));
2280
2281 if (win == NULL)
2282 return;
2283 if (win->ws == NULL)
2284 return;
2285
2286 if (validate_ws(win->ws))
2287 return; /* XXX this gets hit with thunderbird, needs fixing */
2288
2289 if (win->ws->r == NULL)
2290 return;
2291
2292 if (validate_win(win)) {
2293 kill_refs(win);
2294 return;
2295 }
2296
2297 if (win->ws->focus == win) {
2298 win->ws->focus = NULL;
2299 win->ws->focus_prev = win;
2300 }
2301
2302 if (validate_win(win->ws->focus)) {
2303 kill_refs(win->ws->focus);
2304 win->ws->focus = NULL;
2305 }
2306 if (validate_win(win->ws->focus_prev)) {
2307 kill_refs(win->ws->focus_prev);
2308 win->ws->focus_prev = NULL;
2309 }
2310
2311 /* drain all previous unfocus events */
2312 while (XCheckTypedEvent(display, FocusOut, &cne) == True)
2313 ;
2314
2315 grabbuttons(win, 0);
2316 XSetWindowBorder(display, win->id,
2317 win->ws->r->s->c[SWM_S_COLOR_UNFOCUS].color);
2318
2319 XChangeProperty(display, win->s->root,
2320 ewmh[_NET_ACTIVE_WINDOW].atom, XA_WINDOW, 32,
2321 PropModeReplace, (unsigned char *)&none, 1);
2322 }
2323
2324 void
2325 unfocus_all(void)
2326 {
2327 struct ws_win *win;
2328 int i, j;
2329
2330 DNPRINTF(SWM_D_FOCUS, "unfocus_all\n");
2331
2332 for (i = 0; i < ScreenCount(display); i++)
2333 for (j = 0; j < workspace_limit; j++)
2334 TAILQ_FOREACH(win, &screens[i].ws[j].winlist, entry)
2335 unfocus_win(win);
2336 }
2337
2338 void
2339 focus_win(struct ws_win *win)
2340 {
2341 XEvent cne;
2342 Window cur_focus;
2343 int rr;
2344 struct ws_win *cfw = NULL;
2345
2346
2347 DNPRINTF(SWM_D_FOCUS, "focus_win: window: 0x%lx\n", WINID(win));
2348
2349 if (win == NULL)
2350 return;
2351 if (win->ws == NULL)
2352 return;
2353
2354 if (validate_ws(win->ws))
2355 return; /* XXX this gets hit with thunderbird, needs fixing */
2356
2357 if (validate_win(win)) {
2358 kill_refs(win);
2359 return;
2360 }
2361
2362 if (validate_win(win)) {
2363 kill_refs(win);
2364 return;
2365 }
2366
2367 XGetInputFocus(display, &cur_focus, &rr);
2368 if ((cfw = find_window(cur_focus)) != NULL)
2369 unfocus_win(cfw);
2370 else {
2371 /* use larger hammer since the window was killed somehow */
2372 TAILQ_FOREACH(cfw, &win->ws->winlist, entry)
2373 if (cfw->ws && cfw->ws->r && cfw->ws->r->s)
2374 XSetWindowBorder(display, cfw->id,
2375 cfw->ws->r->s->c[SWM_S_COLOR_UNFOCUS].color);
2376 }
2377
2378 win->ws->focus = win;
2379
2380 if (win->ws->r != NULL) {
2381 /* drain all previous focus events */
2382 while (XCheckTypedEvent(display, FocusIn, &cne) == True)
2383 ;
2384
2385 if (win->java == 0)
2386 XSetInputFocus(display, win->id,
2387 RevertToParent, CurrentTime);
2388 grabbuttons(win, 1);
2389 XSetWindowBorder(display, win->id,
2390 win->ws->r->s->c[SWM_S_COLOR_FOCUS].color);
2391 if (win->ws->cur_layout->flags & SWM_L_MAPONFOCUS ||
2392 win->ws->always_raise)
2393 XMapRaised(display, win->id);
2394
2395 XChangeProperty(display, win->s->root,
2396 ewmh[_NET_ACTIVE_WINDOW].atom, XA_WINDOW, 32,
2397 PropModeReplace, (unsigned char *)&win->id, 1);
2398 }
2399
2400 bar_update();
2401 }
2402
2403 void
2404 switchws(struct swm_region *r, union arg *args)
2405 {
2406 int wsid = args->id, unmap_old = 0;
2407 struct swm_region *this_r, *other_r;
2408 struct ws_win *win;
2409 struct workspace *new_ws, *old_ws;
2410 union arg a;
2411
2412 if (!(r && r->s))
2413 return;
2414
2415 if (wsid >= workspace_limit)
2416 return;
2417
2418 this_r = r;
2419 old_ws = this_r->ws;
2420 new_ws = &this_r->s->ws[wsid];
2421
2422 DNPRINTF(SWM_D_WS, "switchws: screen[%d]:%dx%d+%d+%d: %d -> %d\n",
2423 r->s->idx, WIDTH(r), HEIGHT(r), X(r), Y(r), old_ws->idx, wsid);
2424
2425 if (new_ws == NULL || old_ws == NULL)
2426 return;
2427 if (new_ws == old_ws)
2428 return;
2429
2430 other_r = new_ws->r;
2431 if (other_r == NULL) {
2432 /* the other workspace is hidden, hide this one */
2433 old_ws->r = NULL;
2434 unmap_old = 1;
2435 } else {
2436 /* the other ws is visible in another region, exchange them */
2437 other_r->ws_prior = new_ws;
2438 other_r->ws = old_ws;
2439 old_ws->r = other_r;
2440 }
2441 this_r->ws_prior = old_ws;
2442 this_r->ws = new_ws;
2443 new_ws->r = this_r;
2444
2445 /* this is needed so that we can click on a window after a restart */
2446 unfocus_all();
2447
2448 stack();
2449 a.id = SWM_ARG_ID_FOCUSCUR;
2450 focus(new_ws->r, &a);
2451
2452 /* unmap old windows */
2453 if (unmap_old)
2454 TAILQ_FOREACH(win, &old_ws->winlist, entry)
2455 unmap_window(win);
2456
2457 if (focus_mode == SWM_FOCUS_DEFAULT)
2458 drain_enter_notify();
2459 }
2460
2461 void
2462 cyclews(struct swm_region *r, union arg *args)
2463 {
2464 union arg a;
2465 struct swm_screen *s = r->s;
2466 int cycle_all = 0;
2467
2468 DNPRINTF(SWM_D_WS, "cyclews: id: %d, screen[%d]:%dx%d+%d+%d, ws: %d\n",
2469 args->id, r->s->idx, WIDTH(r), HEIGHT(r), X(r), Y(r), r->ws->idx);
2470
2471 a.id = r->ws->idx;
2472 do {
2473 switch (args->id) {
2474 case SWM_ARG_ID_CYCLEWS_UP_ALL:
2475 cycle_all = 1;
2476 /* FALLTHROUGH */
2477 case SWM_ARG_ID_CYCLEWS_UP:
2478 if (a.id < workspace_limit - 1)
2479 a.id++;
2480 else
2481 a.id = 0;
2482 break;
2483 case SWM_ARG_ID_CYCLEWS_DOWN_ALL:
2484 cycle_all = 1;
2485 /* FALLTHROUGH */
2486 case SWM_ARG_ID_CYCLEWS_DOWN:
2487 if (a.id > 0)
2488 a.id--;
2489 else
2490 a.id = workspace_limit - 1;
2491 break;
2492 default:
2493 return;
2494 };
2495
2496 if (!cycle_all &&
2497 (cycle_empty == 0 && TAILQ_EMPTY(&s->ws[a.id].winlist)))
2498 continue;
2499 if (cycle_visible == 0 && s->ws[a.id].r != NULL)
2500 continue;
2501
2502 switchws(r, &a);
2503 } while (a.id != r->ws->idx);
2504 }
2505
2506 void
2507 priorws(struct swm_region *r, union arg *args)
2508 {
2509 union arg a;
2510
2511 DNPRINTF(SWM_D_WS, "priorws: id: %d, screen[%d]:%dx%d+%d+%d, ws: %d\n",
2512 args->id, r->s->idx, WIDTH(r), HEIGHT(r), X(r), Y(r), r->ws->idx);
2513
2514 if (r->ws_prior == NULL)
2515 return;
2516
2517 a.id = r->ws_prior->idx;
2518 switchws(r, &a);
2519 }
2520
2521 void
2522 cyclescr(struct swm_region *r, union arg *args)
2523 {
2524 struct swm_region *rr = NULL;
2525 union arg a;
2526 int i, x, y;
2527
2528 /* do nothing if we don't have more than one screen */
2529 if (!(ScreenCount(display) > 1 || outputs > 1))
2530 return;
2531
2532 i = r->s->idx;
2533 switch (args->id) {
2534 case SWM_ARG_ID_CYCLESC_UP:
2535 rr = TAILQ_NEXT(r, entry);
2536 if (rr == NULL)
2537 rr = TAILQ_FIRST(&screens[i].rl);
2538 break;
2539 case SWM_ARG_ID_CYCLESC_DOWN:
2540 rr = TAILQ_PREV(r, swm_region_list, entry);
2541 if (rr == NULL)
2542 rr = TAILQ_LAST(&screens[i].rl, swm_region_list);
2543 break;
2544 default:
2545 return;
2546 };
2547 if (rr == NULL)
2548 return;
2549
2550 /* move mouse to region */
2551 x = X(rr) + 1;
2552 y = Y(rr) + 1 + (bar_enabled ? bar_height : 0);
2553 XWarpPointer(display, None, rr->s[i].root, 0, 0, 0, 0, x, y);
2554
2555 a.id = SWM_ARG_ID_FOCUSCUR;
2556 focus(rr, &a);
2557
2558 if (rr->ws->focus) {
2559 /* move to focus window */
2560 x = X(rr->ws->focus) + 1;
2561 y = Y(rr->ws->focus) + 1;
2562 XWarpPointer(display, None, rr->s[i].root, 0, 0, 0, 0, x, y);
2563 }
2564 }
2565
2566 void
2567 sort_windows(struct ws_win_list *wl)
2568 {
2569 struct ws_win *win, *parent, *nxt;
2570
2571 if (wl == NULL)
2572 return;
2573
2574 for (win = TAILQ_FIRST(wl); win != TAILQ_END(wl); win = nxt) {
2575 nxt = TAILQ_NEXT(win, entry);
2576 if (win->transient) {
2577 parent = find_window(win->transient);
2578 if (parent == NULL) {
2579 warnx("not possible bug");
2580 continue;
2581 }
2582 TAILQ_REMOVE(wl, win, entry);
2583 TAILQ_INSERT_AFTER(wl, parent, win, entry);
2584 }
2585 }
2586
2587 }
2588
2589 void
2590 swapwin(struct swm_region *r, union arg *args)
2591 {
2592 struct ws_win *target, *source;
2593 struct ws_win *cur_focus;
2594 struct ws_win_list *wl;
2595
2596
2597 DNPRINTF(SWM_D_WS, "swapwin: id: %d, screen[%d]:%dx%d+%d+%d, ws: %d\n",
2598 args->id, r->s->idx, WIDTH(r), HEIGHT(r), X(r), Y(r), r->ws->idx);
2599
2600 cur_focus = r->ws->focus;
2601 if (cur_focus == NULL)
2602 return;
2603
2604 source = cur_focus;
2605 wl = &source->ws->winlist;
2606
2607 switch (args->id) {
2608 case SWM_ARG_ID_SWAPPREV:
2609 if (source->transient)
2610 source = find_window(source->transient);
2611 target = TAILQ_PREV(source, ws_win_list, entry);
2612 if (target && target->transient)
2613 target = find_window(target->transient);
2614 TAILQ_REMOVE(wl, source, entry);
2615 if (target == NULL)
2616 TAILQ_INSERT_TAIL(wl, source, entry);
2617 else
2618 TAILQ_INSERT_BEFORE(target, source, entry);
2619 break;
2620 case SWM_ARG_ID_SWAPNEXT:
2621 target = TAILQ_NEXT(source, entry);
2622 /* move the parent and let the sort handle the move */
2623 if (source->transient)
2624 source = find_window(source->transient);
2625 TAILQ_REMOVE(wl, source, entry);
2626 if (target == NULL)
2627 TAILQ_INSERT_HEAD(wl, source, entry);
2628 else
2629 TAILQ_INSERT_AFTER(wl, target, source, entry);
2630 break;
2631 case SWM_ARG_ID_SWAPMAIN:
2632 target = TAILQ_FIRST(wl);
2633 if (target == source) {
2634 if (source->ws->focus_prev != NULL &&
2635 source->ws->focus_prev != target)
2636 source = source->ws->focus_prev;
2637 else
2638 return;
2639 }
2640 if (target == NULL || source == NULL)
2641 return;
2642 source->ws->focus_prev = target;
2643 TAILQ_REMOVE(wl, target, entry);
2644 TAILQ_INSERT_BEFORE(source, target, entry);
2645 TAILQ_REMOVE(wl, source, entry);
2646 TAILQ_INSERT_HEAD(wl, source, entry);
2647 break;
2648 case SWM_ARG_ID_MOVELAST:
2649 TAILQ_REMOVE(wl, source, entry);
2650 TAILQ_INSERT_TAIL(wl, source, entry);
2651 break;
2652 default:
2653 DNPRINTF(SWM_D_MOVE, "swapwin: invalid id: %d\n", args->id);
2654 return;
2655 }
2656
2657 sort_windows(wl);
2658
2659 stack();
2660 }
2661
2662 void
2663 focus_prev(struct ws_win *win)
2664 {
2665 struct ws_win *winfocus = NULL;
2666 struct ws_win *cur_focus = NULL;
2667 struct ws_win_list *wl = NULL;
2668 struct workspace *ws = NULL;
2669
2670 if (!(win && win->ws))
2671 return;
2672
2673 ws = win->ws;
2674 wl = &ws->winlist;
2675 cur_focus = ws->focus;
2676
2677 DNPRINTF(SWM_D_FOCUS, "focus_prev: window: 0x%lx, cur_focus: 0x%lx\n",
2678 WINID(win), WINID(cur_focus));
2679
2680 /* pickle, just focus on whatever */
2681 if (cur_focus == NULL) {
2682 /* use prev_focus if valid */
2683 if (ws->focus_prev && ws->focus_prev != cur_focus &&
2684 find_window(WINID(ws->focus_prev)))
2685 winfocus = ws->focus_prev;
2686 goto done;
2687 }
2688
2689 /* if transient focus on parent */
2690 if (cur_focus->transient) {
2691 winfocus = find_window(cur_focus->transient);
2692 goto done;
2693 }
2694
2695 /* if in max_stack try harder */
2696 if ((win->quirks & SWM_Q_FOCUSPREV) ||
2697 (ws->cur_layout->flags & SWM_L_FOCUSPREV)) {
2698 if (cur_focus != ws->focus_prev)
2699 winfocus = ws->focus_prev;
2700 else
2701 winfocus = TAILQ_PREV(win, ws_win_list, entry);
2702 if (winfocus)
2703 goto done;
2704 }
2705
2706 DNPRINTF(SWM_D_FOCUS, "focus_prev: focus_close: %d\n", focus_close);
2707
2708 if (winfocus == NULL || winfocus == win) {
2709 switch (focus_close) {
2710 case SWM_STACK_BOTTOM:
2711 winfocus = TAILQ_FIRST(wl);
2712 break;
2713 case SWM_STACK_TOP:
2714 winfocus = TAILQ_LAST(wl, ws_win_list);
2715 break;
2716 case SWM_STACK_ABOVE:
2717 if ((winfocus = TAILQ_NEXT(cur_focus, entry)) == NULL) {
2718 if (focus_close_wrap)
2719 winfocus = TAILQ_FIRST(wl);
2720 else
2721 winfocus = TAILQ_PREV(cur_focus,
2722 ws_win_list, entry);
2723 }
2724 break;
2725 case SWM_STACK_BELOW:
2726 if ((winfocus = TAILQ_PREV(cur_focus, ws_win_list,
2727 entry)) == NULL) {
2728 if (focus_close_wrap)
2729 winfocus = TAILQ_LAST(wl, ws_win_list);
2730 else
2731 winfocus = TAILQ_NEXT(cur_focus, entry);
2732 }
2733 break;
2734 }
2735 }
2736 done:
2737 if (winfocus == NULL) {
2738 if (focus_default == SWM_STACK_TOP)
2739 winfocus = TAILQ_LAST(wl, ws_win_list);
2740 else
2741 winfocus = TAILQ_FIRST(wl);
2742 }
2743
2744 kill_refs(win);
2745 focus_magic(winfocus);
2746 }
2747
2748 void
2749 focus(struct swm_region *r, union arg *args)
2750 {
2751 struct ws_win *winfocus = NULL, *head;
2752 struct ws_win *cur_focus = NULL;
2753 struct ws_win_list *wl = NULL;
2754 struct workspace *ws = NULL;
2755 int all_iconics;
2756
2757 if (!(r && r->ws))
2758 return;
2759
2760 DNPRINTF(SWM_D_FOCUS, "focus: id: %d\n", args->id);
2761
2762 /* treat FOCUS_CUR special */
2763 if (args->id == SWM_ARG_ID_FOCUSCUR) {
2764 if (r->ws->focus && r->ws->focus->iconic == 0)
2765 winfocus = r->ws->focus;
2766 else if (r->ws->focus_prev && r->ws->focus_prev->iconic == 0)
2767 winfocus = r->ws->focus_prev;
2768 else
2769 TAILQ_FOREACH(winfocus, &r->ws->winlist, entry)
2770 if (winfocus->iconic == 0)
2771 break;
2772
2773 focus_magic(winfocus);
2774 return;
2775 }
2776
2777 if ((cur_focus = r->ws->focus) == NULL)
2778 return;
2779 ws = r->ws;
2780 wl = &ws->winlist;
2781 if (TAILQ_EMPTY(wl))
2782 return;
2783 /* make sure there is at least one uniconified window */
2784 all_iconics = 1;
2785 TAILQ_FOREACH(winfocus, wl, entry)
2786 if (winfocus->iconic == 0) {
2787 all_iconics = 0;
2788 break;
2789 }
2790 if (all_iconics)
2791 return;
2792
2793 switch (args->id) {
2794 case SWM_ARG_ID_FOCUSPREV:
2795 head = TAILQ_PREV(cur_focus, ws_win_list, entry);
2796 if (head == NULL)
2797 head = TAILQ_LAST(wl, ws_win_list);
2798 winfocus = head;
2799 if (WINID(winfocus) == cur_focus->transient) {
2800 head = TAILQ_PREV(winfocus, ws_win_list, entry);
2801 if (head == NULL)
2802 head = TAILQ_LAST(wl, ws_win_list);
2803 winfocus = head;
2804 }
2805
2806 /* skip iconics */
2807 if (winfocus && winfocus->iconic) {
2808 while (winfocus != cur_focus) {
2809 if (winfocus == NULL)
2810 winfocus = TAILQ_LAST(wl, ws_win_list);
2811 if (winfocus->iconic == 0)
2812 break;
2813 winfocus = TAILQ_PREV(winfocus, ws_win_list,
2814 entry);
2815 }
2816 }
2817 break;
2818
2819 case SWM_ARG_ID_FOCUSNEXT:
2820 head = TAILQ_NEXT(cur_focus, entry);
2821 if (head == NULL)
2822 head = TAILQ_FIRST(wl);
2823 winfocus = head;
2824
2825 /* skip iconics */
2826 if (winfocus && winfocus->iconic) {
2827 while (winfocus != cur_focus) {
2828 if (winfocus == NULL)
2829 winfocus = TAILQ_FIRST(wl);
2830 if (winfocus->iconic == 0)
2831 break;
2832 winfocus = TAILQ_NEXT(winfocus, entry);
2833 }
2834 }
2835 break;
2836
2837 case SWM_ARG_ID_FOCUSMAIN:
2838 winfocus = TAILQ_FIRST(wl);
2839 if (winfocus == cur_focus)
2840 winfocus = cur_focus->ws->focus_prev;
2841 break;
2842
2843 default:
2844 return;
2845 }
2846
2847 focus_magic(winfocus);
2848 }
2849
2850 void
2851 cycle_layout(struct swm_region *r, union arg *args)
2852 {
2853 struct workspace *ws = r->ws;
2854 union arg a;
2855
2856 DNPRINTF(SWM_D_EVENT, "cycle_layout: workspace: %d\n", ws->idx);
2857
2858 ws->cur_layout++;
2859 if (ws->cur_layout->l_stack == NULL)
2860 ws->cur_layout = &layouts[0];
2861
2862 stack();
2863 if (focus_mode == SWM_FOCUS_DEFAULT)
2864 drain_enter_notify();
2865 a.id = SWM_ARG_ID_FOCUSCUR;
2866 focus(r, &a);
2867 }
2868
2869 void
2870 stack_config(struct swm_region *r, union arg *args)
2871 {
2872 struct workspace *ws = r->ws;
2873
2874 DNPRINTF(SWM_D_STACK, "stack_config: id: %d workspace: %d\n",
2875 args->id, ws->idx);
2876
2877 if (ws->cur_layout->l_config != NULL)
2878 ws->cur_layout->l_config(ws, args->id);
2879
2880 if (args->id != SWM_ARG_ID_STACKINIT)
2881 stack();
2882 bar_update();
2883 }
2884
2885 void
2886 stack(void) {
2887 struct swm_geometry g;
2888 struct swm_region *r;
2889 int i;
2890 #ifdef SWM_DEBUG
2891 int j;
2892 #endif
2893
2894 DNPRINTF(SWM_D_STACK, "stack: begin\n");
2895
2896 for (i = 0; i < ScreenCount(display); i++) {
2897 #ifdef SWM_DEBUG
2898 j = 0;
2899 #endif
2900 TAILQ_FOREACH(r, &screens[i].rl, entry) {
2901 DNPRINTF(SWM_D_STACK, "stack: workspace: %d "
2902 "(screen: %d, region: %d)\n", r->ws->idx, i, j++);
2903
2904 /* start with screen geometry, adjust for bar */
2905 g = r->g;
2906 g.w -= 2 * border_width;
2907 g.h -= 2 * border_width;
2908 if (bar_enabled) {
2909 if (!bar_at_bottom)
2910 g.y += bar_height;
2911 g.h -= bar_height;
2912 }
2913 r->ws->cur_layout->l_stack(r->ws, &g);
2914 r->ws->cur_layout->l_string(r->ws);
2915 /* save r so we can track region changes */
2916 r->ws->old_r = r;
2917 }
2918 }
2919 if (font_adjusted)
2920 font_adjusted--;
2921
2922 if (focus_mode == SWM_FOCUS_DEFAULT)
2923 drain_enter_notify();
2924
2925 DNPRINTF(SWM_D_STACK, "stack: end\n");
2926 }
2927
2928 void
2929 store_float_geom(struct ws_win *win, struct swm_region *r)
2930 {
2931 /* retain window geom and region geom */
2932 win->g_float = win->g;
2933 win->rg_float = r->g;
2934 win->g_floatvalid = 1;
2935 }
2936
2937 void
2938 stack_floater(struct ws_win *win, struct swm_region *r)
2939 {
2940 unsigned int mask;
2941 XWindowChanges wc;
2942
2943 if (win == NULL)
2944 return;
2945
2946 bzero(&wc, sizeof wc);
2947 mask = CWX | CWY | CWBorderWidth | CWWidth | CWHeight;
2948
2949 /*
2950 * to allow windows to change their size (e.g. mplayer fs) only retrieve
2951 * geom on ws switches or return from max mode
2952 */
2953 if (win->floatmaxed || (r != r->ws->old_r && win->g_floatvalid
2954 && !(win->ewmh_flags & EWMH_F_FULLSCREEN))) {
2955 /*
2956 * use stored g and rg to set relative position and size
2957 * as in old region or before max stack mode
2958 */
2959 X(win) = win->g_float.x - win->rg_float.x + X(r);
2960 Y(win) = win->g_float.y - win->rg_float.y + Y(r);
2961 WIDTH(win) = win->g_float.w;
2962 HEIGHT(win) = win->g_float.h;
2963 win->g_floatvalid = 0;
2964 }
2965
2966 win->floatmaxed = 0;
2967
2968 if ((win->quirks & SWM_Q_FULLSCREEN) && (WIDTH(win) >= WIDTH(r)) &&
2969 (HEIGHT(win) >= HEIGHT(r)))
2970 wc.border_width = 0;
2971 else
2972 wc.border_width = border_width;
2973 if (win->transient && (win->quirks & SWM_Q_TRANSSZ)) {
2974 WIDTH(win) = (double)WIDTH(r) * dialog_ratio;
2975 HEIGHT(win) = (double)HEIGHT(r) * dialog_ratio;
2976 }
2977
2978 if (!win->manual) {
2979 /*
2980 * floaters and transients are auto-centred unless moved
2981 * or resized
2982 */
2983 X(win) = X(r) + (WIDTH(r) - WIDTH(win)) / 2 - wc.border_width;
2984 Y(win) = Y(r) + (HEIGHT(r) - HEIGHT(win)) / 2 - wc.border_width;
2985 }
2986
2987 /* win can be outside r if new r smaller than old r */
2988 /* Ensure top left corner inside r (move probs otherwise) */
2989 if (X(win) < X(r) - wc.border_width)
2990 X(win) = X(r) - wc.border_width;
2991 if (X(win) > X(r) + WIDTH(r) - 1)
2992 X(win) = (WIDTH(win) > WIDTH(r)) ? X(r) :
2993 (X(r) + WIDTH(r) - WIDTH(win) - 2 * wc.border_width);
2994 if (Y(win) < Y(r) - wc.border_width)
2995 Y(win) = Y(r) - wc.border_width;
2996 if (Y(win) > Y(r) + HEIGHT(r) - 1)
2997 Y(win) = (HEIGHT(win) > HEIGHT(r)) ? Y(r) :
2998 (Y(r) + HEIGHT(r) - HEIGHT(win) - 2 * wc.border_width);
2999
3000 wc.x = X(win);
3001 wc.y = Y(win);
3002 wc.width = WIDTH(win);
3003 wc.height = HEIGHT(win);
3004
3005 /*
3006 * Retain floater and transient geometry for correct positioning
3007 * when ws changes region
3008 */
3009 if (!(win->ewmh_flags & EWMH_F_FULLSCREEN))
3010 store_float_geom(win, r);
3011
3012 DNPRINTF(SWM_D_MISC, "stack_floater: window: %lu, (x,y) w x h: (%d,%d) "
3013 "%d x %d\n", win->id, wc.x, wc.y, wc.width, wc.height);
3014
3015 XConfigureWindow(display, win->id, mask, &wc);
3016 }
3017
3018 /*
3019 * Send keystrokes to terminal to decrease/increase the font size as the
3020 * window size changes.
3021 */
3022 void
3023 adjust_font(struct ws_win *win)
3024 {
3025 if (!(win->quirks & SWM_Q_XTERM_FONTADJ) ||
3026 win->floating || win->transient)
3027 return;
3028
3029 if (win->sh.width_inc && win->last_inc != win->sh.width_inc &&
3030 WIDTH(win) / win->sh.width_inc < term_width &&
3031 win->font_steps < SWM_MAX_FONT_STEPS) {
3032 win->font_size_boundary[win->font_steps] =
3033 (win->sh.width_inc * term_width) + win->sh.base_width;
3034 win->font_steps++;
3035 font_adjusted++;
3036 win->last_inc = win->sh.width_inc;
3037 fake_keypress(win, XK_KP_Subtract, ShiftMask);
3038 } else if (win->font_steps && win->last_inc != win->sh.width_inc &&
3039 WIDTH(win) > win->font_size_boundary[win->font_steps - 1]) {
3040 win->font_steps--;
3041 font_adjusted++;
3042 win->last_inc = win->sh.width_inc;
3043 fake_keypress(win, XK_KP_Add, ShiftMask);
3044 }
3045 }
3046
3047 #define SWAPXY(g) do { \
3048 int tmp; \
3049 tmp = (g)->y; (g)->y = (g)->x; (g)->x = tmp; \
3050 tmp = (g)->h; (g)->h = (g)->w; (g)->w = tmp; \
3051 } while (0)
3052 void
3053 stack_master(struct workspace *ws, struct swm_geometry *g, int rot, int flip)
3054 {
3055 XWindowChanges wc;
3056 XWindowAttributes wa;
3057 struct swm_geometry win_g, r_g = *g;
3058 struct ws_win *win, *fs_win = 0;
3059 int i, j, s, stacks;
3060 int w_inc = 1, h_inc, w_base = 1, h_base;
3061 int hrh, extra = 0, h_slice, last_h = 0;
3062 int split, colno, winno, mwin, msize, mscale;
3063 int remain, missing, v_slice, reconfigure;
3064 unsigned int mask;
3065
3066 DNPRINTF(SWM_D_STACK, "stack_master: workspace: %d, rot: %s, "
3067 "flip: %s\n", ws->idx, YESNO(rot), YESNO(flip));
3068
3069 winno = count_win(ws, 0);
3070 if (winno == 0 && count_win(ws, 1) == 0)
3071 return;
3072
3073 TAILQ_FOREACH(win, &ws->winlist, entry)
3074 if (win->transient == 0 && win->floating == 0
3075 && win->iconic == 0)
3076 break;
3077
3078 if (win == NULL)
3079 goto notiles;
3080
3081 if (rot) {
3082 w_inc = win->sh.width_inc;
3083 w_base = win->sh.base_width;
3084 mwin = ws->l_state.horizontal_mwin;
3085 mscale = ws->l_state.horizontal_msize;
3086 stacks = ws->l_state.horizontal_stacks;
3087 SWAPXY(&r_g);
3088 } else {
3089 w_inc = win->sh.height_inc;
3090 w_base = win->sh.base_height;
3091 mwin = ws->l_state.vertical_mwin;
3092 mscale = ws->l_state.vertical_msize;
3093 stacks = ws->l_state.vertical_stacks;
3094 }
3095 win_g = r_g;
3096
3097 if (stacks > winno - mwin)
3098 stacks = winno - mwin;
3099 if (stacks < 1)
3100 stacks = 1;
3101
3102 h_slice = r_g.h / SWM_H_SLICE;
3103 if (mwin && winno > mwin) {
3104 v_slice = r_g.w / SWM_V_SLICE;
3105
3106 split = mwin;
3107 colno = split;
3108 win_g.w = v_slice * mscale;
3109
3110 if (w_inc > 1 && w_inc < v_slice) {
3111 /* adjust for window's requested size increment */
3112 remain = (win_g.w - w_base) % w_inc;
3113 win_g.w -= remain;
3114 }
3115
3116 msize = win_g.w;
3117 if (flip)
3118 win_g.x += r_g.w - msize;
3119 } else {
3120 msize = -2;
3121 colno = split = winno / stacks;
3122 win_g.w = ((r_g.w - (stacks * 2 * border_width) +
3123 2 * border_width) / stacks);
3124 }
3125 hrh = r_g.h / colno;
3126 extra = r_g.h - (colno * hrh);
3127 win_g.h = hrh - 2 * border_width;
3128
3129 /* stack all the tiled windows */
3130 i = j = 0, s = stacks;
3131 TAILQ_FOREACH(win, &ws->winlist, entry) {
3132 if (win->transient != 0 || win->floating != 0)
3133 continue;
3134 if (win->iconic != 0)
3135 continue;
3136
3137 if (win->ewmh_flags & EWMH_F_FULLSCREEN) {
3138 fs_win = win;
3139 continue;
3140 }
3141
3142 if (split && i == split) {
3143 colno = (winno - mwin) / stacks;
3144 if (s <= (winno - mwin) % stacks)
3145 colno++;
3146 split = split + colno;
3147 hrh = (r_g.h / colno);
3148 extra = r_g.h - (colno * hrh);
3149 if (flip)
3150 win_g.x = r_g.x;
3151 else
3152 win_g.x += win_g.w + 2 * border_width;
3153 win_g.w = (r_g.w - msize -
3154 (stacks * 2 * border_width)) / stacks;
3155 if (s == 1)
3156 win_g.w += (r_g.w - msize -
3157 (stacks * 2 * border_width)) % stacks;
3158 s--;
3159 j = 0;
3160 }
3161 win_g.h = hrh - 2 * border_width;
3162 if (rot) {
3163 h_inc = win->sh.width_inc;
3164 h_base = win->sh.base_width;
3165 } else {
3166 h_inc = win->sh.height_inc;
3167 h_base = win->sh.base_height;
3168 }
3169 if (j == colno - 1) {
3170 win_g.h = hrh + extra;
3171 } else if (h_inc > 1 && h_inc < h_slice) {
3172 /* adjust for window's requested size increment */
3173 remain = (win_g.h - h_base) % h_inc;
3174 missing = h_inc - remain;
3175
3176 if (missing <= extra || j == 0) {
3177 extra -= missing;
3178 win_g.h += missing;
3179 } else {
3180 win_g.h -= remain;
3181 extra += remain;
3182 }
3183 }
3184
3185 if (j == 0)
3186 win_g.y = r_g.y;
3187 else
3188 win_g.y += last_h + 2 * border_width;
3189
3190 bzero(&wc, sizeof wc);
3191 if (disable_border && bar_enabled == 0 && winno == 1){
3192 wc.border_width = 0;
3193 win_g.w += 2 * border_width;
3194 win_g.h += 2 * border_width;
3195 } else
3196 wc.border_width = border_width;
3197 reconfigure = 0;
3198 if (rot) {
3199 if (X(win) != win_g.y || Y(win) != win_g.x ||
3200 WIDTH(win) != win_g.h || HEIGHT(win) != win_g.w) {
3201 reconfigure = 1;
3202 X(win) = wc.x = win_g.y;
3203 Y(win) = wc.y = win_g.x;
3204 WIDTH(win) = wc.width = win_g.h;
3205 HEIGHT(win) = wc.height = win_g.w;
3206 }
3207 } else {
3208 if (X(win) != win_g.x || Y(win) != win_g.y ||
3209 WIDTH(win) != win_g.w || HEIGHT(win) != win_g.h) {
3210 reconfigure = 1;
3211 X(win) = wc.x = win_g.x;
3212 Y(win) = wc.y = win_g.y;
3213 WIDTH(win) = wc.width = win_g.w;
3214 HEIGHT(win) = wc.height = win_g.h;
3215 }
3216 }
3217 if (reconfigure) {
3218 adjust_font(win);
3219 mask = CWX | CWY | CWWidth | CWHeight | CWBorderWidth;
3220 XConfigureWindow(display, win->id, mask, &wc);
3221 }
3222
3223 if (XGetWindowAttributes(display, win->id, &wa))
3224 if (wa.map_state == IsUnmapped)
3225 XMapRaised(display, win->id);
3226
3227 last_h = win_g.h;
3228 i++;
3229 j++;
3230 }
3231
3232 notiles:
3233 /* now, stack all the floaters and transients */
3234 TAILQ_FOREACH(win, &ws->winlist, entry) {
3235 if (win->transient == 0 && win->floating == 0)
3236 continue;
3237 if (win->iconic == 1)
3238 continue;
3239 if (win->ewmh_flags & EWMH_F_FULLSCREEN) {
3240 fs_win = win;
3241 continue;
3242 }
3243
3244 stack_floater(win, ws->r);
3245 XMapRaised(display, win->id);
3246 }
3247
3248 if (fs_win) {
3249 stack_floater(fs_win, ws->r);
3250 XMapRaised(display, fs_win->id);
3251 }
3252 }
3253
3254 void
3255 vertical_config(struct workspace *ws, int id)
3256 {
3257 DNPRINTF(SWM_D_STACK, "vertical_config: id: %d, workspace: %d\n",
3258 id, ws->idx);
3259
3260 switch (id) {
3261 case SWM_ARG_ID_STACKRESET:
3262 case SWM_ARG_ID_STACKINIT:
3263 ws->l_state.vertical_msize = SWM_V_SLICE / 2;
3264 ws->l_state.vertical_mwin = 1;
3265 ws->l_state.vertical_stacks = 1;
3266 break;
3267 case SWM_ARG_ID_MASTERSHRINK:
3268 if (ws->l_state.vertical_msize > 1)
3269 ws->l_state.vertical_msize--;
3270 break;
3271 case SWM_ARG_ID_MASTERGROW:
3272 if (ws->l_state.vertical_msize < SWM_V_SLICE - 1)
3273 ws->l_state.vertical_msize++;
3274 break;
3275 case SWM_ARG_ID_MASTERADD:
3276 ws->l_state.vertical_mwin++;
3277 break;
3278 case SWM_ARG_ID_MASTERDEL:
3279 if (ws->l_state.vertical_mwin > 0)
3280 ws->l_state.vertical_mwin--;
3281 break;
3282 case SWM_ARG_ID_STACKINC:
3283 ws->l_state.vertical_stacks++;
3284 break;
3285 case SWM_ARG_ID_STACKDEC:
3286 if (ws->l_state.vertical_stacks > 1)
3287 ws->l_state.vertical_stacks--;
3288 break;
3289 case SWM_ARG_ID_FLIPLAYOUT:
3290 ws->l_state.vertical_flip = !ws->l_state.vertical_flip;
3291 break;
3292 default:
3293 return;
3294 }
3295 }
3296
3297 void
3298 vertical_stack(struct workspace *ws, struct swm_geometry *g)
3299 {
3300 DNPRINTF(SWM_D_STACK, "vertical_stack: workspace: %d\n", ws->idx);
3301
3302 stack_master(ws, g, 0, ws->l_state.vertical_flip);
3303 }
3304
3305 void
3306 horizontal_config(struct workspace *ws, int id)
3307 {
3308 DNPRINTF(SWM_D_STACK, "horizontal_config: workspace: %d\n", ws->idx);
3309
3310 switch (id) {
3311 case SWM_ARG_ID_STACKRESET:
3312 case SWM_ARG_ID_STACKINIT:
3313 ws->l_state.horizontal_mwin = 1;
3314 ws->l_state.horizontal_msize = SWM_H_SLICE / 2;
3315 ws->l_state.horizontal_stacks = 1;
3316 break;
3317 case SWM_ARG_ID_MASTERSHRINK:
3318 if (ws->l_state.horizontal_msize > 1)
3319 ws->l_state.horizontal_msize--;
3320 break;
3321 case SWM_ARG_ID_MASTERGROW:
3322 if (ws->l_state.horizontal_msize < SWM_H_SLICE - 1)
3323 ws->l_state.horizontal_msize++;
3324 break;
3325 case SWM_ARG_ID_MASTERADD:
3326 ws->l_state.horizontal_mwin++;
3327 break;
3328 case SWM_ARG_ID_MASTERDEL:
3329 if (ws->l_state.horizontal_mwin > 0)
3330 ws->l_state.horizontal_mwin--;
3331 break;
3332 case SWM_ARG_ID_STACKINC:
3333 ws->l_state.horizontal_stacks++;
3334 break;
3335 case SWM_ARG_ID_STACKDEC:
3336 if (ws->l_state.horizontal_stacks > 1)
3337 ws->l_state.horizontal_stacks--;
3338 break;
3339 case SWM_ARG_ID_FLIPLAYOUT:
3340 ws->l_state.horizontal_flip = !ws->l_state.horizontal_flip;
3341 break;
3342 default:
3343 return;
3344 }
3345 }
3346
3347 void
3348 horizontal_stack(struct workspace *ws, struct swm_geometry *g)
3349 {
3350 DNPRINTF(SWM_D_STACK, "horizontal_stack: workspace: %d\n", ws->idx);
3351
3352 stack_master(ws, g, 1, ws->l_state.horizontal_flip);
3353 }
3354
3355 /* fullscreen view */
3356 void
3357 max_stack(struct workspace *ws, struct swm_geometry *g)
3358 {
3359 XWindowChanges wc;
3360 struct swm_geometry gg = *g;
3361 struct ws_win *win, *wintrans = NULL, *parent = NULL;
3362 unsigned int mask;
3363 int winno;
3364
3365 DNPRINTF(SWM_D_STACK, "max_stack: workspace: %d\n", ws->idx);
3366
3367 if (ws == NULL)
3368 return;
3369
3370 winno = count_win(ws, 0);
3371 if (winno == 0 && count_win(ws, 1) == 0)
3372 return;
3373
3374 TAILQ_FOREACH(win, &ws->winlist, entry) {
3375 if (win->transient) {
3376 wintrans = win;
3377 parent = find_window(win->transient);
3378 continue;
3379 }
3380
3381 if (win->floating && win->floatmaxed == 0 ) {
3382 /*
3383 * retain geometry for retrieval on exit from
3384 * max_stack mode
3385 */
3386 store_float_geom(win, ws->r);
3387 win->floatmaxed = 1;
3388 }
3389
3390 /* only reconfigure if necessary */
3391 if (X(win) != gg.x || Y(win) != gg.y || WIDTH(win) != gg.w ||
3392 HEIGHT(win) != gg.h) {
3393 bzero(&wc, sizeof wc);
3394 X(win) = wc.x = gg.x;
3395 Y(win) = wc.y = gg.y;
3396 if (bar_enabled){
3397 wc.border_width = border_width;
3398 WIDTH(win) = wc.width = gg.w;
3399 HEIGHT(win) = wc.height = gg.h;
3400 } else {
3401 wc.border_width = 0;
3402 WIDTH(win) = wc.width = gg.w + 2 * border_width;
3403 HEIGHT(win) = wc.height = gg.h +
3404 2 * border_width;
3405 }
3406 mask = CWX | CWY | CWWidth | CWHeight | CWBorderWidth;
3407 XConfigureWindow(display, win->id, mask, &wc);
3408 }
3409 /* unmap only if we don't have multi screen */
3410 if (win != ws->focus)
3411 if (!(ScreenCount(display) > 1 || outputs > 1))
3412 unmap_window(win);
3413 }
3414
3415 /* put the last transient on top */
3416 if (wintrans) {
3417 if (parent)
3418 XMapRaised(display, parent->id);
3419 stack_floater(wintrans, ws->r);
3420 focus_magic(wintrans);
3421 }
3422 }
3423
3424 void
3425 send_to_ws(struct swm_region *r, union arg *args)
3426 {
3427 int wsid = args->id;
3428 struct ws_win *win = NULL, *parent;
3429 struct workspace *ws, *nws;
3430 Atom ws_idx_atom = 0;
3431 unsigned char ws_idx_str[SWM_PROPLEN];
3432 union arg a;
3433
3434 if (wsid >= workspace_limit)
3435 return;
3436
3437 if (r && r->ws && r->ws->focus)
3438 win = r->ws->focus;
3439 else
3440 return;
3441 if (win == NULL)
3442 return;
3443 if (win->ws->idx == wsid)
3444 return;
3445
3446 DNPRINTF(SWM_D_MOVE, "send_to_ws: window: 0x%lx\n", win->id);
3447
3448 ws = win->ws;
3449 nws = &win->s->ws[wsid];
3450
3451 a.id = SWM_ARG_ID_FOCUSPREV;
3452 focus(r, &a);
3453 if (win->transient) {
3454 parent = find_window(win->transient);
3455 if (parent) {
3456 unmap_window(parent);
3457 TAILQ_REMOVE(&ws->winlist, parent, entry);
3458 TAILQ_INSERT_TAIL(&nws->winlist, parent, entry);
3459 parent->ws = nws;
3460 }
3461 }
3462 unmap_window(win);
3463 TAILQ_REMOVE(&ws->winlist, win, entry);
3464 TAILQ_INSERT_TAIL(&nws->winlist, win, entry);
3465 if (TAILQ_EMPTY(&ws->winlist))
3466 r->ws->focus = NULL;
3467 win->ws = nws;
3468
3469 /* Try to update the window's workspace property */
3470 ws_idx_atom = XInternAtom(display, "_SWM_WS", False);
3471 if (ws_idx_atom &&
3472 snprintf((char *)ws_idx_str, SWM_PROPLEN, "%d", nws->idx) <
3473 SWM_PROPLEN) {
3474 DNPRINTF(SWM_D_PROP, "send_to_ws: set property: _SWM_WS: %s\n",
3475 ws_idx_str);
3476 XChangeProperty(display, win->id, ws_idx_atom, XA_STRING, 8,
3477 PropModeReplace, ws_idx_str, strlen((char *)ws_idx_str));
3478 }
3479
3480 stack();
3481 bar_update();
3482 }
3483
3484 void
3485 pressbutton(struct swm_region *r, union arg *args)
3486 {
3487 XTestFakeButtonEvent(display, args->id, True, CurrentTime);
3488 XTestFakeButtonEvent(display, args->id, False, CurrentTime);
3489 }
3490
3491 void
3492 raise_toggle(struct swm_region *r, union arg *args)
3493 {
3494 if (r == NULL || r->ws == NULL)
3495 return;
3496
3497 r->ws->always_raise = !r->ws->always_raise;
3498
3499 /* bring floaters back to top */
3500 if (r->ws->always_raise == 0)
3501 stack();
3502 }
3503
3504 void
3505 iconify(struct swm_region *r, union arg *args)
3506 {
3507 union arg a;
3508
3509 if (r->ws->focus == NULL)
3510 return;
3511 unmap_window(r->ws->focus);
3512 update_iconic(r->ws->focus, 1);
3513 stack();
3514 if (focus_mode == SWM_FOCUS_DEFAULT)
3515 drain_enter_notify();
3516 r->ws->focus = NULL;
3517 a.id = SWM_ARG_ID_FOCUSCUR;
3518 focus(r, &a);
3519 }
3520
3521 unsigned char *
3522 get_win_name(Window win)
3523 {
3524 unsigned char *prop = NULL;
3525 unsigned long nbytes, nitems;
3526
3527 /* try _NET_WM_NAME first */
3528 if (get_property(win, a_netwmname, 0L, a_utf8_string, NULL, &nbytes,
3529 &prop)) {
3530 XFree(prop);
3531 if (get_property(win, a_netwmname, nbytes, a_utf8_string,
3532 &nitems, NULL, &prop))
3533 return (prop);
3534 }
3535
3536 /* fallback to WM_NAME */
3537 if (!get_property(win, a_wmname, 0L, a_string, NULL, &nbytes, &prop))
3538 return (NULL);
3539 XFree(prop);
3540 if (get_property(win, a_wmname, nbytes, a_string, &nitems, NULL, &prop))
3541 return (prop);
3542
3543 return (NULL);
3544 }
3545
3546 void
3547 uniconify(struct swm_region *r, union arg *args)
3548 {
3549 struct ws_win *win;
3550 FILE *lfile;
3551 unsigned char *name;
3552 int count = 0;
3553
3554 DNPRINTF(SWM_D_MISC, "uniconify\n");
3555
3556 if (r == NULL || r->ws == NULL)
3557 return;
3558
3559 /* make sure we have anything to uniconify */
3560 TAILQ_FOREACH(win, &r->ws->winlist, entry) {
3561 if (win->ws == NULL)
3562 continue; /* should never happen */
3563 if (win->iconic == 0)
3564 continue;
3565 count++;
3566 }
3567 if (count == 0)
3568 return;
3569
3570 search_r = r;
3571 search_resp_action = SWM_SEARCH_UNICONIFY;
3572
3573 spawn_select(r, args, "search", &searchpid);
3574
3575 if ((lfile = fdopen(select_list_pipe[1], "w")) == NULL)
3576 return;
3577
3578 TAILQ_FOREACH(win, &r->ws->winlist, entry) {
3579 if (win->ws == NULL)
3580 continue; /* should never happen */
3581 if (win->iconic == 0)
3582 continue;
3583
3584 name = get_win_name(win->id);
3585 if (name == NULL)
3586 continue;
3587 fprintf(lfile, "%s.%lu\n", name, win->id);
3588 XFree(name);
3589 }
3590
3591 fclose(lfile);
3592 }
3593
3594 void
3595 name_workspace(struct swm_region *r, union arg *args)
3596 {
3597 FILE *lfile;
3598
3599 DNPRINTF(SWM_D_MISC, "name_workspace\n");
3600
3601 if (r == NULL)
3602 return;
3603
3604 search_r = r;
3605 search_resp_action = SWM_SEARCH_NAME_WORKSPACE;
3606
3607 spawn_select(r, args, "name_workspace", &searchpid);
3608
3609 if ((lfile = fdopen(select_list_pipe[1], "w")) == NULL)
3610 return;
3611
3612 fprintf(lfile, "%s", "");
3613 fclose(lfile);
3614 }
3615
3616 void
3617 search_workspace(struct swm_region *r, union arg *args)
3618 {
3619 int i;
3620 struct workspace *ws;
3621 FILE *lfile;
3622
3623 DNPRINTF(SWM_D_MISC, "search_workspace\n");
3624
3625 if (r == NULL)
3626 return;
3627
3628 search_r = r;
3629 search_resp_action = SWM_SEARCH_SEARCH_WORKSPACE;
3630
3631 spawn_select(r, args, "search", &searchpid);
3632
3633 if ((lfile = fdopen(select_list_pipe[1], "w")) == NULL)
3634 return;
3635
3636 for (i = 0; i < workspace_limit; i++) {
3637 ws = &r->s->ws[i];
3638 if (ws == NULL)
3639 continue;
3640 fprintf(lfile, "%d%s%s\n", ws->idx + 1,
3641 (ws->name ? ":" : ""), (ws->name ? ws->name : ""));
3642 }
3643
3644 fclose(lfile);
3645 }
3646
3647 void
3648 search_win_cleanup(void)
3649 {
3650 struct search_window *sw = NULL;
3651
3652 while ((sw = TAILQ_FIRST(&search_wl)) != NULL) {
3653 XDestroyWindow(display, sw->indicator);
3654 XFreeGC(display, sw->gc);
3655 TAILQ_REMOVE(&search_wl, sw, entry);
3656 free(sw);
3657 }
3658 }
3659
3660 void
3661 search_win(struct swm_region *r, union arg *args)
3662 {
3663 struct ws_win *win = NULL;
3664 struct search_window *sw = NULL;
3665 Window w;
3666 XGCValues gcv;
3667 int i;
3668 char s[8];
3669 FILE *lfile;
3670 size_t len;
3671 XRectangle ibox, lbox;
3672
3673 DNPRINTF(SWM_D_MISC, "search_win\n");
3674
3675 search_r = r;
3676 search_resp_action = SWM_SEARCH_SEARCH_WINDOW;
3677
3678 spawn_select(r, args, "search", &searchpid);
3679
3680 if ((lfile = fdopen(select_list_pipe[1], "w")) == NULL)
3681 return;
3682
3683 TAILQ_INIT(&search_wl);
3684
3685 i = 1;
3686 TAILQ_FOREACH(win, &r->ws->winlist, entry) {
3687 if (win->iconic == 1)
3688 continue;
3689
3690 sw = calloc(1, sizeof(struct search_window));
3691 if (sw == NULL) {
3692 warn("search_win: calloc");
3693 fclose(lfile);
3694 search_win_cleanup();
3695 return;
3696 }
3697 sw->idx = i;
3698 sw->win = win;
3699
3700 snprintf(s, sizeof s, "%d", i);
3701 len = strlen(s);
3702
3703 XmbTextExtents(bar_fs, s, len, &ibox, &lbox);
3704
3705 w = XCreateSimpleWindow(display,
3706 win->id, 0, 0,lbox.width + 4,
3707 bar_fs_extents->max_logical_extent.height, 1,
3708 r->s->c[SWM_S_COLOR_UNFOCUS].color,
3709 r->s->c[SWM_S_COLOR_FOCUS].color);
3710
3711 sw->indicator = w;
3712 TAILQ_INSERT_TAIL(&search_wl, sw, entry);
3713
3714 sw->gc = XCreateGC(display, w, 0, &gcv);
3715 XMapRaised(display, w);
3716 XSetForeground(display, sw->gc, r->s->c[SWM_S_COLOR_BAR].color);
3717
3718 DRAWSTRING(display, w, bar_fs, sw->gc, 2,
3719 (bar_fs_extents->max_logical_extent.height -
3720 lbox.height) / 2 - lbox.y, s, len);
3721
3722 fprintf(lfile, "%d\n", i);
3723 i++;
3724 }
3725
3726 fclose(lfile);
3727 }
3728
3729 void
3730 search_resp_uniconify(char *resp, unsigned long len)
3731 {
3732 unsigned char *name;
3733 struct ws_win *win;
3734 char *s;
3735
3736 DNPRINTF(SWM_D_MISC, "search_resp_uniconify: resp: %s\n", resp);
3737
3738 TAILQ_FOREACH(win, &search_r->ws->winlist, entry) {
3739 if (win->iconic == 0)
3740 continue;
3741 name = get_win_name(win->id);
3742 if (name == NULL)
3743 continue;
3744 if (asprintf(&s, "%s.%lu", name, win->id) == -1) {
3745 XFree(name);
3746 continue;
3747 }
3748 XFree(name);
3749 if (strncmp(s, resp, len) == 0) {
3750 /* XXX this should be a callback to generalize */
3751 update_iconic(win, 0);
3752 free(s);
3753 break;
3754 }
3755 free(s);
3756 }
3757 }
3758
3759 void
3760 search_resp_name_workspace(char *resp, unsigned long len)
3761 {
3762 struct workspace *ws;
3763
3764 DNPRINTF(SWM_D_MISC, "search_resp_name_workspace: resp: %s\n", resp);
3765
3766 if (search_r->ws == NULL)
3767 return;
3768 ws = search_r->ws;
3769
3770 if (ws->name) {
3771 free(search_r->ws->name);
3772 search_r->ws->name = NULL;
3773 }
3774
3775 if (len > 1) {
3776 ws->name = strdup(resp);
3777 if (ws->name == NULL) {
3778 DNPRINTF(SWM_D_MISC, "search_resp_name_workspace: "
3779 "strdup: %s", strerror(errno));
3780 return;
3781 }
3782 }
3783 }
3784
3785 void
3786 search_resp_search_workspace(char *resp, unsigned long len)
3787 {
3788 char *p, *q;
3789 int ws_idx;
3790 const char *errstr;
3791 union arg a;
3792
3793 DNPRINTF(SWM_D_MISC, "search_resp_search_workspace: resp: %s\n", resp);
3794
3795 q = strdup(resp);
3796 if (!q) {
3797 DNPRINTF(SWM_D_MISC, "search_resp_search_workspace: strdup: %s",
3798 strerror(errno));
3799 return;
3800 }
3801 p = strchr(q, ':');
3802 if (p != NULL)
3803 *p = '\0';
3804 ws_idx = strtonum(q, 1, workspace_limit, &errstr);
3805 if (errstr) {
3806 DNPRINTF(SWM_D_MISC, "workspace idx is %s: %s",
3807 errstr, q);
3808 free(q);
3809 return;
3810 }
3811 free(q);
3812 a.id = ws_idx - 1;
3813 switchws(search_r, &a);
3814 }
3815
3816 void
3817 search_resp_search_window(char *resp, unsigned long len)
3818 {
3819 char *s;
3820 int idx;
3821 const char *errstr;
3822 struct search_window *sw;
3823
3824 DNPRINTF(SWM_D_MISC, "search_resp_search_window: resp: %s\n", resp);
3825
3826 s = strdup(resp);
3827 if (!s) {
3828 DNPRINTF(SWM_D_MISC, "search_resp_search_window: strdup: %s",
3829 strerror(errno));
3830 return;
3831 }
3832
3833 idx = strtonum(s, 1, INT_MAX, &errstr);
3834 if (errstr) {
3835 DNPRINTF(SWM_D_MISC, "window idx is %s: %s",
3836 errstr, s);
3837 free(s);
3838 return;
3839 }
3840 free(s);
3841
3842 TAILQ_FOREACH(sw, &search_wl, entry)
3843 if (idx == sw->idx) {
3844 focus_win(sw->win);
3845 break;
3846 }
3847 }
3848
3849 #define MAX_RESP_LEN 1024
3850
3851 void
3852 search_do_resp(void)
3853 {
3854 ssize_t rbytes;
3855 char *resp;
3856 unsigned long len;
3857
3858 DNPRINTF(SWM_D_MISC, "search_do_resp:\n");
3859
3860 search_resp = 0;
3861 searchpid = 0;
3862
3863 if ((resp = calloc(1, MAX_RESP_LEN + 1)) == NULL) {
3864 warn("search: calloc");
3865 goto done;
3866 }
3867
3868 rbytes = read(select_resp_pipe[0], resp, MAX_RESP_LEN);
3869 if (rbytes <= 0) {
3870 warn("search: read error");
3871 goto done;
3872 }
3873 resp[rbytes] = '\0';
3874
3875 /* XXX:
3876 * Older versions of dmenu (Atleast pre 4.4.1) do not send a
3877 * newline, so work around that by sanitizing the resp now.
3878 */
3879 resp[strcspn(resp, "\n")] = '\0';
3880 len = strlen(resp);
3881
3882 switch (search_resp_action) {
3883 case SWM_SEARCH_UNICONIFY:
3884 search_resp_uniconify(resp, len);
3885 break;
3886 case SWM_SEARCH_NAME_WORKSPACE:
3887 search_resp_name_workspace(resp, len);
3888 break;
3889 case SWM_SEARCH_SEARCH_WORKSPACE:
3890 search_resp_search_workspace(resp, len);
3891 break;
3892 case SWM_SEARCH_SEARCH_WINDOW:
3893 search_resp_search_window(resp, len);
3894 break;
3895 }
3896
3897 done:
3898 if (search_resp_action == SWM_SEARCH_SEARCH_WINDOW)
3899 search_win_cleanup();
3900
3901 search_resp_action = SWM_SEARCH_NONE;
3902 close(select_resp_pipe[0]);
3903 free(resp);
3904 }
3905
3906 void
3907 wkill(struct swm_region *r, union arg *args)
3908 {
3909 DNPRINTF(SWM_D_MISC, "wkill: id: %d\n", args->id);
3910
3911 if (r->ws->focus == NULL)
3912 return;
3913
3914 if (args->id == SWM_ARG_ID_KILLWINDOW)
3915 XKillClient(display, r->ws->focus->id);
3916 else
3917 if (r->ws->focus->can_delete)
3918 client_msg(r->ws->focus, adelete);
3919 }
3920
3921
3922 int
3923 floating_toggle_win(struct ws_win *win)
3924 {
3925 struct swm_region *r;
3926
3927 if (win == NULL)
3928 return (0);
3929
3930 if (!win->ws->r)
3931 return (0);
3932
3933 r = win->ws->r;
3934
3935 /* reject floating toggles in max stack mode */
3936 if (win->ws->cur_layout == &layouts[SWM_MAX_STACK])
3937 return (0);
3938
3939 if (win->floating) {
3940 if (!win->floatmaxed) {
3941 /* retain position for refloat */
3942 store_float_geom(win, r);
3943 }
3944 win->floating = 0;
3945 } else {
3946 if (win->g_floatvalid) {
3947 /* refloat at last floating relative position */
3948 X(win) = win->g_float.x - win->rg_float.x + X(r);
3949 Y(win) = win->g_float.y - win->rg_float.y + Y(r);
3950 WIDTH(win) = win->g_float.w;
3951 HEIGHT(win) = win->g_float.h;
3952 }
3953 win->floating = 1;
3954 }
3955
3956 ewmh_update_actions(win);
3957
3958 return (1);
3959 }
3960
3961 void
3962 floating_toggle(struct swm_region *r, union arg *args)
3963 {
3964 struct ws_win *win = r->ws->focus;
3965 union arg a;
3966
3967 if (win == NULL)
3968 return;
3969
3970 ewmh_update_win_state(win, ewmh[_NET_WM_STATE_ABOVE].atom,
3971 _NET_WM_STATE_TOGGLE);
3972
3973 stack();
3974 if (focus_mode == SWM_FOCUS_DEFAULT)
3975 drain_enter_notify();
3976
3977 if (win == win->ws->focus) {
3978 a.id = SWM_ARG_ID_FOCUSCUR;
3979 focus(win->ws->r, &a);
3980 }
3981 }
3982
3983 void
3984 constrain_window(struct ws_win *win, struct swm_region *r, int resizable)
3985 {
3986 if (X(win) + WIDTH(win) > X(r) + WIDTH(r) - border_width) {
3987 if (resizable)
3988 WIDTH(win) = X(r) + WIDTH(r) - X(win) - border_width;
3989 else
3990 X(win) = X(r) + WIDTH(r) - WIDTH(win) - border_width;
3991 }
3992
3993 if (X(win) < X(r) - border_width) {
3994 if (resizable)
3995 WIDTH(win) -= X(r) - X(win) - border_width;
3996
3997 X(win) = X(r) - border_width;
3998 }
3999
4000 if (Y(win) + HEIGHT(win) > Y(r) + HEIGHT(r) - border_width) {
4001 if (resizable)
4002 HEIGHT(win) = Y(r) + HEIGHT(r) - Y(win) - border_width;
4003 else
4004 Y(win) = Y(r) + HEIGHT(r) - HEIGHT(win) - border_width;
4005 }
4006
4007 if (Y(win) < Y(r) - border_width) {
4008 if (resizable)
4009 HEIGHT(win) -= Y(r) - Y(win) - border_width;
4010
4011 Y(win) = Y(r) - border_width;
4012 }
4013
4014 if (WIDTH(win) < 1)
4015 WIDTH(win) = 1;
4016 if (HEIGHT(win) < 1)
4017 HEIGHT(win) = 1;
4018 }
4019
4020 void
4021 update_window(struct ws_win *win)
4022 {
4023 unsigned int mask;
4024 XWindowChanges wc;
4025
4026 bzero(&wc, sizeof wc);
4027 mask = CWBorderWidth | CWWidth | CWHeight | CWX | CWY;
4028 wc.border_width = border_width;
4029 wc.x = X(win);
4030 wc.y = Y(win);
4031 wc.width = WIDTH(win);
4032 wc.height = HEIGHT(win);
4033
4034 DNPRINTF(SWM_D_MISC, "update_window: window: 0x%lx, (x,y) w x h: "
4035 "(%d,%d) %d x %d\n", win->id, wc.x, wc.y, wc.width, wc.height);
4036
4037 XConfigureWindow(display, win->id, mask, &wc);
4038 }
4039
4040 #define SWM_RESIZE_STEPS (50)
4041
4042 void
4043 resize(struct ws_win *win, union arg *args)
4044 {
4045 XEvent ev;
4046 Time time = 0;
4047 struct swm_region *r = NULL;
4048 int resize_step = 0;
4049 Window rr, cr;
4050 int x, y, wx, wy;
4051 unsigned int mask;
4052 struct swm_geometry g;
4053 int top = 0, left = 0;
4054 int dx, dy;
4055 Cursor cursor;
4056 unsigned int shape; /* cursor style */
4057
4058 if (win == NULL)
4059 return;
4060 r = win->ws->r;
4061
4062 DNPRINTF(SWM_D_MOUSE, "resize: window: 0x%lx, floating: %s, "
4063 "transient: 0x%lx\n", win->id, YESNO(win->floating),
4064 win->transient);
4065
4066 if (!(win->transient != 0 || win->floating != 0))
4067 return;
4068
4069 /* reject resizes in max mode for floaters (transient ok) */
4070 if (win->floatmaxed)
4071 return;
4072
4073 win->manual = 1;
4074 ewmh_update_win_state(win, ewmh[_SWM_WM_STATE_MANUAL].atom,
4075 _NET_WM_STATE_ADD);
4076
4077 stack();
4078
4079 switch (args->id) {
4080 case SWM_ARG_ID_WIDTHSHRINK:
4081 WIDTH(win) -= SWM_RESIZE_STEPS;
4082 resize_step = 1;
4083 break;
4084 case SWM_ARG_ID_WIDTHGROW:
4085 WIDTH(win) += SWM_RESIZE_STEPS;
4086 resize_step = 1;
4087 break;
4088 case SWM_ARG_ID_HEIGHTSHRINK:
4089 HEIGHT(win) -= SWM_RESIZE_STEPS;
4090 resize_step = 1;
4091 break;
4092 case SWM_ARG_ID_HEIGHTGROW:
4093 HEIGHT(win) += SWM_RESIZE_STEPS;
4094 resize_step = 1;
4095 break;
4096 default:
4097 break;
4098 }
4099 if (resize_step) {
4100 constrain_window(win, r, 1);
4101 update_window(win);
4102 store_float_geom(win,r);
4103 return;
4104 }
4105
4106 if (focus_mode == SWM_FOCUS_DEFAULT)
4107 drain_enter_notify();
4108
4109 /* get cursor offset from window root */
4110 if (!XQueryPointer(display, win->id, &rr, &cr, &x, &y, &wx, &wy, &mask))
4111 return;
4112
4113 g = win->g;
4114
4115 if (wx < WIDTH(win) / 2)
4116 left = 1;
4117
4118 if (wy < HEIGHT(win) / 2)
4119 top = 1;
4120
4121 if (args->id == SWM_ARG_ID_CENTER)
4122 shape = XC_sizing;
4123 else if (top)
4124 shape = (left) ? XC_top_left_corner : XC_top_right_corner;
4125 else
4126 shape = (left) ? XC_bottom_left_corner : XC_bottom_right_corner;
4127
4128 cursor = XCreateFontCursor(display, shape);
4129
4130 if (XGrabPointer(display, win->id, False, MOUSEMASK, GrabModeAsync,
4131 GrabModeAsync, None, cursor, CurrentTime) != GrabSuccess) {
4132 XFreeCursor(display, cursor);
4133 return;
4134 }
4135
4136 do {
4137 XMaskEvent(display, MOUSEMASK | ExposureMask |
4138 SubstructureRedirectMask, &ev);
4139 switch (ev.type) {
4140 case ConfigureRequest:
4141 case Expose:
4142 case MapRequest:
4143 handler[ev.type](&ev);
4144 break;
4145 case MotionNotify:
4146 /* cursor offset/delta from start of the operation */
4147 dx = ev.xmotion.x_root - x;
4148 dy = ev.xmotion.y_root - y;
4149
4150 /* vertical */
4151 if (top)
4152 dy = -dy;
4153
4154 if (args->id == SWM_ARG_ID_CENTER) {
4155 if (g.h / 2 + dy < 1)
4156 dy = 1 - g.h / 2;
4157
4158 Y(win) = g.y - dy;
4159 HEIGHT(win) = g.h + 2 * dy;
4160 } else {
4161 if (g.h + dy < 1)
4162 dy = 1 - g.h;
4163
4164 if (top)
4165 Y(win) = g.y - dy;
4166
4167 HEIGHT(win) = g.h + dy;
4168 }
4169
4170 /* horizontal */
4171 if (left)
4172 dx = -dx;
4173
4174 if (args->id == SWM_ARG_ID_CENTER) {
4175 if (g.w / 2 + dx < 1)
4176 dx = 1 - g.w / 2;
4177
4178 X(win) = g.x - dx;
4179 WIDTH(win) = g.w + 2 * dx;
4180 } else {
4181 if (g.w + dx < 1)
4182 dx = 1 - g.w;
4183
4184 if (left)
4185 X(win) = g.x - dx;
4186
4187 WIDTH(win) = g.w + dx;
4188 }
4189
4190 constrain_window(win, r, 1);
4191
4192 /* not free, don't sync more than 120 times / second */
4193 if ((ev.xmotion.time - time) > (1000 / 120) ) {
4194 time = ev.xmotion.time;
4195 XSync(display, False);
4196 update_window(win);
4197 }
4198 break;
4199 }
4200 } while (ev.type != ButtonRelease);
4201 if (time) {
4202 XSync(display, False);
4203 update_window(win);
4204 }
4205 store_float_geom(win,r);
4206
4207 XUngrabPointer(display, CurrentTime);
4208 XFreeCursor(display, cursor);
4209
4210 /* drain events */
4211 drain_enter_notify();
4212 }
4213
4214 void
4215 resize_step(struct swm_region *r, union arg *args)
4216 {
4217 struct ws_win *win = NULL;
4218
4219 if (r && r->ws && r->ws->focus)
4220 win = r->ws->focus;
4221 else
4222 return;
4223
4224 resize(win, args);
4225 }
4226
4227 #define SWM_MOVE_STEPS (50)
4228
4229 void
4230 move(struct ws_win *win, union arg *args)
4231 {
4232 XEvent ev;
4233 Time time = 0;
4234 int move_step = 0;
4235 struct swm_region *r = NULL;
4236
4237 Window rr, cr;
4238 int x, y, wx, wy;
4239 unsigned int mask;
4240
4241 if (win == NULL)
4242 return;
4243 r = win->ws->r;
4244
4245 DNPRINTF(SWM_D_MOUSE, "move: window: 0x%lx, floating: %s, transient: "
4246 "0x%lx\n", win->id, YESNO(win->floating), win->transient);
4247
4248 /* in max_stack mode should only move transients */
4249 if (win->ws->cur_layout == &layouts[SWM_MAX_STACK] && !win->transient)
4250 return;
4251
4252 win->manual = 1;
4253 if (win->floating == 0 && !win->transient) {
4254 store_float_geom(win,r);
4255 ewmh_update_win_state(win, ewmh[_NET_WM_STATE_ABOVE].atom,
4256 _NET_WM_STATE_ADD);
4257 }
4258 ewmh_update_win_state(win, ewmh[_SWM_WM_STATE_MANUAL].atom,
4259 _NET_WM_STATE_ADD);
4260
4261 stack();
4262
4263 move_step = 0;
4264 switch (args->id) {
4265 case SWM_ARG_ID_MOVELEFT:
4266 X(win) -= (SWM_MOVE_STEPS - border_width);
4267 move_step = 1;
4268 break;
4269 case SWM_ARG_ID_MOVERIGHT:
4270 X(win) += (SWM_MOVE_STEPS - border_width);
4271 move_step = 1;
4272 break;
4273 case SWM_ARG_ID_MOVEUP:
4274 Y(win) -= (SWM_MOVE_STEPS - border_width);
4275 move_step = 1;
4276 break;
4277 case SWM_ARG_ID_MOVEDOWN:
4278 Y(win) += (SWM_MOVE_STEPS - border_width);
4279 move_step = 1;
4280 break;
4281 default:
4282 break;
4283 }
4284 if (move_step) {
4285 constrain_window(win, r, 0);
4286 update_window(win);
4287 store_float_geom(win, r);
4288 return;
4289 }
4290
4291 if (XGrabPointer(display, win->id, False, MOUSEMASK, GrabModeAsync,
4292 GrabModeAsync, None, XCreateFontCursor(display, XC_fleur),
4293 CurrentTime) != GrabSuccess)
4294 return;
4295
4296 /* get cursor offset from window root */
4297 if (!XQueryPointer(display, win->id, &rr, &cr, &x, &y, &wx, &wy, &mask))
4298 return;
4299
4300 do {
4301 XMaskEvent(display, MOUSEMASK | ExposureMask |
4302 SubstructureRedirectMask, &ev);
4303 switch (ev.type) {
4304 case ConfigureRequest:
4305 case Expose:
4306 case MapRequest:
4307 handler[ev.type](&ev);
4308 break;
4309 case MotionNotify:
4310 X(win) = ev.xmotion.x_root - wx - border_width;
4311 Y(win) = ev.xmotion.y_root - wy - border_width;
4312
4313 constrain_window(win, r, 0);
4314
4315 /* not free, don't sync more than 120 times / second */
4316 if ((ev.xmotion.time - time) > (1000 / 120) ) {
4317 time = ev.xmotion.time;
4318 XSync(display, False);
4319 update_window(win);
4320 }
4321 break;
4322 }
4323 } while (ev.type != ButtonRelease);
4324 if (time) {
4325 XSync(display, False);
4326 update_window(win);
4327 }
4328 store_float_geom(win,r);
4329 XUngrabPointer(display, CurrentTime);
4330
4331 /* drain events */
4332 drain_enter_notify();
4333 }
4334
4335 void
4336 move_step(struct swm_region *r, union arg *args)
4337 {
4338 struct ws_win *win = NULL;
4339
4340 if (r && r->ws && r->ws->focus)
4341 win = r->ws->focus;
4342 else
4343 return;
4344
4345 if (!(win->transient != 0 || win->floating != 0))
4346 return;
4347
4348 move(win, args);
4349 }
4350
4351
4352 /* user/key callable function IDs */
4353 enum keyfuncid {
4354 kf_cycle_layout,
4355 kf_flip_layout,
4356 kf_stack_reset,
4357 kf_master_shrink,
4358 kf_master_grow,
4359 kf_master_add,
4360 kf_master_del,
4361 kf_stack_inc,
4362 kf_stack_dec,
4363 kf_swap_main,
4364 kf_focus_next,
4365 kf_focus_prev,
4366 kf_swap_next,
4367 kf_swap_prev,
4368 kf_spawn_term,
4369 kf_spawn_menu,
4370 kf_quit,
4371 kf_restart,
4372 kf_focus_main,
4373 kf_ws_1,
4374 kf_ws_2,
4375 kf_ws_3,
4376 kf_ws_4,
4377 kf_ws_5,
4378 kf_ws_6,
4379 kf_ws_7,
4380 kf_ws_8,
4381 kf_ws_9,
4382 kf_ws_10,
4383 kf_ws_11,
4384 kf_ws_12,
4385 kf_ws_13,
4386 kf_ws_14,
4387 kf_ws_15,
4388 kf_ws_16,
4389 kf_ws_17,
4390 kf_ws_18,
4391 kf_ws_19,
4392 kf_ws_20,
4393 kf_ws_21,
4394 kf_ws_22,
4395 kf_ws_next,
4396 kf_ws_prev,
4397 kf_ws_next_all,
4398 kf_ws_prev_all,
4399 kf_ws_prior,
4400 kf_screen_next,
4401 kf_screen_prev,
4402 kf_mvws_1,
4403 kf_mvws_2,
4404 kf_mvws_3,
4405 kf_mvws_4,
4406 kf_mvws_5,
4407 kf_mvws_6,
4408 kf_mvws_7,
4409 kf_mvws_8,
4410 kf_mvws_9,
4411 kf_mvws_10,
4412 kf_mvws_11,
4413 kf_mvws_12,
4414 kf_mvws_13,
4415 kf_mvws_14,
4416 kf_mvws_15,
4417 kf_mvws_16,
4418 kf_mvws_17,
4419 kf_mvws_18,
4420 kf_mvws_19,
4421 kf_mvws_20,
4422 kf_mvws_21,
4423 kf_mvws_22,
4424 kf_bar_toggle,
4425 kf_wind_kill,
4426 kf_wind_del,
4427 kf_screenshot_all,
4428 kf_screenshot_wind,
4429 kf_float_toggle,
4430 kf_version,
4431 kf_spawn_lock,
4432 kf_spawn_initscr,
4433 kf_spawn_custom,
4434 kf_iconify,
4435 kf_uniconify,
4436 kf_raise_toggle,
4437 kf_button2,
4438 kf_width_shrink,
4439 kf_width_grow,
4440 kf_height_shrink,
4441 kf_height_grow,
4442 kf_move_left,
4443 kf_move_right,
4444 kf_move_up,
4445 kf_move_down,
4446 kf_name_workspace,
4447 kf_search_workspace,
4448 kf_search_win,
4449 kf_dumpwins, /* MUST BE LAST */
4450 kf_invalid
4451 };
4452
4453 /* key definitions */
4454 void
4455 dummykeyfunc(struct swm_region *r, union arg *args)
4456 {
4457 };
4458
4459 void
4460 legacyfunc(struct swm_region *r, union arg *args)
4461 {
4462 };
4463
4464 struct keyfunc {
4465 char name[SWM_FUNCNAME_LEN];
4466 void (*func)(struct swm_region *r, union arg *);
4467 union arg args;
4468 } keyfuncs[kf_invalid + 1] = {
4469 /* name function argument */
4470 { "cycle_layout", cycle_layout, {0} },
4471 { "flip_layout", stack_config, {.id = SWM_ARG_ID_FLIPLAYOUT} },
4472 { "stack_reset", stack_config, {.id = SWM_ARG_ID_STACKRESET} },
4473 { "master_shrink", stack_config, {.id = SWM_ARG_ID_MASTERSHRINK} },
4474 { "master_grow", stack_config, {.id = SWM_ARG_ID_MASTERGROW} },
4475 { "master_add", stack_config, {.id = SWM_ARG_ID_MASTERADD} },
4476 { "master_del", stack_config, {.id = SWM_ARG_ID_MASTERDEL} },
4477 { "stack_inc", stack_config, {.id = SWM_ARG_ID_STACKINC} },
4478 { "stack_dec", stack_config, {.id = SWM_ARG_ID_STACKDEC} },
4479 { "swap_main", swapwin, {.id = SWM_ARG_ID_SWAPMAIN} },
4480 { "focus_next", focus, {.id = SWM_ARG_ID_FOCUSNEXT} },
4481 { "focus_prev", focus, {.id = SWM_ARG_ID_FOCUSPREV} },
4482 { "swap_next", swapwin, {.id = SWM_ARG_ID_SWAPNEXT} },
4483 { "swap_prev", swapwin, {.id = SWM_ARG_ID_SWAPPREV} },
4484 { "spawn_term", spawnterm, {.argv = spawn_term} },
4485 { "spawn_menu", legacyfunc, {0} },
4486 { "quit", quit, {0} },
4487 { "restart", restart, {0} },
4488 { "focus_main", focus, {.id = SWM_ARG_ID_FOCUSMAIN} },
4489 { "ws_1", switchws, {.id = 0} },
4490 { "ws_2", switchws, {.id = 1} },
4491 { "ws_3", switchws, {.id = 2} },
4492 { "ws_4", switchws, {.id = 3} },
4493 { "ws_5", switchws, {.id = 4} },
4494 { "ws_6", switchws, {.id = 5} },
4495 { "ws_7", switchws, {.id = 6} },
4496 { "ws_8", switchws, {.id = 7} },
4497 { "ws_9", switchws, {.id = 8} },
4498 { "ws_10", switchws, {.id = 9} },
4499 { "ws_11", switchws, {.id = 10} },
4500 { "ws_12", switchws, {.id = 11} },
4501 { "ws_13", switchws, {.id = 12} },
4502 { "ws_14", switchws, {.id = 13} },
4503 { "ws_15", switchws, {.id = 14} },
4504 { "ws_16", switchws, {.id = 15} },
4505 { "ws_17", switchws, {.id = 16} },
4506 { "ws_18", switchws, {.id = 17} },
4507 { "ws_19", switchws, {.id = 18} },
4508 { "ws_20", switchws, {.id = 19} },
4509 { "ws_21", switchws, {.id = 20} },
4510 { "ws_22", switchws, {.id = 21} },
4511 { "ws_next", cyclews, {.id = SWM_ARG_ID_CYCLEWS_UP} },
4512 { "ws_prev", cyclews, {.id = SWM_ARG_ID_CYCLEWS_DOWN} },
4513 { "ws_next_all", cyclews, {.id = SWM_ARG_ID_CYCLEWS_UP_ALL} },
4514 { "ws_prev_all", cyclews, {.id = SWM_ARG_ID_CYCLEWS_DOWN_ALL} },
4515 { "ws_prior", priorws, {0} },
4516 { "screen_next", cyclescr, {.id = SWM_ARG_ID_CYCLESC_UP} },
4517 { "screen_prev", cyclescr, {.id = SWM_ARG_ID_CYCLESC_DOWN} },
4518 { "mvws_1", send_to_ws, {.id = 0} },
4519 { "mvws_2", send_to_ws, {.id = 1} },
4520 { "mvws_3", send_to_ws, {.id = 2} },
4521 { "mvws_4", send_to_ws, {.id = 3} },
4522 { "mvws_5", send_to_ws, {.id = 4} },
4523 { "mvws_6", send_to_ws, {.id = 5} },
4524 { "mvws_7", send_to_ws, {.id = 6} },
4525 { "mvws_8", send_to_ws, {.id = 7} },
4526 { "mvws_9", send_to_ws, {.id = 8} },
4527 { "mvws_10", send_to_ws, {.id = 9} },
4528 { "mvws_11", send_to_ws, {.id = 10} },
4529 { "mvws_12", send_to_ws, {.id = 11} },
4530 { "mvws_13", send_to_ws, {.id = 12} },
4531 { "mvws_14", send_to_ws, {.id = 13} },
4532 { "mvws_15", send_to_ws, {.id = 14} },
4533 { "mvws_16", send_to_ws, {.id = 15} },
4534 { "mvws_17", send_to_ws, {.id = 16} },
4535 { "mvws_18", send_to_ws, {.id = 17} },
4536 { "mvws_19", send_to_ws, {.id = 18} },
4537 { "mvws_20", send_to_ws, {.id = 19} },
4538 { "mvws_21", send_to_ws, {.id = 20} },
4539 { "mvws_22", send_to_ws, {.id = 21} },
4540 { "bar_toggle", bar_toggle, {0} },
4541 { "wind_kill", wkill, {.id = SWM_ARG_ID_KILLWINDOW} },
4542 { "wind_del", wkill, {.id = SWM_ARG_ID_DELETEWINDOW} },
4543 { "screenshot_all", legacyfunc, {0} },
4544 { "screenshot_wind", legacyfunc, {0} },
4545 { "float_toggle", floating_toggle,{0} },
4546 { "version", version, {0} },
4547 { "spawn_lock", legacyfunc, {0} },
4548 { "spawn_initscr", legacyfunc, {0} },
4549 { "spawn_custom", dummykeyfunc, {0} },
4550 { "iconify", iconify, {0} },
4551 { "uniconify", uniconify, {0} },
4552 { "raise_toggle", raise_toggle, {0} },
4553 { "button2", pressbutton, {2} },
4554 { "width_shrink", resize_step, {.id = SWM_ARG_ID_WIDTHSHRINK} },
4555 { "width_grow", resize_step, {.id = SWM_ARG_ID_WIDTHGROW} },
4556 { "height_shrink", resize_step, {.id = SWM_ARG_ID_HEIGHTSHRINK} },
4557 { "height_grow", resize_step, {.id = SWM_ARG_ID_HEIGHTGROW} },
4558 { "move_left", move_step, {.id = SWM_ARG_ID_MOVELEFT} },
4559 { "move_right", move_step, {.id = SWM_ARG_ID_MOVERIGHT} },
4560 { "move_up", move_step, {.id = SWM_ARG_ID_MOVEUP} },
4561 { "move_down", move_step, {.id = SWM_ARG_ID_MOVEDOWN} },
4562 { "name_workspace", name_workspace, {0} },
4563 { "search_workspace", search_workspace, {0} },
4564 { "search_win", search_win, {0} },
4565 { "dumpwins", dumpwins, {0} }, /* MUST BE LAST */
4566 { "invalid key func", NULL, {0} },
4567 };
4568 struct key {
4569 RB_ENTRY(key) entry;
4570 unsigned int mod;
4571 KeySym keysym;
4572 enum keyfuncid funcid;
4573 char *spawn_name;
4574 };
4575 RB_HEAD(key_list, key);
4576
4577 int
4578 key_cmp(struct key *kp1, struct key *kp2)
4579 {
4580 if (kp1->keysym < kp2->keysym)
4581 return (-1);
4582 if (kp1->keysym > kp2->keysym)
4583 return (1);
4584
4585 if (kp1->mod < kp2->mod)
4586 return (-1);
4587 if (kp1->mod > kp2->mod)
4588 return (1);
4589
4590 return (0);
4591 }
4592
4593 RB_GENERATE_STATIC(key_list, key, entry, key_cmp);
4594 struct key_list keys;
4595
4596 /* mouse */
4597 enum { client_click, root_click };
4598 struct button {
4599 unsigned int action;
4600 unsigned int mask;
4601 unsigned int button;
4602 void (*func)(struct ws_win *, union arg *);
4603 union arg args;
4604 } buttons[] = {
4605 /* action key mouse button func args */
4606 { client_click, MODKEY, Button3, resize, {.id = SWM_ARG_ID_DONTCENTER} },
4607 { client_click, MODKEY | ShiftMask, Button3, resize, {.id = SWM_ARG_ID_CENTER} },
4608 { client_click, MODKEY, Button1, move, {0} },
4609 };
4610
4611 void
4612 update_modkey(unsigned int mod)
4613 {
4614 int i;
4615 struct key *kp;
4616
4617 mod_key = mod;
4618 RB_FOREACH(kp, key_list, &keys)
4619 if (kp->mod & ShiftMask)
4620 kp->mod = mod | ShiftMask;
4621 else
4622 kp->mod = mod;
4623
4624 for (i = 0; i < LENGTH(buttons); i++)
4625 if (buttons[i].mask & ShiftMask)
4626 buttons[i].mask = mod | ShiftMask;
4627 else
4628 buttons[i].mask = mod;
4629 }
4630
4631 /* spawn */
4632 struct spawn_prog {
4633 TAILQ_ENTRY(spawn_prog) entry;
4634 char *name;
4635 int argc;
4636 char **argv;
4637 };
4638 TAILQ_HEAD(spawn_list, spawn_prog);
4639 struct spawn_list spawns = TAILQ_HEAD_INITIALIZER(spawns);
4640
4641 int
4642 spawn_expand(struct swm_region *r, union arg *args, char *spawn_name,
4643 char ***ret_args)
4644 {
4645 struct spawn_prog *prog = NULL;
4646 int i;
4647 char *ap, **real_args;
4648
4649 DNPRINTF(SWM_D_SPAWN, "spawn_expand: %s\n", spawn_name);
4650
4651 /* find program */
4652 TAILQ_FOREACH(prog, &spawns, entry) {
4653 if (!strcasecmp(spawn_name, prog->name))
4654 break;
4655 }
4656 if (prog == NULL) {
4657 warnx("spawn_custom: program %s not found", spawn_name);
4658 return (-1);
4659 }
4660
4661 /* make room for expanded args */
4662 if ((real_args = calloc(prog->argc + 1, sizeof(char *))) == NULL)
4663 err(1, "spawn_custom: calloc real_args");
4664
4665 /* expand spawn_args into real_args */
4666 for (i = 0; i < prog->argc; i++) {
4667 ap = prog->argv[i];
4668 DNPRINTF(SWM_D_SPAWN, "spawn_custom: raw arg: %s\n", ap);
4669 if (!strcasecmp(ap, "$bar_border")) {
4670 if ((real_args[i] =
4671 strdup(r->s->c[SWM_S_COLOR_BAR_BORDER].name))
4672 == NULL)
4673 err(1, "spawn_custom border color");
4674 } else if (!strcasecmp(ap, "$bar_color")) {
4675 if ((real_args[i] =
4676 strdup(r->s->c[SWM_S_COLOR_BAR].name))
4677 == NULL)
4678 err(1, "spawn_custom bar color");
4679 } else if (!strcasecmp(ap, "$bar_font")) {
4680 if ((real_args[i] = strdup(bar_fonts))
4681 == NULL)
4682 err(1, "spawn_custom bar fonts");
4683 } else if (!strcasecmp(ap, "$bar_font_color")) {
4684 if ((real_args[i] =
4685 strdup(r->s->c[SWM_S_COLOR_BAR_FONT].name))
4686 == NULL)
4687 err(1, "spawn_custom color font");
4688 } else if (!strcasecmp(ap, "$color_focus")) {
4689 if ((real_args[i] =
4690 strdup(r->s->c[SWM_S_COLOR_FOCUS].name))
4691 == NULL)
4692 err(1, "spawn_custom color focus");
4693 } else if (!strcasecmp(ap, "$color_unfocus")) {
4694 if ((real_args[i] =
4695 strdup(r->s->c[SWM_S_COLOR_UNFOCUS].name))
4696 == NULL)
4697 err(1, "spawn_custom color unfocus");
4698 } else {
4699 /* no match --> copy as is */
4700 if ((real_args[i] = strdup(ap)) == NULL)
4701 err(1, "spawn_custom strdup(ap)");
4702 }
4703 DNPRINTF(SWM_D_SPAWN, "spawn_custom: cooked arg: %s\n",
4704 real_args[i]);
4705 }
4706
4707 #ifdef SWM_DEBUG
4708 DNPRINTF(SWM_D_SPAWN, "spawn_custom: result: ");
4709 for (i = 0; i < prog->argc; i++)
4710 DNPRINTF(SWM_D_SPAWN, "\"%s\" ", real_args[i]);
4711 DNPRINTF(SWM_D_SPAWN, "\n");
4712 #endif
4713 *ret_args = real_args;
4714 return (prog->argc);
4715 }
4716
4717 void
4718 spawn_custom(struct swm_region *r, union arg *args, char *spawn_name)
4719 {
4720 union arg a;
4721 char **real_args;
4722 int spawn_argc, i;
4723
4724 if ((spawn_argc = spawn_expand(r, args, spawn_name, &real_args)) < 0)
4725 return;
4726 a.argv = real_args;
4727 if (fork() == 0)
4728 spawn(r->ws->idx, &a, 1);
4729
4730 for (i = 0; i < spawn_argc; i++)
4731 free(real_args[i]);
4732 free(real_args);
4733 }
4734
4735 void
4736 spawn_select(struct swm_region *r, union arg *args, char *spawn_name, int *pid)
4737 {
4738 union arg a;
4739 char **real_args;
4740 int i, spawn_argc;
4741
4742 if ((spawn_argc = spawn_expand(r, args, spawn_name, &real_args)) < 0)
4743 return;
4744 a.argv = real_args;
4745
4746 if (pipe(select_list_pipe) == -1)
4747 err(1, "pipe error");
4748 if (pipe(select_resp_pipe) == -1)
4749 err(1, "pipe error");
4750
4751 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
4752 err(1, "could not disable SIGPIPE");
4753 switch (*pid = fork()) {
4754 case -1:
4755 err(1, "cannot fork");
4756 break;
4757 case 0: /* child */
4758 if (dup2(select_list_pipe[0], 0) == -1)
4759 err(1, "dup2");
4760 if (dup2(select_resp_pipe[1], 1) == -1)
4761 err(1, "dup2");
4762 close(select_list_pipe[1]);
4763 close(select_resp_pipe[0]);
4764 spawn(r->ws->idx, &a, 0);
4765 break;
4766 default: /* parent */
4767 close(select_list_pipe[0]);
4768 close(select_resp_pipe[1]);
4769 break;
4770 }
4771
4772 for (i = 0; i < spawn_argc; i++)
4773 free(real_args[i]);
4774 free(real_args);
4775 }
4776
4777 void
4778 spawn_insert(char *name, char *args)
4779 {
4780 char *arg, *cp, *ptr;
4781 struct spawn_prog *sp;
4782
4783 DNPRINTF(SWM_D_SPAWN, "spawn_insert: %s\n", name);
4784
4785 if ((sp = calloc(1, sizeof *sp)) == NULL)
4786 err(1, "spawn_insert: malloc");
4787 if ((sp->name = strdup(name)) == NULL)
4788 err(1, "spawn_insert: strdup");
4789
4790 /* convert the arguments to an argument list */
4791 if ((ptr = cp = strdup(args)) == NULL)
4792 err(1, "spawn_insert: strdup");
4793 while ((arg = strsep(&ptr, " \t")) != NULL) {
4794 /* empty field; skip it */
4795 if (*arg == '\0')
4796 continue;
4797
4798 sp->argc++;
4799 if ((sp->argv = realloc(sp->argv, sp->argc *
4800 sizeof *sp->argv)) == NULL)
4801 err(1, "spawn_insert: realloc");
4802 if ((sp->argv[sp->argc - 1] = strdup(arg)) == NULL)
4803 err(1, "spawn_insert: strdup");
4804 }
4805 free(cp);
4806
4807 TAILQ_INSERT_TAIL(&spawns, sp, entry);
4808 DNPRINTF(SWM_D_SPAWN, "spawn_insert: leave\n");
4809 }
4810
4811 void
4812 spawn_remove(struct spawn_prog *sp)
4813 {
4814 int i;
4815
4816 DNPRINTF(SWM_D_SPAWN, "spawn_remove: %s\n", sp->name);
4817
4818 TAILQ_REMOVE(&spawns, sp, entry);
4819 for (i = 0; i < sp->argc; i++)
4820 free(sp->argv[i]);
4821 free(sp->argv);
4822 free(sp->name);
4823 free(sp);
4824
4825 DNPRINTF(SWM_D_SPAWN, "spawn_remove: leave\n");
4826 }
4827
4828 void
4829 spawn_replace(struct spawn_prog *sp, char *name, char *args)
4830 {
4831 DNPRINTF(SWM_D_SPAWN, "spawn_replace: %s [%s]\n", sp->name, name);
4832
4833 spawn_remove(sp);
4834 spawn_insert(name, args);
4835
4836 DNPRINTF(SWM_D_SPAWN, "spawn_replace: leave\n");
4837 }
4838
4839 void
4840 setspawn(char *name, char *args)
4841 {
4842 struct spawn_prog *sp;
4843
4844 DNPRINTF(SWM_D_SPAWN, "setspawn: %s\n", name);
4845
4846 if (name == NULL)
4847 return;
4848
4849 TAILQ_FOREACH(sp, &spawns, entry) {
4850 if (!strcmp(sp->name, name)) {
4851 if (*args == '\0')
4852 spawn_remove(sp);
4853 else
4854 spawn_replace(sp, name, args);
4855 DNPRINTF(SWM_D_SPAWN, "setspawn: leave\n");
4856 return;
4857 }
4858 }
4859 if (*args == '\0') {
4860 warnx("error: setspawn: cannot find program: %s", name);
4861 return;
4862 }
4863
4864 spawn_insert(name, args);
4865 DNPRINTF(SWM_D_SPAWN, "setspawn: leave\n");
4866 }
4867
4868 int
4869 setconfspawn(char *selector, char *value, int flags)
4870 {
4871 DNPRINTF(SWM_D_SPAWN, "setconfspawn: [%s] [%s]\n", selector, value);
4872
4873 setspawn(selector, value);
4874
4875 DNPRINTF(SWM_D_SPAWN, "setconfspawn: done\n");
4876 return (0);
4877 }
4878
4879 void
4880 setup_spawn(void)
4881 {
4882 setconfspawn("term", "xterm", 0);
4883 setconfspawn("screenshot_all", "screenshot.sh full", 0);
4884 setconfspawn("screenshot_wind", "screenshot.sh window", 0);
4885 setconfspawn("lock", "xlock", 0);
4886 setconfspawn("initscr", "initscreen.sh", 0);
4887 setconfspawn("menu", "dmenu_run"
4888 " -fn $bar_font"
4889 " -nb $bar_color"
4890 " -nf $bar_font_color"
4891 " -sb $bar_border"
4892 " -sf $bar_color", 0);
4893 setconfspawn("search", "dmenu"
4894 " -i"
4895 " -fn $bar_font"
4896 " -nb $bar_color"
4897 " -nf $bar_font_color"
4898 " -sb $bar_border"
4899 " -sf $bar_color", 0);
4900 setconfspawn("name_workspace", "dmenu"
4901 " -p Workspace"
4902 " -fn $bar_font"
4903 " -nb $bar_color"
4904 " -nf $bar_font_color"
4905 " -sb $bar_border"
4906 " -sf $bar_color", 0);
4907 }
4908
4909 /* key bindings */
4910 #define SWM_MODNAME_SIZE 32
4911 #define SWM_KEY_WS "\n+ \t"
4912 int
4913 parsekeys(char *keystr, unsigned int currmod, unsigned int *mod, KeySym *ks)
4914 {
4915 char *cp, *name;
4916 KeySym uks;
4917 DNPRINTF(SWM_D_KEY, "parsekeys: enter [%s]\n", keystr);
4918 if (mod == NULL || ks == NULL) {
4919 DNPRINTF(SWM_D_KEY, "parsekeys: no mod or key vars\n");
4920 return (1);
4921 }
4922 if (keystr == NULL || strlen(keystr) == 0) {
4923 DNPRINTF(SWM_D_KEY, "parsekeys: no keystr\n");
4924 return (1);
4925 }
4926 cp = keystr;
4927 *ks = NoSymbol;
4928 *mod = 0;
4929 while ((name = strsep(&cp, SWM_KEY_WS)) != NULL) {
4930 DNPRINTF(SWM_D_KEY, "parsekeys: key [%s]\n", name);
4931 if (cp)
4932 cp += (long)strspn(cp, SWM_KEY_WS);
4933 if (strncasecmp(name, "MOD", SWM_MODNAME_SIZE) == 0)
4934 *mod |= currmod;
4935 else if (!strncasecmp(name, "Mod1", SWM_MODNAME_SIZE))
4936 *mod |= Mod1Mask;
4937 else if (!strncasecmp(name, "Mod2", SWM_MODNAME_SIZE))
4938 *mod += Mod2Mask;
4939 else if (!strncmp(name, "Mod3", SWM_MODNAME_SIZE))
4940 *mod |= Mod3Mask;
4941 else if (!strncmp(name, "Mod4", SWM_MODNAME_SIZE))
4942 *mod |= Mod4Mask;
4943 else if (strncasecmp(name, "SHIFT", SWM_MODNAME_SIZE) == 0)
4944 *mod |= ShiftMask;
4945 else if (strncasecmp(name, "CONTROL", SWM_MODNAME_SIZE) == 0)
4946 *mod |= ControlMask;
4947 else {
4948 *ks = XStringToKeysym(name);
4949 XConvertCase(*ks, ks, &uks);
4950 if (ks == NoSymbol) {
4951 DNPRINTF(SWM_D_KEY,
4952 "parsekeys: invalid key %s\n",
4953 name);
4954 return (1);
4955 }
4956 }
4957 }
4958 DNPRINTF(SWM_D_KEY, "parsekeys: leave ok\n");
4959 return (0);
4960 }
4961
4962 char *
4963 strdupsafe(char *str)
4964 {
4965 if (str == NULL)
4966 return (NULL);
4967 else
4968 return (strdup(str));
4969 }
4970
4971 void
4972 key_insert(unsigned int mod, KeySym ks, enum keyfuncid kfid, char *spawn_name)
4973 {
4974 struct key *kp;
4975
4976 DNPRINTF(SWM_D_KEY, "key_insert: enter %s [%s]\n",
4977 keyfuncs[kfid].name, spawn_name);
4978
4979 if ((kp = malloc(sizeof *kp)) == NULL)
4980 err(1, "key_insert: malloc");
4981
4982 kp->mod = mod;
4983 kp->keysym = ks;
4984 kp->funcid = kfid;
4985 kp->spawn_name = strdupsafe(spawn_name);
4986 RB_INSERT(key_list, &keys, kp);
4987
4988 DNPRINTF(SWM_D_KEY, "key_insert: leave\n");
4989 }
4990
4991 struct key *
4992 key_lookup(unsigned int mod, KeySym ks)
4993 {
4994 struct key kp;
4995
4996 kp.keysym = ks;
4997 kp.mod = mod;
4998
4999 return (RB_FIND(key_list, &keys, &kp));
5000 }
5001
5002 void
5003 key_remove(struct key *kp)
5004 {
5005 DNPRINTF(SWM_D_KEY, "key_remove: %s\n", keyfuncs[kp->funcid].name);
5006
5007 RB_REMOVE(key_list, &keys, kp);
5008 free(kp->spawn_name);
5009 free(kp);
5010
5011 DNPRINTF(SWM_D_KEY, "key_remove: leave\n");
5012 }
5013
5014 void
5015 key_replace(struct key *kp, unsigned int mod, KeySym ks, enum keyfuncid kfid,
5016 char *spawn_name)
5017 {
5018 DNPRINTF(SWM_D_KEY, "key_replace: %s [%s]\n", keyfuncs[kp->funcid].name,
5019 spawn_name);
5020
5021 key_remove(kp);
5022 key_insert(mod, ks, kfid, spawn_name);
5023
5024 DNPRINTF(SWM_D_KEY, "key_replace: leave\n");
5025 }
5026
5027 void
5028 setkeybinding(unsigned int mod, KeySym ks, enum keyfuncid kfid,
5029 char *spawn_name)
5030 {
5031 struct key *kp;
5032
5033 DNPRINTF(SWM_D_KEY, "setkeybinding: enter %s [%s]\n",
5034 keyfuncs[kfid].name, spawn_name);
5035
5036 if ((kp = key_lookup(mod, ks)) != NULL) {
5037 if (kfid == kf_invalid)
5038 key_remove(kp);
5039 else
5040 key_replace(kp, mod, ks, kfid, spawn_name);
5041 DNPRINTF(SWM_D_KEY, "setkeybinding: leave\n");
5042 return;
5043 }
5044 if (kfid == kf_invalid) {
5045 warnx("error: setkeybinding: cannot find mod/key combination");
5046 DNPRINTF(SWM_D_KEY, "setkeybinding: leave\n");
5047 return;
5048 }
5049
5050 key_insert(mod, ks, kfid, spawn_name);
5051 DNPRINTF(SWM_D_KEY, "setkeybinding: leave\n");
5052 }
5053
5054 int
5055 setconfbinding(char *selector, char *value, int flags)
5056 {
5057 enum keyfuncid kfid;
5058 unsigned int mod;
5059 KeySym ks;
5060 struct spawn_prog *sp;
5061 DNPRINTF(SWM_D_KEY, "setconfbinding: enter\n");
5062 if (selector == NULL) {
5063 DNPRINTF(SWM_D_KEY, "setconfbinding: unbind %s\n", value);
5064 if (parsekeys(value, mod_key, &mod, &ks) == 0) {
5065 kfid = kf_invalid;
5066 setkeybinding(mod, ks, kfid, NULL);
5067 return (0);
5068 } else
5069 return (1);
5070 }
5071 /* search by key function name */
5072 for (kfid = 0; kfid < kf_invalid; (kfid)++) {
5073 if (strncasecmp(selector, keyfuncs[kfid].name,
5074 SWM_FUNCNAME_LEN) == 0) {
5075 DNPRINTF(SWM_D_KEY, "setconfbinding: %s: match\n",
5076 selector);
5077 if (parsekeys(value, mod_key, &mod, &ks) == 0) {
5078 setkeybinding(mod, ks, kfid, NULL);
5079 return (0);
5080 } else
5081 return (1);
5082 }
5083 }
5084 /* search by custom spawn name */
5085 TAILQ_FOREACH(sp, &spawns, entry) {
5086 if (strcasecmp(selector, sp->name) == 0) {
5087 DNPRINTF(SWM_D_KEY, "setconfbinding: %s: match\n",
5088 selector);
5089 if (parsekeys(value, mod_key, &mod, &ks) == 0) {
5090 setkeybinding(mod, ks, kf_spawn_custom,
5091 sp->name);
5092 return (0);
5093 } else
5094 return (1);
5095 }
5096 }
5097 DNPRINTF(SWM_D_KEY, "setconfbinding: no match\n");
5098 return (1);
5099 }
5100
5101 void
5102 setup_keys(void)
5103 {
5104 setkeybinding(MODKEY, XK_space, kf_cycle_layout,NULL);
5105 setkeybinding(MODKEY|ShiftMask, XK_backslash, kf_flip_layout, NULL);
5106 setkeybinding(MODKEY|ShiftMask, XK_space, kf_stack_reset, NULL);
5107 setkeybinding(MODKEY, XK_h, kf_master_shrink,NULL);
5108 setkeybinding(MODKEY, XK_l, kf_master_grow, NULL);
5109 setkeybinding(MODKEY, XK_comma, kf_master_add, NULL);
5110 setkeybinding(MODKEY, XK_period, kf_master_del, NULL);
5111 setkeybinding(MODKEY|ShiftMask, XK_comma, kf_stack_inc, NULL);
5112 setkeybinding(MODKEY|ShiftMask, XK_period, kf_stack_dec, NULL);
5113 setkeybinding(MODKEY, XK_Return, kf_swap_main, NULL);
5114 setkeybinding(MODKEY, XK_j, kf_focus_next, NULL);
5115 setkeybinding(MODKEY, XK_k, kf_focus_prev, NULL);
5116 setkeybinding(MODKEY|ShiftMask, XK_j, kf_swap_next, NULL);
5117 setkeybinding(MODKEY|ShiftMask, XK_k, kf_swap_prev, NULL);
5118 setkeybinding(MODKEY|ShiftMask, XK_Return, kf_spawn_term, NULL);
5119 setkeybinding(MODKEY, XK_p, kf_spawn_custom,"menu");
5120 setkeybinding(MODKEY|ShiftMask, XK_q, kf_quit, NULL);
5121 setkeybinding(MODKEY, XK_q, kf_restart, NULL);
5122 setkeybinding(MODKEY, XK_m, kf_focus_main, NULL);
5123 setkeybinding(MODKEY, XK_1, kf_ws_1, NULL);
5124 setkeybinding(MODKEY, XK_2, kf_ws_2, NULL);
5125 setkeybinding(MODKEY, XK_3, kf_ws_3, NULL);
5126 setkeybinding(MODKEY, XK_4, kf_ws_4, NULL);
5127 setkeybinding(MODKEY, XK_5, kf_ws_5, NULL);
5128 setkeybinding(MODKEY, XK_6, kf_ws_6, NULL);
5129 setkeybinding(MODKEY, XK_7, kf_ws_7, NULL);
5130 setkeybinding(MODKEY, XK_8, kf_ws_8, NULL);
5131 setkeybinding(MODKEY, XK_9, kf_ws_9, NULL);
5132 setkeybinding(MODKEY, XK_0, kf_ws_10, NULL);
5133 setkeybinding(MODKEY, XK_F1, kf_ws_11, NULL);
5134 setkeybinding(MODKEY, XK_F2, kf_ws_12, NULL);
5135 setkeybinding(MODKEY, XK_F3, kf_ws_13, NULL);
5136 setkeybinding(MODKEY, XK_F4, kf_ws_14, NULL);
5137 setkeybinding(MODKEY, XK_F5, kf_ws_15, NULL);
5138 setkeybinding(MODKEY, XK_F6, kf_ws_16, NULL);
5139 setkeybinding(MODKEY, XK_F7, kf_ws_17, NULL);
5140 setkeybinding(MODKEY, XK_F8, kf_ws_18, NULL);
5141 setkeybinding(MODKEY, XK_F9, kf_ws_19, NULL);
5142 setkeybinding(MODKEY, XK_F10, kf_ws_20, NULL);
5143 setkeybinding(MODKEY, XK_F11, kf_ws_21, NULL);
5144 setkeybinding(MODKEY, XK_F12, kf_ws_22, NULL);
5145 setkeybinding(MODKEY, XK_Right, kf_ws_next, NULL);
5146 setkeybinding(MODKEY, XK_Left, kf_ws_prev, NULL);
5147 setkeybinding(MODKEY, XK_Up, kf_ws_next_all, NULL);
5148 setkeybinding(MODKEY, XK_Down, kf_ws_prev_all, NULL);
5149 setkeybinding(MODKEY, XK_a, kf_ws_prior, NULL);
5150 setkeybinding(MODKEY|ShiftMask, XK_Right, kf_screen_next, NULL);
5151 setkeybinding(MODKEY|ShiftMask, XK_Left, kf_screen_prev, NULL);
5152 setkeybinding(MODKEY|ShiftMask, XK_1, kf_mvws_1, NULL);
5153 setkeybinding(MODKEY|ShiftMask, XK_2, kf_mvws_2, NULL);
5154 setkeybinding(MODKEY|ShiftMask, XK_3, kf_mvws_3, NULL);
5155 setkeybinding(MODKEY|ShiftMask, XK_4, kf_mvws_4, NULL);
5156 setkeybinding(MODKEY|ShiftMask, XK_5, kf_mvws_5, NULL);
5157 setkeybinding(MODKEY|ShiftMask, XK_6, kf_mvws_6, NULL);
5158 setkeybinding(MODKEY|ShiftMask, XK_7, kf_mvws_7, NULL);
5159 setkeybinding(MODKEY|ShiftMask, XK_8, kf_mvws_8, NULL);
5160 setkeybinding(MODKEY|ShiftMask, XK_9, kf_mvws_9, NULL);
5161 setkeybinding(MODKEY|ShiftMask, XK_0, kf_mvws_10, NULL);
5162 setkeybinding(MODKEY|ShiftMask, XK_F1, kf_mvws_11, NULL);
5163 setkeybinding(MODKEY|ShiftMask, XK_F2, kf_mvws_12, NULL);
5164 setkeybinding(MODKEY|ShiftMask, XK_F3, kf_mvws_13, NULL);
5165 setkeybinding(MODKEY|ShiftMask, XK_F4, kf_mvws_14, NULL);
5166 setkeybinding(MODKEY|ShiftMask, XK_F5, kf_mvws_15, NULL);
5167 setkeybinding(MODKEY|ShiftMask, XK_F6, kf_mvws_16, NULL);
5168 setkeybinding(MODKEY|ShiftMask, XK_F7, kf_mvws_17, NULL);
5169 setkeybinding(MODKEY|ShiftMask, XK_F8, kf_mvws_18, NULL);
5170 setkeybinding(MODKEY|ShiftMask, XK_F9, kf_mvws_19, NULL);
5171 setkeybinding(MODKEY|ShiftMask, XK_F10, kf_mvws_20, NULL);
5172 setkeybinding(MODKEY|ShiftMask, XK_F11, kf_mvws_21, NULL);
5173 setkeybinding(MODKEY|ShiftMask, XK_F12, kf_mvws_22, NULL);
5174 setkeybinding(MODKEY, XK_b, kf_bar_toggle, NULL);
5175 setkeybinding(MODKEY, XK_Tab, kf_focus_next, NULL);
5176 setkeybinding(MODKEY|ShiftMask, XK_Tab, kf_focus_prev, NULL);
5177 setkeybinding(MODKEY|ShiftMask, XK_x, kf_wind_kill, NULL);
5178 setkeybinding(MODKEY, XK_x, kf_wind_del, NULL);
5179 setkeybinding(MODKEY, XK_s, kf_spawn_custom,"screenshot_all");
5180 setkeybinding(MODKEY|ShiftMask, XK_s, kf_spawn_custom,"screenshot_wind");
5181 setkeybinding(MODKEY, XK_t, kf_float_toggle,NULL);
5182 setkeybinding(MODKEY|ShiftMask, XK_v, kf_version, NULL);
5183 setkeybinding(MODKEY|ShiftMask, XK_Delete, kf_spawn_custom,"lock");
5184 setkeybinding(MODKEY|ShiftMask, XK_i, kf_spawn_custom,"initscr");
5185 setkeybinding(MODKEY, XK_w, kf_iconify, NULL);
5186 setkeybinding(MODKEY|ShiftMask, XK_w, kf_uniconify, NULL);
5187 setkeybinding(MODKEY|ShiftMask, XK_r, kf_raise_toggle,NULL);
5188 setkeybinding(MODKEY, XK_v, kf_button2, NULL);
5189 setkeybinding(MODKEY, XK_equal, kf_width_grow, NULL);
5190 setkeybinding(MODKEY, XK_minus, kf_width_shrink,NULL);
5191 setkeybinding(MODKEY|ShiftMask, XK_equal, kf_height_grow, NULL);
5192 setkeybinding(MODKEY|ShiftMask, XK_minus, kf_height_shrink,NULL);
5193 setkeybinding(MODKEY, XK_bracketleft, kf_move_left, NULL);
5194 setkeybinding(MODKEY, XK_bracketright,kf_move_right, NULL);
5195 setkeybinding(MODKEY|ShiftMask, XK_bracketleft, kf_move_up, NULL);
5196 setkeybinding(MODKEY|ShiftMask, XK_bracketright,kf_move_down, NULL);
5197 setkeybinding(MODKEY|ShiftMask, XK_slash, kf_name_workspace,NULL);
5198 setkeybinding(MODKEY, XK_slash, kf_search_workspace,NULL);
5199 setkeybinding(MODKEY, XK_f, kf_search_win, NULL);
5200 #ifdef SWM_DEBUG
5201 setkeybinding(MODKEY|ShiftMask, XK_d, kf_dumpwins, NULL);
5202 #endif
5203 }
5204
5205 void
5206 clear_keys(void)
5207 {
5208 struct key *kp;
5209
5210 while (RB_EMPTY(&keys) == 0) {
5211 kp = RB_ROOT(&keys);
5212 key_remove(kp);
5213 }
5214 }
5215
5216 int
5217 setkeymapping(char *selector, char *value, int flags)
5218 {
5219 char keymapping_file[PATH_MAX];
5220 DNPRINTF(SWM_D_KEY, "setkeymapping: enter\n");
5221 if (value[0] == '~')
5222 snprintf(keymapping_file, sizeof keymapping_file, "%s/%s",
5223 pwd->pw_dir, &value[1]);
5224 else
5225 strlcpy(keymapping_file, value, sizeof keymapping_file);
5226 clear_keys();
5227 /* load new key bindings; if it fails, revert to default bindings */
5228 if (conf_load(keymapping_file, SWM_CONF_KEYMAPPING)) {
5229 clear_keys();
5230 setup_keys();
5231 }
5232 DNPRINTF(SWM_D_KEY, "setkeymapping: leave\n");
5233 return (0);
5234 }
5235
5236 void
5237 updatenumlockmask(void)
5238 {
5239 unsigned int i, j;
5240 XModifierKeymap *modmap;
5241
5242 DNPRINTF(SWM_D_MISC, "updatenumlockmask\n");
5243 numlockmask = 0;
5244 modmap = XGetModifierMapping(display);
5245 for (i = 0; i < 8; i++)
5246 for (j = 0; j < modmap->max_keypermod; j++)
5247 if (modmap->modifiermap[i * modmap->max_keypermod + j]
5248 == XKeysymToKeycode(display, XK_Num_Lock))
5249 numlockmask = (1 << i);
5250
5251 XFreeModifiermap(modmap);
5252 }
5253
5254 void
5255 grabkeys(void)
5256 {
5257 unsigned int j, k;
5258 KeyCode code;
5259 unsigned int modifiers[] =
5260 { 0, LockMask, numlockmask, numlockmask | LockMask };
5261 struct key *kp;
5262
5263 DNPRINTF(SWM_D_MISC, "grabkeys\n");
5264 updatenumlockmask();
5265
5266 for (k = 0; k < ScreenCount(display); k++) {
5267 if (TAILQ_EMPTY(&screens[k].rl))
5268 continue;
5269 XUngrabKey(display, AnyKey, AnyModifier, screens[k].root);
5270 RB_FOREACH(kp, key_list, &keys) {
5271 if ((code = XKeysymToKeycode(display, kp->keysym)))
5272 for (j = 0; j < LENGTH(modifiers); j++)
5273 XGrabKey(display, code,
5274 kp->mod | modifiers[j],
5275 screens[k].root, True,
5276 GrabModeAsync, GrabModeAsync);
5277 }
5278 }
5279 }
5280
5281 void
5282 grabbuttons(struct ws_win *win, int focused)
5283 {
5284 unsigned int i, j;
5285 unsigned int modifiers[] =
5286 { 0, LockMask, numlockmask, numlockmask|LockMask };
5287
5288 updatenumlockmask();
5289 XUngrabButton(display, AnyButton, AnyModifier, win->id);
5290 if (focused) {
5291 for (i = 0; i < LENGTH(buttons); i++)
5292 if (buttons[i].action == client_click)
5293 for (j = 0; j < LENGTH(modifiers); j++)
5294 XGrabButton(display, buttons[i].button,
5295 buttons[i].mask | modifiers[j],
5296 win->id, False, BUTTONMASK,
5297 GrabModeAsync, GrabModeSync, None,
5298 None);
5299 } else
5300 XGrabButton(display, AnyButton, AnyModifier, win->id, False,
5301 BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
5302 }
5303
5304 const char *quirkname[] = {
5305 "NONE", /* config string for "no value" */
5306 "FLOAT",
5307 "TRANSSZ",
5308 "ANYWHERE",
5309 "XTERM_FONTADJ",
5310 "FULLSCREEN",
5311 "FOCUSPREV",
5312 };
5313
5314 /* SWM_Q_WS: retain '|' for back compat for now (2009-08-11) */
5315 #define SWM_Q_WS "\n|+ \t"
5316 int
5317 parsequirks(char *qstr, unsigned long *quirk)
5318 {
5319 char *cp, *name;
5320 int i;
5321
5322 if (quirk == NULL)
5323 return (1);
5324
5325 cp = qstr;
5326 *quirk = 0;
5327 while ((name = strsep(&cp, SWM_Q_WS)) != NULL) {
5328 if (cp)
5329 cp += (long)strspn(cp, SWM_Q_WS);
5330 for (i = 0; i < LENGTH(quirkname); i++) {
5331 if (!strncasecmp(name, quirkname[i], SWM_QUIRK_LEN)) {
5332 DNPRINTF(SWM_D_QUIRK,
5333 "parsequirks: %s\n", name);
5334 if (i == 0) {
5335 *quirk = 0;
5336 return (0);
5337 }
5338 *quirk |= 1 << (i-1);
5339 break;
5340 }
5341 }
5342 if (i >= LENGTH(quirkname)) {
5343 DNPRINTF(SWM_D_QUIRK,
5344 "parsequirks: invalid quirk [%s]\n", name);
5345 return (1);
5346 }
5347 }
5348 return (0);
5349 }
5350
5351 void
5352 quirk_insert(const char *class, const char *name, unsigned long quirk)
5353 {
5354 struct quirk *qp;
5355
5356 DNPRINTF(SWM_D_QUIRK, "quirk_insert: %s:%s [%lu]\n", class, name,
5357 quirk);
5358
5359 if ((qp = malloc(sizeof *qp)) == NULL)
5360 err(1, "quirk_insert: malloc");
5361 if ((qp->class = strdup(class)) == NULL)
5362 err(1, "quirk_insert: strdup");
5363 if ((qp->name = strdup(name)) == NULL)
5364 err(1, "quirk_insert: strdup");
5365
5366 qp->quirk = quirk;
5367 TAILQ_INSERT_TAIL(&quirks, qp, entry);
5368
5369 DNPRINTF(SWM_D_QUIRK, "quirk_insert: leave\n");
5370 }
5371
5372 void
5373 quirk_remove(struct quirk *qp)
5374 {
5375 DNPRINTF(SWM_D_QUIRK, "quirk_remove: %s:%s [%lu]\n", qp->class,
5376 qp->name, qp->quirk);
5377
5378 TAILQ_REMOVE(&quirks, qp, entry);
5379 free(qp->class);
5380 free(qp->name);
5381 free(qp);
5382
5383 DNPRINTF(SWM_D_QUIRK, "quirk_remove: leave\n");
5384 }
5385
5386 void
5387 quirk_replace(struct quirk *qp, const char *class, const char *name,
5388 unsigned long quirk)
5389 {
5390 DNPRINTF(SWM_D_QUIRK, "quirk_replace: %s:%s [%lu]\n", qp->class,
5391 qp->name, qp->quirk);
5392
5393 quirk_remove(qp);
5394 quirk_insert(class, name, quirk);
5395
5396 DNPRINTF(SWM_D_QUIRK, "quirk_replace: leave\n");
5397 }
5398
5399 void
5400 setquirk(const char *class, const char *name, unsigned long quirk)
5401 {
5402 struct quirk *qp;
5403
5404 DNPRINTF(SWM_D_QUIRK, "setquirk: enter %s:%s [%lu]\n", class, name,
5405 quirk);
5406
5407 TAILQ_FOREACH(qp, &quirks, entry) {
5408 if (!strcmp(qp->class, class) && !strcmp(qp->name, name)) {
5409 if (!quirk)
5410 quirk_remove(qp);
5411 else
5412 quirk_replace(qp, class, name, quirk);
5413 DNPRINTF(SWM_D_QUIRK, "setquirk: leave\n");
5414 return;
5415 }
5416 }
5417 if (!quirk) {
5418 warnx("error: setquirk: cannot find class/name combination");
5419 return;
5420 }
5421
5422 quirk_insert(class, name, quirk);
5423 DNPRINTF(SWM_D_QUIRK, "setquirk: leave\n");
5424 }
5425
5426 int
5427 setconfquirk(char *selector, char *value, int flags)
5428 {
5429 char *cp, *class, *name;
5430 int retval;
5431 unsigned long quirks;
5432 if (selector == NULL)
5433 return (0);
5434 if ((cp = strchr(selector, ':')) == NULL)
5435 return (0);
5436 *cp = '\0';
5437 class = selector;
5438 name = cp + 1;
5439 if ((retval = parsequirks(value, &quirks)) == 0)
5440 setquirk(class, name, quirks);
5441 return (retval);
5442 }
5443
5444 void
5445 setup_quirks(void)
5446 {
5447 setquirk("MPlayer", "xv", SWM_Q_FLOAT | SWM_Q_FULLSCREEN | SWM_Q_FOCUSPREV);
5448 setquirk("OpenOffice.org 3.2", "VCLSalFrame", SWM_Q_FLOAT);
5449 setquirk("Firefox-bin", "firefox-bin", SWM_Q_TRANSSZ);
5450 setquirk("Firefox", "Dialog", SWM_Q_FLOAT);
5451 setquirk("Gimp", "gimp", SWM_Q_FLOAT | SWM_Q_ANYWHERE);
5452 setquirk("XTerm", "xterm", SWM_Q_XTERM_FONTADJ);
5453 setquirk("xine", "Xine Window", SWM_Q_FLOAT | SWM_Q_ANYWHERE);
5454 setquirk("Xitk", "Xitk Combo", SWM_Q_FLOAT | SWM_Q_ANYWHERE);
5455 setquirk("xine", "xine Panel", SWM_Q_FLOAT | SWM_Q_ANYWHERE);
5456 setquirk("Xitk", "Xine Window", SWM_Q_FLOAT | SWM_Q_ANYWHERE);
5457 setquirk("xine", "xine Video Fullscreen Window", SWM_Q_FULLSCREEN | SWM_Q_FLOAT);
5458 setquirk("pcb", "pcb", SWM_Q_FLOAT);
5459 setquirk("SDL_App", "SDL_App", SWM_Q_FLOAT | SWM_Q_FULLSCREEN);
5460 }
5461
5462 /* conf file stuff */
5463 #define SWM_CONF_FILE "spectrwm.conf"
5464 #define SWM_CONF_FILE_OLD "scrotwm.conf"
5465
5466 enum { SWM_S_BAR_DELAY, SWM_S_BAR_ENABLED, SWM_S_BAR_BORDER_WIDTH,
5467 SWM_S_STACK_ENABLED, SWM_S_CLOCK_ENABLED, SWM_S_CLOCK_FORMAT,
5468 SWM_S_CYCLE_EMPTY, SWM_S_CYCLE_VISIBLE, SWM_S_WORKSPACE_LIMIT,
5469 SWM_S_SS_ENABLED, SWM_S_TERM_WIDTH, SWM_S_TITLE_CLASS_ENABLED,
5470 SWM_S_TITLE_NAME_ENABLED, SWM_S_WINDOW_NAME_ENABLED,
5471 SWM_S_URGENT_ENABLED, SWM_S_FOCUS_MODE, SWM_S_FOCUS_CLOSE,
5472 SWM_S_FOCUS_CLOSE_WRAP, SWM_S_FOCUS_DEFAULT, SWM_S_SPAWN_ORDER,
5473 SWM_S_DISABLE_BORDER, SWM_S_BORDER_WIDTH, SWM_S_BAR_FONT,
5474 SWM_S_BAR_ACTION, SWM_S_SPAWN_TERM, SWM_S_SS_APP, SWM_S_DIALOG_RATIO,
5475 SWM_S_BAR_AT_BOTTOM, SWM_S_VERBOSE_LAYOUT, SWM_S_BAR_JUSTIFY,
5476 SWM_S_BAR_FORMAT
5477 };
5478
5479 int
5480 setconfvalue(char *selector, char *value, int flags)
5481 {
5482 int i;
5483 char *b;
5484
5485 switch (flags) {
5486 case SWM_S_BAR_DELAY:
5487 bar_delay = atoi(value);
5488 break;
5489 case SWM_S_BAR_ENABLED:
5490 bar_enabled = atoi(value);
5491 break;
5492 case SWM_S_BAR_BORDER_WIDTH:
5493 bar_border_width = atoi(value);
5494 break;
5495 case SWM_S_BAR_AT_BOTTOM:
5496 bar_at_bottom = atoi(value);
5497 break;
5498 case SWM_S_BAR_JUSTIFY:
5499 if (!strcmp(value, "left"))
5500 bar_justify = SWM_BAR_JUSTIFY_LEFT;
5501 else if (!strcmp(value, "center"))
5502 bar_justify = SWM_BAR_JUSTIFY_CENTER;
5503 else if (!strcmp(value, "right"))
5504 bar_justify = SWM_BAR_JUSTIFY_RIGHT;
5505 else
5506 errx(1, "invalid bar_justify");
5507 break;
5508 case SWM_S_BAR_FORMAT:
5509 free(bar_format);
5510 if ((bar_format = strdup(value)) == NULL)
5511 err(1, "setconfvalue: bar_format");
5512 break;
5513 case SWM_S_STACK_ENABLED:
5514 stack_enabled = atoi(value);
5515 break;
5516 case SWM_S_CLOCK_ENABLED:
5517 clock_enabled = atoi(value);
5518 break;
5519 case SWM_S_CLOCK_FORMAT:
5520 #ifndef SWM_DENY_CLOCK_FORMAT
5521 free(clock_format);
5522 if ((clock_format = strdup(value)) == NULL)
5523 err(1, "setconfvalue: clock_format");
5524 #endif
5525 break;
5526 case SWM_S_CYCLE_EMPTY:
5527 cycle_empty = atoi(value);
5528 break;
5529 case SWM_S_CYCLE_VISIBLE:
5530 cycle_visible = atoi(value);
5531 break;
5532 case SWM_S_WORKSPACE_LIMIT:
5533 workspace_limit = atoi(value);
5534 if (workspace_limit > SWM_WS_MAX)
5535 workspace_limit = SWM_WS_MAX;
5536 else if (workspace_limit < 1)
5537 workspace_limit = 1;
5538 break;
5539 case SWM_S_SS_ENABLED:
5540 ss_enabled = atoi(value);
5541 break;
5542 case SWM_S_TERM_WIDTH:
5543 term_width = atoi(value);
5544 break;
5545 case SWM_S_TITLE_CLASS_ENABLED:
5546 title_class_enabled = atoi(value);
5547 break;
5548 case SWM_S_WINDOW_NAME_ENABLED:
5549 window_name_enabled = atoi(value);
5550 break;
5551 case SWM_S_TITLE_NAME_ENABLED:
5552 title_name_enabled = atoi(value);
5553 break;
5554 case SWM_S_URGENT_ENABLED:
5555 urgent_enabled = atoi(value);
5556 break;
5557 case SWM_S_FOCUS_MODE:
5558 if (!strcmp(value, "default"))
5559 focus_mode = SWM_FOCUS_DEFAULT;
5560 else if (!strcmp(value, "follow_cursor"))
5561 focus_mode = SWM_FOCUS_FOLLOW;
5562 else if (!strcmp(value, "synergy"))
5563 focus_mode = SWM_FOCUS_SYNERGY;
5564 else
5565 errx(1, "focus_mode");
5566 break;
5567 case SWM_S_FOCUS_CLOSE:
5568 if (!strcmp(value, "first"))
5569 focus_close = SWM_STACK_BOTTOM;
5570 else if (!strcmp(value, "last"))
5571 focus_close = SWM_STACK_TOP;
5572 else if (!strcmp(value, "next"))
5573 focus_close = SWM_STACK_ABOVE;
5574 else if (!strcmp(value, "previous"))
5575 focus_close = SWM_STACK_BELOW;
5576 else
5577 errx(1, "focus_close");
5578 break;
5579 case SWM_S_FOCUS_CLOSE_WRAP:
5580 focus_close_wrap = atoi(value);
5581 break;
5582 case SWM_S_FOCUS_DEFAULT:
5583 if (!strcmp(value, "last"))
5584 focus_default = SWM_STACK_TOP;
5585 else if (!strcmp(value, "first"))
5586 focus_default = SWM_STACK_BOTTOM;
5587 else
5588 errx(1, "focus_default");
5589 break;
5590 case SWM_S_SPAWN_ORDER:
5591 if (!strcmp(value, "first"))
5592 spawn_position = SWM_STACK_BOTTOM;
5593 else if (!strcmp(value, "last"))
5594 spawn_position = SWM_STACK_TOP;
5595 else if (!strcmp(value, "next"))
5596 spawn_position = SWM_STACK_ABOVE;
5597 else if (!strcmp(value, "previous"))
5598 spawn_position = SWM_STACK_BELOW;
5599 else
5600 errx(1, "spawn_position");
5601 break;
5602 case SWM_S_DISABLE_BORDER:
5603 disable_border = atoi(value);
5604 break;
5605 case SWM_S_BORDER_WIDTH:
5606 border_width = atoi(value);
5607 break;
5608 case SWM_S_BAR_FONT:
5609 b = bar_fonts;
5610 if (asprintf(&bar_fonts, "%s,%s", value, bar_fonts) == -1)
5611 err(1, "setconfvalue: asprintf: failed to allocate "
5612 "memory for bar_fonts.");
5613
5614 free(b);
5615 break;
5616 case SWM_S_BAR_ACTION:
5617 free(bar_argv[0]);
5618 if ((bar_argv[0] = strdup(value)) == NULL)
5619 err(1, "setconfvalue: bar_action");
5620 break;
5621 case SWM_S_SPAWN_TERM:
5622 free(spawn_term[0]);
5623 if ((spawn_term[0] = strdup(value)) == NULL)
5624 err(1, "setconfvalue: spawn_term");
5625 break;
5626 case SWM_S_SS_APP:
5627 break;
5628 case SWM_S_DIALOG_RATIO:
5629 dialog_ratio = atof(value);
5630 if (dialog_ratio > 1.0 || dialog_ratio <= .3)
5631 dialog_ratio = .6;
5632 break;
5633 case SWM_S_VERBOSE_LAYOUT:
5634 verbose_layout = atoi(value);
5635 for (i = 0; layouts[i].l_stack != NULL; i++) {
5636 if (verbose_layout)
5637 layouts[i].l_string = fancy_stacker;
5638 else
5639 layouts[i].l_string = plain_stacker;
5640 }
5641 break;
5642 default:
5643 return (1);
5644 }
5645 return (0);
5646 }
5647
5648 int
5649 setconfmodkey(char *selector, char *value, int flags)
5650 {
5651 if (!strncasecmp(value, "Mod1", strlen("Mod1")))
5652 update_modkey(Mod1Mask);
5653 else if (!strncasecmp(value, "Mod2", strlen("Mod2")))
5654 update_modkey(Mod2Mask);
5655 else if (!strncasecmp(value, "Mod3", strlen("Mod3")))
5656 update_modkey(Mod3Mask);
5657 else if (!strncasecmp(value, "Mod4", strlen("Mod4")))
5658 update_modkey(Mod4Mask);
5659 else
5660 return (1);
5661 return (0);
5662 }
5663
5664 int
5665 setconfcolor(char *selector, char *value, int flags)
5666 {
5667 setscreencolor(value, ((selector == NULL)?-1:atoi(selector)), flags);
5668 return (0);
5669 }
5670
5671 int
5672 setconfregion(char *selector, char *value, int flags)
5673 {
5674 custom_region(value);
5675 return (0);
5676 }
5677
5678 int
5679 setautorun(char *selector, char *value, int flags)
5680 {
5681 int ws_id;
5682 char s[1024];
5683 char *ap, *sp = s;
5684 union arg a;
5685 int argc = 0;
5686 long pid;
5687 struct pid_e *p;
5688
5689 if (getenv("SWM_STARTED"))
5690 return (0);
5691
5692 bzero(s, sizeof s);
5693 if (sscanf(value, "ws[%d]:%1023c", &ws_id, s) != 2)
5694 errx(1, "invalid autorun entry, should be 'ws[<idx>]:command'");
5695 ws_id--;
5696 if (ws_id < 0 || ws_id >= workspace_limit)
5697 errx(1, "autorun: invalid workspace %d", ws_id + 1);
5698
5699 /*
5700 * This is a little intricate
5701 *
5702 * If the pid already exists we simply reuse it because it means it was
5703 * used before AND not claimed by manage_window. We get away with
5704 * altering it in the parent after INSERT because this can not be a race
5705 */
5706 a.argv = NULL;
5707 while ((ap = strsep(&sp, " \t")) != NULL) {
5708 if (*ap == '\0')
5709 continue;
5710 DNPRINTF(SWM_D_SPAWN, "setautorun: arg [%s]\n", ap);
5711 argc++;
5712 if ((a.argv = realloc(a.argv, argc * sizeof(char *))) == NULL)
5713 err(1, "setautorun: realloc");
5714 a.argv[argc - 1] = ap;
5715 }
5716
5717 if ((a.argv = realloc(a.argv, (argc + 1) * sizeof(char *))) == NULL)
5718 err(1, "setautorun: realloc");
5719 a.argv[argc] = NULL;
5720
5721 if ((pid = fork()) == 0) {
5722 spawn(ws_id, &a, 1);
5723 /* NOTREACHED */
5724 _exit(1);
5725 }
5726 free(a.argv);
5727
5728 /* parent */
5729 p = find_pid(pid);
5730 if (p == NULL) {
5731 p = calloc(1, sizeof *p);
5732 if (p == NULL)
5733 return (1);
5734 TAILQ_INSERT_TAIL(&pidlist, p, entry);
5735 }
5736
5737 p->pid = pid;
5738 p->ws = ws_id;
5739
5740 return (0);
5741 }
5742
5743 int
5744 setlayout(char *selector, char *value, int flags)
5745 {
5746 int ws_id, i, x, mg, ma, si, raise;
5747 int st = SWM_V_STACK;
5748 char s[1024];
5749 struct workspace *ws;
5750
5751 if (getenv("SWM_STARTED"))
5752 return (0);
5753
5754 bzero(s, sizeof s);
5755 if (sscanf(value, "ws[%d]:%d:%d:%d:%d:%1023c",
5756 &ws_id, &mg, &ma, &si, &raise, s) != 6)
5757 errx(1, "invalid layout entry, should be 'ws[<idx>]:"
5758 "<master_grow>:<master_add>:<stack_inc>:<always_raise>:"
5759 "<type>'");
5760 ws_id--;
5761 if (ws_id < 0 || ws_id >= workspace_limit)
5762 errx(1, "layout: invalid workspace %d", ws_id + 1);
5763
5764 if (!strcasecmp(s, "vertical"))
5765 st = SWM_V_STACK;
5766 else if (!strcasecmp(s, "horizontal"))
5767 st = SWM_H_STACK;
5768 else if (!strcasecmp(s, "fullscreen"))
5769 st = SWM_MAX_STACK;
5770 else
5771 errx(1, "invalid layout entry, should be 'ws[<idx>]:"
5772 "<master_grow>:<master_add>:<stack_inc>:<always_raise>:"
5773 "<type>'");
5774
5775 for (i = 0; i < ScreenCount(display); i++) {
5776 ws = (struct workspace *)&screens[i].ws;
5777 ws[ws_id].cur_layout = &layouts[st];
5778
5779 ws[ws_id].always_raise = raise;
5780 if (st == SWM_MAX_STACK)
5781 continue;
5782
5783 /* master grow */
5784 for (x = 0; x < abs(mg); x++) {
5785 ws[ws_id].cur_layout->l_config(&ws[ws_id],
5786 mg >= 0 ? SWM_ARG_ID_MASTERGROW :
5787 SWM_ARG_ID_MASTERSHRINK);
5788 stack();
5789 }
5790 /* master add */
5791 for (x = 0; x < abs(ma); x++) {
5792 ws[ws_id].cur_layout->l_config(&ws[ws_id],
5793 ma >= 0 ? SWM_ARG_ID_MASTERADD :
5794 SWM_ARG_ID_MASTERDEL);
5795 stack();
5796 }
5797 /* stack inc */
5798 for (x = 0; x < abs(si); x++) {
5799 ws[ws_id].cur_layout->l_config(&ws[ws_id],
5800 si >= 0 ? SWM_ARG_ID_STACKINC :
5801 SWM_ARG_ID_STACKDEC);
5802 stack();
5803 }
5804 }
5805
5806 return (0);
5807 }
5808
5809 /* config options */
5810 struct config_option {
5811 char *optname;
5812 int (*func)(char*, char*, int);
5813 int funcflags;
5814 };
5815 struct config_option configopt[] = {
5816 { "bar_enabled", setconfvalue, SWM_S_BAR_ENABLED },
5817 { "bar_at_bottom", setconfvalue, SWM_S_BAR_AT_BOTTOM },
5818 { "bar_border", setconfcolor, SWM_S_COLOR_BAR_BORDER },
5819 { "bar_border_width", setconfvalue, SWM_S_BAR_BORDER_WIDTH },
5820 { "bar_color", setconfcolor, SWM_S_COLOR_BAR },
5821 { "bar_font_color", setconfcolor, SWM_S_COLOR_BAR_FONT },
5822 { "bar_font", setconfvalue, SWM_S_BAR_FONT },
5823 { "bar_action", setconfvalue, SWM_S_BAR_ACTION },
5824 { "bar_delay", setconfvalue, SWM_S_BAR_DELAY },
5825 { "bar_justify", setconfvalue, SWM_S_BAR_JUSTIFY },
5826 { "bar_format", setconfvalue, SWM_S_BAR_FORMAT },
5827 { "keyboard_mapping", setkeymapping, 0 },
5828 { "bind", setconfbinding, 0 },
5829 { "stack_enabled", setconfvalue, SWM_S_STACK_ENABLED },
5830 { "clock_enabled", setconfvalue, SWM_S_CLOCK_ENABLED },
5831 { "clock_format", setconfvalue, SWM_S_CLOCK_FORMAT },
5832 { "color_focus", setconfcolor, SWM_S_COLOR_FOCUS },
5833 { "color_unfocus", setconfcolor, SWM_S_COLOR_UNFOCUS },
5834 { "cycle_empty", setconfvalue, SWM_S_CYCLE_EMPTY },
5835 { "cycle_visible", setconfvalue, SWM_S_CYCLE_VISIBLE },
5836 { "workspace_limit", setconfvalue, SWM_S_WORKSPACE_LIMIT },
5837 { "dialog_ratio", setconfvalue, SWM_S_DIALOG_RATIO },
5838 { "verbose_layout", setconfvalue, SWM_S_VERBOSE_LAYOUT },
5839 { "modkey", setconfmodkey, 0 },
5840 { "program", setconfspawn, 0 },
5841 { "quirk", setconfquirk, 0 },
5842 { "region", setconfregion, 0 },
5843 { "spawn_term", setconfvalue, SWM_S_SPAWN_TERM },
5844 { "screenshot_enabled", setconfvalue, SWM_S_SS_ENABLED },
5845 { "screenshot_app", setconfvalue, SWM_S_SS_APP },
5846 { "window_name_enabled", setconfvalue, SWM_S_WINDOW_NAME_ENABLED },
5847 { "urgent_enabled", setconfvalue, SWM_S_URGENT_ENABLED },
5848 { "term_width", setconfvalue, SWM_S_TERM_WIDTH },
5849 { "title_class_enabled", setconfvalue, SWM_S_TITLE_CLASS_ENABLED },
5850 { "title_name_enabled", setconfvalue, SWM_S_TITLE_NAME_ENABLED },
5851 { "focus_mode", setconfvalue, SWM_S_FOCUS_MODE },
5852 { "focus_close", setconfvalue, SWM_S_FOCUS_CLOSE },
5853 { "focus_close_wrap", setconfvalue, SWM_S_FOCUS_CLOSE_WRAP },
5854 { "focus_default", setconfvalue, SWM_S_FOCUS_DEFAULT },
5855 { "spawn_position", setconfvalue, SWM_S_SPAWN_ORDER },
5856 { "disable_border", setconfvalue, SWM_S_DISABLE_BORDER },
5857 { "border_width", setconfvalue, SWM_S_BORDER_WIDTH },
5858 { "autorun", setautorun, 0 },
5859 { "layout", setlayout, 0 },
5860 };
5861
5862
5863 int
5864 conf_load(char *filename, int keymapping)
5865 {
5866 FILE *config;
5867 char *line, *cp, *optsub, *optval;
5868 size_t linelen, lineno = 0;
5869 int wordlen, i, optind;
5870 struct config_option *opt;
5871
5872 DNPRINTF(SWM_D_CONF, "conf_load: begin\n");
5873
5874 if (filename == NULL) {
5875 warnx("conf_load: no filename");
5876 return (1);
5877 }
5878 if ((config = fopen(filename, "r")) == NULL) {
5879 warn("conf_load: fopen: %s", filename);
5880 return (1);
5881 }
5882
5883 while (!feof(config)) {
5884 if ((line = fparseln(config, &linelen, &lineno, NULL, 0))
5885 == NULL) {
5886 if (ferror(config))
5887 err(1, "%s", filename);
5888 else
5889 continue;
5890 }
5891 cp = line;
5892 cp += strspn(cp, " \t\n"); /* eat whitespace */
5893 if (cp[0] == '\0') {
5894 /* empty line */
5895 free(line);
5896 continue;
5897 }
5898 /* get config option */
5899 wordlen = strcspn(cp, "=[ \t\n");
5900 if (wordlen == 0) {
5901 warnx("%s: line %zd: no option found",
5902 filename, lineno);
5903 goto out;
5904 }
5905 optind = -1;
5906 for (i = 0; i < LENGTH(configopt); i++) {
5907 opt = &configopt[i];
5908 if (!strncasecmp(cp, opt->optname, wordlen) &&
5909 strlen(opt->optname) == wordlen) {
5910 optind = i;
5911 break;
5912 }
5913 }
5914 if (optind == -1) {
5915 warnx("%s: line %zd: unknown option %.*s",
5916 filename, lineno, wordlen, cp);
5917 goto out;
5918 }
5919 if (keymapping && strcmp(opt->optname, "bind")) {
5920 warnx("%s: line %zd: invalid option %.*s",
5921 filename, lineno, wordlen, cp);
5922 goto out;
5923 }
5924 cp += wordlen;
5925 cp += strspn(cp, " \t\n"); /* eat whitespace */
5926 /* get [selector] if any */
5927 optsub = NULL;
5928 if (*cp == '[') {
5929 cp++;
5930 wordlen = strcspn(cp, "]");
5931 if (*cp != ']') {
5932 if (wordlen == 0) {
5933 warnx("%s: line %zd: syntax error",
5934 filename, lineno);
5935 goto out;
5936 }
5937
5938 if (asprintf(&optsub, "%.*s", wordlen, cp) ==
5939 -1) {
5940 warnx("%s: line %zd: unable to allocate"
5941 "memory for selector", filename,
5942 lineno);
5943 goto out;
5944 }
5945 }
5946 cp += wordlen;
5947 cp += strspn(cp, "] \t\n"); /* eat trailing */
5948 }
5949 cp += strspn(cp, "= \t\n"); /* eat trailing */
5950 /* get RHS value */
5951 optval = strdup(cp);
5952 /* call function to deal with it all */
5953 if (configopt[optind].func(optsub, optval,
5954 configopt[optind].funcflags) != 0)
5955 errx(1, "%s: line %zd: invalid data for %s",
5956 filename, lineno, configopt[optind].optname);
5957 free(optval);
5958 free(optsub);
5959 free(line);
5960 }
5961
5962 fclose(config);
5963 DNPRINTF(SWM_D_CONF, "conf_load: end\n");
5964
5965 return (0);
5966
5967 out:
5968 free(line);
5969 fclose(config);
5970 DNPRINTF(SWM_D_CONF, "conf_load: end with error.\n");
5971
5972 return (1);
5973 }
5974
5975 void
5976 set_child_transient(struct ws_win *win, Window *trans)
5977 {
5978 struct ws_win *parent, *w;
5979 XWMHints *wmh = NULL;
5980 struct swm_region *r;
5981 struct workspace *ws;
5982
5983 parent = find_window(win->transient);
5984 if (parent)
5985 parent->child_trans = win;
5986 else {
5987 DNPRINTF(SWM_D_MISC, "set_child_transient: parent doesn't exist"
5988 " for 0x%lx trans 0x%lx\n", win->id, win->transient);
5989
5990 if (win->hints == NULL) {
5991 warnx("no hints for 0x%lx", win->id);
5992 return;
5993 }
5994
5995 r = root_to_region(win->wa.root);
5996 ws = r->ws;
5997 /* parent doen't exist in our window list */
5998 TAILQ_FOREACH(w, &ws->winlist, entry) {
5999 if (wmh)
6000 XFree(wmh);
6001
6002 if ((wmh = XGetWMHints(display, w->id)) == NULL) {
6003 warnx("can't get hints for 0x%lx", w->id);
6004 continue;
6005 }
6006
6007 if (win->hints->window_group != wmh->window_group)
6008 continue;
6009
6010 w->child_trans = win;
6011 win->transient = w->id;
6012 *trans = w->id;
6013 DNPRINTF(SWM_D_MISC, "set_child_transient: asjusting "
6014 "transient to 0x%lx\n", win->transient);
6015 break;
6016 }
6017 }
6018
6019 if (wmh)
6020 XFree(wmh);
6021 }
6022
6023 long
6024 window_get_pid(Window win)
6025 {
6026 Atom actual_type_return;
6027 int actual_format_return = 0;
6028 unsigned long nitems_return = 0;
6029 unsigned long bytes_after_return = 0;
6030 long *pid = NULL;
6031 long ret = 0;
6032 const char *errstr;
6033 unsigned char *prop = NULL;
6034
6035 if (XGetWindowProperty(display, win,
6036 XInternAtom(display, "_NET_WM_PID", False), 0, 1, False,
6037 XA_CARDINAL, &actual_type_return, &actual_format_return,
6038 &nitems_return, &bytes_after_return,
6039 (unsigned char**)(void*)&pid) != Success)
6040 goto tryharder;
6041 if (actual_type_return != XA_CARDINAL)
6042 goto tryharder;
6043 if (pid == NULL)
6044 goto tryharder;
6045
6046 ret = *pid;
6047 XFree(pid);
6048
6049 return (ret);
6050
6051 tryharder:
6052 if (XGetWindowProperty(display, win,
6053 XInternAtom(display, "_SWM_PID", False), 0, SWM_PROPLEN, False,
6054 XA_STRING, &actual_type_return, &actual_format_return,
6055 &nitems_return, &bytes_after_return, &prop) != Success)
6056 return (0);
6057 if (actual_type_return != XA_STRING)
6058 return (0);
6059 if (prop == NULL)
6060 return (0);
6061
6062 ret = strtonum((const char *)prop, 0, UINT_MAX, &errstr);
6063 /* ignore error because strtonum returns 0 anyway */
6064 XFree(prop);
6065
6066 return (ret);
6067 }
6068
6069 struct ws_win *
6070 manage_window(Window id)
6071 {
6072 Window trans = 0;
6073 struct workspace *ws;
6074 struct ws_win *win, *ww;
6075 int format, i, ws_idx, n, border_me = 0;
6076 unsigned long nitems, bytes;
6077 Atom ws_idx_atom = 0, type;
6078 Atom *prot = NULL, *pp;
6079 unsigned char ws_idx_str[SWM_PROPLEN], *prop = NULL;
6080 struct swm_region *r;
6081 long mask = 0;
6082 const char *errstr;
6083 XWindowChanges wc;
6084 struct pid_e *p;
6085 struct quirk *qp;
6086
6087 if ((win = find_window(id)) != NULL)
6088 return (win); /* already being managed */
6089
6090 /* see if we are on the unmanaged list */
6091 if ((win = find_unmanaged_window(id)) != NULL) {
6092 DNPRINTF(SWM_D_MISC, "manage_window: previously unmanaged "
6093 "window: 0x%lx\n", win->id);
6094 TAILQ_REMOVE(&win->ws->unmanagedlist, win, entry);
6095 if (win->transient)
6096 set_child_transient(win, &trans);
6097
6098 if (trans && (ww = find_window(trans)))
6099 TAILQ_INSERT_AFTER(&win->ws->winlist, ww, win, entry);
6100 else if ((ww = win->ws->focus) &&
6101 spawn_position == SWM_STACK_ABOVE)
6102 TAILQ_INSERT_AFTER(&win->ws->winlist, win->ws->focus, win, entry);
6103 else if (ww && spawn_position == SWM_STACK_BELOW)
6104 TAILQ_INSERT_AFTER(&win->ws->winlist, win->ws->focus, win, entry);
6105 else switch (spawn_position) {
6106 default:
6107 case SWM_STACK_TOP:
6108 case SWM_STACK_ABOVE:
6109 TAILQ_INSERT_TAIL(&win->ws->winlist, win, entry);
6110 break;
6111 case SWM_STACK_BOTTOM:
6112 case SWM_STACK_BELOW:
6113 TAILQ_INSERT_HEAD(&win->ws->winlist, win, entry);
6114 }
6115
6116 ewmh_update_actions(win);
6117 return (win);
6118 }
6119
6120 if ((win = calloc(1, sizeof(struct ws_win))) == NULL)
6121 err(1, "manage_window: calloc: failed to allocate memory for "
6122 "new window");
6123
6124 win->id = id;
6125
6126 /* see if we need to override the workspace */
6127 p = find_pid(window_get_pid(id));
6128
6129 /* Get all the window data in one shot */
6130 ws_idx_atom = XInternAtom(display, "_SWM_WS", False);
6131 if (ws_idx_atom) {
6132 XGetWindowProperty(display, id, ws_idx_atom, 0, SWM_PROPLEN,
6133 False, XA_STRING, &type, &format, &nitems, &bytes, &prop);
6134 }
6135 XGetWindowAttributes(display, id, &win->wa);
6136 XGetWMNormalHints(display, id, &win->sh, &win->sh_mask);
6137 win->hints = XGetWMHints(display, id);
6138 XGetTransientForHint(display, id, &trans);
6139 if (trans) {
6140 win->transient = trans;
6141 set_child_transient(win, &trans);
6142 DNPRINTF(SWM_D_MISC, "manage_window: window: 0x%lx, "
6143 "transient: 0x%lx\n", win->id, win->transient);
6144 }
6145
6146 /* get supported protocols */
6147 if (XGetWMProtocols(display, id, &prot, &n)) {
6148 for (i = 0, pp = prot; i < n; i++, pp++) {
6149 if (*pp == takefocus)
6150 win->take_focus = 1;
6151 if (*pp == adelete)
6152 win->can_delete = 1;
6153 }
6154 if (prot)
6155 XFree(prot);
6156 }
6157
6158 win->iconic = get_iconic(win);
6159
6160 /*
6161 * Figure out where to put the window. If it was previously assigned to
6162 * a workspace (either by spawn() or manually moving), and isn't
6163 * transient, * put it in the same workspace
6164 */
6165 r = root_to_region(win->wa.root);
6166 if (p) {
6167 ws = &r->s->ws[p->ws];
6168 TAILQ_REMOVE(&pidlist, p, entry);
6169 free(p);
6170 p = NULL;
6171 } else if (prop && win->transient == 0) {
6172 DNPRINTF(SWM_D_PROP, "manage_window: get _SWM_WS: %s\n", prop);
6173 ws_idx = strtonum((const char *)prop, 0, workspace_limit - 1,
6174 &errstr);
6175 if (errstr) {
6176 DNPRINTF(SWM_D_EVENT, "manage_window: window: #%s: %s",
6177 errstr, prop);
6178 }
6179 ws = &r->s->ws[ws_idx];
6180 } else {
6181 ws = r->ws;
6182 /* this should launch transients in the same ws as parent */
6183 if (id && trans)
6184 if ((ww = find_window(trans)) != NULL)
6185 if (ws->r) {
6186 ws = ww->ws;
6187 if (ww->ws->r)
6188 r = ww->ws->r;
6189 else
6190 warnx("manage_window: fix this "
6191 "bug mcbride");
6192 border_me = 1;
6193 }
6194 }
6195
6196 /* set up the window layout */
6197 win->id = id;
6198 win->ws = ws;
6199 win->s = r->s; /* this never changes */
6200 if (trans && (ww = find_window(trans)))
6201 TAILQ_INSERT_AFTER(&ws->winlist, ww, win, entry);
6202 else if (spawn_position == SWM_STACK_ABOVE && win->ws->focus)
6203 TAILQ_INSERT_AFTER(&win->ws->winlist, win->ws->focus, win, entry);
6204 else
6205 TAILQ_INSERT_TAIL(&ws->winlist, win, entry);
6206
6207 WIDTH(win) = win->wa.width;
6208 HEIGHT(win) = win->wa.height;
6209 X(win) = win->wa.x;
6210 Y(win) = win->wa.y;
6211 win->g_floatvalid = 0;
6212 win->floatmaxed = 0;
6213 win->ewmh_flags = 0;
6214
6215 /* Set window properties so we can remember this after reincarnation */
6216 if (ws_idx_atom && prop == NULL &&
6217 snprintf((char *)ws_idx_str, SWM_PROPLEN, "%d", ws->idx) <
6218 SWM_PROPLEN) {
6219 DNPRINTF(SWM_D_PROP, "manage_window: set _SWM_WS: %s\n",
6220 ws_idx_str);
6221 XChangeProperty(display, win->id, ws_idx_atom, XA_STRING, 8,
6222 PropModeReplace, ws_idx_str, strlen((char *)ws_idx_str));
6223 }
6224 if (prop)
6225 XFree(prop);
6226
6227 ewmh_autoquirk(win);
6228
6229 if (XGetClassHint(display, win->id, &win->ch)) {
6230 DNPRINTF(SWM_D_CLASS, "manage_window: class: %s, name: %s\n",
6231 win->ch.res_class, win->ch.res_name);
6232
6233 /* java is retarded so treat it special */
6234 if (strstr(win->ch.res_name, "sun-awt")) {
6235 win->java = 1;
6236 border_me = 1;
6237 }
6238
6239 TAILQ_FOREACH(qp, &quirks, entry) {
6240 if (!strcmp(win->ch.res_class, qp->class) &&
6241 !strcmp(win->ch.res_name, qp->name)) {
6242 DNPRINTF(SWM_D_CLASS, "manage_window: found: "
6243 "class: %s, name: %s\n", win->ch.res_class,
6244 win->ch.res_name);
6245 if (qp->quirk & SWM_Q_FLOAT) {
6246 win->floating = 1;
6247 border_me = 1;
6248 }
6249 win->quirks = qp->quirk;
6250 }
6251 }
6252 }
6253
6254 /* alter window position if quirky */
6255 if (win->quirks & SWM_Q_ANYWHERE) {
6256 win->manual = 1; /* don't center the quirky windows */
6257 bzero(&wc, sizeof wc);
6258 mask = 0;
6259 if (bar_enabled && Y(win) < bar_height) {
6260 Y(win) = wc.y = bar_height;
6261 mask |= CWY;
6262 }
6263 if (WIDTH(win) + X(win) > WIDTH(r)) {
6264 X(win) = wc.x = WIDTH(r) - WIDTH(win) - 2;
6265 mask |= CWX;
6266 }
6267 border_me = 1;
6268 }
6269
6270 /* Reset font sizes (the bruteforce way; no default keybinding). */
6271 if (win->quirks & SWM_Q_XTERM_FONTADJ) {
6272 for (i = 0; i < SWM_MAX_FONT_STEPS; i++)
6273 fake_keypress(win, XK_KP_Subtract, ShiftMask);
6274 for (i = 0; i < SWM_MAX_FONT_STEPS; i++)
6275 fake_keypress(win, XK_KP_Add, ShiftMask);
6276 }
6277
6278 ewmh_get_win_state(win);
6279 ewmh_update_actions(win);
6280 ewmh_update_win_state(win, None, _NET_WM_STATE_REMOVE);
6281
6282 /* border me */
6283 if (border_me) {
6284 bzero(&wc, sizeof wc);
6285 wc.border_width = border_width;
6286 mask |= CWBorderWidth;
6287 XConfigureWindow(display, win->id, mask, &wc);
6288 }
6289
6290 XSelectInput(display, id, EnterWindowMask | FocusChangeMask |
6291 PropertyChangeMask | StructureNotifyMask);
6292
6293 /* floaters need to be mapped if they are in the current workspace */
6294 if ((win->floating || win->transient) && (ws->idx == r->ws->idx))
6295 XMapRaised(display, win->id);
6296
6297 return (win);
6298 }
6299
6300 void
6301 free_window(struct ws_win *win)
6302 {
6303 DNPRINTF(SWM_D_MISC, "free_window: window: 0x%lx\n", win->id);
6304
6305 if (win == NULL)
6306 return;
6307
6308 /* needed for restart wm */
6309 set_win_state(win, WithdrawnState);
6310
6311 TAILQ_REMOVE(&win->ws->unmanagedlist, win, entry);
6312
6313 if (win->ch.res_class)
6314 XFree(win->ch.res_class);
6315 if (win->ch.res_name)
6316 XFree(win->ch.res_name);
6317
6318 kill_refs(win);
6319
6320 /* paint memory */
6321 memset(win, 0xff, sizeof *win); /* XXX kill later */
6322
6323 free(win);
6324 }
6325
6326 void
6327 unmanage_window(struct ws_win *win)
6328 {
6329 struct ws_win *parent;
6330
6331 if (win == NULL)
6332 return;
6333
6334 DNPRINTF(SWM_D_MISC, "unmanage_window: window: 0x%lx\n", win->id);
6335
6336 if (win->transient) {
6337 parent = find_window(win->transient);
6338 if (parent)
6339 parent->child_trans = NULL;
6340 }
6341
6342 /* focus on root just in case */
6343 XSetInputFocus(display, PointerRoot, PointerRoot, CurrentTime);
6344
6345 focus_prev(win);
6346
6347 if (win->hints) {
6348 XFree(win->hints);
6349 win->hints = NULL;
6350 }
6351
6352 TAILQ_REMOVE(&win->ws->winlist, win, entry);
6353 TAILQ_INSERT_TAIL(&win->ws->unmanagedlist, win, entry);
6354 }
6355
6356 void
6357 focus_magic(struct ws_win *win)
6358 {
6359 DNPRINTF(SWM_D_FOCUS, "focus_magic: window: 0x%lx\n", WINID(win));
6360
6361 if (win == NULL) {
6362 /* if there are no windows clear the status-bar */
6363 bar_update();
6364 return;
6365 }
6366
6367 if (win->child_trans) {
6368 /* win = parent & has a transient so focus on that */
6369 if (win->java) {
6370 focus_win(win->child_trans);
6371 if (win->child_trans->take_focus)
6372 client_msg(win, takefocus);
6373 } else {
6374 /* make sure transient hasn't disappeared */
6375 if (validate_win(win->child_trans) == 0) {
6376 focus_win(win->child_trans);
6377 if (win->child_trans->take_focus)
6378 client_msg(win->child_trans, takefocus);
6379 } else {
6380 win->child_trans = NULL;
6381 focus_win(win);
6382 if (win->take_focus)
6383 client_msg(win, takefocus);
6384 }
6385 }
6386 } else {
6387 /* regular focus */
6388 focus_win(win);
6389 if (win->take_focus)
6390 client_msg(win, takefocus);
6391 }
6392 }
6393
6394 void
6395 expose(XEvent *e)
6396 {
6397 DNPRINTF(SWM_D_EVENT, "expose: window: 0x%lx\n", e->xexpose.window);
6398 }
6399
6400 void
6401 keypress(XEvent *e)
6402 {
6403 KeySym keysym;
6404 XKeyEvent *ev = &e->xkey;
6405 struct key *kp;
6406 struct swm_region *r;
6407
6408 keysym = XkbKeycodeToKeysym(display, (KeyCode)ev->keycode, 0, 0);
6409 if ((kp = key_lookup(CLEANMASK(ev->state), keysym)) == NULL)
6410 return;
6411 if (keyfuncs[kp->funcid].func == NULL)
6412 return;
6413
6414 r = root_to_region(ev->root);
6415 if (kp->funcid == kf_spawn_custom)
6416 spawn_custom(r, &(keyfuncs[kp->funcid].args), kp->spawn_name);
6417 else
6418 keyfuncs[kp->funcid].func(r, &(keyfuncs[kp->funcid].args));
6419 }
6420
6421 void
6422 buttonpress(XEvent *e)
6423 {
6424 struct ws_win *win;
6425 int i, action;
6426 XButtonPressedEvent *ev = &e->xbutton;
6427
6428 if ((win = find_window(ev->window)) == NULL)
6429 return;
6430
6431 focus_magic(win);
6432 action = client_click;
6433
6434 for (i = 0; i < LENGTH(buttons); i++)
6435 if (action == buttons[i].action && buttons[i].func &&
6436 buttons[i].button == ev->button &&
6437 CLEANMASK(buttons[i].mask) == CLEANMASK(ev->state))
6438 buttons[i].func(win, &buttons[i].args);
6439 }
6440
6441 void
6442 configurerequest(XEvent *e)
6443 {
6444 XConfigureRequestEvent *ev = &e->xconfigurerequest;
6445 struct ws_win *win;
6446 int new = 0;
6447 XWindowChanges wc;
6448
6449 if ((win = find_window(ev->window)) == NULL)
6450 if ((win = find_unmanaged_window(ev->window)) == NULL)
6451 new = 1;
6452
6453 DNPRINTF(SWM_D_EVENT, "configurerequest: window: 0x%lx, new: %s\n",
6454 ev->window, YESNO(new));
6455
6456 if (new) {
6457 bzero(&wc, sizeof wc);
6458 wc.x = ev->x;
6459 wc.y = ev->y;
6460 wc.width = ev->width;
6461 wc.height = ev->height;
6462 wc.border_width = ev->border_width;
6463 wc.sibling = ev->above;
6464 wc.stack_mode = ev->detail;
6465 XConfigureWindow(display, ev->window, ev->value_mask, &wc);
6466 } else
6467 config_win(win, ev);
6468 }
6469
6470 void
6471 configurenotify(XEvent *e)
6472 {
6473 struct ws_win *win;
6474
6475 DNPRINTF(SWM_D_EVENT, "configurenotify: window: 0x%lx\n",
6476 e->xconfigure.window);
6477
6478 win = find_window(e->xconfigure.window);
6479 if (win) {
6480 XGetWMNormalHints(display, win->id, &win->sh, &win->sh_mask);
6481 adjust_font(win);
6482 if (font_adjusted)
6483 stack();
6484 if (focus_mode == SWM_FOCUS_DEFAULT)
6485 drain_enter_notify();
6486 }
6487 }
6488
6489 void
6490 destroynotify(XEvent *e)
6491 {
6492 struct ws_win *win;
6493 XDestroyWindowEvent *ev = &e->xdestroywindow;
6494
6495 DNPRINTF(SWM_D_EVENT, "destroynotify: window: 0x%lx\n", ev->window);
6496
6497 if ((win = find_window(ev->window)) == NULL) {
6498 if ((win = find_unmanaged_window(ev->window)) == NULL)
6499 return;
6500 free_window(win);
6501 return;
6502 }
6503
6504 /* make sure we focus on something */
6505 win->floating = 0;
6506
6507 unmanage_window(win);
6508 stack();
6509 if (focus_mode == SWM_FOCUS_DEFAULT)
6510 drain_enter_notify();
6511 free_window(win);
6512 }
6513
6514 void
6515 enternotify(XEvent *e)
6516 {
6517 XCrossingEvent *ev = &e->xcrossing;
6518 XEvent cne;
6519 struct ws_win *win;
6520 #if 0
6521 struct ws_win *w;
6522 Window focus_return;
6523 int revert_to_return;
6524 #endif
6525 DNPRINTF(SWM_D_FOCUS, "enternotify: window: 0x%lx, mode: %d, detail: "
6526 "%d, root: 0x%lx, subwindow: 0x%lx, same_screen: %s, focus: %s, "
6527 "state: %d\n", ev->window, ev->mode, ev->detail, ev->root,
6528 ev->subwindow, YESNO(ev->same_screen), YESNO(ev->focus), ev->state);
6529
6530 if (ev->mode != NotifyNormal) {
6531 DNPRINTF(SWM_D_EVENT, "skip enternotify: generated by "
6532 "cursor grab.\n");
6533 return;
6534 }
6535
6536 switch (focus_mode) {
6537 case SWM_FOCUS_DEFAULT:
6538 break;
6539 case SWM_FOCUS_FOLLOW:
6540 break;
6541 case SWM_FOCUS_SYNERGY:
6542 #if 0
6543 /*
6544 * all these checks need to be in this order because the
6545 * XCheckTypedWindowEvent relies on weeding out the previous events
6546 *
6547 * making this code an option would enable a follow mouse for focus
6548 * feature
6549 */
6550
6551 /*
6552 * state is set when we are switching workspaces and focus is set when
6553 * the window or a subwindow already has focus (occurs during restart).
6554 *
6555 * Only honor the focus flag if last_focus_event is not FocusOut,
6556 * this allows spectrwm to continue to control focus when another
6557 * program is also playing with it.
6558 */
6559 if (ev->state || (ev->focus && last_focus_event != FocusOut)) {
6560 DNPRINTF(SWM_D_EVENT, "ignoring enternotify: focus\n");
6561 return;
6562 }
6563
6564 /*
6565 * happens when a window is created or destroyed and the border
6566 * crosses the mouse pointer and when switching ws
6567 *
6568 * we need the subwindow test to see if we came from root in order
6569 * to give focus to floaters
6570 */
6571 if (ev->mode == NotifyNormal && ev->detail == NotifyVirtual &&
6572 ev->subwindow == 0) {
6573 DNPRINTF(SWM_D_EVENT, "ignoring enternotify: NotifyVirtual\n");
6574 return;
6575 }
6576
6577 /* this window already has focus */
6578 if (ev->mode == NotifyNormal && ev->detail == NotifyInferior) {
6579 DNPRINTF(SWM_D_EVENT, "ignoring enternotify: win has focus\n");
6580 return;
6581 }
6582
6583 /* this window is being deleted or moved to another ws */
6584 if (XCheckTypedWindowEvent(display, ev->window, ConfigureNotify,
6585 &cne) == True) {
6586 DNPRINTF(SWM_D_EVENT, "ignoring enternotify: configurenotify\n");
6587 XPutBackEvent(display, &cne);
6588 return;
6589 }
6590
6591 if ((win = find_window(ev->window)) == NULL) {
6592 DNPRINTF(SWM_D_EVENT, "ignoring enternotify: win == NULL\n");
6593 return;
6594 }
6595
6596 /*
6597 * In fullstack kill all enters unless they come from a different ws
6598 * (i.e. another region) or focus has been grabbed externally.
6599 */
6600 if (win->ws->cur_layout->flags & SWM_L_FOCUSPREV &&
6601 last_focus_event != FocusOut) {
6602 XGetInputFocus(display, &focus_return, &revert_to_return);
6603 if ((w = find_window(focus_return)) == NULL ||
6604 w->ws == win->ws) {
6605 DNPRINTF(SWM_D_EVENT, "ignoring event: fullstack\n");
6606 return;
6607 }
6608 }
6609 #endif
6610 break;
6611 }
6612
6613 if ((win = find_window(ev->window)) == NULL) {
6614 DNPRINTF(SWM_D_EVENT, "skip enternotify: window is NULL\n");
6615 return;
6616 }
6617
6618 /*
6619 * if we have more enternotifies let them handle it in due time
6620 */
6621 if (XCheckTypedEvent(display, EnterNotify, &cne) == True) {
6622 DNPRINTF(SWM_D_EVENT,
6623 "ignoring enternotify: got more enternotify\n");
6624 XPutBackEvent(display, &cne);
6625 return;
6626 }
6627
6628 focus_magic(win);
6629 }
6630
6631 /* lets us use one switch statement for arbitrary mode/detail combinations */
6632 #define MERGE_MEMBERS(a,b) (((a & 0xffff) << 16) | (b & 0xffff))
6633
6634 void
6635 focusevent(XEvent *e)
6636 {
6637 #if 0
6638 struct ws_win *win;
6639 u_int32_t mode_detail;
6640 XFocusChangeEvent *ev = &e->xfocus;
6641
6642 DNPRINTF(SWM_D_EVENT, "focusevent: %s window: 0x%lx mode: %d "
6643 "detail: %d\n", ev->type == FocusIn ? "entering" : "leaving",
6644 ev->window, ev->mode, ev->detail);
6645
6646 if (last_focus_event == ev->type) {
6647 DNPRINTF(SWM_D_FOCUS, "ignoring focusevent: bad ordering\n");
6648 return;
6649 }
6650
6651 last_focus_event = ev->type;
6652 mode_detail = MERGE_MEMBERS(ev->mode, ev->detail);
6653
6654 switch (mode_detail) {
6655 /* synergy client focus operations */
6656 case MERGE_MEMBERS(NotifyNormal, NotifyNonlinear):
6657 case MERGE_MEMBERS(NotifyNormal, NotifyNonlinearVirtual):
6658
6659 /* synergy server focus operations */
6660 case MERGE_MEMBERS(NotifyWhileGrabbed, NotifyNonlinear):
6661
6662 /* Entering applications like rdesktop that mangle the pointer */
6663 case MERGE_MEMBERS(NotifyNormal, NotifyPointer):
6664
6665 if ((win = find_window(e->xfocus.window)) != NULL && win->ws->r)
6666 XSetWindowBorder(display, win->id,
6667 win->ws->r->s->c[ev->type == FocusIn ?
6668 SWM_S_COLOR_FOCUS : SWM_S_COLOR_UNFOCUS].color);
6669 break;
6670 default:
6671 warnx("ignoring focusevent");
6672 DNPRINTF(SWM_D_FOCUS, "ignoring focusevent\n");
6673 break;
6674 }
6675 #endif
6676 }
6677
6678 void
6679 mapnotify(XEvent *e)
6680 {
6681 struct ws_win *win;
6682 XMapEvent *ev = &e->xmap;
6683
6684 DNPRINTF(SWM_D_EVENT, "mapnotify: window: 0x%lx\n", ev->window);
6685
6686 win = manage_window(ev->window);
6687 if (win)
6688 set_win_state(win, NormalState);
6689
6690 /*
6691 * focus_win can only set input focus on a mapped window.
6692 * make sure the window really has focus since it is just being mapped.
6693 */
6694 if (win->ws->focus == win)
6695 focus_win(win);
6696 }
6697
6698 void
6699 mappingnotify(XEvent *e)
6700 {
6701 XMappingEvent *ev = &e->xmapping;
6702
6703 XRefreshKeyboardMapping(ev);
6704 if (ev->request == MappingKeyboard)
6705 grabkeys();
6706 }
6707
6708 void
6709 maprequest(XEvent *e)
6710 {
6711 struct ws_win *win;
6712 struct swm_region *r;
6713 XWindowAttributes wa;
6714 XMapRequestEvent *ev = &e->xmaprequest;
6715
6716 DNPRINTF(SWM_D_EVENT, "maprequest: window: 0x%lx\n",
6717 e->xmaprequest.window);
6718
6719 if (!XGetWindowAttributes(display, ev->window, &wa))
6720 return;
6721 if (wa.override_redirect)
6722 return;
6723
6724 win = manage_window(e->xmaprequest.window);
6725 if (win == NULL)
6726 return; /* can't happen */
6727
6728 stack();
6729
6730 /* make new win focused */
6731 r = root_to_region(win->wa.root);
6732 if (win->ws == r->ws)
6733 focus_magic(win);
6734 }
6735
6736 void
6737 propertynotify(XEvent *e)
6738 {
6739 struct ws_win *win;
6740 XPropertyEvent *ev = &e->xproperty;
6741 #ifdef SWM_DEBUG
6742 char *name;
6743 name = XGetAtomName(display, ev->atom);
6744 DNPRINTF(SWM_D_EVENT, "propertynotify: window: 0x%lx, atom: %s\n",
6745 ev->window, name);
6746 XFree(name);
6747 #endif
6748
6749 win = find_window(ev->window);
6750 if (win == NULL)
6751 return;
6752
6753 if (ev->state == PropertyDelete && ev->atom == a_swm_iconic) {
6754 update_iconic(win, 0);
6755 XMapRaised(display, win->id);
6756 stack();
6757 focus_win(win);
6758 return;
6759 }
6760
6761 switch (ev->atom) {
6762 #if 0
6763 case XA_WM_NORMAL_HINTS:
6764 long mask;
6765 XGetWMNormalHints(display, win->id, &win->sh, &mask);
6766 warnx("normal hints: flag 0x%x", win->sh.flags);
6767 if (win->sh.flags & PMinSize) {
6768 WIDTH(win) = win->sh.min_width;
6769 HEIGHT(win) = win->sh.min_height;
6770 warnx("min %d %d", WIDTH(win), HEIGHT(win));
6771 }
6772 XMoveResizeWindow(display, win->id,
6773 X(win), Y(win), WIDTH(win), HEIGHT(win));
6774 #endif
6775 case XA_WM_CLASS:
6776 case XA_WM_NAME:
6777 bar_update();
6778 break;
6779 default:
6780 break;
6781 }
6782 }
6783
6784 void
6785 unmapnotify(XEvent *e)
6786 {
6787 struct ws_win *win;
6788
6789 DNPRINTF(SWM_D_EVENT, "unmapnotify: window: 0x%lx\n", e->xunmap.window);
6790
6791 /* determine if we need to help unmanage this window */
6792 win = find_window(e->xunmap.window);
6793 if (win == NULL)
6794 return;
6795
6796 if (getstate(e->xunmap.window) == NormalState) {
6797 unmanage_window(win);
6798 stack();
6799
6800 /* giant hack for apps that don't destroy transient windows */
6801 /* eat a bunch of events to prevent remanaging the window */
6802 XEvent cne;
6803 while (XCheckWindowEvent(display, e->xunmap.window,
6804 EnterWindowMask, &cne))
6805 ;
6806 while (XCheckWindowEvent(display, e->xunmap.window,
6807 StructureNotifyMask, &cne))
6808 ;
6809 while (XCheckWindowEvent(display, e->xunmap.window,
6810 SubstructureNotifyMask, &cne))
6811 ;
6812 /* resend unmap because we ated it */
6813 XUnmapWindow(display, e->xunmap.window);
6814 }
6815
6816 if (focus_mode == SWM_FOCUS_DEFAULT)
6817 drain_enter_notify();
6818 }
6819
6820 void
6821 visibilitynotify(XEvent *e)
6822 {
6823 int i;
6824 struct swm_region *r;
6825
6826 DNPRINTF(SWM_D_EVENT, "visibilitynotify: window: 0x%lx\n",
6827 e->xvisibility.window);
6828 if (e->xvisibility.state == VisibilityUnobscured)
6829 for (i = 0; i < ScreenCount(display); i++)
6830 TAILQ_FOREACH(r, &screens[i].rl, entry)
6831 if (e->xvisibility.window == r->bar_window)
6832 bar_update();
6833 }
6834
6835 void
6836 clientmessage(XEvent *e)
6837 {
6838 XClientMessageEvent *ev;
6839 struct ws_win *win;
6840
6841 ev = &e->xclient;
6842
6843 win = find_window(ev->window);
6844 if (win == NULL)
6845 return;
6846
6847 DNPRINTF(SWM_D_EVENT, "clientmessage: window: 0x%lx, type: %ld\n",
6848 ev->window, ev->message_type);
6849
6850 if (ev->message_type == ewmh[_NET_ACTIVE_WINDOW].atom) {
6851 DNPRINTF(SWM_D_EVENT, "clientmessage: _NET_ACTIVE_WINDOW\n");
6852 focus_win(win);
6853 }
6854 if (ev->message_type == ewmh[_NET_CLOSE_WINDOW].atom) {
6855 DNPRINTF(SWM_D_EVENT, "clientmessage: _NET_CLOSE_WINDOW\n");
6856 if (win->can_delete)
6857 client_msg(win, adelete);
6858 else
6859 XKillClient(display, win->id);
6860 }
6861 if (ev->message_type == ewmh[_NET_MOVERESIZE_WINDOW].atom) {
6862 DNPRINTF(SWM_D_EVENT,
6863 "clientmessage: _NET_MOVERESIZE_WINDOW\n");
6864 if (win->floating) {
6865 if (ev->data.l[0] & (1<<8)) /* x */
6866 X(win) = ev->data.l[1];
6867 if (ev->data.l[0] & (1<<9)) /* y */
6868 Y(win) = ev->data.l[2];
6869 if (ev->data.l[0] & (1<<10)) /* width */
6870 WIDTH(win) = ev->data.l[3];
6871 if (ev->data.l[0] & (1<<11)) /* height */
6872 HEIGHT(win) = ev->data.l[4];
6873
6874 update_window(win);
6875 }
6876 else {
6877 /* TODO: Change stack sizes */
6878 /* notify no change was made. */
6879 config_win(win, NULL);
6880 }
6881 }
6882 if (ev->message_type == ewmh[_NET_WM_STATE].atom) {
6883 DNPRINTF(SWM_D_EVENT, "clientmessage: _NET_WM_STATE\n");
6884 ewmh_update_win_state(win, ev->data.l[1], ev->data.l[0]);
6885 if (ev->data.l[2])
6886 ewmh_update_win_state(win, ev->data.l[2],
6887 ev->data.l[0]);
6888
6889 stack();
6890 }
6891 }
6892
6893 int
6894 xerror_start(Display *d, XErrorEvent *ee)
6895 {
6896 other_wm = 1;
6897 return (-1);
6898 }
6899
6900 int
6901 xerror(Display *d, XErrorEvent *ee)
6902 {
6903 /* warnx("error: %p %p", display, ee); */
6904 return (-1);
6905 }
6906
6907 int
6908 active_wm(void)
6909 {
6910 other_wm = 0;
6911 xerrorxlib = XSetErrorHandler(xerror_start);
6912
6913 /* this causes an error if some other window manager is running */
6914 XSelectInput(display, DefaultRootWindow(display),
6915 SubstructureRedirectMask);
6916 XSync(display, False);
6917 if (other_wm)
6918 return (1);
6919
6920 XSetErrorHandler(xerror);
6921 XSync(display, False);
6922 return (0);
6923 }
6924
6925 void
6926 new_region(struct swm_screen *s, int x, int y, int w, int h)
6927 {
6928 struct swm_region *r, *n;
6929 struct workspace *ws = NULL;
6930 int i;
6931
6932 DNPRINTF(SWM_D_MISC, "new region: screen[%d]:%dx%d+%d+%d\n",
6933 s->idx, w, h, x, y);
6934
6935 /* remove any conflicting regions */
6936 n = TAILQ_FIRST(&s->rl);
6937 while (n) {
6938 r = n;
6939 n = TAILQ_NEXT(r, entry);
6940 if (X(r) < (x + w) &&
6941 (X(r) + WIDTH(r)) > x &&
6942 Y(r) < (y + h) &&
6943 (Y(r) + HEIGHT(r)) > y) {
6944 if (r->ws->r != NULL)
6945 r->ws->old_r = r->ws->r;
6946 r->ws->r = NULL;
6947 XDestroyWindow(display, r->bar_window);
6948 TAILQ_REMOVE(&s->rl, r, entry);
6949 TAILQ_INSERT_TAIL(&s->orl, r, entry);
6950 }
6951 }
6952
6953 /* search old regions for one to reuse */
6954
6955 /* size + location match */
6956 TAILQ_FOREACH(r, &s->orl, entry)
6957 if (X(r) == x && Y(r) == y &&
6958 HEIGHT(r) == h && WIDTH(r) == w)
6959 break;
6960
6961 /* size match */
6962 TAILQ_FOREACH(r, &s->orl, entry)
6963 if (HEIGHT(r) == h && WIDTH(r) == w)
6964 break;
6965
6966 if (r != NULL) {
6967 TAILQ_REMOVE(&s->orl, r, entry);
6968 /* try to use old region's workspace */
6969 if (r->ws->r == NULL)
6970 ws = r->ws;
6971 } else
6972 if ((r = calloc(1, sizeof(struct swm_region))) == NULL)
6973 err(1, "new_region: calloc: failed to allocate memory "
6974 "for screen");
6975
6976 /* if we don't have a workspace already, find one */
6977 if (ws == NULL) {
6978 for (i = 0; i < workspace_limit; i++)
6979 if (s->ws[i].r == NULL) {
6980 ws = &s->ws[i];
6981 break;
6982 }
6983 }
6984
6985 if (ws == NULL)
6986 errx(1, "new_region: no free workspaces");
6987
6988 X(r) = x;
6989 Y(r) = y;
6990 WIDTH(r) = w;
6991 HEIGHT(r) = h;
6992 r->s = s;
6993 r->ws = ws;
6994 r->ws_prior = NULL;
6995 ws->r = r;
6996 outputs++;
6997 TAILQ_INSERT_TAIL(&s->rl, r, entry);
6998 }
6999
7000 void
7001 scan_xrandr(int i)
7002 {
7003 #ifdef SWM_XRR_HAS_CRTC
7004 XRRCrtcInfo *ci;
7005 XRRScreenResources *sr;
7006 int c;
7007 int ncrtc = 0;
7008 #endif /* SWM_XRR_HAS_CRTC */
7009 struct swm_region *r;
7010
7011
7012 if (i >= ScreenCount(display))
7013 errx(1, "scan_xrandr: invalid screen");
7014
7015 /* remove any old regions */
7016 while ((r = TAILQ_FIRST(&screens[i].rl)) != NULL) {
7017 r->ws->old_r = r->ws->r = NULL;
7018 XDestroyWindow(display, r->bar_window);
7019 TAILQ_REMOVE(&screens[i].rl, r, entry);
7020 TAILQ_INSERT_TAIL(&screens[i].orl, r, entry);
7021 }
7022 outputs = 0;
7023
7024 /* map virtual screens onto physical screens */
7025 #ifdef SWM_XRR_HAS_CRTC
7026 if (xrandr_support) {
7027 sr = XRRGetScreenResources(display, screens[i].root);
7028 if (sr == NULL)
7029 new_region(&screens[i], 0, 0,
7030 DisplayWidth(display, i),
7031 DisplayHeight(display, i));
7032 else
7033 ncrtc = sr->ncrtc;
7034
7035 for (c = 0, ci = NULL; c < ncrtc; c++) {
7036 ci = XRRGetCrtcInfo(display, sr, sr->crtcs[c]);
7037 if (ci->noutput == 0)
7038 continue;
7039
7040 if (ci != NULL && ci->mode == None)
7041 new_region(&screens[i], 0, 0,
7042 DisplayWidth(display, i),
7043 DisplayHeight(display, i));
7044 else
7045 new_region(&screens[i],
7046 ci->x, ci->y, ci->width, ci->height);
7047 }
7048 if (ci)
7049 XRRFreeCrtcInfo(ci);
7050 XRRFreeScreenResources(sr);
7051 } else
7052 #endif /* SWM_XRR_HAS_CRTC */
7053 {
7054 new_region(&screens[i], 0, 0, DisplayWidth(display, i),
7055 DisplayHeight(display, i));
7056 }
7057 }
7058
7059 void
7060 screenchange(XEvent *e) {
7061 XRRScreenChangeNotifyEvent *xe = (XRRScreenChangeNotifyEvent *)e;
7062 struct swm_region *r;
7063 int i;
7064
7065 DNPRINTF(SWM_D_EVENT, "screenchange: root: 0x%lx\n", xe->root);
7066
7067 if (!XRRUpdateConfiguration(e))
7068 return;
7069
7070 /* silly event doesn't include the screen index */
7071 for (i = 0; i < ScreenCount(display); i++)
7072 if (screens[i].root == xe->root)
7073 break;
7074 if (i >= ScreenCount(display))
7075 errx(1, "screenchange: screen not found");
7076
7077 /* brute force for now, just re-enumerate the regions */
7078 scan_xrandr(i);
7079
7080 /* add bars to all regions */
7081 for (i = 0; i < ScreenCount(display); i++)
7082 TAILQ_FOREACH(r, &screens[i].rl, entry)
7083 bar_setup(r);
7084 stack();
7085 if (focus_mode == SWM_FOCUS_DEFAULT)
7086 drain_enter_notify();
7087 }
7088
7089 void
7090 grab_windows(void)
7091 {
7092 Window d1, d2, *wins = NULL;
7093 XWindowAttributes wa;
7094 unsigned int no;
7095 int i, j;
7096 long state, manage;
7097
7098 for (i = 0; i < ScreenCount(display); i++) {
7099 if (!XQueryTree(display, screens[i].root, &d1, &d2, &wins, &no))
7100 continue;
7101
7102 /* attach windows to a region */
7103 /* normal windows */
7104 for (j = 0; j < no; j++) {
7105 if (!XGetWindowAttributes(display, wins[j], &wa) ||
7106 wa.override_redirect ||
7107 XGetTransientForHint(display, wins[j], &d1))
7108 continue;
7109
7110 state = getstate(wins[j]);
7111 manage = state == IconicState;
7112 if (wa.map_state == IsViewable || manage)
7113 manage_window(wins[j]);
7114 }
7115 /* transient windows */
7116 for (j = 0; j < no; j++) {
7117 if (!XGetWindowAttributes(display, wins[j], &wa) ||
7118 wa.override_redirect)
7119 continue;
7120
7121 state = getstate(wins[j]);
7122 manage = state == IconicState;
7123 if (XGetTransientForHint(display, wins[j], &d1) &&
7124 manage)
7125 manage_window(wins[j]);
7126 }
7127 if (wins) {
7128 XFree(wins);
7129 wins = NULL;
7130 }
7131 }
7132 }
7133
7134 void
7135 setup_screens(void)
7136 {
7137 int i, j, k;
7138 int errorbase, major, minor;
7139 struct workspace *ws;
7140 XGCValues gcv;
7141
7142 if ((screens = calloc(ScreenCount(display),
7143 sizeof(struct swm_screen))) == NULL)
7144 err(1, "setup_screens: calloc: failed to allocate memory for "
7145 "screens");
7146
7147 /* initial Xrandr setup */
7148 xrandr_support = XRRQueryExtension(display,
7149 &xrandr_eventbase, &errorbase);
7150 if (xrandr_support)
7151 if (XRRQueryVersion(display, &major, &minor) && major < 1)
7152 xrandr_support = 0;
7153
7154 /* map physical screens */
7155 for (i = 0; i < ScreenCount(display); i++) {
7156 DNPRINTF(SWM_D_WS, "setup_screens: init screen: %d\n", i);
7157 screens[i].idx = i;
7158 TAILQ_INIT(&screens[i].rl);
7159 TAILQ_INIT(&screens[i].orl);
7160 screens[i].root = RootWindow(display, i);
7161
7162 /* set default colors */
7163 setscreencolor("red", i + 1, SWM_S_COLOR_FOCUS);
7164 setscreencolor("rgb:88/88/88", i + 1, SWM_S_COLOR_UNFOCUS);
7165 setscreencolor("rgb:00/80/80", i + 1, SWM_S_COLOR_BAR_BORDER);
7166 setscreencolor("black", i + 1, SWM_S_COLOR_BAR);
7167 setscreencolor("rgb:a0/a0/a0", i + 1, SWM_S_COLOR_BAR_FONT);
7168
7169 /* create graphics context on screen with default font color */
7170 screens[i].bar_gc = XCreateGC(display, screens[i].root, 0,
7171 &gcv);
7172
7173 XSetForeground(display, screens[i].bar_gc,
7174 screens[i].c[SWM_S_COLOR_BAR_FONT].color);
7175
7176 /* set default cursor */
7177 XDefineCursor(display, screens[i].root,
7178 XCreateFontCursor(display, XC_left_ptr));
7179
7180 /* init all workspaces */
7181 /* XXX these should be dynamically allocated too */
7182 for (j = 0; j < SWM_WS_MAX; j++) {
7183 ws = &screens[i].ws[j];
7184 ws->idx = j;
7185 ws->name = NULL;
7186 ws->focus = NULL;
7187 ws->r = NULL;
7188 ws->old_r = NULL;
7189 TAILQ_INIT(&ws->winlist);
7190 TAILQ_INIT(&ws->unmanagedlist);
7191
7192 for (k = 0; layouts[k].l_stack != NULL; k++)
7193 if (layouts[k].l_config != NULL)
7194 layouts[k].l_config(ws,
7195 SWM_ARG_ID_STACKINIT);
7196 ws->cur_layout = &layouts[0];
7197 ws->cur_layout->l_string(ws);
7198 }
7199
7200 scan_xrandr(i);
7201
7202 if (xrandr_support)
7203 XRRSelectInput(display, screens[i].root,
7204 RRScreenChangeNotifyMask);
7205 }
7206 }
7207
7208 void
7209 setup_globals(void)
7210 {
7211 if ((bar_fonts = strdup(SWM_BAR_FONTS)) == NULL)
7212 err(1, "setup_globals: strdup: failed to allocate memory.");
7213
7214 if ((spawn_term[0] = strdup("xterm")) == NULL)
7215 err(1, "setup_globals: strdup: failed to allocate memory.");
7216
7217 if ((clock_format = strdup("%a %b %d %R %Z %Y")) == NULL)
7218 err(1, "setup_globals: strdup: failed to allocate memory.");
7219 }
7220
7221 void
7222 workaround(void)
7223 {
7224 int i;
7225 Atom netwmcheck, netwmname, utf8_string;
7226 Window root, win;
7227
7228 /* work around sun jdk bugs, code from wmname */
7229 netwmcheck = XInternAtom(display, "_NET_SUPPORTING_WM_CHECK", False);
7230 netwmname = XInternAtom(display, "_NET_WM_NAME", False);
7231 utf8_string = XInternAtom(display, "UTF8_STRING", False);
7232 for (i = 0; i < ScreenCount(display); i++) {
7233 root = screens[i].root;
7234 win = XCreateSimpleWindow(display,root, 0, 0, 1, 1, 0,
7235 screens[i].c[SWM_S_COLOR_UNFOCUS].color,
7236 screens[i].c[SWM_S_COLOR_UNFOCUS].color);
7237
7238 XChangeProperty(display, root, netwmcheck, XA_WINDOW, 32,
7239 PropModeReplace, (unsigned char *)&win, 1);
7240 XChangeProperty(display, win, netwmcheck, XA_WINDOW, 32,
7241 PropModeReplace, (unsigned char *)&win, 1);
7242 XChangeProperty(display, win, netwmname, utf8_string, 8,
7243 PropModeReplace, (unsigned char*)"LG3D", strlen("LG3D"));
7244 }
7245 }
7246
7247 int
7248 main(int argc, char *argv[])
7249 {
7250 struct swm_region *r, *rr;
7251 struct ws_win *winfocus = NULL;
7252 struct timeval tv;
7253 union arg a;
7254 char conf[PATH_MAX], *cfile = NULL;
7255 struct stat sb;
7256 XEvent e;
7257 int xfd, i;
7258 fd_set rd;
7259 struct sigaction sact;
7260
7261 start_argv = argv;
7262 warnx("Welcome to spectrwm V%s Build: %s", SPECTRWM_VERSION, buildstr);
7263 if (!setlocale(LC_CTYPE, "") || !setlocale(LC_TIME, "") ||
7264 !XSupportsLocale())
7265 warnx("no locale support");
7266
7267 if (!X_HAVE_UTF8_STRING)
7268 warnx("no UTF-8 support");
7269
7270 if (!(display = XOpenDisplay(0)))
7271 errx(1, "can not open display");
7272
7273 if (active_wm())
7274 errx(1, "other wm running");
7275
7276 /* handle some signals */
7277 bzero(&sact, sizeof(sact));
7278 sigemptyset(&sact.sa_mask);
7279 sact.sa_flags = 0;
7280 sact.sa_handler = sighdlr;
7281 sigaction(SIGINT, &sact, NULL);
7282 sigaction(SIGQUIT, &sact, NULL);
7283 sigaction(SIGTERM, &sact, NULL);
7284 sigaction(SIGHUP, &sact, NULL);
7285
7286 sact.sa_handler = sighdlr;
7287 sact.sa_flags = SA_NOCLDSTOP;
7288 sigaction(SIGCHLD, &sact, NULL);
7289
7290 astate = XInternAtom(display, "WM_STATE", False);
7291 aprot = XInternAtom(display, "WM_PROTOCOLS", False);
7292 adelete = XInternAtom(display, "WM_DELETE_WINDOW", False);
7293 takefocus = XInternAtom(display, "WM_TAKE_FOCUS", False);
7294 a_wmname = XInternAtom(display, "WM_NAME", False);
7295 a_netwmname = XInternAtom(display, "_NET_WM_NAME", False);
7296 a_utf8_string = XInternAtom(display, "UTF8_STRING", False);
7297 a_string = XInternAtom(display, "STRING", False);
7298 a_swm_iconic = XInternAtom(display, "_SWM_ICONIC", False);
7299
7300 /* look for local and global conf file */
7301 pwd = getpwuid(getuid());
7302 if (pwd == NULL)
7303 errx(1, "invalid user: %d", getuid());
7304
7305 setup_globals();
7306 setup_screens();
7307 setup_keys();
7308 setup_quirks();
7309 setup_spawn();
7310
7311 /* load config */
7312 for (i = 0; ; i++) {
7313 conf[0] = '\0';
7314 switch (i) {
7315 case 0:
7316 /* ~ */
7317 snprintf(conf, sizeof conf, "%s/.%s",
7318 pwd->pw_dir, SWM_CONF_FILE);
7319 break;
7320 case 1:
7321 /* global */
7322 snprintf(conf, sizeof conf, "/etc/%s",
7323 SWM_CONF_FILE);
7324 break;
7325 case 2:
7326 /* ~ compat */
7327 snprintf(conf, sizeof conf, "%s/.%s",
7328 pwd->pw_dir, SWM_CONF_FILE_OLD);
7329 break;
7330 case 3:
7331 /* global compat */
7332 snprintf(conf, sizeof conf, "/etc/%s",
7333 SWM_CONF_FILE_OLD);
7334 break;
7335 default:
7336 goto noconfig;
7337 }
7338
7339 if (strlen(conf) && stat(conf, &sb) != -1)
7340 if (S_ISREG(sb.st_mode)) {
7341 cfile = conf;
7342 break;
7343 }
7344 }
7345 noconfig:
7346
7347 /* load conf (if any) and refresh font color in bar graphics contexts */
7348 if (cfile && conf_load(cfile, SWM_CONF_DEFAULT) == 0)
7349 for (i = 0; i < ScreenCount(display); ++i)
7350 XSetForeground(display, screens[i].bar_gc,
7351 screens[i].c[SWM_S_COLOR_BAR_FONT].color);
7352
7353 setup_ewmh();
7354 /* set some values to work around bad programs */
7355 workaround();
7356 /* grab existing windows (before we build the bars) */
7357 grab_windows();
7358
7359 if (getenv("SWM_STARTED") == NULL)
7360 setenv("SWM_STARTED", "YES", 1);
7361
7362 /* setup all bars */
7363 for (i = 0; i < ScreenCount(display); i++)
7364 TAILQ_FOREACH(r, &screens[i].rl, entry) {
7365 if (winfocus == NULL)
7366 winfocus = TAILQ_FIRST(&r->ws->winlist);
7367 bar_setup(r);
7368 }
7369
7370 unfocus_all();
7371
7372 grabkeys();
7373 stack();
7374 if (focus_mode == SWM_FOCUS_DEFAULT)
7375 drain_enter_notify();
7376
7377 xfd = ConnectionNumber(display);
7378 while (running) {
7379 while (XPending(display)) {
7380 XNextEvent(display, &e);
7381 if (running == 0)
7382 goto done;
7383 if (e.type < LASTEvent) {
7384 DNPRINTF(SWM_D_EVENTQ ,"XEvent: handled: %s, "
7385 "window: 0x%lx, type: %s (%d), %d remaining"
7386 "\n", YESNO(handler[e.type]),
7387 e.xany.window, geteventname(&e),
7388 e.type, QLength(display));
7389
7390 if (handler[e.type])
7391 handler[e.type](&e);
7392 } else {
7393 DNPRINTF(SWM_D_EVENTQ, "XRandr Event: window: "
7394 "0x%lx, type: %s (%d)\n", e.xany.window,
7395 xrandr_geteventname(&e), e.type);
7396
7397 switch (e.type - xrandr_eventbase) {
7398 case RRScreenChangeNotify:
7399 screenchange(&e);
7400 break;
7401 default:
7402 break;
7403 }
7404 }
7405 }
7406
7407 /* if we are being restarted go focus on first window */
7408 if (winfocus) {
7409 rr = winfocus->ws->r;
7410 if (rr == NULL) {
7411 /* not a visible window */
7412 winfocus = NULL;
7413 continue;
7414 }
7415 /* move pointer to first screen if multi screen */
7416 if (ScreenCount(display) > 1 || outputs > 1)
7417 XWarpPointer(display, None, rr->s[0].root,
7418 0, 0, 0, 0, X(rr),
7419 Y(rr) + (bar_enabled ? bar_height : 0));
7420
7421 a.id = SWM_ARG_ID_FOCUSCUR;
7422 focus(rr, &a);
7423 winfocus = NULL;
7424 continue;
7425 }
7426
7427 FD_ZERO(&rd);
7428 FD_SET(xfd, &rd);
7429 tv.tv_sec = 1;
7430 tv.tv_usec = 0;
7431 if (select(xfd + 1, &rd, NULL, NULL, &tv) == -1)
7432 if (errno != EINTR)
7433 DNPRINTF(SWM_D_MISC, "select failed");
7434 if (restart_wm == 1)
7435 restart(NULL, NULL);
7436 if (search_resp == 1)
7437 search_do_resp();
7438 if (running == 0)
7439 goto done;
7440 if (bar_alarm) {
7441 bar_alarm = 0;
7442 bar_update();
7443 }
7444 }
7445 done:
7446 teardown_ewmh();
7447 bar_extra_stop();
7448
7449 for (i = 0; i < ScreenCount(display); ++i)
7450 if (screens[i].bar_gc != NULL)
7451 XFreeGC(display, screens[i].bar_gc);
7452
7453 XFreeFontSet(display, bar_fs);
7454 XCloseDisplay(display);
7455
7456 return (0);
7457 }