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