tony / oxwm

Fixed merge conflicts.; Browse files
tonybtw committed 2026-01-11 parents 5db5675 45257ca commit 1ee9ed195ff6e32d60ce25a1f07161b1f6de2aee
Showing 20 changed files with 1129 additions and 602 deletions. UnifiedSplit
+1 −1 Cargo.lock
@@ -291,7 +291,7 @@ checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d"
291 291
292 [[package]] 292 [[package]]
293 name = "oxwm" 293 name = "oxwm"
294 -version = "0.9.0" 294 +version = "0.10.0"
295 dependencies = [ 295 dependencies = [
296 "chrono", 296 "chrono",
297 "dirs", 297 "dirs",
+1 −1 Cargo.toml
@@ -1,6 +1,6 @@
1 [package] 1 [package]
2 name = "oxwm" 2 name = "oxwm"
3 -version = "0.9.0" 3 +version = "0.10.0"
4 edition = "2024" 4 edition = "2024"
5 5
6 [lib] 6 [lib]
+14 −10 justfile
@@ -3,10 +3,14 @@ build:
3 3
4 install: build 4 install: build
5 cp target/release/oxwm /usr/bin/oxwm 5 cp target/release/oxwm /usr/bin/oxwm
6 + cp resources/oxwm.desktop /usr/share/xsessions/oxwm.desktop
6 chmod +x /usr/bin/oxwm 7 chmod +x /usr/bin/oxwm
7 @echo "✓ oxwm installed to /usr/bin/oxwm" 8 @echo "✓ oxwm installed to /usr/bin/oxwm"
8 @echo " Run 'oxwm --init' to create your config" 9 @echo " Run 'oxwm --init' to create your config"
9 10
11 +checkinstall:
12 + checkinstall --pkgname oxwm --exclude /root -y just install
13 +
10 uninstall: 14 uninstall:
11 rm -f /usr/bin/oxwm 15 rm -f /usr/bin/oxwm
12 @echo "✓ oxwm uninstalled" 16 @echo "✓ oxwm uninstalled"
@@ -16,20 +20,20 @@ clean:
16 cargo clean 20 cargo clean
17 21
18 test-clean: 22 test-clean:
19 - pkill Xephyr || true 23 + pkill Xephyr || true
20 - rm -rf ~/.config/oxwm 24 + rm -rf ~/.config/oxwm
21 - Xephyr -screen 1280x800 :1 & sleep 1 25 + Xephyr -screen 1280x800 :1 & sleep 1
22 - DISPLAY=:1 cargo run --release -- --config resources/test-config.lua 26 + DISPLAY=:1 cargo run --release -- --config resources/test-config.lua
23 27
24 test: 28 test:
25 - pkill Xephyr || true 29 + pkill Xephyr || true
26 - Xephyr -screen 1280x800 :2 & sleep 1 30 + Xephyr -screen 1280x800 :2 & sleep 1
27 - DISPLAY=:2 cargo run --release -- --config resources/test-config.lua 31 + DISPLAY=:2 cargo run --release -- --config resources/test-config.lua
28 32
29 test-multimon: 33 test-multimon:
30 - pkill Xephyr || true 34 + pkill Xephyr || true
31 - Xephyr +xinerama -screen 640x480 -screen 640x480 :1 & sleep 1 35 + Xephyr +xinerama -screen 640x480 -screen 640x480 :1 & sleep 1
32 - DISPLAY=:1 cargo run --release -- --config resources/test-config.lua 36 + DISPLAY=:1 cargo run --release -- --config resources/test-config.lua
33 37
34 init: 38 init:
35 cargo run --release -- --init 39 cargo run --release -- --init
+2 −0 resources/test-config.lua
@@ -28,12 +28,14 @@ local colors = {
28 blue = 0x6dade3, 28 blue = 0x6dade3,
29 } 29 }
30 30
31 +
31 local modkey = "Mod1" 32 local modkey = "Mod1"
32 33
33 oxwm.set_terminal("st") 34 oxwm.set_terminal("st")
34 oxwm.set_modkey(modkey) 35 oxwm.set_modkey(modkey)
35 oxwm.set_tags({ "1", "2", "3", "4", "5", "6", "7", "8", "9" }) 36 oxwm.set_tags({ "1", "2", "3", "4", "5", "6", "7", "8", "9" })
36 oxwm.auto_tile(true); 37 oxwm.auto_tile(true);
38 +oxwm.bar.set_hide_vacant_tags(true);
37 39
38 oxwm.set_layout_symbol("tiling", "[T]") 40 oxwm.set_layout_symbol("tiling", "[T]")
39 oxwm.set_layout_symbol("normie", "[F]") 41 oxwm.set_layout_symbol("normie", "[F]")
+47 −40 src/bar/bar.rs
@@ -1,5 +1,5 @@
1 use super::blocks::Block; 1 use super::blocks::Block;
2 -use super::font::{Font, FontDraw}; 2 +use super::font::{DrawingSurface, Font};
3 use crate::Config; 3 use crate::Config;
4 use crate::errors::X11Error; 4 use crate::errors::X11Error;
5 use std::time::Instant; 5 use std::time::Instant;
@@ -13,10 +13,7 @@ pub struct Bar {
13 width: u16, 13 width: u16,
14 height: u16, 14 height: u16,
15 graphics_context: Gcontext, 15 graphics_context: Gcontext,
16 - pixmap: x11::xlib::Pixmap, 16 + surface: DrawingSurface,
17 - display: *mut x11::xlib::Display,
18 -
19 - font_draw: FontDraw,
20 17
21 tag_widths: Vec<u16>, 18 tag_widths: Vec<u16>,
22 needs_redraw: bool, 19 needs_redraw: bool,
@@ -31,6 +28,9 @@ pub struct Bar {
31 scheme_occupied: crate::ColorScheme, 28 scheme_occupied: crate::ColorScheme,
32 scheme_selected: crate::ColorScheme, 29 scheme_selected: crate::ColorScheme,
33 scheme_urgent: crate::ColorScheme, 30 scheme_urgent: crate::ColorScheme,
31 + hide_vacant_tags: bool,
32 + last_occupied_tags: u32,
33 + last_current_tags: u32,
34 } 34 }
35 35
36 impl Bar { 36 impl Bar {
@@ -80,19 +80,15 @@ impl Bar {
80 80
81 let visual = unsafe { x11::xlib::XDefaultVisual(display, screen_num as i32) }; 81 let visual = unsafe { x11::xlib::XDefaultVisual(display, screen_num as i32) };
82 let colormap = unsafe { x11::xlib::XDefaultColormap(display, screen_num as i32) }; 82 let colormap = unsafe { x11::xlib::XDefaultColormap(display, screen_num as i32) };
83 - let depth = unsafe { x11::xlib::XDefaultDepth(display, screen_num as i32) };
84 -
85 - let pixmap = unsafe {
86 - x11::xlib::XCreatePixmap(
87 - display,
88 - window as x11::xlib::Drawable,
89 - width as u32,
90 - height as u32,
91 - depth as u32,
92 - )
93 - };
94 83
95 - let font_draw = FontDraw::new(display, pixmap, visual, colormap)?; 84 + let surface = DrawingSurface::new(
85 + display,
86 + window as x11::xlib::Drawable,
87 + width as u32,
88 + height as u32,
89 + visual,
90 + colormap,
91 + )?;
96 92
97 let horizontal_padding = (font.height() as f32 * 0.4) as u16; 93 let horizontal_padding = (font.height() as f32 * 0.4) as u16;
98 94
@@ -124,9 +120,7 @@ impl Bar {
124 width, 120 width,
125 height, 121 height,
126 graphics_context, 122 graphics_context,
127 - pixmap, 123 + surface,
128 - display,
129 - font_draw,
130 tag_widths, 124 tag_widths,
131 needs_redraw: true, 125 needs_redraw: true,
132 blocks, 126 blocks,
@@ -138,6 +132,9 @@ impl Bar {
138 scheme_occupied: config.scheme_occupied, 132 scheme_occupied: config.scheme_occupied,
139 scheme_selected: config.scheme_selected, 133 scheme_selected: config.scheme_selected,
140 scheme_urgent: config.scheme_urgent, 134 scheme_urgent: config.scheme_urgent,
135 + hide_vacant_tags: config.hide_vacant_tags,
136 + last_occupied_tags: 0,
137 + last_current_tags: 0,
141 }) 138 })
142 } 139 }
143 140
@@ -201,11 +198,11 @@ impl Bar {
201 connection.flush()?; 198 connection.flush()?;
202 199
203 unsafe { 200 unsafe {
204 - let gc = x11::xlib::XCreateGC(display, self.pixmap, 0, std::ptr::null_mut()); 201 + let gc = x11::xlib::XCreateGC(display, self.surface.pixmap(), 0, std::ptr::null_mut());
205 x11::xlib::XSetForeground(display, gc, self.scheme_normal.background as u64); 202 x11::xlib::XSetForeground(display, gc, self.scheme_normal.background as u64);
206 x11::xlib::XFillRectangle( 203 x11::xlib::XFillRectangle(
207 display, 204 display,
208 - self.pixmap, 205 + self.surface.pixmap(),
209 gc, 206 gc,
210 0, 207 0,
211 0, 208 0,
@@ -215,6 +212,9 @@ impl Bar {
215 x11::xlib::XFreeGC(display, gc); 212 x11::xlib::XFreeGC(display, gc);
216 } 213 }
217 214
215 + self.last_occupied_tags = occupied_tags;
216 + self.last_current_tags = current_tags;
217 +
218 let mut x_position: i16 = 0; 218 let mut x_position: i16 = 0;
219 219
220 for (tag_index, tag) in self.tags.iter().enumerate() { 220 for (tag_index, tag) in self.tags.iter().enumerate() {
@@ -223,6 +223,10 @@ impl Bar {
223 let is_occupied = (occupied_tags & tag_mask) != 0; 223 let is_occupied = (occupied_tags & tag_mask) != 0;
224 let is_urgent = (urgent_tags & tag_mask) != 0; 224 let is_urgent = (urgent_tags & tag_mask) != 0;
225 225
226 + if self.hide_vacant_tags && !is_occupied && !is_selected {
227 + continue;
228 + }
229 +
226 let tag_width = self.tag_widths[tag_index]; 230 let tag_width = self.tag_widths[tag_index];
227 231
228 let scheme = if is_selected { 232 let scheme = if is_selected {
@@ -241,7 +245,8 @@ impl Bar {
241 let top_padding = 4; 245 let top_padding = 4;
242 let text_y = top_padding + font.ascent(); 246 let text_y = top_padding + font.ascent();
243 247
244 - self.font_draw 248 + self.surface
249 + .font_draw()
245 .draw_text(font, scheme.foreground, text_x, text_y, tag); 250 .draw_text(font, scheme.foreground, text_x, text_y, tag);
246 251
247 if is_selected || is_urgent { 252 if is_selected || is_urgent {
@@ -255,11 +260,11 @@ impl Bar {
255 let underline_x = x_position + (underline_padding / 2) as i16; 260 let underline_x = x_position + (underline_padding / 2) as i16;
256 261
257 unsafe { 262 unsafe {
258 - let gc = x11::xlib::XCreateGC(display, self.pixmap, 0, std::ptr::null_mut()); 263 + let gc = x11::xlib::XCreateGC(display, self.surface.pixmap(), 0, std::ptr::null_mut());
259 x11::xlib::XSetForeground(display, gc, scheme.underline as u64); 264 x11::xlib::XSetForeground(display, gc, scheme.underline as u64);
260 x11::xlib::XFillRectangle( 265 x11::xlib::XFillRectangle(
261 display, 266 display,
262 - self.pixmap, 267 + self.surface.pixmap(),
263 gc, 268 gc,
264 underline_x as i32, 269 underline_x as i32,
265 underline_y as i32, 270 underline_y as i32,
@@ -279,7 +284,7 @@ impl Bar {
279 let top_padding = 4; 284 let top_padding = 4;
280 let text_y = top_padding + font.ascent(); 285 let text_y = top_padding + font.ascent();
281 286
282 - self.font_draw.draw_text( 287 + self.surface.font_draw().draw_text(
283 font, 288 font,
284 self.scheme_normal.foreground, 289 self.scheme_normal.foreground,
285 text_x, 290 text_x,
@@ -295,7 +300,7 @@ impl Bar {
295 let text_x = x_position; 300 let text_x = x_position;
296 let text_y = top_padding + font.ascent(); 301 let text_y = top_padding + font.ascent();
297 302
298 - self.font_draw.draw_text( 303 + self.surface.font_draw().draw_text(
299 font, 304 font,
300 self.scheme_selected.foreground, 305 self.scheme_selected.foreground,
301 text_x, 306 text_x,
@@ -316,7 +321,8 @@ impl Bar {
316 let top_padding = 4; 321 let top_padding = 4;
317 let text_y = top_padding + font.ascent(); 322 let text_y = top_padding + font.ascent();
318 323
319 - self.font_draw 324 + self.surface
325 + .font_draw()
320 .draw_text(font, block.color(), x_position, text_y, &text); 326 .draw_text(font, block.color(), x_position, text_y, &text);
321 327
322 if self.block_underlines[i] { 328 if self.block_underlines[i] {
@@ -331,11 +337,11 @@ impl Bar {
331 337
332 unsafe { 338 unsafe {
333 let gc = 339 let gc =
334 - x11::xlib::XCreateGC(display, self.pixmap, 0, std::ptr::null_mut()); 340 + x11::xlib::XCreateGC(display, self.surface.pixmap(), 0, std::ptr::null_mut());
335 x11::xlib::XSetForeground(display, gc, block.color() as u64); 341 x11::xlib::XSetForeground(display, gc, block.color() as u64);
336 x11::xlib::XFillRectangle( 342 x11::xlib::XFillRectangle(
337 display, 343 display,
338 - self.pixmap, 344 + self.surface.pixmap(),
339 gc, 345 gc,
340 underline_x as i32, 346 underline_x as i32,
341 underline_y as i32, 347 underline_y as i32,
@@ -358,7 +364,7 @@ impl Bar {
358 ); 364 );
359 x11::xlib::XCopyArea( 365 x11::xlib::XCopyArea(
360 display, 366 display,
361 - self.pixmap, 367 + self.surface.pixmap(),
362 self.window as x11::xlib::Drawable, 368 self.window as x11::xlib::Drawable,
363 gc, 369 gc,
364 0, 370 0,
@@ -369,7 +375,7 @@ impl Bar {
369 0, 375 0,
370 ); 376 );
371 x11::xlib::XFreeGC(display, gc); 377 x11::xlib::XFreeGC(display, gc);
372 - x11::xlib::XSync(display, 0); 378 + x11::xlib::XSync(display, 1);
373 } 379 }
374 380
375 self.needs_redraw = false; 381 self.needs_redraw = false;
@@ -381,6 +387,14 @@ impl Bar {
381 let mut current_x_position = 0; 387 let mut current_x_position = 0;
382 388
383 for (tag_index, &tag_width) in self.tag_widths.iter().enumerate() { 389 for (tag_index, &tag_width) in self.tag_widths.iter().enumerate() {
390 + let tag_mask = 1 << tag_index;
391 + let is_selected = (self.last_current_tags & tag_mask) != 0;
392 + let is_occupied = (self.last_occupied_tags & tag_mask) != 0;
393 +
394 + if self.hide_vacant_tags && !is_occupied && !is_selected {
395 + continue;
396 + }
397 +
384 if click_x >= current_x_position && click_x < current_x_position + tag_width as i16 { 398 if click_x >= current_x_position && click_x < current_x_position + tag_width as i16 {
385 return Some(tag_index); 399 return Some(tag_index);
386 } 400 }
@@ -413,16 +427,9 @@ impl Bar {
413 self.scheme_occupied = config.scheme_occupied; 427 self.scheme_occupied = config.scheme_occupied;
414 self.scheme_selected = config.scheme_selected; 428 self.scheme_selected = config.scheme_selected;
415 self.scheme_urgent = config.scheme_urgent; 429 self.scheme_urgent = config.scheme_urgent;
430 + self.hide_vacant_tags = config.hide_vacant_tags;
416 431
417 self.status_text.clear(); 432 self.status_text.clear();
418 self.needs_redraw = true; 433 self.needs_redraw = true;
419 } 434 }
420 } 435 }
421 -
422 -impl Drop for Bar {
423 - fn drop(&mut self) {
424 - unsafe {
425 - x11::xlib::XFreePixmap(self.display, self.pixmap);
426 - }
427 - }
428 -}
+39 −4 src/bar/blocks/battery.rs
@@ -1,6 +1,7 @@
1 use super::Block; 1 use super::Block;
2 use crate::errors::BlockError; 2 use crate::errors::BlockError;
3 use std::fs; 3 use std::fs;
4 +use std::path::{Path, PathBuf};
4 use std::time::Duration; 5 use std::time::Duration;
5 6
6 pub struct Battery { 7 pub struct Battery {
@@ -12,6 +13,39 @@ pub struct Battery {
12 battery_path: String, 13 battery_path: String,
13 } 14 }
14 15
16 +fn detect_battery_name() -> Option<String> {
17 + let base = Path::new("/sys/class/power_supply");
18 + let entries = fs::read_dir(base).ok()?;
19 +
20 + for entry in entries.flatten() {
21 + let path: PathBuf = entry.path();
22 +
23 + let type_path = path.join("type");
24 + let present_path = path.join("present");
25 +
26 + let is_battery = fs::read_to_string(&type_path)
27 + .map(|s| s.trim() == "Battery")
28 + .unwrap_or(false);
29 +
30 + let is_present = fs::read_to_string(&present_path)
31 + .map(|s| s.trim() == "1")
32 + .unwrap_or(true);
33 +
34 + let is_device_scope = fs::read_to_string(path.join("scope"))
35 + .map(|s| s.trim().eq_ignore_ascii_case("device"))
36 + .unwrap_or(false);
37 +
38 + if !is_battery || !is_present || is_device_scope {
39 + continue;
40 + }
41 +
42 + if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
43 + return Some(name.to_string());
44 + }
45 + }
46 + None
47 +}
48 +
15 impl Battery { 49 impl Battery {
16 pub fn new( 50 pub fn new(
17 format_charging: &str, 51 format_charging: &str,
@@ -21,16 +55,17 @@ impl Battery {
21 color: u32, 55 color: u32,
22 battery_name: Option<String>, 56 battery_name: Option<String>,
23 ) -> Self { 57 ) -> Self {
58 + let name = battery_name
59 + .or_else(detect_battery_name)
60 + .unwrap_or_else(|| "BAT0".to_string());
61 +
24 Self { 62 Self {
25 format_charging: format_charging.to_string(), 63 format_charging: format_charging.to_string(),
26 format_discharging: format_discharging.to_string(), 64 format_discharging: format_discharging.to_string(),
27 format_full: format_full.to_string(), 65 format_full: format_full.to_string(),
28 interval: Duration::from_secs(interval_secs), 66 interval: Duration::from_secs(interval_secs),
29 color, 67 color,
30 - battery_path: format!( 68 + battery_path: format!("/sys/class/power_supply/{}", name),
31 - "/sys/class/power_supply/{}",
32 - battery_name.unwrap_or_else(|| "BAT0".to_string())
33 - ),
34 } 69 }
35 } 70 }
36 71
+29 −5 src/bar/blocks/shell.rs
@@ -1,13 +1,15 @@
1 use super::Block; 1 use super::Block;
2 use crate::errors::BlockError; 2 use crate::errors::BlockError;
3 use std::process::Command; 3 use std::process::Command;
4 -use std::time::Duration; 4 +use std::time::{Duration, Instant};
5 5
6 pub struct ShellBlock { 6 pub struct ShellBlock {
7 format: String, 7 format: String,
8 command: String, 8 command: String,
9 interval: Duration, 9 interval: Duration,
10 color: u32, 10 color: u32,
11 + cached_output: Option<String>,
12 + last_run: Option<Instant>,
11 } 13 }
12 14
13 impl ShellBlock { 15 impl ShellBlock {
@@ -17,12 +19,12 @@ impl ShellBlock {
17 command: command.to_string(), 19 command: command.to_string(),
18 interval: Duration::from_secs(interval_secs), 20 interval: Duration::from_secs(interval_secs),
19 color, 21 color,
22 + cached_output: None,
23 + last_run: None,
20 } 24 }
21 } 25 }
22 -}
23 26
24 -impl Block for ShellBlock { 27 + fn execute(&mut self) -> Result<String, BlockError> {
25 - fn content(&mut self) -> Result<String, BlockError> {
26 let output = Command::new("sh") 28 let output = Command::new("sh")
27 .arg("-c") 29 .arg("-c")
28 .arg(&self.command) 30 .arg(&self.command)
@@ -37,7 +39,29 @@ impl Block for ShellBlock {
37 } 39 }
38 40
39 let result = String::from_utf8_lossy(&output.stdout).trim().to_string(); 41 let result = String::from_utf8_lossy(&output.stdout).trim().to_string();
40 - Ok(self.format.replace("{}", &result)) 42 + let formatted = self.format.replace("{}", &result);
43 +
44 + self.cached_output = Some(formatted.clone());
45 + self.last_run = Some(Instant::now());
46 +
47 + Ok(formatted)
48 + }
49 +}
50 +
51 +impl Block for ShellBlock {
52 + fn content(&mut self) -> Result<String, BlockError> {
53 + let should_refresh = match self.last_run {
54 + None => true,
55 + Some(last) => last.elapsed() >= self.interval,
56 + };
57 +
58 + if should_refresh {
59 + return self.execute();
60 + }
61 +
62 + self.cached_output
63 + .clone()
64 + .ok_or_else(|| BlockError::CommandFailed("No cached output".to_string()))
41 } 65 }
42 66
43 fn interval(&self) -> Duration { 67 fn interval(&self) -> Duration {
+49 −1 src/bar/font.rs
@@ -135,7 +135,7 @@ impl FontDraw {
135 pub fn sync(&self) { 135 pub fn sync(&self) {
136 unsafe { 136 unsafe {
137 let display = x11::xft::XftDrawDisplay(self.xft_draw); 137 let display = x11::xft::XftDrawDisplay(self.xft_draw);
138 - x11::xlib::XSync(display, 0); 138 + x11::xlib::XSync(display, 1);
139 } 139 }
140 } 140 }
141 } 141 }
@@ -149,3 +149,51 @@ impl Drop for FontDraw {
149 } 149 }
150 } 150 }
151 } 151 }
152 +
153 +pub struct DrawingSurface {
154 + font_draw: FontDraw,
155 + pixmap: x11::xlib::Pixmap,
156 + display: *mut Display,
157 +}
158 +
159 +impl DrawingSurface {
160 + pub fn new(
161 + display: *mut Display,
162 + window: x11::xlib::Drawable,
163 + width: u32,
164 + height: u32,
165 + visual: *mut Visual,
166 + colormap: Colormap,
167 + ) -> Result<Self, crate::errors::X11Error> {
168 + let depth = unsafe { x11::xlib::XDefaultDepth(display, 0) };
169 + let pixmap = unsafe {
170 + x11::xlib::XCreatePixmap(display, window, width, height, depth as u32)
171 + };
172 +
173 + let font_draw = FontDraw::new(display, pixmap, visual, colormap)?;
174 +
175 + Ok(Self {
176 + font_draw,
177 + pixmap,
178 + display,
179 + })
180 + }
181 +
182 + pub fn pixmap(&self) -> x11::xlib::Pixmap {
183 + self.pixmap
184 + }
185 +
186 + pub fn font_draw(&self) -> &FontDraw {
187 + &self.font_draw
188 + }
189 +}
190 +
191 +impl Drop for DrawingSurface {
192 + fn drop(&mut self) {
193 + unsafe {
194 + x11::xft::XftDrawDestroy(self.font_draw.xft_draw);
195 + self.font_draw.xft_draw = std::ptr::null_mut();
196 + x11::xlib::XFreePixmap(self.display, self.pixmap);
197 + }
198 + }
199 +}
+142 −91 src/bin/main.rs
@@ -1,112 +1,88 @@
1 +use oxwm::errors::ConfigError;
2 +use oxwm::errors::MainError;
3 +use std::path::Path;
1 use std::path::PathBuf; 4 use std::path::PathBuf;
2 5
3 -fn main() -> Result<(), Box<dyn std::error::Error>> { 6 +const CONFIG_FILE: &str = "config.lua";
4 - let arguments: Vec<String> = std::env::args().collect(); 7 +const TEMPLATE: &str = include_str!("../../templates/config.lua");
5 8
6 - let mut custom_config_path: Option<PathBuf> = None; 9 +enum Args {
10 + Exit,
11 + Arguments(Vec<String>),
12 + Error(MainError),
13 +}
7 14
8 - match arguments.get(1).map(|string| string.as_str()) { 15 +fn main() -> Result<(), MainError> {
9 - Some("--version") => { 16 + let arguments = match process_args() {
10 - println!("oxwm {}", env!("CARGO_PKG_VERSION")); 17 + Args::Exit => return Ok(()),
11 - return Ok(()); 18 + Args::Arguments(v) => v,
12 - } 19 + Args::Error(e) => return Err(e),
13 - Some("--help") => { 20 + };
14 - print_help();
15 - return Ok(());
16 - }
17 - Some("--init") => {
18 - init_config()?;
19 - return Ok(());
20 - }
21 - Some("--config") => {
22 - if let Some(path) = arguments.get(2) {
23 - custom_config_path = Some(PathBuf::from(path));
24 - } else {
25 - eprintln!("Error: --config requires a path argument");
26 - std::process::exit(1);
27 - }
28 - }
29 - _ => {}
30 - }
31 21
32 - let (config, had_broken_config) = load_config(custom_config_path)?; 22 + let (config, config_warning) = load_config(arguments.get(2))?;
33 23
34 - let mut window_manager = oxwm::window_manager::WindowManager::new(config)?; 24 + let mut window_manager = match oxwm::window_manager::WindowManager::new(config) {
25 + Ok(wm) => wm,
26 + Err(e) => return Err(MainError::CouldNotStartWm(e)),
27 + };
35 28
36 - if had_broken_config { 29 + if let Some(warning) = config_warning {
37 - window_manager.show_migration_overlay(); 30 + window_manager.show_startup_config_error(warning);
38 } 31 }
39 32
40 - let should_restart = window_manager.run()?; 33 + if let Err(e) = window_manager.run() {
41 - 34 + return Err(MainError::WmError(e));
42 - drop(window_manager);
43 -
44 - if should_restart {
45 - use std::os::unix::process::CommandExt;
46 - let error = std::process::Command::new(&arguments[0])
47 - .args(&arguments[1..])
48 - .exec();
49 - eprintln!("Failed to restart: {}", error);
50 } 35 }
51 36
52 Ok(()) 37 Ok(())
53 } 38 }
54 39
55 fn load_config( 40 fn load_config(
56 - custom_path: Option<PathBuf>, 41 + config_path: Option<&String>,
57 -) -> Result<(oxwm::Config, bool), Box<dyn std::error::Error>> { 42 +) -> Result<(oxwm::Config, Option<ConfigError>), MainError> {
58 - let config_path = if let Some(path) = custom_path { 43 + let path = match config_path {
59 - path 44 + None => {
60 - } else { 45 + let config_dir = get_config_path()?;
61 - let config_directory = get_config_path(); 46 + let config_path = config_dir.join(CONFIG_FILE);
62 - let lua_path = config_directory.join("config.lua"); 47 + check_convert(&config_path)?;
63 - 48 + config_path
64 - if !lua_path.exists() {
65 - let ron_path = config_directory.join("config.ron");
66 - let had_ron_config = ron_path.exists();
67 -
68 - println!("No config found at {:?}", config_directory);
69 - println!("Creating default Lua config...");
70 - init_config()?;
71 -
72 - if had_ron_config {
73 - println!("\n NOTICE: OXWM has migrated to Lua configuration.");
74 - println!(" Your old config.ron has been preserved, but is no longer used.");
75 - println!(" Your settings have been reset to defaults.");
76 - println!(" Please manually port your configuration to the new Lua format.");
77 - println!(" See the new config.lua template for examples.\n");
78 - }
79 } 49 }
80 - 50 + Some(p) => PathBuf::from(p),
81 - lua_path
82 }; 51 };
83 52
84 - let config_string = std::fs::read_to_string(&config_path) 53 + let config_string = match std::fs::read_to_string(&path) {
85 - .map_err(|error| format!("Failed to read config file: {}", error))?; 54 + Ok(c) => c,
86 - 55 + Err(e) => return Err(MainError::FailedReadConfig(e)),
87 - let config_directory = config_path.parent(); 56 + };
88 57
89 - match oxwm::config::parse_lua_config(&config_string, config_directory) { 58 + let config_directory = path.parent();
90 - Ok(mut config) => { 59 +
91 - config.path = Some(config_path); 60 + let (mut config, config_warning) =
92 - Ok((config, false)) 61 + match oxwm::config::parse_lua_config(&config_string, config_directory) {
93 - } 62 + Ok(config) => (config, None),
94 - Err(_error) => { 63 + Err(warning) => {
95 - let template = include_str!("../../templates/config.lua"); 64 + let config = match oxwm::config::parse_lua_config(TEMPLATE, None) {
96 - let config = oxwm::config::parse_lua_config(template, None) 65 + Ok(c) => c,
97 - .map_err(|error| format!("Failed to parse default template config: {}", error))?; 66 + Err(e) => return Err(MainError::FailedReadConfigTemplate(e)),
98 - Ok((config, true)) 67 + };
99 - } 68 + (config, Some(warning))
100 - } 69 + }
70 + };
71 + config.path = Some(path);
72 + Ok((config, config_warning))
101 } 73 }
102 74
103 -fn init_config() -> Result<(), Box<dyn std::error::Error>> { 75 +fn init_config() -> Result<(), MainError> {
104 - let config_directory = get_config_path(); 76 + let config_directory = get_config_path()?;
105 - std::fs::create_dir_all(&config_directory)?; 77 + if let Err(e) = std::fs::create_dir_all(&config_directory) {
78 + return Err(MainError::CouldNotCreateConfigDir(e));
79 + }
106 80
107 - let config_template = include_str!("../../templates/config.lua"); 81 + let config_template = TEMPLATE;
108 - let config_path = config_directory.join("config.lua"); 82 + let config_path = config_directory.join(CONFIG_FILE);
109 - std::fs::write(&config_path, config_template)?; 83 + if let Err(e) = std::fs::write(&config_path, config_template) {
84 + return Err(MainError::CouldNotWriteConfig(e));
85 + }
110 86
111 println!("✓ Config created at {:?}", config_path); 87 println!("✓ Config created at {:?}", config_path);
112 println!(" Edit the file and reload with Mod+Shift+R"); 88 println!(" Edit the file and reload with Mod+Shift+R");
@@ -115,10 +91,11 @@ fn init_config() -> Result<(), Box<dyn std::error::Error>> {
115 Ok(()) 91 Ok(())
116 } 92 }
117 93
118 -fn get_config_path() -> PathBuf { 94 +fn get_config_path() -> Result<PathBuf, MainError> {
119 - dirs::config_dir() 95 + match dirs::config_dir() {
120 - .expect("Could not find config directory") 96 + Some(p) => Ok(p.join("oxwm")),
121 - .join("oxwm") 97 + None => Err(MainError::NoConfigDir),
98 + }
122 } 99 }
123 100
124 fn print_help() { 101 fn print_help() {
@@ -139,3 +116,77 @@ fn print_help() {
139 println!(" Run 'oxwm --init' to create a config file"); 116 println!(" Run 'oxwm --init' to create a config file");
140 println!(" Or just start oxwm and it will create one automatically\n"); 117 println!(" Or just start oxwm and it will create one automatically\n");
141 } 118 }
119 +
120 +fn process_args() -> Args {
121 + let mut args = std::env::args();
122 + let name = match args.next() {
123 + Some(n) => n,
124 + None => return Args::Error(MainError::NoProgramName),
125 + };
126 + let switch = args.next();
127 + let path = args.next();
128 +
129 + let switch = match switch {
130 + Some(s) => s,
131 + None => return Args::Arguments(vec![name]),
132 + };
133 +
134 + match switch.as_str() {
135 + "--version" => {
136 + println!("{name} {}", env!("CARGO_PKG_VERSION"));
137 + Args::Exit
138 + }
139 + "--help" => {
140 + print_help();
141 + Args::Exit
142 + }
143 + "--init" => match init_config() {
144 + Ok(_) => Args::Exit,
145 + Err(e) => Args::Error(e),
146 + },
147 + "--config" => match check_custom_config(path) {
148 + Ok(p) => Args::Arguments(vec![name, switch, p]),
149 + Err(e) => Args::Error(e),
150 + },
151 + _ => Args::Error(MainError::InvalidArguments),
152 + }
153 +}
154 +
155 +fn check_custom_config(path: Option<String>) -> Result<String, MainError> {
156 + let path = match path {
157 + Some(p) => p,
158 + None => {
159 + return Err(MainError::NoConfigPath);
160 + }
161 + };
162 +
163 + match std::fs::exists(&path) {
164 + Ok(b) => match b {
165 + true => Ok(path),
166 + false => Err(MainError::BadConfigPath),
167 + },
168 + Err(e) => Err(MainError::FailedCheckExist(e)),
169 + }
170 +}
171 +
172 +fn check_convert(path: &Path) -> Result<(), MainError> {
173 + let config_directory = get_config_path()?;
174 +
175 + if !path.exists() {
176 + let ron_path = config_directory.join("config.ron");
177 + let had_ron_config = ron_path.exists();
178 +
179 + println!("No config found at {:?}", config_directory);
180 + println!("Creating default Lua config...");
181 + init_config()?;
182 +
183 + if had_ron_config {
184 + println!("\n NOTICE: OXWM has migrated to Lua configuration.");
185 + println!(" Your old config.ron has been preserved, but is no longer used.");
186 + println!(" Your settings have been reset to defaults.");
187 + println!(" Please manually port your configuration to the new Lua format.");
188 + println!(" See the new config.lua template for examples.\n");
189 + }
190 + }
191 + Ok(())
192 +}
+1 −0 src/config/lua.rs
@@ -51,6 +51,7 @@ pub fn parse_lua_config(
51 scheme_urgent: builder_data.scheme_urgent, 51 scheme_urgent: builder_data.scheme_urgent,
52 autostart: builder_data.autostart, 52 autostart: builder_data.autostart,
53 auto_tile: builder_data.auto_tile, 53 auto_tile: builder_data.auto_tile,
54 + hide_vacant_tags: builder_data.hide_vacant_tags,
54 path: None, 55 path: None,
55 }) 56 })
56 } 57 }
+11 −0 src/config/lua_api.rs
@@ -35,6 +35,7 @@ pub struct ConfigBuilder {
35 pub scheme_urgent: ColorScheme, 35 pub scheme_urgent: ColorScheme,
36 pub autostart: Vec<String>, 36 pub autostart: Vec<String>,
37 pub auto_tile: bool, 37 pub auto_tile: bool,
38 + pub hide_vacant_tags: bool,
38 } 39 }
39 40
40 impl Default for ConfigBuilder { 41 impl Default for ConfigBuilder {
@@ -80,6 +81,7 @@ impl Default for ConfigBuilder {
80 }, 81 },
81 autostart: Vec::new(), 82 autostart: Vec::new(),
82 auto_tile: false, 83 auto_tile: false,
84 + hide_vacant_tags: false,
83 } 85 }
84 } 86 }
85 } 87 }
@@ -398,6 +400,7 @@ fn register_rule_module(
398 let title: Option<String> = config.get("title").ok(); 400 let title: Option<String> = config.get("title").ok();
399 let is_floating: Option<bool> = config.get("floating").ok(); 401 let is_floating: Option<bool> = config.get("floating").ok();
400 let monitor: Option<usize> = config.get("monitor").ok(); 402 let monitor: Option<usize> = config.get("monitor").ok();
403 + let focus: Option<bool> = config.get("focus").ok();
401 404
402 let tags: Option<u32> = if let Ok(tag_index) = config.get::<i32>("tag") { 405 let tags: Option<u32> = if let Ok(tag_index) = config.get::<i32>("tag") {
403 if tag_index > 0 { 406 if tag_index > 0 {
@@ -414,6 +417,7 @@ fn register_rule_module(
414 instance, 417 instance,
415 title, 418 title,
416 tags, 419 tags,
420 + focus,
417 is_floating, 421 is_floating,
418 monitor, 422 monitor,
419 }; 423 };
@@ -734,6 +738,12 @@ fn register_bar_module(
734 Ok(()) 738 Ok(())
735 })?; 739 })?;
736 740
741 + let builder_clone = builder.clone();
742 + let set_hide_vacant_tags = lua.create_function(move |_, hide: bool| {
743 + builder_clone.borrow_mut().hide_vacant_tags = hide;
744 + Ok(())
745 + })?;
746 +
737 bar_table.set("set_font", set_font)?; 747 bar_table.set("set_font", set_font)?;
738 bar_table.set("block", block_table)?; 748 bar_table.set("block", block_table)?;
739 bar_table.set("add_block", add_block)?; // Deprecated, for backwards compatibility 749 bar_table.set("add_block", add_block)?; // Deprecated, for backwards compatibility
@@ -742,6 +752,7 @@ fn register_bar_module(
742 bar_table.set("set_scheme_occupied", set_scheme_occupied)?; 752 bar_table.set("set_scheme_occupied", set_scheme_occupied)?;
743 bar_table.set("set_scheme_selected", set_scheme_selected)?; 753 bar_table.set("set_scheme_selected", set_scheme_selected)?;
744 bar_table.set("set_scheme_urgent", set_scheme_urgent)?; 754 bar_table.set("set_scheme_urgent", set_scheme_urgent)?;
755 + bar_table.set("set_hide_vacant_tags", set_hide_vacant_tags)?;
745 parent.set("bar", bar_table)?; 756 parent.set("bar", bar_table)?;
746 Ok(()) 757 Ok(())
747 } 758 }
+46 −8 src/errors.rs
@@ -29,6 +29,9 @@ pub enum ConfigError {
29 UnknownBlockCommand(String), 29 UnknownBlockCommand(String),
30 MissingCommandArg { command: String, field: String }, 30 MissingCommandArg { command: String, field: String },
31 ValidationError(String), 31 ValidationError(String),
32 + NoConfigPathSet,
33 + NoConfigAtPath,
34 + CouldNotReadConfig(std::io::Error),
32 } 35 }
33 36
34 #[derive(Debug)] 37 #[derive(Debug)]
@@ -40,6 +43,21 @@ pub enum BlockError {
40 CommandFailed(String), 43 CommandFailed(String),
41 } 44 }
42 45
46 +pub enum MainError {
47 + CouldNotCreateConfigDir(std::io::Error),
48 + CouldNotWriteConfig(std::io::Error),
49 + FailedCheckExist(std::io::Error),
50 + FailedReadConfig(std::io::Error),
51 + FailedReadConfigTemplate(ConfigError),
52 + CouldNotStartWm(WmError),
53 + WmError(WmError),
54 + BadConfigPath,
55 + NoConfigPath,
56 + InvalidArguments,
57 + NoProgramName,
58 + NoConfigDir,
59 +}
60 +
43 impl std::fmt::Display for WmError { 61 impl std::fmt::Display for WmError {
44 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 62 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
45 match self { 63 match self {
@@ -56,8 +74,6 @@ impl std::fmt::Display for WmError {
56 } 74 }
57 } 75 }
58 76
59 -impl std::error::Error for WmError {}
60 -
61 impl std::fmt::Display for X11Error { 77 impl std::fmt::Display for X11Error {
62 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 78 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
63 match self { 79 match self {
@@ -72,8 +88,6 @@ impl std::fmt::Display for X11Error {
72 } 88 }
73 } 89 }
74 90
75 -impl std::error::Error for X11Error {}
76 -
77 impl std::fmt::Display for ConfigError { 91 impl std::fmt::Display for ConfigError {
78 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 92 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
79 match self { 93 match self {
@@ -86,12 +100,16 @@ impl std::fmt::Display for ConfigError {
86 write!(f, "{} command requires {}", command, field) 100 write!(f, "{} command requires {}", command, field)
87 } 101 }
88 Self::ValidationError(msg) => write!(f, "{}", msg), 102 Self::ValidationError(msg) => write!(f, "{}", msg),
103 + Self::NoConfigPathSet => write!(
104 + f,
105 + "Could not find config file. Config path should've been set while loading"
106 + ),
107 + Self::NoConfigAtPath => write!(f, "Could not find config file, has it been moved?"),
108 + Self::CouldNotReadConfig(e) => write!(f, "Could not read config: {e}"),
89 } 109 }
90 } 110 }
91 } 111 }
92 112
93 -impl std::error::Error for ConfigError {}
94 -
95 impl std::fmt::Display for BlockError { 113 impl std::fmt::Display for BlockError {
96 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 114 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
97 match self { 115 match self {
@@ -104,8 +122,6 @@ impl std::fmt::Display for BlockError {
104 } 122 }
105 } 123 }
106 124
107 -impl std::error::Error for BlockError {}
108 -
109 impl<T: Into<X11Error>> From<T> for WmError { 125 impl<T: Into<X11Error>> From<T> for WmError {
110 fn from(value: T) -> Self { 126 fn from(value: T) -> Self {
111 Self::X11(value.into()) 127 Self::X11(value.into())
@@ -181,3 +197,25 @@ impl<T> LuaResultExt<T> for Result<T, mlua::Error> {
181 self.map_err(|e| ConfigError::LuaError(format!("{}: {}", context, e))) 197 self.map_err(|e| ConfigError::LuaError(format!("{}: {}", context, e)))
182 } 198 }
183 } 199 }
200 +
201 +impl std::fmt::Debug for MainError {
202 + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
203 + use MainError::*;
204 +
205 + match self {
206 + CouldNotCreateConfigDir(e)
207 + | CouldNotWriteConfig(e)
208 + | FailedCheckExist(e)
209 + | FailedReadConfig(e) => {
210 + write!(f, "{e}")
211 + }
212 + FailedReadConfigTemplate(e) => write!(f, "{e}"),
213 + CouldNotStartWm(e) | WmError(e) => write!(f, "{e}"),
214 + BadConfigPath => write!(f, "Given config path does not exist"),
215 + NoConfigPath => write!(f, "The --config switch requires a path value"),
216 + InvalidArguments => write!(f, "The arguments given are invalid try --help"),
217 + NoProgramName => write!(f, "Could not get the program name from the environment"),
218 + NoConfigDir => write!(f, "Could not get the config dir"),
219 + }
220 + }
221 +}
+1 −1 src/keyboard/keysyms.rs
@@ -238,7 +238,7 @@ pub fn keysym_from_str(s: &str) -> Option<Keysym> {
238 "XF86AudioPause" => Some(XF86_AUDIO_PAUSE), 238 "XF86AudioPause" => Some(XF86_AUDIO_PAUSE),
239 "XF86AudioPlay" => Some(XF86_AUDIO_PLAY), 239 "XF86AudioPlay" => Some(XF86_AUDIO_PLAY),
240 "XF86AudioPrev" => Some(XF86_AUDIO_PREV), 240 "XF86AudioPrev" => Some(XF86_AUDIO_PREV),
241 - "XF86AudioRaiseVolume" => Some(XF86_AUDIO_RAISE_VOLUME), 241 + "AudioRaiseVolume" | "XF86AudioRaiseVolume" => Some(XF86_AUDIO_RAISE_VOLUME),
242 "AudioLowerVolume" | "XF86AudioLowerVolume" => Some(XF86_AUDIO_LOWER_VOLUME), 242 "AudioLowerVolume" | "XF86AudioLowerVolume" => Some(XF86_AUDIO_LOWER_VOLUME),
243 "AudioMute" | "XF86AudioMute" => Some(XF86_AUDIO_MUTE), 243 "AudioMute" | "XF86AudioMute" => Some(XF86_AUDIO_MUTE),
244 "XF86AudioMicMute" => Some(XF86_AUDIO_MIC_MUTE), 244 "XF86AudioMicMute" => Some(XF86_AUDIO_MIC_MUTE),
+3 −0 src/lib.rs
@@ -35,6 +35,7 @@ pub struct WindowRule {
35 pub instance: Option<String>, 35 pub instance: Option<String>,
36 pub title: Option<String>, 36 pub title: Option<String>,
37 pub tags: Option<u32>, 37 pub tags: Option<u32>,
38 + pub focus: Option<bool>,
38 pub is_floating: Option<bool>, 39 pub is_floating: Option<bool>,
39 pub monitor: Option<usize>, 40 pub monitor: Option<usize>,
40 } 41 }
@@ -104,6 +105,7 @@ pub struct Config {
104 105
105 pub autostart: Vec<String>, 106 pub autostart: Vec<String>,
106 pub auto_tile: bool, 107 pub auto_tile: bool,
108 + pub hide_vacant_tags: bool,
107 } 109 }
108 110
109 #[derive(Debug, Clone, Copy)] 111 #[derive(Debug, Clone, Copy)]
@@ -354,6 +356,7 @@ impl Default for Config {
354 }, 356 },
355 autostart: vec![], 357 autostart: vec![],
356 auto_tile: false, 358 auto_tile: false,
359 + hide_vacant_tags: false,
357 } 360 }
358 } 361 }
359 } 362 }
+42 −0 src/monitor.rs
@@ -6,6 +6,36 @@ use x11rb::rust_connection::RustConnection;
6 6
7 type WmResult<T> = Result<T, WmError>; 7 type WmResult<T> = Result<T, WmError>;
8 8
9 +#[derive(Debug, Clone)]
10 +pub struct Pertag {
11 + pub current_tag: usize,
12 + pub previous_tag: usize,
13 + pub num_masters: Vec<i32>,
14 + pub master_factors: Vec<f32>,
15 + pub layouts: Vec<String>,
16 + pub show_bars: Vec<bool>,
17 +}
18 +
19 +impl Pertag {
20 + pub fn new(
21 + num_tags: usize,
22 + default_num_master: i32,
23 + default_master_factor: f32,
24 + default_show_bar: bool,
25 + default_layout: &str,
26 + ) -> Self {
27 + let len = num_tags + 1;
28 + Self {
29 + current_tag: 1,
30 + previous_tag: 1,
31 + num_masters: vec![default_num_master; len],
32 + master_factors: vec![default_master_factor; len],
33 + layouts: vec![default_layout.to_string(); len],
34 + show_bars: vec![default_show_bar; len],
35 + }
36 + }
37 +}
38 +
9 #[derive(Debug, Clone)] 39 #[derive(Debug, Clone)]
10 pub struct Monitor { 40 pub struct Monitor {
11 pub layout_symbol: String, 41 pub layout_symbol: String,
@@ -36,6 +66,7 @@ pub struct Monitor {
36 pub bar_window: Option<Window>, 66 pub bar_window: Option<Window>,
37 pub layout_indices: [usize; 2], 67 pub layout_indices: [usize; 2],
38 pub scroll_offset: i32, 68 pub scroll_offset: i32,
69 + pub pertag: Option<Pertag>,
39 } 70 }
40 71
41 impl Monitor { 72 impl Monitor {
@@ -69,9 +100,20 @@ impl Monitor {
69 bar_window: None, 100 bar_window: None,
70 layout_indices: [0, 1], 101 layout_indices: [0, 1],
71 scroll_offset: 0, 102 scroll_offset: 0,
103 + pertag: None,
72 } 104 }
73 } 105 }
74 106
107 + pub fn init_pertag(&mut self, num_tags: usize, default_layout: &str) {
108 + self.pertag = Some(Pertag::new(
109 + num_tags,
110 + self.num_master,
111 + self.master_factor,
112 + self.show_bar,
113 + default_layout,
114 + ));
115 + }
116 +
75 pub fn contains_point(&self, x: i32, y: i32) -> bool { 117 pub fn contains_point(&self, x: i32, y: i32) -> bool {
76 x >= self.screen_x 118 x >= self.screen_x
77 && x < self.screen_x + self.screen_width 119 && x < self.screen_x + self.screen_width
+3 −3 src/overlay/error.rs
@@ -1,6 +1,6 @@
1 use super::{Overlay, OverlayBase}; 1 use super::{Overlay, OverlayBase};
2 use crate::bar::font::Font; 2 use crate::bar::font::Font;
3 -use crate::errors::X11Error; 3 +use crate::errors::{ConfigError, X11Error};
4 use x11rb::connection::Connection; 4 use x11rb::connection::Connection;
5 use x11rb::protocol::xproto::*; 5 use x11rb::protocol::xproto::*;
6 use x11rb::rust_connection::RustConnection; 6 use x11rb::rust_connection::RustConnection;
@@ -47,14 +47,14 @@ impl ErrorOverlay {
47 &mut self, 47 &mut self,
48 connection: &RustConnection, 48 connection: &RustConnection,
49 font: &Font, 49 font: &Font,
50 - error_text: &str, 50 + error: ConfigError,
51 monitor_x: i16, 51 monitor_x: i16,
52 monitor_y: i16, 52 monitor_y: i16,
53 screen_width: u16, 53 screen_width: u16,
54 screen_height: u16, 54 screen_height: u16,
55 ) -> Result<(), X11Error> { 55 ) -> Result<(), X11Error> {
56 let max_line_width = (screen_width as i16 / 2 - PADDING * 4).max(300) as u16; 56 let max_line_width = (screen_width as i16 / 2 - PADDING * 4).max(300) as u16;
57 - let error_with_instruction = format!("{}\n\nFix the config file and reload.", error_text); 57 + let error_with_instruction = format!("{}\n\nFix the config file and reload.", error);
58 self.lines = self.wrap_text(&error_with_instruction, font, max_line_width); 58 self.lines = self.wrap_text(&error_with_instruction, font, max_line_width);
59 59
60 let mut content_width = 0u16; 60 let mut content_width = 0u16;
+27 −47 src/tab_bar.rs
@@ -1,5 +1,5 @@
1 use crate::ColorScheme; 1 use crate::ColorScheme;
2 -use crate::bar::font::{Font, FontDraw}; 2 +use crate::bar::font::{DrawingSurface, Font};
3 use crate::errors::X11Error; 3 use crate::errors::X11Error;
4 use crate::layout::tabbed::TAB_BAR_HEIGHT; 4 use crate::layout::tabbed::TAB_BAR_HEIGHT;
5 use x11rb::COPY_DEPTH_FROM_PARENT; 5 use x11rb::COPY_DEPTH_FROM_PARENT;
@@ -14,9 +14,8 @@ pub struct TabBar {
14 x_offset: i16, 14 x_offset: i16,
15 y_offset: i16, 15 y_offset: i16,
16 graphics_context: Gcontext, 16 graphics_context: Gcontext,
17 - pixmap: x11::xlib::Pixmap,
18 display: *mut x11::xlib::Display, 17 display: *mut x11::xlib::Display,
19 - font_draw: FontDraw, 18 + surface: DrawingSurface,
20 scheme_normal: ColorScheme, 19 scheme_normal: ColorScheme,
21 scheme_selected: ColorScheme, 20 scheme_selected: ColorScheme,
22 } 21 }
@@ -69,19 +68,15 @@ impl TabBar {
69 68
70 let visual = unsafe { x11::xlib::XDefaultVisual(display, screen_num as i32) }; 69 let visual = unsafe { x11::xlib::XDefaultVisual(display, screen_num as i32) };
71 let colormap = unsafe { x11::xlib::XDefaultColormap(display, screen_num as i32) }; 70 let colormap = unsafe { x11::xlib::XDefaultColormap(display, screen_num as i32) };
72 - let depth = unsafe { x11::xlib::XDefaultDepth(display, screen_num as i32) };
73 71
74 - let pixmap = unsafe { 72 + let surface = DrawingSurface::new(
75 - x11::xlib::XCreatePixmap( 73 + display,
76 - display, 74 + window as x11::xlib::Drawable,
77 - window as x11::xlib::Drawable, 75 + width as u32,
78 - width as u32, 76 + height as u32,
79 - height as u32, 77 + visual,
80 - depth as u32, 78 + colormap,
81 - ) 79 + )?;
82 - };
83 -
84 - let font_draw = FontDraw::new(display, pixmap, visual, colormap)?;
85 80
86 Ok(Self { 81 Ok(Self {
87 window, 82 window,
@@ -90,9 +85,8 @@ impl TabBar {
90 x_offset: x, 85 x_offset: x,
91 y_offset: y, 86 y_offset: y,
92 graphics_context, 87 graphics_context,
93 - pixmap,
94 display, 88 display,
95 - font_draw, 89 + surface,
96 scheme_normal, 90 scheme_normal,
97 scheme_selected, 91 scheme_selected,
98 }) 92 })
@@ -116,11 +110,11 @@ impl TabBar {
116 connection.flush()?; 110 connection.flush()?;
117 111
118 unsafe { 112 unsafe {
119 - let gc = x11::xlib::XCreateGC(self.display, self.pixmap, 0, std::ptr::null_mut()); 113 + let gc = x11::xlib::XCreateGC(self.display, self.surface.pixmap(), 0, std::ptr::null_mut());
120 x11::xlib::XSetForeground(self.display, gc, self.scheme_normal.background as u64); 114 x11::xlib::XSetForeground(self.display, gc, self.scheme_normal.background as u64);
121 x11::xlib::XFillRectangle( 115 x11::xlib::XFillRectangle(
122 self.display, 116 self.display,
123 - self.pixmap, 117 + self.surface.pixmap(),
124 gc, 118 gc,
125 0, 119 0,
126 0, 120 0,
@@ -158,7 +152,8 @@ impl TabBar {
158 let top_padding = 6; 152 let top_padding = 6;
159 let text_y = top_padding + font.ascent(); 153 let text_y = top_padding + font.ascent();
160 154
161 - self.font_draw 155 + self.surface
156 + .font_draw()
162 .draw_text(font, scheme.foreground, text_x, text_y, &display_title); 157 .draw_text(font, scheme.foreground, text_x, text_y, &display_title);
163 158
164 if is_focused { 159 if is_focused {
@@ -167,11 +162,11 @@ impl TabBar {
167 162
168 unsafe { 163 unsafe {
169 let gc = 164 let gc =
170 - x11::xlib::XCreateGC(self.display, self.pixmap, 0, std::ptr::null_mut()); 165 + x11::xlib::XCreateGC(self.display, self.surface.pixmap(), 0, std::ptr::null_mut());
171 x11::xlib::XSetForeground(self.display, gc, scheme.underline as u64); 166 x11::xlib::XSetForeground(self.display, gc, scheme.underline as u64);
172 x11::xlib::XFillRectangle( 167 x11::xlib::XFillRectangle(
173 self.display, 168 self.display,
174 - self.pixmap, 169 + self.surface.pixmap(),
175 gc, 170 gc,
176 x_position as i32, 171 x_position as i32,
177 underline_y as i32, 172 underline_y as i32,
@@ -195,7 +190,7 @@ impl TabBar {
195 x11::xlib::XCreateGC(self.display, self.window as u64, 0, std::ptr::null_mut()); 190 x11::xlib::XCreateGC(self.display, self.window as u64, 0, std::ptr::null_mut());
196 x11::xlib::XCopyArea( 191 x11::xlib::XCopyArea(
197 self.display, 192 self.display,
198 - self.pixmap, 193 + self.surface.pixmap(),
199 self.window as u64, 194 self.window as u64,
200 gc, 195 gc,
201 0, 196 0,
@@ -239,24 +234,17 @@ impl TabBar {
239 .width(width as u32), 234 .width(width as u32),
240 )?; 235 )?;
241 236
242 - unsafe {
243 - x11::xlib::XFreePixmap(self.display, self.pixmap);
244 - }
245 -
246 - let depth = unsafe { x11::xlib::XDefaultDepth(self.display, 0) };
247 - self.pixmap = unsafe {
248 - x11::xlib::XCreatePixmap(
249 - self.display,
250 - self.window as x11::xlib::Drawable,
251 - width as u32,
252 - self.height as u32,
253 - depth as u32,
254 - )
255 - };
256 -
257 let visual = unsafe { x11::xlib::XDefaultVisual(self.display, 0) }; 237 let visual = unsafe { x11::xlib::XDefaultVisual(self.display, 0) };
258 let colormap = unsafe { x11::xlib::XDefaultColormap(self.display, 0) }; 238 let colormap = unsafe { x11::xlib::XDefaultColormap(self.display, 0) };
259 - self.font_draw = FontDraw::new(self.display, self.pixmap, visual, colormap)?; 239 +
240 + self.surface = DrawingSurface::new(
241 + self.display,
242 + self.window as x11::xlib::Drawable,
243 + width as u32,
244 + self.height as u32,
245 + visual,
246 + colormap,
247 + )?;
260 248
261 connection.flush()?; 249 connection.flush()?;
262 Ok(()) 250 Ok(())
@@ -274,11 +262,3 @@ impl TabBar {
274 Ok(()) 262 Ok(())
275 } 263 }
276 } 264 }
277 -
278 -impl Drop for TabBar {
279 - fn drop(&mut self) {
280 - unsafe {
281 - x11::xlib::XFreePixmap(self.display, self.pixmap);
282 - }
283 - }
284 -}
+661 −388 src/window_manager.rs Large diff collapsed, click to expand
@@ -2,7 +2,7 @@ use crate::Config;
2 use crate::animations::{AnimationConfig, ScrollAnimation}; 2 use crate::animations::{AnimationConfig, ScrollAnimation};
3 use crate::bar::Bar; 3 use crate::bar::Bar;
4 use crate::client::{Client, TagMask}; 4 use crate::client::{Client, TagMask};
5 -use crate::errors::WmError; 5 +use crate::errors::{ConfigError, WmError};
6 use crate::keyboard::{self, Arg, KeyAction, handlers}; 6 use crate::keyboard::{self, Arg, KeyAction, handlers};
7 use crate::layout::GapConfig; 7 use crate::layout::GapConfig;
8 use crate::layout::tiling::TilingLayout; 8 use crate::layout::tiling::TilingLayout;
@@ -17,17 +17,22 @@ use x11rb::protocol::Event;
17 use x11rb::protocol::xproto::*; 17 use x11rb::protocol::xproto::*;
18 use x11rb::rust_connection::RustConnection; 18 use x11rb::rust_connection::RustConnection;
19 19
20 +enum Control {
21 + Continue,
22 + Quit,
23 +}
24 +
20 pub fn tag_mask(tag: usize) -> TagMask { 25 pub fn tag_mask(tag: usize) -> TagMask {
21 1 << tag 26 1 << tag
22 } 27 }
23 28
24 -/// Get back a tag index from a [`TagMask`]
25 pub fn unmask_tag(mask: TagMask) -> usize { 29 pub fn unmask_tag(mask: TagMask) -> usize {
26 - // mask only has one bit set, so this works.
27 mask.trailing_zeros() as usize 30 mask.trailing_zeros() as usize
28 } 31 }
29 32
30 struct AtomCache { 33 struct AtomCache {
34 + net_supported: Atom,
35 + net_supporting_wm_check: Atom,
31 net_current_desktop: Atom, 36 net_current_desktop: Atom,
32 net_client_info: Atom, 37 net_client_info: Atom,
33 wm_state: Atom, 38 wm_state: Atom,
@@ -41,10 +46,22 @@ struct AtomCache {
41 net_wm_name: Atom, 46 net_wm_name: Atom,
42 utf8_string: Atom, 47 utf8_string: Atom,
43 net_active_window: Atom, 48 net_active_window: Atom,
49 + wm_take_focus: Atom,
50 + net_client_list: Atom,
44 } 51 }
45 52
46 impl AtomCache { 53 impl AtomCache {
47 fn new(connection: &RustConnection) -> WmResult<Self> { 54 fn new(connection: &RustConnection) -> WmResult<Self> {
55 + let net_supported = connection
56 + .intern_atom(false, b"_NET_SUPPORTED")?
57 + .reply()?
58 + .atom;
59 +
60 + let net_supporting_wm_check = connection
61 + .intern_atom(false, b"_NET_SUPPORTING_WM_CHECK")?
62 + .reply()?
63 + .atom;
64 +
48 let net_current_desktop = connection 65 let net_current_desktop = connection
49 .intern_atom(false, b"_NET_CURRENT_DESKTOP")? 66 .intern_atom(false, b"_NET_CURRENT_DESKTOP")?
50 .reply()? 67 .reply()?
@@ -98,7 +115,19 @@ impl AtomCache {
98 .reply()? 115 .reply()?
99 .atom; 116 .atom;
100 117
118 + let wm_take_focus = connection
119 + .intern_atom(false, b"WM_TAKE_FOCUS")?
120 + .reply()?
121 + .atom;
122 +
123 + let net_client_list = connection
124 + .intern_atom(false, b"_NET_CLIENT_LIST")?
125 + .reply()?
126 + .atom;
127 +
101 Ok(Self { 128 Ok(Self {
129 + net_supported,
130 + net_supporting_wm_check,
102 net_current_desktop, 131 net_current_desktop,
103 net_client_info, 132 net_client_info,
104 wm_state, 133 wm_state,
@@ -112,6 +141,8 @@ impl AtomCache {
112 net_wm_name, 141 net_wm_name,
113 utf8_string, 142 utf8_string,
114 net_active_window, 143 net_active_window,
144 + wm_take_focus,
145 + net_client_list,
115 }) 146 })
116 } 147 }
117 } 148 }
@@ -121,6 +152,7 @@ pub struct WindowManager {
121 connection: RustConnection, 152 connection: RustConnection,
122 screen_number: usize, 153 screen_number: usize,
123 root: Window, 154 root: Window,
155 + _wm_check_window: Window,
124 screen: Screen, 156 screen: Screen,
125 windows: Vec<Window>, 157 windows: Vec<Window>,
126 clients: HashMap<Window, Client>, 158 clients: HashMap<Window, Client>,
@@ -128,11 +160,9 @@ pub struct WindowManager {
128 gaps_enabled: bool, 160 gaps_enabled: bool,
129 floating_windows: HashSet<Window>, 161 floating_windows: HashSet<Window>,
130 fullscreen_windows: HashSet<Window>, 162 fullscreen_windows: HashSet<Window>,
131 - floating_geometry_before_fullscreen: HashMap<Window, (i16, i16, u16, u16, u16)>,
132 bars: Vec<Bar>, 163 bars: Vec<Bar>,
133 tab_bars: Vec<crate::tab_bar::TabBar>, 164 tab_bars: Vec<crate::tab_bar::TabBar>,
134 show_bar: bool, 165 show_bar: bool,
135 - last_layout: Option<&'static str>,
136 monitors: Vec<Monitor>, 166 monitors: Vec<Monitor>,
137 selected_monitor: usize, 167 selected_monitor: usize,
138 atoms: AtomCache, 168 atoms: AtomCache,
@@ -216,7 +246,10 @@ impl WindowManager {
216 )?; 246 )?;
217 } 247 }
218 248
219 - let monitors = detect_monitors(&connection, &screen, root)?; 249 + let mut monitors = detect_monitors(&connection, &screen, root)?;
250 + for monitor in monitors.iter_mut() {
251 + monitor.init_pertag(config.tags.len(), "tiling");
252 + }
220 253
221 let display = unsafe { x11::xlib::XOpenDisplay(std::ptr::null()) }; 254 let display = unsafe { x11::xlib::XOpenDisplay(std::ptr::null()) };
222 if display.is_null() { 255 if display.is_null() {
@@ -265,6 +298,78 @@ impl WindowManager {
265 298
266 let atoms = AtomCache::new(&connection)?; 299 let atoms = AtomCache::new(&connection)?;
267 300
301 + let supported_atoms: Vec<Atom> = vec![
302 + atoms.net_supported,
303 + atoms.net_supporting_wm_check,
304 + atoms.net_wm_state,
305 + atoms.net_wm_state_fullscreen,
306 + atoms.net_wm_window_type,
307 + atoms.net_wm_window_type_dialog,
308 + atoms.net_active_window,
309 + atoms.net_wm_name,
310 + atoms.net_current_desktop,
311 + atoms.net_client_info,
312 + atoms.net_client_list,
313 + ];
314 + let supported_bytes: Vec<u8> = supported_atoms
315 + .iter()
316 + .flat_map(|a| a.to_ne_bytes())
317 + .collect();
318 + connection.change_property(
319 + PropMode::REPLACE,
320 + root,
321 + atoms.net_supported,
322 + AtomEnum::ATOM,
323 + 32,
324 + supported_atoms.len() as u32,
325 + &supported_bytes,
326 + )?;
327 +
328 + let wm_check_window = connection.generate_id()?;
329 + connection.create_window(
330 + screen.root_depth,
331 + wm_check_window,
332 + root,
333 + 0,
334 + 0,
335 + 1,
336 + 1,
337 + 0,
338 + WindowClass::INPUT_OUTPUT,
339 + 0,
340 + &CreateWindowAux::new(),
341 + )?;
342 +
343 + connection.change_property(
344 + PropMode::REPLACE,
345 + wm_check_window,
346 + atoms.net_supporting_wm_check,
347 + AtomEnum::WINDOW,
348 + 32,
349 + 1,
350 + &wm_check_window.to_ne_bytes(),
351 + )?;
352 +
353 + connection.change_property(
354 + PropMode::REPLACE,
355 + wm_check_window,
356 + atoms.net_wm_name,
357 + atoms.utf8_string,
358 + 8,
359 + 4,
360 + b"oxwm",
361 + )?;
362 +
363 + connection.change_property(
364 + PropMode::REPLACE,
365 + root,
366 + atoms.net_supporting_wm_check,
367 + AtomEnum::WINDOW,
368 + 32,
369 + 1,
370 + &wm_check_window.to_ne_bytes(),
371 + )?;
372 +
268 let overlay = ErrorOverlay::new( 373 let overlay = ErrorOverlay::new(
269 &connection, 374 &connection,
270 &screen, 375 &screen,
@@ -282,6 +387,7 @@ impl WindowManager {
282 connection, 387 connection,
283 screen_number, 388 screen_number,
284 root, 389 root,
390 + _wm_check_window: wm_check_window,
285 screen, 391 screen,
286 windows: Vec::new(), 392 windows: Vec::new(),
287 clients: HashMap::new(), 393 clients: HashMap::new(),
@@ -289,11 +395,9 @@ impl WindowManager {
289 gaps_enabled, 395 gaps_enabled,
290 floating_windows: HashSet::new(), 396 floating_windows: HashSet::new(),
291 fullscreen_windows: HashSet::new(), 397 fullscreen_windows: HashSet::new(),
292 - floating_geometry_before_fullscreen: HashMap::new(),
293 bars, 398 bars,
294 tab_bars, 399 tab_bars,
295 show_bar: true, 400 show_bar: true,
296 - last_layout: None,
297 monitors, 401 monitors,
298 selected_monitor: 0, 402 selected_monitor: 0,
299 atoms, 403 atoms,
@@ -321,16 +425,7 @@ impl WindowManager {
321 Ok(window_manager) 425 Ok(window_manager)
322 } 426 }
323 427
324 - pub fn show_migration_overlay(&mut self) { 428 + pub fn show_startup_config_error(&mut self, error: ConfigError) {
325 - let message = "We are on version 0.8.0 now.\n\n\
326 - Your config file has been deprecated once again.\n\
327 - Backup your current config, and run oxwm --init to generate a new one with correct values.\n\n\
328 - Please reach out to Tony, or check out the\n\
329 - documentation for help with migration.\n\n\
330 - We appreciate you testing oxwm!\n\n\
331 - Press Mod+Shift+/ to see keybinds\n\
332 - Press Mod+Shift+R to reload after fixing your config";
333 -
334 let monitor = &self.monitors[self.selected_monitor]; 429 let monitor = &self.monitors[self.selected_monitor];
335 let monitor_x = monitor.screen_x as i16; 430 let monitor_x = monitor.screen_x as i16;
336 let monitor_y = monitor.screen_y as i16; 431 let monitor_y = monitor.screen_y as i16;
@@ -340,36 +435,38 @@ impl WindowManager {
340 if let Err(e) = self.overlay.show_error( 435 if let Err(e) = self.overlay.show_error(
341 &self.connection, 436 &self.connection,
342 &self.font, 437 &self.font,
343 - message, 438 + error,
344 monitor_x, 439 monitor_x,
345 monitor_y, 440 monitor_y,
346 screen_width, 441 screen_width,
347 screen_height, 442 screen_height,
348 ) { 443 ) {
349 - eprintln!("Failed to show migration overlay: {:?}", e); 444 + eprintln!("Failed to show config error overlay: {:?}", e);
350 } 445 }
351 } 446 }
352 447
353 - fn try_reload_config(&mut self) -> Result<(), String> { 448 + fn try_reload_config(&mut self) -> Result<(), ConfigError> {
354 - let lua_path = 449 + let lua_path = self
355 - self.config.path.take().ok_or( 450 + .config
356 - "Could not find config file. Config path should've been set while loading", 451 + .path
357 - )?; 452 + .as_ref()
453 + .ok_or(ConfigError::NoConfigPathSet)?;
358 454
359 if !lua_path.exists() { 455 if !lua_path.exists() {
360 - return Err("Could not find config file, has it been moved?".to_string()); 456 + return Err(ConfigError::NoConfigAtPath);
361 } 457 }
362 458
363 - let config_str = std::fs::read_to_string(&lua_path) 459 + let config_str =
364 - .map_err(|e| format!("Failed to read config: {}", e))?; 460 + std::fs::read_to_string(lua_path).map_err(|e| ConfigError::CouldNotReadConfig(e))?;
365 461
366 let config_dir = lua_path.parent(); 462 let config_dir = lua_path.parent();
367 463
368 - let new_config = crate::config::parse_lua_config(&config_str, config_dir) 464 + let new_config = crate::config::parse_lua_config(&config_str, config_dir)?;
369 - .map_err(|e| format!("{}", e))?; 465 +
466 + let lua_path = self.config.path.take();
370 467
371 self.config = new_config; 468 self.config = new_config;
372 - self.config.path = Some(lua_path); 469 + self.config.path = lua_path;
373 self.error_message = None; 470 self.error_message = None;
374 471
375 for bar in &mut self.bars { 472 for bar in &mut self.bars {
@@ -506,7 +603,27 @@ impl WindowManager {
506 Ok(()) 603 Ok(())
507 } 604 }
508 605
509 - pub fn run(&mut self) -> WmResult<bool> { 606 + fn update_client_list(&self) -> WmResult<()> {
607 + let window_bytes: Vec<u8> = self
608 + .windows
609 + .iter()
610 + .flat_map(|window| window.to_ne_bytes())
611 + .collect();
612 +
613 + self.connection.change_property(
614 + PropMode::REPLACE,
615 + self.root,
616 + self.atoms.net_client_list,
617 + AtomEnum::WINDOW,
618 + 32,
619 + self.windows.len() as u32,
620 + &window_bytes,
621 + )?;
622 +
623 + Ok(())
624 + }
625 +
626 + pub fn run(&mut self) -> WmResult<()> {
510 println!("oxwm started on display {}", self.screen_number); 627 println!("oxwm started on display {}", self.screen_number);
511 628
512 self.grab_keys()?; 629 self.grab_keys()?;
@@ -518,8 +635,8 @@ impl WindowManager {
518 loop { 635 loop {
519 match self.connection.poll_for_event_with_sequence()? { 636 match self.connection.poll_for_event_with_sequence()? {
520 Some((event, _sequence)) => { 637 Some((event, _sequence)) => {
521 - if let Some(should_restart) = self.handle_event(event)? { 638 + if matches!(self.handle_event(event)?, Control::Quit) {
522 - return Ok(should_restart); 639 + return Ok(());
523 } 640 }
524 } 641 }
525 None => { 642 None => {
@@ -603,6 +720,9 @@ impl WindowManager {
603 if let Some(monitor) = self.monitors.get_mut(self.selected_monitor) { 720 if let Some(monitor) = self.monitors.get_mut(self.selected_monitor) {
604 let new_mfact = (monitor.master_factor + delta).clamp(0.05, 0.95); 721 let new_mfact = (monitor.master_factor + delta).clamp(0.05, 0.95);
605 monitor.master_factor = new_mfact; 722 monitor.master_factor = new_mfact;
723 + if let Some(ref mut pertag) = monitor.pertag {
724 + pertag.master_factors[pertag.current_tag] = new_mfact;
725 + }
606 self.apply_layout()?; 726 self.apply_layout()?;
607 } 727 }
608 Ok(()) 728 Ok(())
@@ -612,6 +732,9 @@ impl WindowManager {
612 if let Some(monitor) = self.monitors.get_mut(self.selected_monitor) { 732 if let Some(monitor) = self.monitors.get_mut(self.selected_monitor) {
613 let new_nmaster = (monitor.num_master + delta).max(0); 733 let new_nmaster = (monitor.num_master + delta).max(0);
614 monitor.num_master = new_nmaster; 734 monitor.num_master = new_nmaster;
735 + if let Some(ref mut pertag) = monitor.pertag {
736 + pertag.num_masters[pertag.current_tag] = new_nmaster;
737 + }
615 self.apply_layout()?; 738 self.apply_layout()?;
616 } 739 }
617 Ok(()) 740 Ok(())
@@ -775,6 +898,19 @@ impl WindowManager {
775 Ok(()) 898 Ok(())
776 } 899 }
777 900
901 + fn toggle_bar(&mut self) -> WmResult<()> {
902 + if let Some(monitor) = self.monitors.get_mut(self.selected_monitor) {
903 + monitor.show_bar = !monitor.show_bar;
904 + self.show_bar = monitor.show_bar;
905 + if let Some(ref mut pertag) = monitor.pertag {
906 + pertag.show_bars[pertag.current_tag] = monitor.show_bar;
907 + }
908 + }
909 + self.apply_layout()?;
910 + self.update_bar()?;
911 + Ok(())
912 + }
913 +
778 fn get_layout_symbol(&self) -> String { 914 fn get_layout_symbol(&self) -> String {
779 let layout_name = self.layout.name(); 915 let layout_name = self.layout.name();
780 916
@@ -967,13 +1103,6 @@ impl WindowManager {
967 } 1103 }
968 } 1104 }
969 KeyAction::ToggleFullScreen => { 1105 KeyAction::ToggleFullScreen => {
970 - // Disable gaps and save previous state in config if not already in fullscreen
971 - if self.fullscreen_windows.is_empty() {
972 - self.config.gaps_enabled = std::mem::take(&mut self.gaps_enabled);
973 - } else {
974 - self.gaps_enabled = self.config.gaps_enabled;
975 - }
976 -
977 self.fullscreen()?; 1106 self.fullscreen()?;
978 self.restack()?; 1107 self.restack()?;
979 } 1108 }
@@ -982,6 +1111,11 @@ impl WindowManager {
982 match layout_from_str(layout_name) { 1111 match layout_from_str(layout_name) {
983 Ok(layout) => { 1112 Ok(layout) => {
984 self.layout = layout; 1113 self.layout = layout;
1114 + if let Some(monitor) = self.monitors.get_mut(self.selected_monitor) {
1115 + if let Some(ref mut pertag) = monitor.pertag {
1116 + pertag.layouts[pertag.current_tag] = layout_name.to_string();
1117 + }
1118 + }
985 if layout_name != "normie" && layout_name != "floating" { 1119 if layout_name != "normie" && layout_name != "floating" {
986 self.floating_windows.clear(); 1120 self.floating_windows.clear();
987 } 1121 }
@@ -999,6 +1133,11 @@ impl WindowManager {
999 match layout_from_str(next_name) { 1133 match layout_from_str(next_name) {
1000 Ok(layout) => { 1134 Ok(layout) => {
1001 self.layout = layout; 1135 self.layout = layout;
1136 + if let Some(monitor) = self.monitors.get_mut(self.selected_monitor) {
1137 + if let Some(ref mut pertag) = monitor.pertag {
1138 + pertag.layouts[pertag.current_tag] = next_name.to_string();
1139 + }
1140 + }
1002 if next_name != "normie" && next_name != "floating" { 1141 if next_name != "normie" && next_name != "floating" {
1003 self.floating_windows.clear(); 1142 self.floating_windows.clear();
1004 } 1143 }
@@ -1026,9 +1165,7 @@ impl WindowManager {
1026 self.restack()?; 1165 self.restack()?;
1027 } 1166 }
1028 } 1167 }
1029 - KeyAction::Quit | KeyAction::Restart => { 1168 + KeyAction::Quit | KeyAction::Restart => {}
1030 - // Handled in handle_event
1031 - }
1032 KeyAction::ViewTag => { 1169 KeyAction::ViewTag => {
1033 if let Arg::Int(tag_index) = arg { 1170 if let Arg::Int(tag_index) = arg {
1034 self.view_tag(*tag_index as usize)?; 1171 self.view_tag(*tag_index as usize)?;
@@ -1230,7 +1367,7 @@ impl WindowManager {
1230 return Ok(()); 1367 return Ok(());
1231 } 1368 }
1232 1369
1233 - self.unfocus(window)?; 1370 + self.unfocus(window, false)?;
1234 self.detach(window); 1371 self.detach(window);
1235 self.detach_stack(window); 1372 self.detach_stack(window);
1236 1373
@@ -1362,21 +1499,48 @@ impl WindowManager {
1362 return Ok(()); 1499 return Ok(());
1363 } 1500 }
1364 1501
1365 - let monitor = match self.monitors.get_mut(self.selected_monitor) {
1366 - Some(m) => m,
1367 - None => return Ok(()),
1368 - };
1369 -
1370 let new_tagset = tag_mask(tag_index); 1502 let new_tagset = tag_mask(tag_index);
1503 + let mut layout_name: Option<String> = None;
1504 + let mut toggle_bar = false;
1371 1505
1372 - if new_tagset == monitor.tagset[monitor.selected_tags_index] { 1506 + if let Some(monitor) = self.monitors.get_mut(self.selected_monitor) {
1373 - if !self.config.tag_back_and_forth { 1507 + if new_tagset == monitor.tagset[monitor.selected_tags_index] {
1374 - return Ok(()); 1508 + if !self.config.tag_back_and_forth {
1509 + return Ok(());
1510 + }
1511 + monitor.tagset.swap(0, 1);
1512 + if let Some(ref mut pertag) = monitor.pertag {
1513 + let tmp = pertag.previous_tag;
1514 + pertag.previous_tag = pertag.current_tag;
1515 + pertag.current_tag = tmp;
1516 + }
1517 + } else {
1518 + monitor.selected_tags_index ^= 1;
1519 + monitor.tagset[monitor.selected_tags_index] = new_tagset;
1520 + if let Some(ref mut pertag) = monitor.pertag {
1521 + pertag.previous_tag = pertag.current_tag;
1522 + pertag.current_tag = tag_index + 1;
1523 + }
1524 + }
1525 +
1526 + if let Some(ref pertag) = monitor.pertag {
1527 + monitor.num_master = pertag.num_masters[pertag.current_tag];
1528 + monitor.master_factor = pertag.master_factors[pertag.current_tag];
1529 + layout_name = Some(pertag.layouts[pertag.current_tag].clone());
1530 + if monitor.show_bar != pertag.show_bars[pertag.current_tag] {
1531 + toggle_bar = true;
1532 + }
1375 } 1533 }
1376 - monitor.tagset.swap(0, 1); 1534 + }
1377 - } else { 1535 +
1378 - monitor.selected_tags_index ^= 1; 1536 + if let Some(name) = layout_name {
1379 - monitor.tagset[monitor.selected_tags_index] = new_tagset; 1537 + if let Ok(layout) = layout_from_str(&name) {
1538 + self.layout = layout;
1539 + }
1540 + }
1541 +
1542 + if toggle_bar {
1543 + self.toggle_bar()?;
1380 } 1544 }
1381 1545
1382 self.save_selected_tags()?; 1546 self.save_selected_tags()?;
@@ -1392,19 +1556,50 @@ impl WindowManager {
1392 return Ok(()); 1556 return Ok(());
1393 } 1557 }
1394 1558
1395 - let monitor = match self.monitors.get_mut(self.selected_monitor) { 1559 + let num_tags = self.config.tags.len();
1396 - Some(m) => m, 1560 + let all_tags_mask = (1u32 << num_tags) - 1;
1397 - None => return Ok(()), 1561 + let mut layout_name: Option<String> = None;
1398 - }; 1562 + let mut toggle_bar = false;
1399 1563
1400 - let mask = tag_mask(tag_index); 1564 + if let Some(monitor) = self.monitors.get_mut(self.selected_monitor) {
1401 - let new_tagset = monitor.tagset[monitor.selected_tags_index] ^ mask; 1565 + let mask = tag_mask(tag_index);
1566 + let new_tagset = monitor.tagset[monitor.selected_tags_index] ^ mask;
1402 1567
1403 - if new_tagset == 0 { 1568 + if new_tagset == 0 {
1404 - return Ok(()); 1569 + return Ok(());
1570 + }
1571 +
1572 + monitor.tagset[monitor.selected_tags_index] = new_tagset;
1573 +
1574 + if let Some(ref mut pertag) = monitor.pertag {
1575 + if new_tagset == all_tags_mask {
1576 + pertag.previous_tag = pertag.current_tag;
1577 + pertag.current_tag = 0;
1578 + }
1579 +
1580 + if pertag.current_tag > 0 && (new_tagset & (1 << (pertag.current_tag - 1))) == 0 {
1581 + pertag.previous_tag = pertag.current_tag;
1582 + pertag.current_tag = (new_tagset.trailing_zeros() as usize) + 1;
1583 + }
1584 +
1585 + monitor.num_master = pertag.num_masters[pertag.current_tag];
1586 + monitor.master_factor = pertag.master_factors[pertag.current_tag];
1587 + layout_name = Some(pertag.layouts[pertag.current_tag].clone());
1588 + if monitor.show_bar != pertag.show_bars[pertag.current_tag] {
1589 + toggle_bar = true;
1590 + }
1591 + }
1405 } 1592 }
1406 1593
1407 - monitor.tagset[monitor.selected_tags_index] = new_tagset; 1594 + if let Some(name) = layout_name {
1595 + if let Ok(layout) = layout_from_str(&name) {
1596 + self.layout = layout;
1597 + }
1598 + }
1599 +
1600 + if toggle_bar {
1601 + self.toggle_bar()?;
1602 + }
1408 1603
1409 self.save_selected_tags()?; 1604 self.save_selected_tags()?;
1410 self.focus(None)?; 1605 self.focus(None)?;
@@ -1687,156 +1882,36 @@ impl WindowManager {
1687 } 1882 }
1688 } 1883 }
1689 1884
1690 - fn fullscreen(&mut self) -> WmResult<()> { 1885 + fn get_window_atom_list_property(&self, window: Window, property: Atom) -> WmResult<Vec<Atom>> {
1691 - if self.show_bar { 1886 + let reply = self
1692 - let Some(focused_window) = self 1887 + .connection
1693 - .monitors 1888 + .get_property(false, window, property, AtomEnum::ATOM, 0, 32)?
1694 - .get(self.selected_monitor) 1889 + .reply();
1695 - .and_then(|m| m.selected_client)
1696 - else {
1697 - return Ok(());
1698 - };
1699 -
1700 - self.fullscreen_windows.insert(focused_window);
1701 -
1702 - let windows: Vec<Window> = self
1703 - .windows
1704 - .iter()
1705 - .filter(|&&w| self.is_window_visible(w))
1706 - .copied()
1707 - .collect();
1708 -
1709 - for window in &windows {
1710 - if let Ok(geom) = self.connection.get_geometry(*window)?.reply() {
1711 - self.floating_geometry_before_fullscreen.insert(
1712 - *window,
1713 - (geom.x, geom.y, geom.width, geom.height, geom.border_width),
1714 - );
1715 - }
1716 - }
1717 -
1718 - self.last_layout = Some(self.layout.name());
1719 - if let Ok(layout) = layout_from_str("monocle") {
1720 - self.layout = layout;
1721 - }
1722 - self.toggle_bar()?;
1723 - self.apply_layout()?;
1724 -
1725 - for window in &windows {
1726 - self.connection.configure_window(
1727 - *window,
1728 - &x11rb::protocol::xproto::ConfigureWindowAux::new().border_width(0),
1729 - )?;
1730 - }
1731 -
1732 - let border_width = self.config.border_width;
1733 - let floating_windows: Vec<Window> = windows
1734 - .iter()
1735 - .filter(|&&w| self.floating_windows.contains(&w))
1736 - .copied()
1737 - .collect();
1738 -
1739 - for window in floating_windows {
1740 - let monitor_idx = self
1741 - .clients
1742 - .get(&window)
1743 - .map(|c| c.monitor_index)
1744 - .unwrap_or(self.selected_monitor);
1745 - let monitor = &self.monitors[monitor_idx];
1746 -
1747 - let (outer_gap_h, outer_gap_v) = if self.gaps_enabled {
1748 - (
1749 - self.config.gap_outer_horizontal,
1750 - self.config.gap_outer_vertical,
1751 - )
1752 - } else {
1753 - (0, 0)
1754 - };
1755 -
1756 - let window_x = monitor.screen_x + outer_gap_h as i32;
1757 - let window_y = monitor.screen_y + outer_gap_v as i32;
1758 - let window_width = monitor
1759 - .screen_width
1760 - .saturating_sub(2 * outer_gap_h as i32)
1761 - .saturating_sub(2 * border_width as i32);
1762 - let window_height = monitor
1763 - .screen_height
1764 - .saturating_sub(2 * outer_gap_v as i32)
1765 - .saturating_sub(2 * border_width as i32);
1766 -
1767 - self.connection.configure_window(
1768 - window,
1769 - &x11rb::protocol::xproto::ConfigureWindowAux::new()
1770 - .x(window_x)
1771 - .y(window_y)
1772 - .width(window_width as u32)
1773 - .height(window_height as u32),
1774 - )?;
1775 - }
1776 - self.connection.flush()?;
1777 - } else {
1778 - let Some(focused_window) = self
1779 - .monitors
1780 - .get(self.selected_monitor)
1781 - .and_then(|m| m.selected_client)
1782 - else {
1783 - return Ok(());
1784 - };
1785 -
1786 - self.fullscreen_windows.remove(&focused_window);
1787 -
1788 - if let Some(last) = self.last_layout
1789 - && let Ok(layout) = layout_from_str(last)
1790 - {
1791 - self.layout = layout;
1792 - }
1793 -
1794 - let windows_to_restore: Vec<Window> = self
1795 - .floating_geometry_before_fullscreen
1796 - .keys()
1797 - .copied()
1798 - .collect();
1799 -
1800 - for window in windows_to_restore {
1801 - if let Some(&(x, y, width, height, border_width)) =
1802 - self.floating_geometry_before_fullscreen.get(&window)
1803 - {
1804 - self.connection.configure_window(
1805 - window,
1806 - &ConfigureWindowAux::new()
1807 - .x(x as i32)
1808 - .y(y as i32)
1809 - .width(width as u32)
1810 - .height(height as u32)
1811 - .border_width(border_width as u32),
1812 - )?;
1813 -
1814 - if let Some(c) = self.clients.get_mut(&window) {
1815 - c.x_position = x;
1816 - c.y_position = y;
1817 - c.width = width;
1818 - c.height = height;
1819 - c.border_width = border_width;
1820 - }
1821 1890
1822 - self.floating_geometry_before_fullscreen.remove(&window); 1891 + match reply {
1823 - } 1892 + Ok(prop) if !prop.value.is_empty() => {
1893 + let atoms: Vec<Atom> = prop
1894 + .value
1895 + .chunks_exact(4)
1896 + .map(|chunk| u32::from_ne_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]))
1897 + .collect();
1898 + Ok(atoms)
1824 } 1899 }
1825 - self.connection.flush()?; 1900 + _ => Ok(Vec::new()),
1901 + }
1902 + }
1826 1903
1827 - self.toggle_bar()?; 1904 + fn fullscreen(&mut self) -> WmResult<()> {
1905 + let Some(focused_window) = self
1906 + .monitors
1907 + .get(self.selected_monitor)
1908 + .and_then(|m| m.selected_client)
1909 + else {
1910 + return Ok(());
1911 + };
1828 1912
1829 - if self.layout.name() != "normie" { 1913 + let is_fullscreen = self.fullscreen_windows.contains(&focused_window);
1830 - self.apply_layout()?; 1914 + self.set_window_fullscreen(focused_window, !is_fullscreen)?;
1831 - } else if let Some(bar) = self.bars.get(self.selected_monitor) {
1832 - self.connection.configure_window(
1833 - bar.window(),
1834 - &x11rb::protocol::xproto::ConfigureWindowAux::new()
1835 - .stack_mode(x11rb::protocol::xproto::StackMode::ABOVE),
1836 - )?;
1837 - self.connection.flush()?;
1838 - }
1839 - }
1840 Ok(()) 1915 Ok(())
1841 } 1916 }
1842 1917
@@ -1864,11 +1939,16 @@ impl WindowManager {
1864 client.is_fullscreen = true; 1939 client.is_fullscreen = true;
1865 client.old_state = client.is_floating; 1940 client.old_state = client.is_floating;
1866 client.old_border_width = client.border_width; 1941 client.old_border_width = client.border_width;
1942 + client.old_x_position = client.x_position;
1943 + client.old_y_position = client.y_position;
1944 + client.old_width = client.width;
1945 + client.old_height = client.height;
1867 client.border_width = 0; 1946 client.border_width = 0;
1868 client.is_floating = true; 1947 client.is_floating = true;
1869 } 1948 }
1870 1949
1871 self.fullscreen_windows.insert(window); 1950 self.fullscreen_windows.insert(window);
1951 + self.floating_windows.insert(window);
1872 1952
1873 self.connection.configure_window( 1953 self.connection.configure_window(
1874 window, 1954 window,
@@ -1895,48 +1975,51 @@ impl WindowManager {
1895 1975
1896 self.fullscreen_windows.remove(&window); 1976 self.fullscreen_windows.remove(&window);
1897 1977
1978 + let (was_floating, restored_x, restored_y, restored_width, restored_height, restored_border) = self
1979 + .clients
1980 + .get(&window)
1981 + .map(|client| {
1982 + (
1983 + client.old_state,
1984 + client.old_x_position,
1985 + client.old_y_position,
1986 + client.old_width,
1987 + client.old_height,
1988 + client.old_border_width,
1989 + )
1990 + })
1991 + .unwrap_or((false, 0, 0, 100, 100, 0));
1992 +
1993 + if !was_floating {
1994 + self.floating_windows.remove(&window);
1995 + }
1996 +
1898 if let Some(client) = self.clients.get_mut(&window) { 1997 if let Some(client) = self.clients.get_mut(&window) {
1899 client.is_fullscreen = false; 1998 client.is_fullscreen = false;
1900 client.is_floating = client.old_state; 1999 client.is_floating = client.old_state;
1901 client.border_width = client.old_border_width; 2000 client.border_width = client.old_border_width;
1902 - 2001 + client.x_position = client.old_x_position;
1903 - let x = client.old_x_position; 2002 + client.y_position = client.old_y_position;
1904 - let y = client.old_y_position; 2003 + client.width = client.old_width;
1905 - let w = client.old_width; 2004 + client.height = client.old_height;
1906 - let h = client.old_height;
1907 - let bw = client.border_width;
1908 -
1909 - self.connection.configure_window(
1910 - window,
1911 - &x11rb::protocol::xproto::ConfigureWindowAux::new()
1912 - .x(x as i32)
1913 - .y(y as i32)
1914 - .width(w as u32)
1915 - .height(h as u32)
1916 - .border_width(bw as u32),
1917 - )?;
1918 } 2005 }
1919 2006
2007 + self.connection.configure_window(
2008 + window,
2009 + &ConfigureWindowAux::new()
2010 + .x(restored_x as i32)
2011 + .y(restored_y as i32)
2012 + .width(restored_width as u32)
2013 + .height(restored_height as u32)
2014 + .border_width(restored_border as u32),
2015 + )?;
2016 +
1920 self.apply_layout()?; 2017 self.apply_layout()?;
1921 } 2018 }
1922 2019
1923 Ok(()) 2020 Ok(())
1924 } 2021 }
1925 2022
1926 - fn toggle_bar(&mut self) -> WmResult<()> {
1927 - self.show_bar = !self.show_bar;
1928 - if let Some(bar) = self.bars.get(self.selected_monitor) {
1929 - if self.show_bar {
1930 - self.connection.map_window(bar.window())?;
1931 - } else {
1932 - self.connection.unmap_window(bar.window())?;
1933 - }
1934 - self.connection.flush()?;
1935 - }
1936 - self.apply_layout()?;
1937 - Ok(())
1938 - }
1939 -
1940 fn get_transient_parent(&self, window: Window) -> Option<Window> { 2023 fn get_transient_parent(&self, window: Window) -> Option<Window> {
1941 self.connection 2024 self.connection
1942 .get_property( 2025 .get_property(
@@ -1996,6 +2079,7 @@ impl WindowManager {
1996 let mut rule_tags: Option<u32> = None; 2079 let mut rule_tags: Option<u32> = None;
1997 let mut rule_floating: Option<bool> = None; 2080 let mut rule_floating: Option<bool> = None;
1998 let mut rule_monitor: Option<usize> = None; 2081 let mut rule_monitor: Option<usize> = None;
2082 + let mut rule_focus = false;
1999 2083
2000 for rule in &self.config.window_rules { 2084 for rule in &self.config.window_rules {
2001 if rule.matches(&class, &instance, &title) { 2085 if rule.matches(&class, &instance, &title) {
@@ -2008,6 +2092,7 @@ impl WindowManager {
2008 if rule.monitor.is_some() { 2092 if rule.monitor.is_some() {
2009 rule_monitor = rule.monitor; 2093 rule_monitor = rule.monitor;
2010 } 2094 }
2095 + rule_focus = rule.focus.unwrap_or(false);
2011 } 2096 }
2012 } 2097 }
2013 2098
@@ -2027,14 +2112,23 @@ impl WindowManager {
2027 client.monitor_index = monitor_index; 2112 client.monitor_index = monitor_index;
2028 } 2113 }
2029 2114
2030 - let tags = rule_tags.unwrap_or_else(|| { 2115 + if let Some(tags) = rule_tags {
2031 - self.monitors 2116 + client.tags = tags;
2032 - .get(client.monitor_index)
2033 - .map(|m| m.tagset[m.selected_tags_index])
2034 - .unwrap_or(tag_mask(0))
2035 - });
2036 2117
2037 - client.tags = tags; 2118 + if rule_focus {
2119 + let tag_index = unmask_tag(tags);
2120 + let monitor_tagset = self
2121 + .monitors
2122 + .get(client.monitor_index)
2123 + .map(|monitor| monitor.get_selected_tag())
2124 + .unwrap_or(tag_mask(0));
2125 + let is_tag_focused = monitor_tagset & tags == tags;
2126 +
2127 + if !is_tag_focused {
2128 + self.view_tag(tag_index)?;
2129 + }
2130 + }
2131 + }
2038 } 2132 }
2039 2133
2040 Ok(()) 2134 Ok(())
@@ -2054,7 +2148,7 @@ impl WindowManager {
2054 let tags = self 2148 let tags = self
2055 .monitors 2149 .monitors
2056 .get(self.selected_monitor) 2150 .get(self.selected_monitor)
2057 - .map(|m| m.tagset[m.selected_tags_index]) 2151 + .map(|monitor| monitor.tagset[monitor.selected_tags_index])
2058 .unwrap_or(tag_mask(0)); 2152 .unwrap_or(tag_mask(0));
2059 (self.selected_monitor, tags) 2153 (self.selected_monitor, tags)
2060 } 2154 }
@@ -2062,7 +2156,7 @@ impl WindowManager {
2062 let tags = self 2156 let tags = self
2063 .monitors 2157 .monitors
2064 .get(self.selected_monitor) 2158 .get(self.selected_monitor)
2065 - .map(|m| m.tagset[m.selected_tags_index]) 2159 + .map(|monitor| monitor.tagset[monitor.selected_tags_index])
2066 .unwrap_or(tag_mask(0)); 2160 .unwrap_or(tag_mask(0));
2067 (self.selected_monitor, tags) 2161 (self.selected_monitor, tags)
2068 }; 2162 };
@@ -2200,6 +2294,7 @@ impl WindowManager {
2200 )?; 2294 )?;
2201 2295
2202 self.set_wm_state(window, 1)?; 2296 self.set_wm_state(window, 1)?;
2297 + self.update_client_list()?;
2203 2298
2204 let final_tags = self.clients.get(&window).map(|c| c.tags).unwrap_or(tags); 2299 let final_tags = self.clients.get(&window).map(|c| c.tags).unwrap_or(tags);
2205 let _ = self.save_client_tag(window, final_tags); 2300 let _ = self.save_client_tag(window, final_tags);
@@ -2210,7 +2305,7 @@ impl WindowManager {
2210 .get(self.selected_monitor) 2305 .get(self.selected_monitor)
2211 .and_then(|m| m.selected_client) 2306 .and_then(|m| m.selected_client)
2212 { 2307 {
2213 - self.unfocus(old_sel)?; 2308 + self.unfocus(old_sel, false)?;
2214 } 2309 }
2215 2310
2216 if let Some(m) = self.monitors.get_mut(client_monitor) { 2311 if let Some(m) = self.monitors.get_mut(client_monitor) {
@@ -2223,7 +2318,7 @@ impl WindowManager {
2223 2318
2224 self.apply_layout()?; 2319 self.apply_layout()?;
2225 self.connection.map_window(window)?; 2320 self.connection.map_window(window)?;
2226 - self.focus(Some(window))?; 2321 + self.focus(None)?;
2227 self.update_bar()?; 2322 self.update_bar()?;
2228 2323
2229 if self.layout.name() == "tabbed" { 2324 if self.layout.name() == "tabbed" {
@@ -2234,108 +2329,190 @@ impl WindowManager {
2234 } 2329 }
2235 2330
2236 pub fn set_focus(&mut self, window: Window) -> WmResult<()> { 2331 pub fn set_focus(&mut self, window: Window) -> WmResult<()> {
2237 - let old_focused = self.previous_focused; 2332 + let never_focus = self
2333 + .clients
2334 + .get(&window)
2335 + .map(|c| c.never_focus)
2336 + .unwrap_or(false);
2238 2337
2239 - if let Some(monitor) = self.monitors.get_mut(self.selected_monitor) { 2338 + if !never_focus {
2240 - monitor.selected_client = Some(window); 2339 + self.connection
2340 + .set_input_focus(InputFocus::POINTER_ROOT, window, x11rb::CURRENT_TIME)?;
2341 +
2342 + self.connection.change_property(
2343 + PropMode::REPLACE,
2344 + self.root,
2345 + self.atoms.net_active_window,
2346 + AtomEnum::WINDOW,
2347 + 32,
2348 + 1,
2349 + &window.to_ne_bytes(),
2350 + )?;
2241 } 2351 }
2242 2352
2243 - self.connection 2353 + let _ = self.send_event(window, self.atoms.wm_take_focus);
2244 - .set_input_focus(InputFocus::POINTER_ROOT, window, x11rb::CURRENT_TIME)?;
2245 self.connection.flush()?; 2354 self.connection.flush()?;
2246 2355
2247 - self.update_focus_visuals(old_focused, window)?; 2356 + Ok(())
2248 - self.previous_focused = Some(window); 2357 + }
2249 2358
2250 - if self.layout.name() == "tabbed" { 2359 + fn grabbuttons(&self, window: Window, focused: bool) -> WmResult<()> {
2251 - self.update_tab_bars()?; 2360 + self.connection.ungrab_button(ButtonIndex::ANY, window, ModMask::ANY)?;
2361 +
2362 + if !focused {
2363 + self.connection.grab_button(
2364 + false,
2365 + window,
2366 + EventMask::BUTTON_PRESS | EventMask::BUTTON_RELEASE,
2367 + GrabMode::SYNC,
2368 + GrabMode::SYNC,
2369 + x11rb::NONE,
2370 + x11rb::NONE,
2371 + ButtonIndex::ANY,
2372 + ModMask::ANY,
2373 + )?;
2374 + }
2375 +
2376 + let ignore_modifiers = [
2377 + 0u16,
2378 + u16::from(ModMask::LOCK),
2379 + u16::from(ModMask::M2),
2380 + u16::from(ModMask::LOCK | ModMask::M2),
2381 + ];
2382 +
2383 + for &ignore_mask in &ignore_modifiers {
2384 + let grab_mask = u16::from(self.config.modkey) | ignore_mask;
2385 +
2386 + self.connection.grab_button(
2387 + false,
2388 + window,
2389 + EventMask::BUTTON_PRESS | EventMask::BUTTON_RELEASE,
2390 + GrabMode::ASYNC,
2391 + GrabMode::SYNC,
2392 + x11rb::NONE,
2393 + x11rb::NONE,
2394 + ButtonIndex::M1,
2395 + grab_mask.into(),
2396 + )?;
2397 +
2398 + self.connection.grab_button(
2399 + false,
2400 + window,
2401 + EventMask::BUTTON_PRESS | EventMask::BUTTON_RELEASE,
2402 + GrabMode::ASYNC,
2403 + GrabMode::SYNC,
2404 + x11rb::NONE,
2405 + x11rb::NONE,
2406 + ButtonIndex::M3,
2407 + grab_mask.into(),
2408 + )?;
2252 } 2409 }
2253 2410
2254 Ok(()) 2411 Ok(())
2255 } 2412 }
2256 2413
2257 - fn unfocus(&self, window: Window) -> WmResult<()> { 2414 + fn unfocus(&self, window: Window, reset_input_focus: bool) -> WmResult<()> {
2258 if !self.windows.contains(&window) { 2415 if !self.windows.contains(&window) {
2259 return Ok(()); 2416 return Ok(());
2260 } 2417 }
2261 2418
2419 + self.grabbuttons(window, false)?;
2420 +
2262 self.connection.change_window_attributes( 2421 self.connection.change_window_attributes(
2263 window, 2422 window,
2264 &ChangeWindowAttributesAux::new().border_pixel(self.config.border_unfocused), 2423 &ChangeWindowAttributesAux::new().border_pixel(self.config.border_unfocused),
2265 )?; 2424 )?;
2266 2425
2267 - self.connection.grab_button( 2426 + if reset_input_focus {
2268 - false, 2427 + self.connection.set_input_focus(
2269 - window, 2428 + InputFocus::POINTER_ROOT,
2270 - EventMask::BUTTON_PRESS, 2429 + self.root,
2271 - GrabMode::SYNC, 2430 + x11rb::CURRENT_TIME,
2272 - GrabMode::SYNC, 2431 + )?;
2273 - x11rb::NONE, 2432 + self.connection.delete_property(self.root, self.atoms.net_active_window)?;
2274 - x11rb::NONE, 2433 + }
2275 - ButtonIndex::ANY,
2276 - ModMask::ANY,
2277 - )?;
2278 2434
2279 Ok(()) 2435 Ok(())
2280 } 2436 }
2281 2437
2282 fn focus(&mut self, window: Option<Window>) -> WmResult<()> { 2438 fn focus(&mut self, window: Option<Window>) -> WmResult<()> {
2283 - let monitor = self.monitors.get_mut(self.selected_monitor).unwrap(); 2439 + let old_selected = self
2284 - let old_selected = monitor.selected_client; 2440 + .monitors
2441 + .get(self.selected_monitor)
2442 + .and_then(|m| m.selected_client);
2285 2443
2286 - if let Some(old_win) = old_selected 2444 + let mut focus_client = window;
2287 - && old_selected != window 2445 + if focus_client.is_none()
2446 + || focus_client.is_some_and(|w| !self.is_visible(w))
2288 { 2447 {
2289 - self.unfocus(old_win)?;
2290 - }
2291 -
2292 - let mut win = window;
2293 - if win.is_none() || !self.is_visible(win.unwrap()) {
2294 let mut current = self 2448 let mut current = self
2295 .monitors 2449 .monitors
2296 .get(self.selected_monitor) 2450 .get(self.selected_monitor)
2297 .and_then(|m| m.stack_head); 2451 .and_then(|m| m.stack_head);
2298 2452
2453 + focus_client = None;
2299 while let Some(w) = current { 2454 while let Some(w) = current {
2300 if self.is_visible(w) { 2455 if self.is_visible(w) {
2301 - win = Some(w); 2456 + focus_client = Some(w);
2302 break; 2457 break;
2303 } 2458 }
2304 current = self.clients.get(&w).and_then(|c| c.stack_next); 2459 current = self.clients.get(&w).and_then(|c| c.stack_next);
2305 } 2460 }
2306 } 2461 }
2307 2462
2308 - if let Some(win) = win { 2463 + if old_selected != focus_client {
2309 - if !self.windows.contains(&win) { 2464 + if let Some(old_win) = old_selected {
2310 - return Ok(()); 2465 + self.unfocus(old_win, false)?;
2311 - }
2312 -
2313 - if self.clients.get(&win).is_some_and(|c| c.is_urgent) {
2314 - self.set_urgent(win, false)?;
2315 } 2466 }
2467 + }
2316 2468
2469 + if let Some(win) = focus_client {
2317 let monitor_idx = self 2470 let monitor_idx = self
2318 .clients 2471 .clients
2319 .get(&win) 2472 .get(&win)
2320 .map(|c| c.monitor_index) 2473 .map(|c| c.monitor_index)
2321 .unwrap_or(self.selected_monitor); 2474 .unwrap_or(self.selected_monitor);
2475 +
2322 if monitor_idx != self.selected_monitor { 2476 if monitor_idx != self.selected_monitor {
2323 self.selected_monitor = monitor_idx; 2477 self.selected_monitor = monitor_idx;
2324 } 2478 }
2325 2479
2480 + if self.clients.get(&win).is_some_and(|c| c.is_urgent) {
2481 + self.set_urgent(win, false)?;
2482 + }
2483 +
2326 self.detach_stack(win); 2484 self.detach_stack(win);
2327 self.attach_stack(win, monitor_idx); 2485 self.attach_stack(win, monitor_idx);
2328 2486
2487 + self.grabbuttons(win, true)?;
2488 +
2329 self.connection.change_window_attributes( 2489 self.connection.change_window_attributes(
2330 win, 2490 win,
2331 &ChangeWindowAttributesAux::new().border_pixel(self.config.border_focused), 2491 &ChangeWindowAttributesAux::new().border_pixel(self.config.border_focused),
2332 )?; 2492 )?;
2333 2493
2334 - self.connection 2494 + let never_focus = self
2335 - .ungrab_button(ButtonIndex::ANY, win, ModMask::ANY)?; 2495 + .clients
2496 + .get(&win)
2497 + .map(|client| client.never_focus)
2498 + .unwrap_or(false);
2336 2499
2337 - self.connection 2500 + if !never_focus {
2338 - .set_input_focus(InputFocus::POINTER_ROOT, win, x11rb::CURRENT_TIME)?; 2501 + self.connection
2502 + .set_input_focus(InputFocus::POINTER_ROOT, win, x11rb::CURRENT_TIME)?;
2503 +
2504 + self.connection.change_property(
2505 + PropMode::REPLACE,
2506 + self.root,
2507 + self.atoms.net_active_window,
2508 + AtomEnum::WINDOW,
2509 + 32,
2510 + 1,
2511 + &win.to_ne_bytes(),
2512 + )?;
2513 + }
2514 +
2515 + let _ = self.send_event(win, self.atoms.wm_take_focus);
2339 2516
2340 if let Some(monitor) = self.monitors.get_mut(self.selected_monitor) { 2517 if let Some(monitor) = self.monitors.get_mut(self.selected_monitor) {
2341 monitor.selected_client = Some(win); 2518 monitor.selected_client = Some(win);
@@ -2349,6 +2526,9 @@ impl WindowManager {
2349 x11rb::CURRENT_TIME, 2526 x11rb::CURRENT_TIME,
2350 )?; 2527 )?;
2351 2528
2529 + self.connection
2530 + .delete_property(self.root, self.atoms.net_active_window)?;
2531 +
2352 if let Some(monitor) = self.monitors.get_mut(self.selected_monitor) { 2532 if let Some(monitor) = self.monitors.get_mut(self.selected_monitor) {
2353 monitor.selected_client = None; 2533 monitor.selected_client = None;
2354 } 2534 }
@@ -2413,25 +2593,35 @@ impl WindowManager {
2413 2593
2414 fn focusstack(&mut self, direction: i32) -> WmResult<()> { 2594 fn focusstack(&mut self, direction: i32) -> WmResult<()> {
2415 let monitor = match self.monitors.get(self.selected_monitor) { 2595 let monitor = match self.monitors.get(self.selected_monitor) {
2416 - Some(m) => m, 2596 + Some(monitor) => monitor,
2417 None => return Ok(()), 2597 None => return Ok(()),
2418 }; 2598 };
2419 2599
2420 - let selected = match monitor.selected_client { 2600 + let selected_window = match monitor.selected_client {
2421 - Some(win) => win, 2601 + Some(window) => window,
2422 None => return Ok(()), 2602 None => return Ok(()),
2423 }; 2603 };
2424 2604
2605 + let selected_is_fullscreen = self
2606 + .clients
2607 + .get(&selected_window)
2608 + .map(|client| client.is_fullscreen)
2609 + .unwrap_or(false);
2610 +
2611 + if selected_is_fullscreen {
2612 + return Ok(());
2613 + }
2614 +
2425 let selected_tags = monitor.tagset[monitor.selected_tags_index]; 2615 let selected_tags = monitor.tagset[monitor.selected_tags_index];
2426 2616
2427 let mut stack_windows: Vec<Window> = Vec::new(); 2617 let mut stack_windows: Vec<Window> = Vec::new();
2428 - let mut current = monitor.clients_head; 2618 + let mut current_window = monitor.clients_head;
2429 - while let Some(win) = current { 2619 + while let Some(window) = current_window {
2430 - if let Some(client) = self.clients.get(&win) { 2620 + if let Some(client) = self.clients.get(&window) {
2431 if client.tags & selected_tags != 0 && !client.is_floating { 2621 if client.tags & selected_tags != 0 && !client.is_floating {
2432 - stack_windows.push(win); 2622 + stack_windows.push(window);
2433 } 2623 }
2434 - current = client.next; 2624 + current_window = client.next;
2435 } else { 2625 } else {
2436 break; 2626 break;
2437 } 2627 }
@@ -2441,17 +2631,19 @@ impl WindowManager {
2441 return Ok(()); 2631 return Ok(());
2442 } 2632 }
2443 2633
2444 - let current_idx = stack_windows.iter().position(|&w| w == selected); 2634 + let current_index = stack_windows
2635 + .iter()
2636 + .position(|&window| window == selected_window);
2445 2637
2446 - let next_window = if let Some(idx) = current_idx { 2638 + let next_window = if let Some(index) = current_index {
2447 if direction > 0 { 2639 if direction > 0 {
2448 - if idx + 1 < stack_windows.len() { 2640 + if index + 1 < stack_windows.len() {
2449 - stack_windows[idx + 1] 2641 + stack_windows[index + 1]
2450 } else { 2642 } else {
2451 stack_windows[0] 2643 stack_windows[0]
2452 } 2644 }
2453 - } else if idx > 0 { 2645 + } else if index > 0 {
2454 - stack_windows[idx - 1] 2646 + stack_windows[index - 1]
2455 } else { 2647 } else {
2456 stack_windows[stack_windows.len() - 1] 2648 stack_windows[stack_windows.len() - 1]
2457 } 2649 }
@@ -2465,6 +2657,7 @@ impl WindowManager {
2465 self.scroll_to_window(next_window, true)?; 2657 self.scroll_to_window(next_window, true)?;
2466 } 2658 }
2467 2659
2660 + self.restack()?;
2468 self.update_tab_bars()?; 2661 self.update_tab_bars()?;
2469 2662
2470 Ok(()) 2663 Ok(())
@@ -2618,7 +2811,7 @@ impl WindowManager {
2618 .and_then(|m| m.selected_client); 2811 .and_then(|m| m.selected_client);
2619 2812
2620 if let Some(win) = old_selected { 2813 if let Some(win) = old_selected {
2621 - self.unfocus(win)?; 2814 + self.unfocus(win, true)?;
2622 } 2815 }
2623 2816
2624 self.selected_monitor = target_monitor; 2817 self.selected_monitor = target_monitor;
@@ -2652,39 +2845,6 @@ impl WindowManager {
2652 Ok(()) 2845 Ok(())
2653 } 2846 }
2654 2847
2655 - fn update_focus_visuals(
2656 - &self,
2657 - old_focused: Option<Window>,
2658 - new_focused: Window,
2659 - ) -> WmResult<()> {
2660 - if let Some(old_win) = old_focused
2661 - && old_win != new_focused
2662 - {
2663 - self.connection.configure_window(
2664 - old_win,
2665 - &ConfigureWindowAux::new().border_width(self.config.border_width),
2666 - )?;
2667 -
2668 - self.connection.change_window_attributes(
2669 - old_win,
2670 - &ChangeWindowAttributesAux::new().border_pixel(self.config.border_unfocused),
2671 - )?;
2672 - }
2673 -
2674 - self.connection.configure_window(
2675 - new_focused,
2676 - &ConfigureWindowAux::new().border_width(self.config.border_width),
2677 - )?;
2678 -
2679 - self.connection.change_window_attributes(
2680 - new_focused,
2681 - &ChangeWindowAttributesAux::new().border_pixel(self.config.border_focused),
2682 - )?;
2683 -
2684 - self.connection.flush()?;
2685 - Ok(())
2686 - }
2687 -
2688 fn drag_window(&mut self, window: Window) -> WmResult<()> { 2848 fn drag_window(&mut self, window: Window) -> WmResult<()> {
2689 let is_fullscreen = self 2849 let is_fullscreen = self
2690 .clients 2850 .clients
@@ -3091,7 +3251,7 @@ impl WindowManager {
3091 Ok(()) 3251 Ok(())
3092 } 3252 }
3093 3253
3094 - fn handle_event(&mut self, event: Event) -> WmResult<Option<bool>> { 3254 + fn handle_event(&mut self, event: Event) -> WmResult<Control> {
3095 match event { 3255 match event {
3096 Event::KeyPress(ref key_event) if key_event.event == self.overlay.window() => { 3256 Event::KeyPress(ref key_event) if key_event.event == self.overlay.window() => {
3097 if self.overlay.is_visible() 3257 if self.overlay.is_visible()
@@ -3099,7 +3259,7 @@ impl WindowManager {
3099 { 3259 {
3100 eprintln!("Failed to hide overlay: {:?}", error); 3260 eprintln!("Failed to hide overlay: {:?}", error);
3101 } 3261 }
3102 - return Ok(None); 3262 + return Ok(Control::Continue);
3103 } 3263 }
3104 Event::ButtonPress(ref button_event) if button_event.event == self.overlay.window() => { 3264 Event::ButtonPress(ref button_event) if button_event.event == self.overlay.window() => {
3105 if self.overlay.is_visible() 3265 if self.overlay.is_visible()
@@ -3107,7 +3267,7 @@ impl WindowManager {
3107 { 3267 {
3108 eprintln!("Failed to hide overlay: {:?}", error); 3268 eprintln!("Failed to hide overlay: {:?}", error);
3109 } 3269 }
3110 - return Ok(None); 3270 + return Ok(Control::Continue);
3111 } 3271 }
3112 Event::Expose(ref expose_event) if expose_event.window == self.overlay.window() => { 3272 Event::Expose(ref expose_event) if expose_event.window == self.overlay.window() => {
3113 if self.overlay.is_visible() 3273 if self.overlay.is_visible()
@@ -3115,7 +3275,7 @@ impl WindowManager {
3115 { 3275 {
3116 eprintln!("Failed to draw overlay: {:?}", error); 3276 eprintln!("Failed to draw overlay: {:?}", error);
3117 } 3277 }
3118 - return Ok(None); 3278 + return Ok(Control::Continue);
3119 } 3279 }
3120 Event::KeyPress(ref e) if e.event == self.keybind_overlay.window() => { 3280 Event::KeyPress(ref e) if e.event == self.keybind_overlay.window() => {
3121 if self.keybind_overlay.is_visible() 3281 if self.keybind_overlay.is_visible()
@@ -3133,12 +3293,12 @@ impl WindowManager {
3133 } 3293 }
3134 } 3294 }
3135 } 3295 }
3136 - return Ok(None); 3296 + return Ok(Control::Continue);
3137 } 3297 }
3138 Event::ButtonPress(ref e) if e.event == self.keybind_overlay.window() => { 3298 Event::ButtonPress(ref e) if e.event == self.keybind_overlay.window() => {
3139 self.connection 3299 self.connection
3140 .allow_events(Allow::REPLAY_POINTER, e.time)?; 3300 .allow_events(Allow::REPLAY_POINTER, e.time)?;
3141 - return Ok(None); 3301 + return Ok(Control::Continue);
3142 } 3302 }
3143 Event::Expose(ref expose_event) 3303 Event::Expose(ref expose_event)
3144 if expose_event.window == self.keybind_overlay.window() => 3304 if expose_event.window == self.keybind_overlay.window() =>
@@ -3148,16 +3308,16 @@ impl WindowManager {
3148 { 3308 {
3149 eprintln!("Failed to draw keybind overlay: {:?}", error); 3309 eprintln!("Failed to draw keybind overlay: {:?}", error);
3150 } 3310 }
3151 - return Ok(None); 3311 + return Ok(Control::Continue);
3152 } 3312 }
3153 Event::MapRequest(event) => { 3313 Event::MapRequest(event) => {
3154 let attrs = match self.connection.get_window_attributes(event.window)?.reply() { 3314 let attrs = match self.connection.get_window_attributes(event.window)?.reply() {
3155 Ok(attrs) => attrs, 3315 Ok(attrs) => attrs,
3156 - Err(_) => return Ok(None), 3316 + Err(_) => return Ok(Control::Continue),
3157 }; 3317 };
3158 3318
3159 if attrs.override_redirect { 3319 if attrs.override_redirect {
3160 - return Ok(None); 3320 + return Ok(Control::Continue);
3161 } 3321 }
3162 3322
3163 if !self.windows.contains(&event.window) { 3323 if !self.windows.contains(&event.window) {
@@ -3166,21 +3326,21 @@ impl WindowManager {
3166 } 3326 }
3167 Event::UnmapNotify(event) => { 3327 Event::UnmapNotify(event) => {
3168 if self.windows.contains(&event.window) && self.is_window_visible(event.window) { 3328 if self.windows.contains(&event.window) && self.is_window_visible(event.window) {
3169 - self.remove_window(event.window)?; 3329 + self.remove_window(event.window, false)?;
3170 } 3330 }
3171 } 3331 }
3172 Event::DestroyNotify(event) => { 3332 Event::DestroyNotify(event) => {
3173 if self.windows.contains(&event.window) { 3333 if self.windows.contains(&event.window) {
3174 - self.remove_window(event.window)?; 3334 + self.remove_window(event.window, true)?;
3175 } 3335 }
3176 } 3336 }
3177 Event::PropertyNotify(event) => { 3337 Event::PropertyNotify(event) => {
3178 if event.state == Property::DELETE { 3338 if event.state == Property::DELETE {
3179 - return Ok(None); 3339 + return Ok(Control::Continue);
3180 } 3340 }
3181 3341
3182 if !self.clients.contains_key(&event.window) { 3342 if !self.clients.contains_key(&event.window) {
3183 - return Ok(None); 3343 + return Ok(Control::Continue);
3184 } 3344 }
3185 3345
3186 if event.atom == AtomEnum::WM_TRANSIENT_FOR.into() { 3346 if event.atom == AtomEnum::WM_TRANSIENT_FOR.into() {
@@ -3220,13 +3380,22 @@ impl WindowManager {
3220 } 3380 }
3221 } 3381 }
3222 Event::EnterNotify(event) => { 3382 Event::EnterNotify(event) => {
3223 - if event.mode != x11rb::protocol::xproto::NotifyMode::NORMAL { 3383 + if event.mode != x11rb::protocol::xproto::NotifyMode::NORMAL
3224 - return Ok(None); 3384 + || event.detail == x11rb::protocol::xproto::NotifyDetail::INFERIOR
3385 + {
3386 + return Ok(Control::Continue);
3225 } 3387 }
3226 if self.windows.contains(&event.event) { 3388 if self.windows.contains(&event.event) {
3227 if let Some(client) = self.clients.get(&event.event) 3389 if let Some(client) = self.clients.get(&event.event)
3228 && client.monitor_index != self.selected_monitor 3390 && client.monitor_index != self.selected_monitor
3229 { 3391 {
3392 + if let Some(old_selected) = self
3393 + .monitors
3394 + .get(self.selected_monitor)
3395 + .and_then(|monitor| monitor.selected_client)
3396 + {
3397 + self.unfocus(old_selected, false)?;
3398 + }
3230 self.selected_monitor = client.monitor_index; 3399 self.selected_monitor = client.monitor_index;
3231 self.update_bar()?; 3400 self.update_bar()?;
3232 } 3401 }
@@ -3236,26 +3405,30 @@ impl WindowManager {
3236 } 3405 }
3237 Event::MotionNotify(event) => { 3406 Event::MotionNotify(event) => {
3238 if event.event != self.root { 3407 if event.event != self.root {
3239 - return Ok(None); 3408 + return Ok(Control::Continue);
3240 } 3409 }
3241 3410
3242 if let Some(monitor_index) = 3411 if let Some(monitor_index) =
3243 self.get_monitor_at_point(event.root_x as i32, event.root_y as i32) 3412 self.get_monitor_at_point(event.root_x as i32, event.root_y as i32)
3244 && monitor_index != self.selected_monitor 3413 && monitor_index != self.selected_monitor
3245 { 3414 {
3415 + if let Some(old_selected) = self
3416 + .monitors
3417 + .get(self.selected_monitor)
3418 + .and_then(|monitor| monitor.selected_client)
3419 + {
3420 + self.unfocus(old_selected, true)?;
3421 + }
3422 +
3246 self.selected_monitor = monitor_index; 3423 self.selected_monitor = monitor_index;
3424 + self.focus(None)?;
3247 self.update_bar()?; 3425 self.update_bar()?;
3248 - 3426 + self.update_tab_bars()?;
3249 - let visible = self.visible_windows_on_monitor(monitor_index);
3250 - if let Some(&win) = visible.first() {
3251 - self.focus(Some(win))?;
3252 - self.update_tab_bars()?;
3253 - }
3254 } 3427 }
3255 } 3428 }
3256 Event::KeyPress(event) => { 3429 Event::KeyPress(event) => {
3257 let Some(mapping) = &self.keyboard_mapping else { 3430 let Some(mapping) = &self.keyboard_mapping else {
3258 - return Ok(None); 3431 + return Ok(Control::Continue);
3259 }; 3432 };
3260 3433
3261 let result = keyboard::handle_key_press( 3434 let result = keyboard::handle_key_press(
@@ -3273,7 +3446,7 @@ impl WindowManager {
3273 self.update_bar()?; 3446 self.update_bar()?;
3274 3447
3275 match action { 3448 match action {
3276 - KeyAction::Quit => return Ok(Some(false)), 3449 + KeyAction::Quit => return Ok(Control::Quit),
3277 KeyAction::Restart => match self.try_reload_config() { 3450 KeyAction::Restart => match self.try_reload_config() {
3278 Ok(()) => { 3451 Ok(()) => {
3279 self.gaps_enabled = self.config.gaps_enabled; 3452 self.gaps_enabled = self.config.gaps_enabled;
@@ -3289,7 +3462,7 @@ impl WindowManager {
3289 } 3462 }
3290 Err(err) => { 3463 Err(err) => {
3291 eprintln!("Config reload error: {}", err); 3464 eprintln!("Config reload error: {}", err);
3292 - self.error_message = Some(err.clone()); 3465 + self.error_message = Some(err.to_string());
3293 let monitor = &self.monitors[self.selected_monitor]; 3466 let monitor = &self.monitors[self.selected_monitor];
3294 let monitor_x = monitor.screen_x as i16; 3467 let monitor_x = monitor.screen_x as i16;
3295 let monitor_y = monitor.screen_y as i16; 3468 let monitor_y = monitor.screen_y as i16;
@@ -3298,7 +3471,7 @@ impl WindowManager {
3298 match self.overlay.show_error( 3471 match self.overlay.show_error(
3299 &self.connection, 3472 &self.connection,
3300 &self.font, 3473 &self.font,
3301 - &err, 3474 + err,
3302 monitor_x, 3475 monitor_x,
3303 monitor_y, 3476 monitor_y,
3304 screen_width, 3477 screen_width,
@@ -3468,12 +3641,15 @@ impl WindowManager {
3468 if let Some(client) = self.clients.get(&event.window) { 3641 if let Some(client) = self.clients.get(&event.window) {
3469 let monitor = &self.monitors[client.monitor_index]; 3642 let monitor = &self.monitors[client.monitor_index];
3470 let is_floating = client.is_floating; 3643 let is_floating = client.is_floating;
3644 + let is_fullscreen = client.is_fullscreen;
3471 let has_layout = self.layout.name() != "normie"; 3645 let has_layout = self.layout.name() != "normie";
3472 3646
3473 if event.value_mask.contains(ConfigWindow::BORDER_WIDTH) { 3647 if event.value_mask.contains(ConfigWindow::BORDER_WIDTH) {
3474 if let Some(c) = self.clients.get_mut(&event.window) { 3648 if let Some(c) = self.clients.get_mut(&event.window) {
3475 c.border_width = event.border_width; 3649 c.border_width = event.border_width;
3476 } 3650 }
3651 + } else if is_fullscreen {
3652 + self.send_configure_notify(event.window)?;
3477 } else if is_floating || !has_layout { 3653 } else if is_floating || !has_layout {
3478 let mut x = client.x_position as i32; 3654 let mut x = client.x_position as i32;
3479 let mut y = client.y_position as i32; 3655 let mut y = client.y_position as i32;
@@ -3575,21 +3751,26 @@ impl WindowManager {
3575 } 3751 }
3576 Event::ClientMessage(event) => { 3752 Event::ClientMessage(event) => {
3577 if !self.clients.contains_key(&event.window) { 3753 if !self.clients.contains_key(&event.window) {
3578 - return Ok(None); 3754 + return Ok(Control::Continue);
3579 } 3755 }
3580 3756
3581 if event.type_ == self.atoms.net_wm_state { 3757 if event.type_ == self.atoms.net_wm_state {
3582 - if let Some(data) = event.data.as_data32().get(1) 3758 + let data = event.data.as_data32();
3583 - && *data == self.atoms.net_wm_state_fullscreen 3759 + let atom1 = data.get(1).copied().unwrap_or(0);
3760 + let atom2 = data.get(2).copied().unwrap_or(0);
3761 +
3762 + if atom1 == self.atoms.net_wm_state_fullscreen
3763 + || atom2 == self.atoms.net_wm_state_fullscreen
3584 { 3764 {
3585 - let action = event.data.as_data32()[0]; 3765 + let action = data[0];
3586 let fullscreen = match action { 3766 let fullscreen = match action {
3587 1 => true, 3767 1 => true,
3588 0 => false, 3768 0 => false,
3589 2 => !self.fullscreen_windows.contains(&event.window), 3769 2 => !self.fullscreen_windows.contains(&event.window),
3590 - _ => return Ok(None), 3770 + _ => return Ok(Control::Continue),
3591 }; 3771 };
3592 self.set_window_fullscreen(event.window, fullscreen)?; 3772 self.set_window_fullscreen(event.window, fullscreen)?;
3773 + self.restack()?;
3593 } 3774 }
3594 } else if event.type_ == self.atoms.net_active_window { 3775 } else if event.type_ == self.atoms.net_active_window {
3595 let selected_window = self 3776 let selected_window = self
@@ -3609,15 +3790,25 @@ impl WindowManager {
3609 } 3790 }
3610 } 3791 }
3611 Event::FocusIn(event) => { 3792 Event::FocusIn(event) => {
3612 - let selected_window = self 3793 + if !self.windows.contains(&event.event) {
3613 - .monitors 3794 + return Ok(Control::Continue);
3614 - .get(self.selected_monitor) 3795 + }
3615 - .and_then(|m| m.selected_client);
3616 3796
3617 - if let Some(sel_win) = selected_window 3797 + let event_window_visible = self.is_visible(event.event);
3618 - && event.event != sel_win 3798 +
3619 - { 3799 + if !event_window_visible {
3620 - self.set_focus(sel_win)?; 3800 + self.focus(None)?;
3801 + } else {
3802 + let selected_window = self
3803 + .monitors
3804 + .get(self.selected_monitor)
3805 + .and_then(|monitor| monitor.selected_client);
3806 +
3807 + if let Some(focused_window) = selected_window
3808 + && event.event != focused_window
3809 + {
3810 + self.set_focus(focused_window)?;
3811 + }
3621 } 3812 }
3622 } 3813 }
3623 Event::MappingNotify(event) => { 3814 Event::MappingNotify(event) => {
@@ -3632,13 +3823,45 @@ impl WindowManager {
3632 3823
3633 if event.width != old_width || event.height != old_height { 3824 if event.width != old_width || event.height != old_height {
3634 self.screen = self.connection.setup().roots[self.screen_number].clone(); 3825 self.screen = self.connection.setup().roots[self.screen_number].clone();
3826 +
3827 + for monitor_index in 0..self.monitors.len() {
3828 + let monitor = &self.monitors[monitor_index];
3829 + let monitor_x = monitor.screen_x;
3830 + let monitor_y = monitor.screen_y;
3831 + let monitor_width = monitor.screen_width as u32;
3832 + let monitor_height = monitor.screen_height as u32;
3833 +
3834 + let fullscreen_on_monitor: Vec<Window> = self
3835 + .fullscreen_windows
3836 + .iter()
3837 + .filter(|&&window| {
3838 + self.clients
3839 + .get(&window)
3840 + .map(|client| client.monitor_index == monitor_index)
3841 + .unwrap_or(false)
3842 + })
3843 + .copied()
3844 + .collect();
3845 +
3846 + for window in fullscreen_on_monitor {
3847 + self.connection.configure_window(
3848 + window,
3849 + &ConfigureWindowAux::new()
3850 + .x(monitor_x)
3851 + .y(monitor_y)
3852 + .width(monitor_width)
3853 + .height(monitor_height),
3854 + )?;
3855 + }
3856 + }
3857 +
3635 self.apply_layout()?; 3858 self.apply_layout()?;
3636 } 3859 }
3637 } 3860 }
3638 } 3861 }
3639 _ => {} 3862 _ => {}
3640 } 3863 }
3641 - Ok(None) 3864 + Ok(Control::Continue)
3642 } 3865 }
3643 3866
3644 fn apply_layout(&mut self) -> WmResult<()> { 3867 fn apply_layout(&mut self) -> WmResult<()> {
@@ -3770,6 +3993,44 @@ impl WindowManager {
3770 self.showhide(stack_head)?; 3993 self.showhide(stack_head)?;
3771 } 3994 }
3772 3995
3996 + for monitor_index in 0..self.monitors.len() {
3997 + let monitor = &self.monitors[monitor_index];
3998 + let tags = monitor.tagset[monitor.selected_tags_index];
3999 +
4000 + let has_visible_fullscreen = self.fullscreen_windows.iter().any(|&w| {
4001 + self.clients.get(&w).map_or(false, |c| {
4002 + c.monitor_index == monitor_index && (c.tags & tags) != 0
4003 + })
4004 + });
4005 +
4006 + if has_visible_fullscreen {
4007 + if let Some(bar) = self.bars.get(monitor_index) {
4008 + self.connection.unmap_window(bar.window())?;
4009 + }
4010 +
4011 + for &window in &self.fullscreen_windows {
4012 + if let Some(client) = self.clients.get(&window) {
4013 + if client.monitor_index == monitor_index && (client.tags & tags) != 0 {
4014 + self.connection.configure_window(
4015 + window,
4016 + &ConfigureWindowAux::new()
4017 + .border_width(0)
4018 + .x(monitor.screen_x)
4019 + .y(monitor.screen_y)
4020 + .width(monitor.screen_width as u32)
4021 + .height(monitor.screen_height as u32)
4022 + .stack_mode(StackMode::ABOVE),
4023 + )?;
4024 + }
4025 + }
4026 + }
4027 + } else if self.show_bar {
4028 + if let Some(bar) = self.bars.get(monitor_index) {
4029 + self.connection.map_window(bar.window())?;
4030 + }
4031 + }
4032 + }
4033 +
3773 self.connection.flush()?; 4034 self.connection.flush()?;
3774 4035
3775 let is_tabbed = self.layout.name() == LayoutType::Tabbed.as_str(); 4036 let is_tabbed = self.layout.name() == LayoutType::Tabbed.as_str();
@@ -4089,10 +4350,11 @@ impl WindowManager {
4089 } 4350 }
4090 4351
4091 fn update_window_type(&mut self, window: Window) -> WmResult<()> { 4352 fn update_window_type(&mut self, window: Window) -> WmResult<()> {
4092 - if let Ok(Some(state_atom)) = self.get_window_atom_property(window, self.atoms.net_wm_state) 4353 + if let Ok(state_atoms) = self.get_window_atom_list_property(window, self.atoms.net_wm_state)
4093 - && state_atom == self.atoms.net_wm_state_fullscreen
4094 { 4354 {
4095 - self.set_window_fullscreen(window, true)?; 4355 + if state_atoms.contains(&self.atoms.net_wm_state_fullscreen) {
4356 + self.set_window_fullscreen(window, true)?;
4357 + }
4096 } 4358 }
4097 4359
4098 if let Ok(Some(type_atom)) = 4360 if let Ok(Some(type_atom)) =
@@ -4425,7 +4687,7 @@ impl WindowManager {
4425 } 4687 }
4426 } 4688 }
4427 4689
4428 - fn remove_window(&mut self, window: Window) -> WmResult<()> { 4690 + fn remove_window(&mut self, window: Window, destroyed: bool) -> WmResult<()> {
4429 let initial_count = self.windows.len(); 4691 let initial_count = self.windows.len();
4430 4692
4431 let focused = self 4693 let focused = self
@@ -4433,6 +4695,17 @@ impl WindowManager {
4433 .get(self.selected_monitor) 4695 .get(self.selected_monitor)
4434 .and_then(|m| m.selected_client); 4696 .and_then(|m| m.selected_client);
4435 4697
4698 + if !destroyed {
4699 + if let Some(client) = self.clients.get(&window) {
4700 + let old_border_width = client.old_border_width;
4701 + self.connection.configure_window(
4702 + window,
4703 + &ConfigureWindowAux::new().border_width(old_border_width as u32),
4704 + )?;
4705 + }
4706 + self.set_wm_state(window, 0)?;
4707 + }
4708 +
4436 if self.clients.contains_key(&window) { 4709 if self.clients.contains_key(&window) {
4437 self.detach(window); 4710 self.detach(window);
4438 self.detach_stack(window); 4711 self.detach_stack(window);
@@ -4441,6 +4714,7 @@ impl WindowManager {
4441 4714
4442 self.windows.retain(|&w| w != window); 4715 self.windows.retain(|&w| w != window);
4443 self.floating_windows.remove(&window); 4716 self.floating_windows.remove(&window);
4717 + self.update_client_list()?;
4444 4718
4445 if self.windows.len() < initial_count { 4719 if self.windows.len() < initial_count {
4446 if focused == Some(window) { 4720 if focused == Some(window) {
@@ -4469,7 +4743,6 @@ impl WindowManager {
4469 4743
4470 let mut current = monitor.clients_head; 4744 let mut current = monitor.clients_head;
4471 while let Some(window) = current { 4745 while let Some(window) = current {
4472 - // A window should always have a client attatched to it.
4473 let Some(client) = self.clients.get(&window) else { 4746 let Some(client) = self.clients.get(&window) else {
4474 break; 4747 break;
4475 }; 4748 };
+5 −1 templates/config.lua
@@ -21,7 +21,7 @@
21 -- Modifier key: "Mod4" is the Super/Windows key, "Mod1" is Alt 21 -- Modifier key: "Mod4" is the Super/Windows key, "Mod1" is Alt
22 local modkey = "Mod4" 22 local modkey = "Mod4"
23 23
24 --- Terminal emulator command (defualts to alacritty) 24 +-- Terminal emulator command (defaults to alacritty)
25 local terminal = "alacritty" 25 local terminal = "alacritty"
26 26
27 -- Color palette - customize these to match your theme 27 -- Color palette - customize these to match your theme
@@ -144,6 +144,7 @@ oxwm.gaps.set_outer(5, 5)
144 144
145 -- Examples (uncomment to use): 145 -- Examples (uncomment to use):
146 oxwm.rule.add({ instance = "gimp", floating = true }) 146 oxwm.rule.add({ instance = "gimp", floating = true })
147 +-- oxwm.rule.add({ class = "Alacritty", tag = 9, focus = true })
147 -- oxwm.rule.add({ class = "firefox", title = "Library", floating = true }) 148 -- oxwm.rule.add({ class = "firefox", title = "Library", floating = true })
148 -- oxwm.rule.add({ class = "firefox", tag = 2 }) 149 -- oxwm.rule.add({ class = "firefox", tag = 2 })
149 -- oxwm.rule.add({ instance = "mpv", floating = true }) 150 -- oxwm.rule.add({ instance = "mpv", floating = true })
@@ -172,6 +173,9 @@ oxwm.bar.set_scheme_selected(colors.cyan, colors.bg, colors.purple)
172 -- Urgent tags (windows requesting attention) 173 -- Urgent tags (windows requesting attention)
173 oxwm.bar.set_scheme_urgent(colors.red, colors.bg, colors.red) 174 oxwm.bar.set_scheme_urgent(colors.red, colors.bg, colors.red)
174 175
176 +-- Hide tags that have no windows and are not selected
177 +-- oxwm.bar.set_hide_vacant_tags(true)
178 +
175 ------------------------------------------------------------------------------- 179 -------------------------------------------------------------------------------
176 -- Keybindings 180 -- Keybindings
177 ------------------------------------------------------------------------------- 181 -------------------------------------------------------------------------------
+5 −1 templates/oxwm.lua
@@ -51,7 +51,7 @@ function oxwm.set_layout_symbol(name, symbol) end
51 oxwm.rule = {} 51 oxwm.rule = {}
52 52
53 ---Add a window rule 53 ---Add a window rule
54 ----@param rule {class: string?, instance: string?, title: string?, role: string?, floating: boolean?, tag: integer?, fullscreen: boolean?} Rule configuration 54 +---@param rule {class: string?, instance: string?, title: string?, role: string?, floating: boolean?, tag: integer?, fullscreen: boolean?, focus: boolean?} Rule configuration
55 function oxwm.rule.add(rule) end 55 function oxwm.rule.add(rule) end
56 56
57 ---Quit the window manager 57 ---Quit the window manager
@@ -323,6 +323,10 @@ function oxwm.bar.set_scheme_selected(foreground, background, underline) end
323 ---@param underline string|integer Underline color 323 ---@param underline string|integer Underline color
324 function oxwm.bar.set_scheme_urgent(foreground, background, underline) end 324 function oxwm.bar.set_scheme_urgent(foreground, background, underline) end
325 325
326 +---Hide tags that have no windows and are not currently selected
327 +---@param hide boolean Whether to hide vacant tags
328 +function oxwm.bar.set_hide_vacant_tags(hide) end
329 +
326 ---Add an autostart command 330 ---Add an autostart command
327 ---@param cmd string Command to run at startup 331 ---@param cmd string Command to run at startup
328 function oxwm.autostart(cmd) end 332 function oxwm.autostart(cmd) end