tony / oxwm

Merge pull request #43 from tonybanters/cleanup Browse files
Performance & Cleanup: Event Loop Optimization and Dead Code Removal
Tony, btw. committed 2025-11-21 parents d2136f3 1a68569 commit b23ed69c4c1f9fd5270b5abe70b928f518d859a2
Showing 8 changed files with 450 additions and 998 deletions. UnifiedSplit
+1 −8 Cargo.lock
@@ -11,12 +11,6 @@ dependencies = [
11 11 "libc",
12 12 ]
13 13
14 -[[package]]
15 -name = "anyhow"
16 -version = "1.0.100"
17 -source = "registry+https://github.com/rust-lang/crates.io-index"
18 -checksum = "a23eb6b1614318a8071c9b2521f36b424b2c83db5eb3a0fead4a6c0809af6e61"
19 -
20 14 [[package]]
21 15 name = "autocfg"
22 16 version = "1.5.0"
@@ -297,9 +291,8 @@ checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d"
297 291
298 292 [[package]]
299 293 name = "oxwm"
300 -version = "0.7.1"
294 +version = "0.7.2"
301 295 dependencies = [
302 - "anyhow",
303 296 "chrono",
304 297 "dirs",
305 298 "mlua",
+1 −2 Cargo.toml
@@ -1,6 +1,6 @@
1 1 [package]
2 2 name = "oxwm"
3 -version = "0.7.1"
3 +version = "0.7.2"
4 4 edition = "2024"
5 5
6 6 [lib]
@@ -14,7 +14,6 @@ path = "src/bin/main.rs"
14 14 [dependencies]
15 15 x11 = { version = "2.21", features = ["xlib", "xft"] }
16 16 x11rb = { version = "0.13", features = ["cursor", "xinerama"] }
17 -anyhow = "1"
18 17 chrono = "0.4"
19 18 dirs = "5.0"
20 19 serde = { version = "1.0", features = ["derive"] }
+3 −3 flake.lock
@@ -2,11 +2,11 @@
2 2 "nodes": {
3 3 "nixpkgs": {
4 4 "locked": {
5 - "lastModified": 1760038930,
6 - "narHash": "sha256-Oncbh0UmHjSlxO7ErQDM3KM0A5/Znfofj2BSzlHLeVw=",
5 + "lastModified": 1762977756,
6 + "narHash": "sha256-4PqRErxfe+2toFJFgcRKZ0UI9NSIOJa+7RXVtBhy4KE=",
7 7 "owner": "NixOS",
8 8 "repo": "nixpkgs",
9 - "rev": "0b4defa2584313f3b781240b29d61f6f9f7e0df3",
9 + "rev": "c5ae371f1a6a7fd27823bc500d9390b38c05fa55",
10 10 "type": "github"
11 11 },
12 12 "original": {
+14 −5 resources/test-config.lua
@@ -107,14 +107,23 @@ oxwm.key.bind({ modkey, "Shift" }, "9", oxwm.tag.move_to(8))
107 107
108 108 oxwm.bar.set_blocks({
109 109 oxwm.bar.block.battery({
110 - charging = "󰂄 Bat: {}%",
111 - discharging = "󰁹 Bat: {}%",
112 - full = "󰁹 Bat: {}%",
113 - format = "",
110 + format = "Bat: {}%",
111 + charging = "⚡ Bat: {}%",
112 + discharging = "🔋 Bat: {}%",
113 + full = "✓ Bat: {}%",
114 114 interval = 30,
115 115 color = colors.green,
116 - underline = true
116 + underline = true,
117 117 }),
118 + -- oxwm.bar.block.battery({
119 + -- charging = "󰂄 Bat: {}%",
120 + -- discharging = "󰁹 Bat: {}%",
121 + -- full = "󰁹 Bat: {}%",
122 + -- format = "",
123 + -- interval = 30,
124 + -- color = colors.green,
125 + -- underline = true
126 + -- }),
118 127 oxwm.bar.block.static({
119 128 text = " │ ",
120 129 format = "",
+32 −33 src/bin/main.rs
@@ -1,12 +1,11 @@
1 -use anyhow::{Context, Result};
2 1 use std::path::PathBuf;
3 2
4 -fn main() -> Result<()> {
5 - let args: Vec<String> = std::env::args().collect();
3 +fn main() -> Result<(), Box<dyn std::error::Error>> {
4 + let arguments: Vec<String> = std::env::args().collect();
6 5
7 6 let mut custom_config_path: Option<PathBuf> = None;
8 7
9 - match args.get(1).map(|s| s.as_str()) {
8 + match arguments.get(1).map(|string| string.as_str()) {
10 9 Some("--version") => {
11 10 println!("oxwm {}", env!("CARGO_PKG_VERSION"));
12 11 return Ok(());
@@ -20,7 +19,7 @@ fn main() -> Result<()> {
20 19 return Ok(());
21 20 }
22 21 Some("--config") => {
23 - if let Some(path) = args.get(2) {
22 + if let Some(path) = arguments.get(2) {
24 23 custom_config_path = Some(PathBuf::from(path));
25 24 } else {
26 25 eprintln!("Error: --config requires a path argument");
@@ -32,37 +31,37 @@ fn main() -> Result<()> {
32 31
33 32 let (config, had_broken_config) = load_config(custom_config_path)?;
34 33
35 - let mut wm = oxwm::window_manager::WindowManager::new(config)?;
34 + let mut window_manager = oxwm::window_manager::WindowManager::new(config)?;
36 35
37 36 if had_broken_config {
38 - wm.show_migration_overlay();
37 + window_manager.show_migration_overlay();
39 38 }
40 39
41 - let should_restart = wm.run()?;
40 + let should_restart = window_manager.run()?;
42 41
43 - drop(wm);
42 + drop(window_manager);
44 43
45 44 if should_restart {
46 45 use std::os::unix::process::CommandExt;
47 - let err = std::process::Command::new(&args[0]).args(&args[1..]).exec();
48 - eprintln!("Failed to restart: {}", err);
46 + let error = std::process::Command::new(&arguments[0]).args(&arguments[1..]).exec();
47 + eprintln!("Failed to restart: {}", error);
49 48 }
50 49
51 50 Ok(())
52 51 }
53 52
54 -fn load_config(custom_path: Option<PathBuf>) -> Result<(oxwm::Config, bool)> {
53 +fn load_config(custom_path: Option<PathBuf>) -> Result<(oxwm::Config, bool), Box<dyn std::error::Error>> {
55 54 let config_path = if let Some(path) = custom_path {
56 55 path
57 56 } else {
58 - let config_dir = get_config_path();
59 - let lua_path = config_dir.join("config.lua");
57 + let config_directory = get_config_path();
58 + let lua_path = config_directory.join("config.lua");
60 59
61 60 if !lua_path.exists() {
62 - let ron_path = config_dir.join("config.ron");
61 + let ron_path = config_directory.join("config.ron");
63 62 let had_ron_config = ron_path.exists();
64 63
65 - println!("No config found at {:?}", config_dir);
64 + println!("No config found at {:?}", config_directory);
66 65 println!("Creating default Lua config...");
67 66 init_config()?;
68 67
@@ -80,48 +79,48 @@ fn load_config(custom_path: Option<PathBuf>) -> Result<(oxwm::Config, bool)> {
80 79 lua_path
81 80 };
82 81
83 - let config_str =
84 - std::fs::read_to_string(&config_path).with_context(|| "Failed to read config file")?;
82 + let config_string = std::fs::read_to_string(&config_path)
83 + .map_err(|error| format!("Failed to read config file: {}", error))?;
85 84
86 - let config_dir = config_path.parent();
85 + let config_directory = config_path.parent();
87 86
88 - match oxwm::config::parse_lua_config(&config_str, config_dir) {
87 + match oxwm::config::parse_lua_config(&config_string, config_directory) {
89 88 Ok(config) => Ok((config, false)),
90 - Err(_) => {
89 + Err(_error) => {
91 90 let template = include_str!("../../templates/config.lua");
92 91 let config = oxwm::config::parse_lua_config(template, None)
93 - .with_context(|| "Failed to parse default template config")?;
92 + .map_err(|error| format!("Failed to parse default template config: {}", error))?;
94 93 Ok((config, true))
95 94 }
96 95 }
97 96 }
98 97
99 -fn init_config() -> Result<()> {
100 - let config_dir = get_config_path();
101 - std::fs::create_dir_all(&config_dir)?;
98 +fn init_config() -> Result<(), Box<dyn std::error::Error>> {
99 + let config_directory = get_config_path();
100 + std::fs::create_dir_all(&config_directory)?;
102 101
103 102 let config_template = include_str!("../../templates/config.lua");
104 - let config_path = config_dir.join("config.lua");
103 + let config_path = config_directory.join("config.lua");
105 104 std::fs::write(&config_path, config_template)?;
106 105
107 106 update_lsp_files()?;
108 107
109 108 println!("✓ Config created at {:?}", config_path);
110 - println!("✓ LSP definitions installed at {:?}/lib/oxwm.lua", config_dir);
109 + println!("✓ LSP definitions installed at {:?}/lib/oxwm.lua", config_directory);
111 110 println!(" Edit the file and reload with Mod+Shift+R");
112 111 println!(" No compilation needed - changes take effect immediately!");
113 112
114 113 Ok(())
115 114 }
116 115
117 -fn update_lsp_files() -> Result<()> {
118 - let config_dir = get_config_path();
116 +fn update_lsp_files() -> Result<(), Box<dyn std::error::Error>> {
117 + let config_directory = get_config_path();
119 118
120 - let lib_dir = config_dir.join("lib");
121 - std::fs::create_dir_all(&lib_dir)?;
119 + let library_directory = config_directory.join("lib");
120 + std::fs::create_dir_all(&library_directory)?;
122 121
123 122 let oxwm_lua_template = include_str!("../../templates/oxwm.lua");
124 - let oxwm_lua_path = lib_dir.join("oxwm.lua");
123 + let oxwm_lua_path = library_directory.join("oxwm.lua");
125 124 std::fs::write(&oxwm_lua_path, oxwm_lua_template)?;
126 125
127 126 let luarc_content = r#"{
@@ -130,7 +129,7 @@ fn update_lsp_files() -> Result<()> {
130 129 ]
131 130 }
132 131 "#;
133 - let luarc_path = config_dir.join(".luarc.json");
132 + let luarc_path = config_directory.join(".luarc.json");
134 133 std::fs::write(&luarc_path, luarc_content)?;
135 134
136 135 Ok(())
+17 −547 src/config/lua.rs Large diff collapsed, click to expand
@@ -1,11 +1,5 @@
1 -use crate::bar::{BlockCommand, BlockConfig};
2 1 use crate::errors::ConfigError;
3 -use crate::keyboard::handlers::{KeyBinding, KeyPress};
4 -use crate::keyboard::keysyms::{self, Keysym};
5 -use crate::keyboard::{Arg, KeyAction};
6 -use crate::{ColorScheme, LayoutSymbolOverride};
7 -use mlua::{Lua, Table, Value};
8 -use x11rb::protocol::xproto::KeyButMask;
2 +use mlua::Lua;
9 3
10 4 use super::lua_api;
11 5
@@ -52,522 +46,9 @@ pub fn parse_lua_config(
52 46 scheme_occupied: builder_data.scheme_occupied,
53 47 scheme_selected: builder_data.scheme_selected,
54 48 autostart: builder_data.autostart,
55 - });
56 -
57 - #[allow(unreachable_code)]
58 - {
59 - let config: Table = lua
60 - .load(input)
61 - .eval()
62 - .map_err(|e| ConfigError::LuaError(format!("{}", e)))?;
63 - let border_width: u32 = get_table_field(&config, "border_width")?;
64 - let border_focused: u32 = parse_color(&config, "border_focused")?;
65 - let border_unfocused: u32 = parse_color(&config, "border_unfocused")?;
66 - let font: String = get_table_field(&config, "font")?;
67 -
68 - let gaps_enabled: bool = get_table_field(&config, "gaps_enabled")?;
69 - let gap_inner_horizontal: u32 = get_table_field(&config, "gap_inner_horizontal")?;
70 - let gap_inner_vertical: u32 = get_table_field(&config, "gap_inner_vertical")?;
71 - let gap_outer_horizontal: u32 = get_table_field(&config, "gap_outer_horizontal")?;
72 - let gap_outer_vertical: u32 = get_table_field(&config, "gap_outer_vertical")?;
73 -
74 - let terminal: String = get_table_field(&config, "terminal")?;
75 - let modkey = parse_modkey(&config)?;
76 -
77 - let tags = parse_tags(&config)?;
78 - let layout_symbols = parse_layout_symbols(&config)?;
79 - let keybindings = parse_keybindings(&config, modkey)?;
80 - let status_blocks = parse_status_blocks(&config)?;
81 -
82 - let scheme_normal = parse_color_scheme(&config, "scheme_normal")?;
83 - let scheme_occupied = parse_color_scheme(&config, "scheme_occupied")?;
84 - let scheme_selected = parse_color_scheme(&config, "scheme_selected")?;
85 -
86 - let autostart = parse_autostart(&config)?;
87 -
88 - Ok(crate::Config {
89 - border_width,
90 - border_focused,
91 - border_unfocused,
92 - font,
93 - gaps_enabled,
94 - gap_inner_horizontal,
95 - gap_inner_vertical,
96 - gap_outer_horizontal,
97 - gap_outer_vertical,
98 - terminal,
99 - modkey,
100 - tags,
101 - layout_symbols,
102 - keybindings,
103 - status_blocks,
104 - scheme_normal,
105 - scheme_occupied,
106 - scheme_selected,
107 - autostart,
108 - })
109 - }
110 -}
111 -
112 -fn get_table_field<T>(table: &Table, field: &str) -> Result<T, ConfigError>
113 -where
114 - T: mlua::FromLua,
115 -{
116 - table
117 - .get::<T>(field)
118 - .map_err(|e| ConfigError::LuaError(format!("Failed to get field '{}': {}", field, e)))
119 -}
120 -
121 -fn parse_color(table: &Table, field: &str) -> Result<u32, ConfigError> {
122 - let value: Value = table.get(field).map_err(|e| {
123 - ConfigError::LuaError(format!("Failed to get color field '{}': {}", field, e))
124 - })?;
125 -
126 - match value {
127 - Value::String(s) => {
128 - let s = s.to_str().map_err(|e| {
129 - ConfigError::LuaError(format!("Invalid UTF-8 in color string: {}", e))
130 - })?;
131 - parse_color_string(&s)
132 - }
133 - Value::Integer(i) => Ok(i as u32),
134 - Value::Number(n) => Ok(n as u32),
135 - _ => Err(ConfigError::LuaError(format!(
136 - "Color field '{}' must be a string or number",
137 - field
138 - ))),
139 - }
140 -}
141 -
142 -fn parse_color_string(s: &str) -> Result<u32, ConfigError> {
143 - let s = s.trim();
144 - if s.starts_with('#') {
145 - u32::from_str_radix(&s[1..], 16)
146 - .map_err(|e| ConfigError::LuaError(format!("Invalid hex color '{}': {}", s, e)))
147 - } else if s.starts_with("0x") {
148 - u32::from_str_radix(&s[2..], 16)
149 - .map_err(|e| ConfigError::LuaError(format!("Invalid hex color '{}': {}", s, e)))
150 - } else {
151 - s.parse::<u32>()
152 - .map_err(|e| ConfigError::LuaError(format!("Invalid color '{}': {}", s, e)))
153 - }
154 -}
155 -
156 -fn parse_modkey(config: &Table) -> Result<KeyButMask, ConfigError> {
157 - let modkey_str: String = get_table_field(config, "modkey")?;
158 - parse_modkey_string(&modkey_str)
159 -}
160 -
161 -fn parse_modkey_string(s: &str) -> Result<KeyButMask, ConfigError> {
162 - match s {
163 - "Mod1" => Ok(KeyButMask::MOD1),
164 - "Mod2" => Ok(KeyButMask::MOD2),
165 - "Mod3" => Ok(KeyButMask::MOD3),
166 - "Mod4" => Ok(KeyButMask::MOD4),
167 - "Mod5" => Ok(KeyButMask::MOD5),
168 - "Shift" => Ok(KeyButMask::SHIFT),
169 - "Control" => Ok(KeyButMask::CONTROL),
170 - _ => Err(ConfigError::InvalidModkey(s.to_string())),
171 - }
172 -}
173 -
174 -fn parse_tags(config: &Table) -> Result<Vec<String>, ConfigError> {
175 - let tags_table: Table = get_table_field(config, "tags")?;
176 - let mut tags = Vec::new();
177 -
178 - for i in 1..=tags_table
179 - .len()
180 - .map_err(|e| ConfigError::LuaError(format!("Failed to get tags length: {}", e)))?
181 - {
182 - let tag: String = tags_table.get(i).map_err(|e| {
183 - ConfigError::LuaError(format!("Failed to get tag at index {}: {}", i, e))
184 - })?;
185 - tags.push(tag);
186 - }
187 -
188 - Ok(tags)
189 -}
190 -
191 -fn parse_layout_symbols(config: &Table) -> Result<Vec<LayoutSymbolOverride>, ConfigError> {
192 - let layout_symbols_result: Result<Table, _> = config.get("layout_symbols");
193 -
194 - match layout_symbols_result {
195 - Ok(layout_symbols_table) => {
196 - let mut layout_symbols = Vec::new();
197 -
198 - for i in 1..=layout_symbols_table.len().map_err(|e| {
199 - ConfigError::LuaError(format!("Failed to get layout_symbols length: {}", e))
200 - })? {
201 - let entry: Table = layout_symbols_table.get(i).map_err(|e| {
202 - ConfigError::LuaError(format!(
203 - "Failed to get layout_symbol at index {}: {}",
204 - i, e
205 - ))
206 - })?;
207 -
208 - let name: String = get_table_field(&entry, "name")?;
209 - let symbol: String = get_table_field(&entry, "symbol")?;
210 -
211 - layout_symbols.push(LayoutSymbolOverride { name, symbol });
212 - }
213 -
214 - Ok(layout_symbols)
215 - }
216 - Err(_) => Ok(Vec::new()),
217 - }
218 -}
219 -
220 -fn parse_keybindings(config: &Table, modkey: KeyButMask) -> Result<Vec<KeyBinding>, ConfigError> {
221 - let keybindings_table: Table = get_table_field(config, "keybindings")?;
222 - let mut keybindings = Vec::new();
223 -
224 - for i in 1..=keybindings_table
225 - .len()
226 - .map_err(|e| ConfigError::LuaError(format!("Failed to get keybindings length: {}", e)))?
227 - {
228 - let kb_table: Table = keybindings_table.get(i).map_err(|e| {
229 - ConfigError::LuaError(format!("Failed to get keybinding at index {}: {}", i, e))
230 - })?;
231 -
232 - let keys = parse_keypress_list(&kb_table, modkey)?;
233 - let action = parse_key_action(&kb_table)?;
234 - let arg = parse_arg(&kb_table)?;
235 -
236 - keybindings.push(KeyBinding::new(keys, action, arg));
237 - }
238 -
239 - Ok(keybindings)
240 -}
241 -
242 -fn parse_keypress_list(kb_table: &Table, modkey: KeyButMask) -> Result<Vec<KeyPress>, ConfigError> {
243 - let keys_result: Result<Table, _> = kb_table.get("keys");
244 -
245 - if let Ok(keys_table) = keys_result {
246 - let mut keys = Vec::new();
247 - for i in 1..=keys_table
248 - .len()
249 - .map_err(|e| ConfigError::LuaError(format!("Failed to get keys length: {}", e)))?
250 - {
251 - let key_entry: Table = keys_table.get(i).map_err(|e| {
252 - ConfigError::LuaError(format!("Failed to get key at index {}: {}", i, e))
253 - })?;
254 -
255 - let modifiers = parse_modifiers(&key_entry, "modifiers", modkey)?;
256 - let keysym = parse_keysym(&key_entry, "key")?;
257 -
258 - keys.push(KeyPress { modifiers, keysym });
259 - }
260 - Ok(keys)
261 - } else {
262 - let modifiers = parse_modifiers(kb_table, "modifiers", modkey)?;
263 - let keysym = parse_keysym(kb_table, "key")?;
264 -
265 - Ok(vec![KeyPress { modifiers, keysym }])
266 - }
267 -}
268 -
269 -fn parse_modifiers(
270 - table: &Table,
271 - field: &str,
272 - modkey: KeyButMask,
273 -) -> Result<Vec<KeyButMask>, ConfigError> {
274 - let mods_table: Table = get_table_field(table, field)?;
275 - let mut modifiers = Vec::new();
276 -
277 - for i in 1..=mods_table
278 - .len()
279 - .map_err(|e| ConfigError::LuaError(format!("Failed to get modifiers length: {}", e)))?
280 - {
281 - let mod_str: String = mods_table.get(i).map_err(|e| {
282 - ConfigError::LuaError(format!("Failed to get modifier at index {}: {}", i, e))
283 - })?;
284 -
285 - let modifier = if mod_str == "Mod" {
286 - modkey
287 - } else {
288 - parse_modkey_string(&mod_str)?
289 - };
290 -
291 - modifiers.push(modifier);
292 - }
293 -
294 - Ok(modifiers)
295 -}
296 -
297 -fn parse_keysym(table: &Table, field: &str) -> Result<Keysym, ConfigError> {
298 - let key_str: String = get_table_field(table, field)?;
299 - string_to_keysym(&key_str)
300 -}
301 -
302 -fn string_to_keysym(s: &str) -> Result<Keysym, ConfigError> {
303 - let keysym = match s {
304 - "Return" => keysyms::XK_RETURN,
305 - "Q" => keysyms::XK_Q,
306 - "Escape" => keysyms::XK_ESCAPE,
307 - "Space" => keysyms::XK_SPACE,
308 - "Tab" => keysyms::XK_TAB,
309 - "Backspace" => keysyms::XK_BACKSPACE,
310 - "Delete" => keysyms::XK_DELETE,
311 - "F1" => keysyms::XK_F1,
312 - "F2" => keysyms::XK_F2,
313 - "F3" => keysyms::XK_F3,
314 - "F4" => keysyms::XK_F4,
315 - "F5" => keysyms::XK_F5,
316 - "F6" => keysyms::XK_F6,
317 - "F7" => keysyms::XK_F7,
318 - "F8" => keysyms::XK_F8,
319 - "F9" => keysyms::XK_F9,
320 - "F10" => keysyms::XK_F10,
321 - "F11" => keysyms::XK_F11,
322 - "F12" => keysyms::XK_F12,
323 - "A" => keysyms::XK_A,
324 - "B" => keysyms::XK_B,
325 - "C" => keysyms::XK_C,
326 - "D" => keysyms::XK_D,
327 - "E" => keysyms::XK_E,
328 - "F" => keysyms::XK_F,
329 - "G" => keysyms::XK_G,
330 - "H" => keysyms::XK_H,
331 - "I" => keysyms::XK_I,
332 - "J" => keysyms::XK_J,
333 - "K" => keysyms::XK_K,
334 - "L" => keysyms::XK_L,
335 - "M" => keysyms::XK_M,
336 - "N" => keysyms::XK_N,
337 - "O" => keysyms::XK_O,
338 - "P" => keysyms::XK_P,
339 - "R" => keysyms::XK_R,
340 - "S" => keysyms::XK_S,
341 - "T" => keysyms::XK_T,
342 - "U" => keysyms::XK_U,
343 - "V" => keysyms::XK_V,
344 - "W" => keysyms::XK_W,
345 - "X" => keysyms::XK_X,
346 - "Y" => keysyms::XK_Y,
347 - "Z" => keysyms::XK_Z,
348 - "0" => keysyms::XK_0,
349 - "1" => keysyms::XK_1,
350 - "2" => keysyms::XK_2,
351 - "3" => keysyms::XK_3,
352 - "4" => keysyms::XK_4,
353 - "5" => keysyms::XK_5,
354 - "6" => keysyms::XK_6,
355 - "7" => keysyms::XK_7,
356 - "8" => keysyms::XK_8,
357 - "9" => keysyms::XK_9,
358 - "Left" => keysyms::XK_LEFT,
359 - "Right" => keysyms::XK_RIGHT,
360 - "Up" => keysyms::XK_UP,
361 - "Down" => keysyms::XK_DOWN,
362 - "Home" => keysyms::XK_HOME,
363 - "End" => keysyms::XK_END,
364 - "PageUp" => keysyms::XK_PAGE_UP,
365 - "PageDown" => keysyms::XK_PAGE_DOWN,
366 - "Insert" => keysyms::XK_INSERT,
367 - "Minus" => keysyms::XK_MINUS,
368 - "Equal" => keysyms::XK_EQUAL,
369 - "BracketLeft" => keysyms::XK_LEFT_BRACKET,
370 - "BracketRight" => keysyms::XK_RIGHT_BRACKET,
371 - "Semicolon" => keysyms::XK_SEMICOLON,
372 - "Apostrophe" => keysyms::XK_APOSTROPHE,
373 - "Grave" => keysyms::XK_GRAVE,
374 - "Backslash" => keysyms::XK_BACKSLASH,
375 - "Comma" => keysyms::XK_COMMA,
376 - "Period" => keysyms::XK_PERIOD,
377 - "Slash" => keysyms::XK_SLASH,
378 - "AudioRaiseVolume" => keysyms::XF86_AUDIO_RAISE_VOLUME,
379 - "AudioLowerVolume" => keysyms::XF86_AUDIO_LOWER_VOLUME,
380 - "AudioMute" => keysyms::XF86_AUDIO_MUTE,
381 - "MonBrightnessUp" => keysyms::XF86_MON_BRIGHTNESS_UP,
382 - "MonBrightnessDown" => keysyms::XF86_MON_BRIGHTNESS_DOWN,
383 - _ => return Err(ConfigError::UnknownKey(s.to_string())),
384 - };
385 -
386 - Ok(keysym)
387 -}
388 -
389 -fn parse_key_action(kb_table: &Table) -> Result<KeyAction, ConfigError> {
390 - let action_str: String = get_table_field(kb_table, "action")?;
391 - string_to_key_action(&action_str)
392 -}
393 -
394 -fn string_to_key_action(s: &str) -> Result<KeyAction, ConfigError> {
395 - let action = match s {
396 - "Spawn" => KeyAction::Spawn,
397 - "SpawnTerminal" => KeyAction::SpawnTerminal,
398 - "KillClient" => KeyAction::KillClient,
399 - "FocusStack" => KeyAction::FocusStack,
400 - "FocusDirection" => KeyAction::FocusDirection,
401 - "SwapDirection" => KeyAction::SwapDirection,
402 - "Quit" => KeyAction::Quit,
403 - "Restart" => KeyAction::Restart,
404 - "Recompile" => KeyAction::Recompile,
405 - "ViewTag" => KeyAction::ViewTag,
406 - "ToggleGaps" => KeyAction::ToggleGaps,
407 - "ToggleFullScreen" => KeyAction::ToggleFullScreen,
408 - "ToggleFloating" => KeyAction::ToggleFloating,
409 - "ChangeLayout" => KeyAction::ChangeLayout,
410 - "CycleLayout" => KeyAction::CycleLayout,
411 - "MoveToTag" => KeyAction::MoveToTag,
412 - "FocusMonitor" => KeyAction::FocusMonitor,
413 - "SmartMoveWin" => KeyAction::SmartMoveWin,
414 - "ExchangeClient" => KeyAction::ExchangeClient,
415 - "ShowKeybindOverlay" => KeyAction::ShowKeybindOverlay,
416 - "None" => KeyAction::None,
417 - _ => return Err(ConfigError::UnknownAction(s.to_string())),
418 - };
419 -
420 - Ok(action)
421 -}
422 -
423 -fn parse_arg(kb_table: &Table) -> Result<Arg, ConfigError> {
424 - let arg_result: Result<Value, _> = kb_table.get("arg");
425 -
426 - match arg_result {
427 - Ok(Value::Nil) | Err(_) => Ok(Arg::None),
428 - Ok(Value::String(s)) => {
429 - let s = s
430 - .to_str()
431 - .map_err(|e| ConfigError::LuaError(format!("Invalid UTF-8 in arg: {}", e)))?;
432 - Ok(Arg::Str(s.to_string()))
433 - }
434 - Ok(Value::Integer(i)) => Ok(Arg::Int(i as i32)),
435 - Ok(Value::Number(n)) => Ok(Arg::Int(n as i32)),
436 - Ok(Value::Table(t)) => {
437 - let mut arr = Vec::new();
438 - for i in 1..=t.len().map_err(|e| {
439 - ConfigError::LuaError(format!("Failed to get arg array length: {}", e))
440 - })? {
441 - let item: String = t.get(i).map_err(|e| {
442 - ConfigError::LuaError(format!(
443 - "Failed to get arg array item at index {}: {}",
444 - i, e
445 - ))
446 - })?;
447 - arr.push(item);
448 - }
449 - Ok(Arg::Array(arr))
450 - }
451 - Ok(_) => Err(ConfigError::LuaError(
452 - "Arg must be nil, string, number, or array".to_string(),
453 - )),
454 - }
455 -}
456 -
457 -fn parse_status_blocks(config: &Table) -> Result<Vec<BlockConfig>, ConfigError> {
458 - let blocks_table: Table = get_table_field(config, "status_blocks")?;
459 - let mut blocks = Vec::new();
460 -
461 - for i in 1..=blocks_table
462 - .len()
463 - .map_err(|e| ConfigError::LuaError(format!("Failed to get status_blocks length: {}", e)))?
464 - {
465 - let block_table: Table = blocks_table.get(i).map_err(|e| {
466 - ConfigError::LuaError(format!("Failed to get status_block at index {}: {}", i, e))
467 - })?;
468 -
469 - let format: String = get_table_field(&block_table, "format")?;
470 - let command_str: String = get_table_field(&block_table, "command")?;
471 -
472 - let interval_secs: u64 = {
473 - let value: Value = block_table.get("interval_secs").map_err(|e| {
474 - ConfigError::LuaError(format!("Failed to get interval_secs: {}", e))
475 - })?;
476 - match value {
477 - Value::Integer(i) => i as u64,
478 - Value::Number(n) => n as u64,
479 - _ => {
480 - return Err(ConfigError::LuaError(
481 - "interval_secs must be a number".to_string(),
482 - ));
483 - }
484 - }
485 - };
486 -
487 - let color: u32 = parse_color(&block_table, "color")?;
488 - let underline: bool = get_table_field(&block_table, "underline")?;
489 -
490 - let command = match command_str.as_str() {
491 - "DateTime" => {
492 - let fmt: String = get_table_field(&block_table, "command_arg")?;
493 - BlockCommand::DateTime(fmt)
494 - }
495 - "Shell" => {
496 - let cmd: String = get_table_field(&block_table, "command_arg")?;
497 - BlockCommand::Shell(cmd)
498 - }
499 - "Ram" => BlockCommand::Ram,
500 - "Static" => {
501 - let text_result: Result<String, _> = block_table.get("command_arg");
502 - let text = text_result.unwrap_or_default();
503 - BlockCommand::Static(text)
504 - }
505 - "Battery" => {
506 - let formats_table: Table = get_table_field(&block_table, "battery_formats")?;
507 - let format_charging: String = get_table_field(&formats_table, "charging")?;
508 - let format_discharging: String = get_table_field(&formats_table, "discharging")?;
509 - let format_full: String = get_table_field(&formats_table, "full")?;
510 -
511 - BlockCommand::Battery {
512 - format_charging,
513 - format_discharging,
514 - format_full,
515 - }
516 - }
517 - _ => return Err(ConfigError::UnknownBlockCommand(command_str)),
518 - };
519 -
520 - blocks.push(BlockConfig {
521 - format,
522 - command,
523 - interval_secs,
524 - color,
525 - underline,
526 - });
527 - }
528 -
529 - Ok(blocks)
530 -}
531 -
532 -fn parse_color_scheme(config: &Table, field: &str) -> Result<ColorScheme, ConfigError> {
533 - let scheme_table: Table = get_table_field(config, field)?;
534 -
535 - let foreground = parse_color(&scheme_table, "foreground")?;
536 - let background = parse_color(&scheme_table, "background")?;
537 - let underline = parse_color(&scheme_table, "underline")?;
538 -
539 - Ok(ColorScheme {
540 - foreground,
541 - background,
542 - underline,
543 49 })
544 50 }
545 51
546 -fn parse_autostart(config: &Table) -> Result<Vec<String>, ConfigError> {
547 - let autostart_result: Result<Table, _> = config.get("autostart");
548 -
549 - match autostart_result {
550 - Ok(autostart_table) => {
551 - let mut autostart = Vec::new();
552 -
553 - for i in 1..=autostart_table.len().map_err(|e| {
554 - ConfigError::LuaError(format!("Failed to get autostart length: {}", e))
555 - })? {
556 - let cmd: String = autostart_table.get(i).map_err(|e| {
557 - ConfigError::LuaError(format!(
558 - "Failed to get autostart command at index {}: {}",
559 - i, e
560 - ))
561 - })?;
562 - autostart.push(cmd);
563 - }
564 -
565 - Ok(autostart)
566 - }
567 - Err(_) => Ok(Vec::new()),
568 - }
569 -}
570 -
571 52 #[cfg(test)]
572 53 mod tests {
573 54 use super::*;
@@ -575,38 +56,27 @@ mod tests {
575 56 #[test]
576 57 fn test_parse_minimal_lua_config() {
577 58 let config_str = r#"
578 -return {
579 - border_width = 2,
580 - border_focused = 0x6dade3,
581 - border_unfocused = 0xbbbbbb,
582 - font = "monospace:style=Bold:size=10",
59 +oxwm.border.set_width(2)
60 +oxwm.border.set_focused_color(0x6dade3)
61 +oxwm.border.set_unfocused_color(0xbbbbbb)
62 +oxwm.bar.set_font("monospace:style=Bold:size=10")
583 63
584 - gaps_enabled = true,
585 - gap_inner_horizontal = 5,
586 - gap_inner_vertical = 5,
587 - gap_outer_horizontal = 5,
588 - gap_outer_vertical = 5,
64 +oxwm.gaps.set_enabled(true)
65 +oxwm.gaps.set_inner(5, 5)
66 +oxwm.gaps.set_outer(5, 5)
589 67
590 - modkey = "Mod4",
591 - terminal = "st",
68 +oxwm.set_modkey("Mod4")
69 +oxwm.set_terminal("st")
70 +oxwm.set_tags({"1", "2", "3"})
592 71
593 - tags = {"1", "2", "3"},
72 +oxwm.key.bind({"Mod4"}, "Return", oxwm.spawn("st"))
73 +oxwm.key.bind({"Mod4"}, "Q", oxwm.client.kill())
594 74
595 - keybindings = {
596 - {modifiers = {"Mod4"}, key = "Return", action = "Spawn", arg = "st"},
597 - {modifiers = {"Mod4"}, key = "Q", action = "KillClient"},
598 - },
75 +oxwm.bar.add_block("{}", "DateTime", "%H:%M", 1, 0xffffff, true)
599 76
600 - status_blocks = {
601 - {format = "{}", command = "DateTime", command_arg = "%H:%M", interval_secs = 1, color = 0xffffff, underline = true},
602 - },
603 -
604 - scheme_normal = {foreground = 0xffffff, background = 0x000000, underline = 0x444444},
605 - scheme_occupied = {foreground = 0xffffff, background = 0x000000, underline = 0x444444},
606 - scheme_selected = {foreground = 0xffffff, background = 0x000000, underline = 0x444444},
607 -
608 - autostart = {},
609 -}
77 +oxwm.bar.set_scheme_normal(0xffffff, 0x000000, 0x444444)
78 +oxwm.bar.set_scheme_occupied(0xffffff, 0x000000, 0x444444)
79 +oxwm.bar.set_scheme_selected(0xffffff, 0x000000, 0x444444)
610 80 "#;
611 81
612 82 let config = parse_lua_config(config_str, None).expect("Failed to parse config");
+382 −379 src/window_manager.rs Large diff collapsed, click to expand
@@ -16,6 +16,20 @@ use x11rb::protocol::Event;
16 16 use x11rb::protocol::xproto::*;
17 17 use x11rb::rust_connection::RustConnection;
18 18
19 +const DEFAULT_FLOAT_WIDTH_RATIO: f32 = 0.5;
20 +const DEFAULT_FLOAT_HEIGHT_RATIO: f32 = 0.5;
21 +const SMART_MOVE_STEP_RATIO_VERTICAL: i32 = 4;
22 +const SMART_MOVE_STEP_RATIO_HORIZONTAL: i32 = 6;
23 +
24 +#[derive(Debug, Clone, Copy)]
25 +pub struct CachedGeometry {
26 + pub x_position: i16,
27 + pub y_position: i16,
28 + pub width: u16,
29 + pub height: u16,
30 + pub border_width: u16,
31 +}
32 +
19 33 pub type TagMask = u32;
20 34 pub fn tag_mask(tag: usize) -> TagMask {
21 35 1 << tag
@@ -87,6 +101,7 @@ pub struct WindowManager {
87 101 layout: LayoutBox,
88 102 window_tags: std::collections::HashMap<Window, TagMask>,
89 103 window_monitor: std::collections::HashMap<Window, usize>,
104 + window_geometry_cache: std::collections::HashMap<Window, CachedGeometry>,
90 105 gaps_enabled: bool,
91 106 floating_windows: HashSet<Window>,
92 107 fullscreen_windows: HashSet<Window>,
@@ -213,6 +228,7 @@ impl WindowManager {
213 228 layout: Box::new(TilingLayout),
214 229 window_tags: std::collections::HashMap::new(),
215 230 window_monitor: std::collections::HashMap::new(),
231 + window_geometry_cache: std::collections::HashMap::new(),
216 232 gaps_enabled,
217 233 floating_windows: HashSet::new(),
218 234 fullscreen_windows: HashSet::new(),
@@ -239,45 +255,6 @@ impl WindowManager {
239 255 Ok(window_manager)
240 256 }
241 257
242 - /**
243 - *
244 - * This function is deprecated for now, but will potentially be used in the future.
245 - *
246 - */
247 - fn _get_saved_selected_tags(
248 - connection: &RustConnection,
249 - root: Window,
250 - tag_count: usize,
251 - ) -> WmResult<TagMask> {
252 - let net_current_desktop = connection
253 - .intern_atom(false, b"_NET_CURRENT_DESKTOP")?
254 - .reply()?
255 - .atom;
256 -
257 - match connection
258 - .get_property(false, root, net_current_desktop, AtomEnum::CARDINAL, 0, 1)?
259 - .reply()
260 - {
261 - Ok(prop) if prop.value.len() >= 4 => {
262 - let desktop = u32::from_ne_bytes([
263 - prop.value[0],
264 - prop.value[1],
265 - prop.value[2],
266 - prop.value[3],
267 - ]);
268 - if desktop < tag_count as u32 {
269 - let mask = tag_mask(desktop as usize);
270 - return Ok(mask);
271 - }
272 - }
273 - Ok(_) => {}
274 - Err(e) => {
275 - eprintln!("No _NET_CURRENT_DESKTOP property ({})", e);
276 - }
277 - }
278 - Ok(tag_mask(0))
279 - }
280 -
281 258 pub fn show_migration_overlay(&mut self) {
282 259 let message = "Your config.lua uses legacy syntax or has errors.\n\n\
283 260 You are now running with default configuration.\n\n\
@@ -466,22 +443,31 @@ impl WindowManager {
466 443 keyboard::setup_keybinds(&self.connection, self.root, &self.config.keybindings)?;
467 444 self.update_bar()?;
468 445
446 + let mut last_bar_update = std::time::Instant::now();
447 + const BAR_UPDATE_INTERVAL_MS: u64 = 100;
448 +
469 449 loop {
470 - while let Some(event) = self.connection.poll_for_event()? {
471 - if let Some(should_restart) = self.handle_event(event)? {
472 - return Ok(should_restart);
450 + match self.connection.poll_for_event_with_sequence()? {
451 + Some((event, _sequence)) => {
452 + if let Some(should_restart) = self.handle_event(event)? {
453 + return Ok(should_restart);
454 + }
473 455 }
474 - }
475 -
476 - if let Some(bar) = self.bars.get_mut(self.selected_monitor) {
477 - bar.update_blocks();
478 - }
456 + None => {
457 + if last_bar_update.elapsed().as_millis() >= BAR_UPDATE_INTERVAL_MS as u128 {
458 + if let Some(bar) = self.bars.get_mut(self.selected_monitor) {
459 + bar.update_blocks();
460 + }
461 + if self.bars.iter().any(|bar| bar.needs_redraw()) {
462 + self.update_bar()?;
463 + }
464 + last_bar_update = std::time::Instant::now();
465 + }
479 466
480 - if self.bars.iter().any(|bar| bar.needs_redraw()) {
481 - self.update_bar()?;
467 + self.connection.flush()?;
468 + std::thread::sleep(std::time::Duration::from_millis(16));
469 + }
482 470 }
483 -
484 - std::thread::sleep(std::time::Duration::from_millis(100));
485 471 }
486 472 }
487 473
@@ -502,7 +488,9 @@ impl WindowManager {
502 488
503 489 self.window_tags.insert(focused, selected_tags);
504 490 self.window_monitor.insert(focused, self.selected_monitor);
505 - let _ = self.save_client_tag(focused, selected_tags);
491 + if let Err(error) = self.save_client_tag(focused, selected_tags) {
492 + eprintln!("Failed to save client tag: {:?}", error);
493 + }
506 494
507 495 self.apply_layout()?;
508 496 } else {
@@ -534,52 +522,40 @@ impl WindowManager {
534 522 Ok(())
535 523 }
536 524
537 - fn smart_move_window(&mut self, direction: i32) -> WmResult<()> {
538 - let focused = match self
539 - .monitors
540 - .get(self.selected_monitor)
541 - .and_then(|m| m.focused_window)
542 - {
543 - Some(win) => win,
544 - None => return Ok(()),
545 - };
546 -
547 - if !self.floating_windows.contains(&focused) {
548 - let float_width = (self.screen.width_in_pixels / 2) as u32;
549 - let float_height = (self.screen.height_in_pixels / 2) as u32;
550 - let border_width = self.config.border_width;
551 - let center_width = ((self.screen.width_in_pixels - float_width as u16) / 2) as i32;
552 - let center_height = ((self.screen.height_in_pixels - float_height as u16) / 2) as i32;
553 -
554 - self.connection.configure_window(
555 - focused,
556 - &ConfigureWindowAux::new()
557 - .x(center_width)
558 - .y(center_height)
559 - .width(float_width)
560 - .height(float_height)
561 - .border_width(border_width)
562 - .stack_mode(StackMode::ABOVE),
563 - )?;
564 - self.floating_windows.insert(focused);
565 - }
566 -
567 - let current_geom = match self.connection.get_geometry(focused)?.reply() {
568 - Ok(geom) => geom,
569 - Err(_) => return Ok(()),
570 - };
571 -
572 - let c_x = current_geom.x as i32;
573 - let c_y = current_geom.y as i32;
574 - let c_width = current_geom.width as i32;
575 - let c_height = current_geom.height as i32;
525 + fn collect_visible_floating_geometries(&mut self) -> Vec<(Window, CachedGeometry)> {
526 + let focused_window = self.monitors.get(self.selected_monitor)
527 + .and_then(|monitor| monitor.focused_window)
528 + .unwrap_or(0);
529 + let selected_monitor_index = self.selected_monitor;
530 +
531 + let candidate_windows: Vec<Window> = self.windows.iter()
532 + .filter(|&&window| {
533 + window != focused_window
534 + && self.floating_windows.contains(&window)
535 + && self.is_window_visible(window)
536 + && self.window_monitor.get(&window).copied().unwrap_or(0) == selected_monitor_index
537 + })
538 + .copied()
539 + .collect();
576 540
577 - let monitor = match self.monitors.get(self.selected_monitor) {
578 - Some(m) => m,
579 - None => return Ok(()),
580 - };
541 + candidate_windows.into_iter()
542 + .filter_map(|window| {
543 + self.get_or_query_geometry(window).ok().map(|geometry| (window, geometry))
544 + })
545 + .collect()
546 + }
581 547
582 - let (gap_ih, gap_iv, gap_oh, gap_ov) = if self.gaps_enabled {
548 + fn calculate_smart_move_position(
549 + &self,
550 + current_x: i32,
551 + current_y: i32,
552 + current_width: i32,
553 + current_height: i32,
554 + direction: i32,
555 + monitor: &Monitor,
556 + other_geometries: &[(Window, CachedGeometry)],
557 + ) -> (i32, i32) {
558 + let (gap_inner_horizontal, gap_inner_vertical, gap_outer_horizontal, gap_outer_vertical) = if self.gaps_enabled {
583 559 (
584 560 self.config.gap_inner_horizontal as i32,
585 561 self.config.gap_inner_vertical as i32,
@@ -590,204 +566,186 @@ impl WindowManager {
590 566 (0, 0, 0, 0)
591 567 };
592 568
593 - let (new_x, new_y) = match direction {
569 + match direction {
594 570 0 => {
595 - // UP
596 - let mut target = i32::MIN;
597 - let top = c_y;
598 - let mut ny = c_y - (monitor.height as i32 / 4);
571 + let mut target_position = i32::MIN;
572 + let current_top = current_y;
573 + let mut new_y_position = current_y - (monitor.height as i32 / SMART_MOVE_STEP_RATIO_VERTICAL);
599 574
600 - for &other_window in &self.windows {
601 - if other_window == focused {
602 - continue;
603 - }
604 - if !self.floating_windows.contains(&other_window) {
605 - continue;
606 - }
607 - if !self.is_window_visible(other_window) {
608 - continue;
609 - }
610 - let other_mon = self.window_monitor.get(&other_window).copied().unwrap_or(0);
611 - if other_mon != self.selected_monitor {
612 - continue;
613 - }
575 + for (_other_window, other_geometry) in other_geometries {
576 + let other_x = other_geometry.x_position as i32;
577 + let other_y = other_geometry.y_position as i32;
578 + let other_width = other_geometry.width as i32;
579 + let other_height = other_geometry.height as i32;
614 580
615 - let other_geom = match self.connection.get_geometry(other_window)?.reply() {
616 - Ok(geom) => geom,
617 - Err(_) => continue,
618 - };
619 -
620 - let o_x = other_geom.x as i32;
621 - let o_y = other_geom.y as i32;
622 - let o_width = other_geom.width as i32;
623 - let o_height = other_geom.height as i32;
624 -
625 - if c_x + c_width < o_x || c_x > o_x + o_width {
581 + if current_x + current_width < other_x || current_x > other_x + other_width {
626 582 continue;
627 583 }
628 584
629 - let bottom = o_y + o_height + gap_iv;
630 - if top > bottom && ny < bottom {
631 - target = target.max(bottom);
585 + let other_bottom = other_y + other_height + gap_inner_vertical;
586 + if current_top > other_bottom && new_y_position < other_bottom {
587 + target_position = target_position.max(other_bottom);
632 588 }
633 589 }
634 590
635 - if target != i32::MIN {
636 - ny = target;
591 + if target_position != i32::MIN {
592 + new_y_position = target_position;
637 593 }
638 - ny = ny.max(monitor.y as i32 + gap_ov);
639 - (c_x, ny)
594 + new_y_position = new_y_position.max(monitor.y as i32 + gap_outer_vertical);
595 + (current_x, new_y_position)
640 596 }
641 597 1 => {
642 - // DOWN
643 - let mut target = i32::MAX;
644 - let bottom = c_y + c_height;
645 - let mut ny = c_y + (monitor.height as i32 / 4);
646 -
647 - for &other_window in &self.windows {
648 - if other_window == focused {
649 - continue;
650 - }
651 - if !self.floating_windows.contains(&other_window) {
652 - continue;
653 - }
654 - if !self.is_window_visible(other_window) {
655 - continue;
656 - }
657 - let other_mon = self.window_monitor.get(&other_window).copied().unwrap_or(0);
658 - if other_mon != self.selected_monitor {
659 - continue;
660 - }
661 -
662 - let other_geom = match self.connection.get_geometry(other_window)?.reply() {
663 - Ok(geom) => geom,
664 - Err(_) => continue,
665 - };
598 + let mut target_position = i32::MAX;
599 + let current_bottom = current_y + current_height;
600 + let mut new_y_position = current_y + (monitor.height as i32 / SMART_MOVE_STEP_RATIO_VERTICAL);
666 601
667 - let o_x = other_geom.x as i32;
668 - let o_y = other_geom.y as i32;
669 - let o_width = other_geom.width as i32;
602 + for (_other_window, other_geometry) in other_geometries {
603 + let other_x = other_geometry.x_position as i32;
604 + let other_y = other_geometry.y_position as i32;
605 + let other_width = other_geometry.width as i32;
670 606
671 - if c_x + c_width < o_x || c_x > o_x + o_width {
607 + if current_x + current_width < other_x || current_x > other_x + other_width {
672 608 continue;
673 609 }
674 610
675 - let top = o_y - gap_iv;
676 - if bottom < top && (ny + c_height) > top {
677 - target = target.min(top - c_height);
611 + let other_top = other_y - gap_inner_vertical;
612 + if current_bottom < other_top && (new_y_position + current_height) > other_top {
613 + target_position = target_position.min(other_top - current_height);
678 614 }
679 615 }
680 616
681 - if target != i32::MAX {
682 - ny = target;
617 + if target_position != i32::MAX {
618 + new_y_position = target_position;
683 619 }
684 - ny = ny.min(monitor.y as i32 + monitor.height as i32 - c_height - gap_ov);
685 - (c_x, ny)
620 + new_y_position = new_y_position.min(monitor.y as i32 + monitor.height as i32 - current_height - gap_outer_vertical);
621 + (current_x, new_y_position)
686 622 }
687 623 2 => {
688 - // LEFT
689 - let mut target = i32::MIN;
690 - let left = c_x;
691 - let mut nx = c_x - (monitor.width as i32 / 6);
624 + let mut target_position = i32::MIN;
625 + let current_left = current_x;
626 + let mut new_x_position = current_x - (monitor.width as i32 / SMART_MOVE_STEP_RATIO_HORIZONTAL);
692 627
693 - for &other_window in &self.windows {
694 - if other_window == focused {
695 - continue;
696 - }
697 - if !self.floating_windows.contains(&other_window) {
698 - continue;
699 - }
700 - if !self.is_window_visible(other_window) {
701 - continue;
702 - }
703 - let other_mon = self.window_monitor.get(&other_window).copied().unwrap_or(0);
704 - if other_mon != self.selected_monitor {
705 - continue;
706 - }
707 -
708 - let other_geom = match self.connection.get_geometry(other_window)?.reply() {
709 - Ok(geom) => geom,
710 - Err(_) => continue,
711 - };
712 -
713 - let o_x = other_geom.x as i32;
714 - let o_y = other_geom.y as i32;
715 - let o_width = other_geom.width as i32;
716 - let o_height = other_geom.height as i32;
628 + for (_other_window, other_geometry) in other_geometries {
629 + let other_x = other_geometry.x_position as i32;
630 + let other_y = other_geometry.y_position as i32;
631 + let other_width = other_geometry.width as i32;
632 + let other_height = other_geometry.height as i32;
717 633
718 - if c_y + c_height < o_y || c_y > o_y + o_height {
634 + if current_y + current_height < other_y || current_y > other_y + other_height {
719 635 continue;
720 636 }
721 637
722 - let right = o_x + o_width + gap_ih;
723 - if left > right && nx < right {
724 - target = target.max(right);
638 + let other_right = other_x + other_width + gap_inner_horizontal;
639 + if current_left > other_right && new_x_position < other_right {
640 + target_position = target_position.max(other_right);
725 641 }
726 642 }
727 643
728 - if target != i32::MIN {
729 - nx = target;
644 + if target_position != i32::MIN {
645 + new_x_position = target_position;
730 646 }
731 - nx = nx.max(monitor.x as i32 + gap_oh);
732 - (nx, c_y)
647 + new_x_position = new_x_position.max(monitor.x as i32 + gap_outer_horizontal);
648 + (new_x_position, current_y)
733 649 }
734 650 3 => {
735 - // RIGHT
736 - let mut target = i32::MAX;
737 - let right = c_x + c_width;
738 - let mut nx = c_x + (monitor.width as i32 / 6);
739 -
740 - for &other_window in &self.windows {
741 - if other_window == focused {
742 - continue;
743 - }
744 - if !self.floating_windows.contains(&other_window) {
745 - continue;
746 - }
747 - if !self.is_window_visible(other_window) {
748 - continue;
749 - }
750 - let other_mon = self.window_monitor.get(&other_window).copied().unwrap_or(0);
751 - if other_mon != self.selected_monitor {
752 - continue;
753 - }
754 -
755 - let other_geom = match self.connection.get_geometry(other_window)?.reply() {
756 - Ok(geom) => geom,
757 - Err(_) => continue,
758 - };
651 + let mut target_position = i32::MAX;
652 + let current_right = current_x + current_width;
653 + let mut new_x_position = current_x + (monitor.width as i32 / SMART_MOVE_STEP_RATIO_HORIZONTAL);
759 654
760 - let o_x = other_geom.x as i32;
761 - let o_y = other_geom.y as i32;
762 - let o_height = other_geom.height as i32;
655 + for (_other_window, other_geometry) in other_geometries {
656 + let other_x = other_geometry.x_position as i32;
657 + let other_y = other_geometry.y_position as i32;
658 + let other_height = other_geometry.height as i32;
763 659
764 - if c_y + c_height < o_y || c_y > o_y + o_height {
660 + if current_y + current_height < other_y || current_y > other_y + other_height {
765 661 continue;
766 662 }
767 663
768 - let left = o_x - gap_ih;
769 - if right < left && (nx + c_width) > left {
770 - target = target.min(left - c_width);
664 + let other_left = other_x - gap_inner_horizontal;
665 + if current_right < other_left && (new_x_position + current_width) > other_left {
666 + target_position = target_position.min(other_left - current_width);
771 667 }
772 668 }
773 669
774 - if target != i32::MAX {
775 - nx = target;
670 + if target_position != i32::MAX {
671 + new_x_position = target_position;
776 672 }
777 - nx = nx.min(monitor.x as i32 + monitor.width as i32 - c_width - gap_oh);
778 - (nx, c_y)
673 + new_x_position = new_x_position.min(monitor.x as i32 + monitor.width as i32 - current_width - gap_outer_horizontal);
674 + (new_x_position, current_y)
779 675 }
780 - _ => return Ok(()),
676 + _ => (current_x, current_y),
677 + }
678 + }
679 +
680 + fn smart_move_window(&mut self, direction: i32) -> WmResult<()> {
681 + let focused = match self
682 + .monitors
683 + .get(self.selected_monitor)
684 + .and_then(|monitor| monitor.focused_window)
685 + {
686 + Some(window) => window,
687 + None => return Ok(()),
688 + };
689 +
690 + if !self.floating_windows.contains(&focused) {
691 + let float_width = (self.screen.width_in_pixels as f32 * DEFAULT_FLOAT_WIDTH_RATIO) as u32;
692 + let float_height = (self.screen.height_in_pixels as f32 * DEFAULT_FLOAT_HEIGHT_RATIO) as u32;
693 + let border_width = self.config.border_width;
694 + let center_x_position = ((self.screen.width_in_pixels - float_width as u16) / 2) as i32;
695 + let center_y_position = ((self.screen.height_in_pixels - float_height as u16) / 2) as i32;
696 +
697 + self.connection.configure_window(
698 + focused,
699 + &ConfigureWindowAux::new()
700 + .x(center_x_position)
701 + .y(center_y_position)
702 + .width(float_width)
703 + .height(float_height)
704 + .border_width(border_width)
705 + .stack_mode(StackMode::ABOVE),
706 + )?;
707 + self.floating_windows.insert(focused);
708 + }
709 +
710 + let current_geometry = self.get_or_query_geometry(focused)?;
711 + let current_x = current_geometry.x_position as i32;
712 + let current_y = current_geometry.y_position as i32;
713 + let current_width = current_geometry.width as i32;
714 + let current_height = current_geometry.height as i32;
715 +
716 + let other_geometries = self.collect_visible_floating_geometries();
717 +
718 + let monitor = match self.monitors.get(self.selected_monitor) {
719 + Some(monitor) => monitor,
720 + None => return Ok(()),
781 721 };
782 722
723 + let (new_x_position, new_y_position) = self.calculate_smart_move_position(
724 + current_x,
725 + current_y,
726 + current_width,
727 + current_height,
728 + direction,
729 + monitor,
730 + &other_geometries,
731 + );
732 +
783 733 self.connection.configure_window(
784 734 focused,
785 735 &ConfigureWindowAux::new()
786 - .x(new_x)
787 - .y(new_y)
736 + .x(new_x_position)
737 + .y(new_y_position)
788 738 .stack_mode(StackMode::ABOVE),
789 739 )?;
790 740
741 + self.update_geometry_cache(focused, CachedGeometry {
742 + x_position: new_x_position as i16,
743 + y_position: new_y_position as i16,
744 + width: current_width as u16,
745 + height: current_height as u16,
746 + border_width: current_geometry.border_width,
747 + });
748 +
791 749 self.connection.flush()?;
792 750 Ok(())
793 751 }
@@ -952,7 +910,9 @@ impl WindowManager {
952 910 KeyAction::SpawnTerminal => {
953 911 use std::process::Command;
954 912 let terminal = &self.config.terminal;
955 - let _ = Command::new(terminal).spawn();
913 + if let Err(error) = Command::new(terminal).spawn() {
914 + eprintln!("Failed to spawn terminal {}: {:?}", terminal, error);
915 + }
956 916 }
957 917 KeyAction::KillClient => {
958 918 if let Some(focused) = self
@@ -1224,7 +1184,9 @@ impl WindowManager {
1224 1184 let mask = tag_mask(tag_index);
1225 1185 self.window_tags.insert(focused, mask);
1226 1186
1227 - let _ = self.save_client_tag(focused, mask);
1187 + if let Err(error) = self.save_client_tag(focused, mask) {
1188 + eprintln!("Failed to save client tag: {:?}", error);
1189 + }
1228 1190
1229 1191 self.update_window_visibility()?;
1230 1192 self.apply_layout()?;
@@ -1265,43 +1227,30 @@ impl WindowManager {
1265 1227 Ok(())
1266 1228 }
1267 1229
1268 - pub fn focus_direction(&mut self, direction: i32) -> WmResult<()> {
1269 - let focused = match self
1270 - .monitors
1271 - .get(self.selected_monitor)
1272 - .and_then(|m| m.focused_window)
1273 - {
1274 - Some(win) => win,
1275 - None => return Ok(()),
1276 - };
1277 -
1278 - let visible = self.visible_windows();
1279 - if visible.len() < 2 {
1280 - return Ok(());
1230 + fn find_directional_window_candidate(&mut self, focused_window: Window, direction: i32) -> Option<Window> {
1231 + let visible_windows = self.visible_windows();
1232 + if visible_windows.len() < 2 {
1233 + return None;
1281 1234 }
1282 1235
1283 - let focused_geom = match self.connection.get_geometry(focused)?.reply() {
1284 - Ok(geom) => geom,
1285 - Err(_) => return Ok(()),
1286 - };
1287 -
1288 - let focused_center_x = focused_geom.x + (focused_geom.width as i16 / 2);
1289 - let focused_center_y = focused_geom.y + (focused_geom.height as i16 / 2);
1236 + let focused_geometry = self.get_or_query_geometry(focused_window).ok()?;
1237 + let focused_center_x = focused_geometry.x_position + (focused_geometry.width as i16 / 2);
1238 + let focused_center_y = focused_geometry.y_position + (focused_geometry.height as i16 / 2);
1290 1239
1291 1240 let mut candidates = Vec::new();
1292 1241
1293 - for &window in &visible {
1294 - if window == focused {
1242 + for &window in &visible_windows {
1243 + if window == focused_window {
1295 1244 continue;
1296 1245 }
1297 1246
1298 - let geom = match self.connection.get_geometry(window)?.reply() {
1299 - Ok(g) => g,
1247 + let geometry = match self.get_or_query_geometry(window) {
1248 + Ok(geometry) => geometry,
1300 1249 Err(_) => continue,
1301 1250 };
1302 1251
1303 - let center_x = geom.x + (geom.width as i16 / 2);
1304 - let center_y = geom.y + (geom.height as i16 / 2);
1252 + let center_x = geometry.x_position + (geometry.width as i16 / 2);
1253 + let center_y = geometry.y_position + (geometry.height as i16 / 2);
1305 1254
1306 1255 let is_valid_direction = match direction {
1307 1256 0 => center_y < focused_center_y,
@@ -1312,87 +1261,56 @@ impl WindowManager {
1312 1261 };
1313 1262
1314 1263 if is_valid_direction {
1315 - let dx = (center_x - focused_center_x) as i32;
1316 - let dy = (center_y - focused_center_y) as i32;
1317 - let distance = dx * dx + dy * dy;
1318 - candidates.push((window, distance));
1264 + let delta_x = (center_x - focused_center_x) as i32;
1265 + let delta_y = (center_y - focused_center_y) as i32;
1266 + let distance_squared = delta_x * delta_x + delta_y * delta_y;
1267 + candidates.push((window, distance_squared));
1319 1268 }
1320 1269 }
1321 1270
1322 - if let Some(&(closest_window, _)) = candidates.iter().min_by_key(|&(_, dist)| dist) {
1323 - self.set_focus(closest_window)?;
1324 - }
1325 -
1326 - Ok(())
1271 + candidates.iter().min_by_key(|&(_window, distance)| distance).map(|&(window, _distance)| window)
1327 1272 }
1328 1273
1329 - pub fn swap_direction(&mut self, direction: i32) -> WmResult<()> {
1330 - let focused = match self
1274 + pub fn focus_direction(&mut self, direction: i32) -> WmResult<()> {
1275 + let focused_window = match self
1331 1276 .monitors
1332 1277 .get(self.selected_monitor)
1333 - .and_then(|m| m.focused_window)
1278 + .and_then(|monitor| monitor.focused_window)
1334 1279 {
1335 - Some(win) => win,
1280 + Some(window) => window,
1336 1281 None => return Ok(()),
1337 1282 };
1338 1283
1339 - let visible = self.visible_windows();
1340 - if visible.len() < 2 {
1341 - return Ok(());
1284 + if let Some(target_window) = self.find_directional_window_candidate(focused_window, direction) {
1285 + self.set_focus(target_window)?;
1342 1286 }
1343 1287
1344 - let focused_geom = match self.connection.get_geometry(focused)?.reply() {
1345 - Ok(geom) => geom,
1346 - Err(_) => return Ok(()),
1347 - };
1348 -
1349 - let focused_center_x = focused_geom.x + (focused_geom.width as i16 / 2);
1350 - let focused_center_y = focused_geom.y + (focused_geom.height as i16 / 2);
1351 -
1352 - let mut candidates = Vec::new();
1353 -
1354 - for &window in &visible {
1355 - if window == focused {
1356 - continue;
1357 - }
1358 -
1359 - let geom = match self.connection.get_geometry(window)?.reply() {
1360 - Ok(g) => g,
1361 - Err(_) => continue,
1362 - };
1363 -
1364 - let center_x = geom.x + (geom.width as i16 / 2);
1365 - let center_y = geom.y + (geom.height as i16 / 2);
1366 -
1367 - let is_valid_direction = match direction {
1368 - 0 => center_y < focused_center_y,
1369 - 1 => center_y > focused_center_y,
1370 - 2 => center_x < focused_center_x,
1371 - 3 => center_x > focused_center_x,
1372 - _ => false,
1373 - };
1288 + Ok(())
1289 + }
1374 1290
1375 - if is_valid_direction {
1376 - let dx = (center_x - focused_center_x) as i32;
1377 - let dy = (center_y - focused_center_y) as i32;
1378 - let distance = dx * dx + dy * dy;
1379 - candidates.push((window, distance));
1380 - }
1381 - }
1291 + pub fn swap_direction(&mut self, direction: i32) -> WmResult<()> {
1292 + let focused_window = match self
1293 + .monitors
1294 + .get(self.selected_monitor)
1295 + .and_then(|monitor| monitor.focused_window)
1296 + {
1297 + Some(window) => window,
1298 + None => return Ok(()),
1299 + };
1382 1300
1383 - if let Some(&(target_window, _)) = candidates.iter().min_by_key(|&(_, dist)| dist) {
1384 - let focused_pos = self.windows.iter().position(|&w| w == focused);
1385 - let target_pos = self.windows.iter().position(|&w| w == target_window);
1301 + if let Some(target_window) = self.find_directional_window_candidate(focused_window, direction) {
1302 + let focused_position = self.windows.iter().position(|&window| window == focused_window);
1303 + let target_position = self.windows.iter().position(|&window| window == target_window);
1386 1304
1387 - if let (Some(f_pos), Some(t_pos)) = (focused_pos, target_pos) {
1388 - self.windows.swap(f_pos, t_pos);
1305 + if let (Some(focused_index), Some(target_index)) = (focused_position, target_position) {
1306 + self.windows.swap(focused_index, target_index);
1389 1307 self.apply_layout()?;
1390 - self.set_focus(focused)?;
1308 + self.set_focus(focused_window)?;
1391 1309
1392 - if let Ok(geometry) = self.connection.get_geometry(focused)?.reply() {
1310 + if let Ok(geometry) = self.get_or_query_geometry(focused_window) {
1393 1311 self.connection.warp_pointer(
1394 1312 x11rb::NONE,
1395 - focused,
1313 + focused_window,
1396 1314 0,
1397 1315 0,
1398 1316 0,
@@ -1552,6 +1470,20 @@ impl WindowManager {
1552 1470
1553 1471 fn fullscreen(&mut self) -> WmResult<()> {
1554 1472 if self.show_bar {
1473 + let windows: Vec<Window> = self.windows.iter()
1474 + .filter(|&&w| self.is_window_visible(w))
1475 + .copied()
1476 + .collect();
1477 +
1478 + for window in &windows {
1479 + if let Ok(geom) = self.connection.get_geometry(*window)?.reply() {
1480 + self.floating_geometry_before_fullscreen.insert(
1481 + *window,
1482 + (geom.x, geom.y, geom.width, geom.height, geom.border_width as u16),
1483 + );
1484 + }
1485 + }
1486 +
1555 1487 self.last_layout = Some(self.layout.name());
1556 1488 if let Ok(layout) = layout_from_str("monocle") {
1557 1489 self.layout = layout;
@@ -1560,19 +1492,12 @@ impl WindowManager {
1560 1492 self.apply_layout()?;
1561 1493
1562 1494 let border_width = self.config.border_width;
1563 - let windows: Vec<Window> = self.windows.iter()
1564 - .filter(|&&w| self.floating_windows.contains(&w) && self.is_window_visible(w))
1495 + let floating_windows: Vec<Window> = windows.iter()
1496 + .filter(|&&w| self.floating_windows.contains(&w))
1565 1497 .copied()
1566 1498 .collect();
1567 1499
1568 - for window in windows {
1569 - if let Ok(geom) = self.connection.get_geometry(window)?.reply() {
1570 - self.floating_geometry_before_fullscreen.insert(
1571 - window,
1572 - (geom.x, geom.y, geom.width, geom.height, geom.border_width as u16),
1573 - );
1574 - }
1575 -
1500 + for window in floating_windows {
1576 1501 let monitor_idx = *self.window_monitor.get(&window).unwrap_or(&self.selected_monitor);
1577 1502 let monitor = &self.monitors[monitor_idx];
1578 1503
@@ -1585,18 +1510,18 @@ impl WindowManager {
1585 1510 (0, 0)
1586 1511 };
1587 1512
1588 - let x = monitor.x + outer_gap_h as i32;
1589 - let y = monitor.y + outer_gap_v as i32;
1590 - let width = monitor.width.saturating_sub(2 * outer_gap_h).saturating_sub(2 * border_width);
1591 - let height = monitor.height.saturating_sub(2 * outer_gap_v).saturating_sub(2 * border_width);
1513 + let window_x = monitor.x + outer_gap_h as i32;
1514 + let window_y = monitor.y + outer_gap_v as i32;
1515 + let window_width = monitor.width.saturating_sub(2 * outer_gap_h).saturating_sub(2 * border_width);
1516 + let window_height = monitor.height.saturating_sub(2 * outer_gap_v).saturating_sub(2 * border_width);
1592 1517
1593 1518 self.connection.configure_window(
1594 1519 window,
1595 1520 &x11rb::protocol::xproto::ConfigureWindowAux::new()
1596 - .x(x)
1597 - .y(y)
1598 - .width(width)
1599 - .height(height),
1521 + .x(window_x)
1522 + .y(window_y)
1523 + .width(window_width)
1524 + .height(window_height),
1600 1525 )?;
1601 1526 }
1602 1527 self.connection.flush()?;
@@ -1606,15 +1531,13 @@ impl WindowManager {
1606 1531 self.layout = layout;
1607 1532 }
1608 1533 }
1609 - self.toggle_bar()?;
1610 - self.apply_layout()?;
1611 1534
1612 - let windows: Vec<Window> = self.windows.iter()
1613 - .filter(|&&w| self.floating_windows.contains(&w) && self.is_window_visible(w))
1535 + let windows_to_restore: Vec<Window> = self.floating_geometry_before_fullscreen
1536 + .keys()
1614 1537 .copied()
1615 1538 .collect();
1616 1539
1617 - for window in windows {
1540 + for window in windows_to_restore {
1618 1541 if let Some(&(x, y, width, height, border_width)) = self.floating_geometry_before_fullscreen.get(&window) {
1619 1542 self.connection.configure_window(
1620 1543 window,
@@ -1625,10 +1548,34 @@ impl WindowManager {
1625 1548 .height(height as u32)
1626 1549 .border_width(border_width as u32),
1627 1550 )?;
1551 +
1552 + self.update_geometry_cache(window, CachedGeometry {
1553 + x_position: x,
1554 + y_position: y,
1555 + width,
1556 + height,
1557 + border_width,
1558 + });
1559 +
1628 1560 self.floating_geometry_before_fullscreen.remove(&window);
1629 1561 }
1630 1562 }
1631 1563 self.connection.flush()?;
1564 +
1565 + self.toggle_bar()?;
1566 +
1567 + if self.layout.name() != "normie" {
1568 + self.apply_layout()?;
1569 + } else {
1570 + if let Some(bar) = self.bars.get(self.selected_monitor) {
1571 + self.connection.configure_window(
1572 + bar.window(),
1573 + &x11rb::protocol::xproto::ConfigureWindowAux::new()
1574 + .stack_mode(x11rb::protocol::xproto::StackMode::ABOVE),
1575 + )?;
1576 + self.connection.flush()?;
1577 + }
1578 + }
1632 1579 }
1633 1580 Ok(())
1634 1581 }
@@ -1901,21 +1848,27 @@ impl WindowManager {
1901 1848
1902 1849 fn handle_event(&mut self, event: Event) -> WmResult<Option<bool>> {
1903 1850 match event {
1904 - Event::KeyPress(ref e) if e.event == self.overlay.window() => {
1851 + Event::KeyPress(ref key_event) if key_event.event == self.overlay.window() => {
1905 1852 if self.overlay.is_visible() {
1906 - let _ = self.overlay.hide(&self.connection);
1853 + if let Err(error) = self.overlay.hide(&self.connection) {
1854 + eprintln!("Failed to hide overlay: {:?}", error);
1855 + }
1907 1856 }
1908 1857 return Ok(None);
1909 1858 }
1910 - Event::ButtonPress(ref e) if e.event == self.overlay.window() => {
1859 + Event::ButtonPress(ref button_event) if button_event.event == self.overlay.window() => {
1911 1860 if self.overlay.is_visible() {
1912 - let _ = self.overlay.hide(&self.connection);
1861 + if let Err(error) = self.overlay.hide(&self.connection) {
1862 + eprintln!("Failed to hide overlay: {:?}", error);
1863 + }
1913 1864 }
1914 1865 return Ok(None);
1915 1866 }
1916 - Event::Expose(ref e) if e.window == self.overlay.window() => {
1867 + Event::Expose(ref expose_event) if expose_event.window == self.overlay.window() => {
1917 1868 if self.overlay.is_visible() {
1918 - let _ = self.overlay.draw(&self.connection, &self.font);
1869 + if let Err(error) = self.overlay.draw(&self.connection, &self.font) {
1870 + eprintln!("Failed to draw overlay: {:?}", error);
1871 + }
1919 1872 }
1920 1873 return Ok(None);
1921 1874 }
@@ -1940,7 +1893,9 @@ impl WindowManager {
1940 1893
1941 1894 if let Some(&keysym) = keyboard_mapping.keysyms.get(index) {
1942 1895 if keysym == keysyms::XK_ESCAPE || keysym == keysyms::XK_Q {
1943 - let _ = self.keybind_overlay.hide(&self.connection);
1896 + if let Err(error) = self.keybind_overlay.hide(&self.connection) {
1897 + eprintln!("Failed to hide keybind overlay: {:?}", error);
1898 + }
1944 1899 }
1945 1900 }
1946 1901 }
@@ -1949,9 +1904,11 @@ impl WindowManager {
1949 1904 Event::ButtonPress(ref e) if e.event == self.keybind_overlay.window() => {
1950 1905 return Ok(None);
1951 1906 }
1952 - Event::Expose(ref e) if e.window == self.keybind_overlay.window() => {
1907 + Event::Expose(ref expose_event) if expose_event.window == self.keybind_overlay.window() => {
1953 1908 if self.keybind_overlay.is_visible() {
1954 - let _ = self.keybind_overlay.draw(&self.connection, &self.font);
1909 + if let Err(error) = self.keybind_overlay.draw(&self.connection, &self.font) {
1910 + eprintln!("Failed to draw keybind overlay: {:?}", error);
1911 + }
1955 1912 }
1956 1913 return Ok(None);
1957 1914 }
@@ -1986,7 +1943,9 @@ impl WindowManager {
1986 1943 self.window_monitor
1987 1944 .insert(event.window, self.selected_monitor);
1988 1945 self.set_wm_state(event.window, 1)?;
1989 - let _ = self.save_client_tag(event.window, selected_tags);
1946 + if let Err(error) = self.save_client_tag(event.window, selected_tags) {
1947 + eprintln!("Failed to save client tag for new window: {:?}", error);
1948 + }
1990 1949
1991 1950 let is_transient = self.is_transient_window(event.window);
1992 1951 if is_transient {
@@ -2100,7 +2059,9 @@ impl WindowManager {
2100 2059 Ok(()) => {
2101 2060 self.gaps_enabled = self.config.gaps_enabled;
2102 2061 self.error_message = None;
2103 - let _ = self.overlay.hide(&self.connection);
2062 + if let Err(error) = self.overlay.hide(&self.connection) {
2063 + eprintln!("Failed to hide overlay after config reload: {:?}", error);
2064 + }
2104 2065 self.apply_layout()?;
2105 2066 self.update_bar()?;
2106 2067 }
@@ -2202,12 +2163,14 @@ impl WindowManager {
2202 2163 Ok(None)
2203 2164 }
2204 2165
2205 - fn apply_layout(&self) -> WmResult<()> {
2166 + fn apply_layout(&mut self) -> WmResult<()> {
2206 2167 if self.layout.name() == LayoutType::Normie.as_str() {
2207 2168 return Ok(());
2208 2169 }
2209 2170
2210 - for (monitor_index, monitor) in self.monitors.iter().enumerate() {
2171 + let monitor_count = self.monitors.len();
2172 + for monitor_index in 0..monitor_count {
2173 + let monitor = &self.monitors[monitor_index];
2211 2174 let border_width = self.config.border_width;
2212 2175
2213 2176 let gaps = if self.gaps_enabled {
@@ -2226,22 +2189,28 @@ impl WindowManager {
2226 2189 }
2227 2190 };
2228 2191
2192 + let monitor_selected_tags = monitor.selected_tags;
2193 + let monitor_x = monitor.x;
2194 + let monitor_y = monitor.y;
2195 + let monitor_width = monitor.width;
2196 + let monitor_height = monitor.height;
2197 +
2229 2198 let visible: Vec<Window> = self
2230 2199 .windows
2231 2200 .iter()
2232 - .filter(|&&w| {
2233 - let window_mon = self.window_monitor.get(&w).copied().unwrap_or(0);
2234 - if window_mon != monitor_index {
2201 + .filter(|&&window| {
2202 + let window_monitor_index = self.window_monitor.get(&window).copied().unwrap_or(0);
2203 + if window_monitor_index != monitor_index {
2235 2204 return false;
2236 2205 }
2237 - if self.floating_windows.contains(&w) {
2206 + if self.floating_windows.contains(&window) {
2238 2207 return false;
2239 2208 }
2240 - if self.fullscreen_windows.contains(&w) {
2209 + if self.fullscreen_windows.contains(&window) {
2241 2210 return false;
2242 2211 }
2243 - if let Some(&tags) = self.window_tags.get(&w) {
2244 - (tags & monitor.selected_tags) != 0
2212 + if let Some(&tags) = self.window_tags.get(&window) {
2213 + (tags & monitor_selected_tags) != 0
2245 2214 } else {
2246 2215 false
2247 2216 }
@@ -2252,23 +2221,23 @@ impl WindowManager {
2252 2221 let bar_height = if self.show_bar {
2253 2222 self.bars
2254 2223 .get(monitor_index)
2255 - .map(|b| b.height() as u32)
2224 + .map(|bar| bar.height() as u32)
2256 2225 .unwrap_or(0)
2257 2226 } else {
2258 2227 0
2259 2228 };
2260 - let usable_height = monitor.height.saturating_sub(bar_height);
2229 + let usable_height = monitor_height.saturating_sub(bar_height);
2261 2230
2262 2231 let geometries = self
2263 2232 .layout
2264 - .arrange(&visible, monitor.width, usable_height, &gaps);
2233 + .arrange(&visible, monitor_width, usable_height, &gaps);
2265 2234
2266 2235 for (window, geometry) in visible.iter().zip(geometries.iter()) {
2267 2236 let adjusted_width = geometry.width.saturating_sub(2 * border_width);
2268 2237 let adjusted_height = geometry.height.saturating_sub(2 * border_width);
2269 2238
2270 - let adjusted_x = geometry.x_coordinate + monitor.x;
2271 - let adjusted_y = geometry.y_coordinate + monitor.y + bar_height as i32;
2239 + let adjusted_x = geometry.x_coordinate + monitor_x;
2240 + let adjusted_y = geometry.y_coordinate + monitor_y + bar_height as i32;
2272 2241
2273 2242 self.connection.configure_window(
2274 2243 *window,
@@ -2279,6 +2248,14 @@ impl WindowManager {
2279 2248 .height(adjusted_height)
2280 2249 .border_width(border_width),
2281 2250 )?;
2251 +
2252 + self.update_geometry_cache(*window, CachedGeometry {
2253 + x_position: adjusted_x as i16,
2254 + y_position: adjusted_y as i16,
2255 + width: adjusted_width as u16,
2256 + height: adjusted_height as u16,
2257 + border_width: border_width as u16,
2258 + });
2282 2259 }
2283 2260 }
2284 2261
@@ -2292,12 +2269,38 @@ impl WindowManager {
2292 2269 Ok(())
2293 2270 }
2294 2271
2272 + fn update_geometry_cache(&mut self, window: Window, geometry: CachedGeometry) {
2273 + self.window_geometry_cache.insert(window, geometry);
2274 + }
2275 +
2276 + fn get_cached_geometry(&self, window: Window) -> Option<CachedGeometry> {
2277 + self.window_geometry_cache.get(&window).copied()
2278 + }
2279 +
2280 + fn get_or_query_geometry(&mut self, window: Window) -> WmResult<CachedGeometry> {
2281 + if let Some(cached) = self.get_cached_geometry(window) {
2282 + return Ok(cached);
2283 + }
2284 +
2285 + let geometry = self.connection.get_geometry(window)?.reply()?;
2286 + let cached = CachedGeometry {
2287 + x_position: geometry.x,
2288 + y_position: geometry.y,
2289 + width: geometry.width,
2290 + height: geometry.height,
2291 + border_width: geometry.border_width as u16,
2292 + };
2293 + self.update_geometry_cache(window, cached);
2294 + Ok(cached)
2295 + }
2296 +
2295 2297 fn remove_window(&mut self, window: Window) -> WmResult<()> {
2296 2298 let initial_count = self.windows.len();
2297 2299
2298 2300 self.windows.retain(|&w| w != window);
2299 2301 self.window_tags.remove(&window);
2300 2302 self.window_monitor.remove(&window);
2303 + self.window_geometry_cache.remove(&window);
2301 2304 self.floating_windows.remove(&window);
2302 2305
2303 2306 if self.windows.len() < initial_count {
+0 −21 templates/main.rs deleted file mode 100644
@@ -1,21 +0,0 @@
1 -mod config;
2 -
3 -use anyhow::Result;
4 -
5 -fn main() -> Result<()> {
6 - let cfg = config::build_config();
7 -
8 - let args: Vec<String> = std::env::args().collect();
9 - let mut wm = oxwm::window_manager::WindowManager::new(cfg)?;
10 - let should_restart = wm.run()?;
11 -
12 - drop(wm);
13 -
14 - if should_restart {
15 - use std::os::unix::process::CommandExt;
16 - let err = std::process::Command::new(&args[0]).args(&args[1..]).exec();
17 - eprintln!("Failed to restart: {}", err);
18 - }
19 -
20 - Ok(())
21 -}