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