tony / oxwm

Merge pull request #91 from ScottADeJong/update/mainfile Browse files
Update/mainfile
Tony, btw. committed 2025-12-24 parents 84f46f6 be13d76 commit aaad324a2542c2d3c3468cfb45ce9131046753d7
Showing 3 changed files with 181 additions and 93 deletions. UnifiedSplit
+140 −82 src/bin/main.rs
@@ -1,43 +1,39 @@
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 +static CONFIG_FILE: &str = "config.lua";
4 - let arguments: Vec<String> = std::env::args().collect(); 7 +static 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, config_error) = 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 let Some(error) = config_error { 29 + if let Some(warning) = config_warning {
37 - window_manager.show_startup_config_error(&error); 30 + window_manager.show_startup_config_error(warning);
38 } 31 }
39 32
40 - let should_restart = window_manager.run()?; 33 + let should_restart = match window_manager.run() {
34 + Ok(sr) => sr,
35 + Err(e) => return Err(MainError::BadRestartStatus(e)),
36 + };
41 37
42 drop(window_manager); 38 drop(window_manager);
43 39
@@ -46,70 +42,57 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
46 let error = std::process::Command::new(&arguments[0]) 42 let error = std::process::Command::new(&arguments[0])
47 .args(&arguments[1..]) 43 .args(&arguments[1..])
48 .exec(); 44 .exec();
49 - eprintln!("Failed to restart: {}", error); 45 + eprintln!("Error: Failed to restart: {}", error);
50 } 46 }
51 -
52 Ok(()) 47 Ok(())
53 } 48 }
54 49
55 fn load_config( 50 fn load_config(
56 - custom_path: Option<PathBuf>, 51 + config_path: Option<&String>,
57 -) -> Result<(oxwm::Config, Option<String>), Box<dyn std::error::Error>> { 52 +) -> Result<(oxwm::Config, Option<ConfigError>), MainError> {
58 - let config_path = if let Some(path) = custom_path { 53 + let path = match config_path {
59 - path 54 + None => {
60 - } else { 55 + let config_dir = get_config_path()?;
61 - let config_directory = get_config_path(); 56 + let config_path = config_dir.join(CONFIG_FILE);
62 - let lua_path = config_directory.join("config.lua"); 57 + check_convert(&config_path)?;
63 - 58 + 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 } 59 }
80 - 60 + Some(p) => PathBuf::from(p),
81 - lua_path
82 }; 61 };
83 62
84 - let config_string = std::fs::read_to_string(&config_path) 63 + let config_string = match std::fs::read_to_string(&path) {
85 - .map_err(|error| format!("Failed to read config file: {}", error))?; 64 + Ok(c) => c,
65 + Err(e) => return Err(MainError::FailedReadConfig(e)),
66 + };
86 67
87 - let config_directory = config_path.parent(); 68 + let config_directory = path.parent();
88 69
89 - let (mut config, config_error) = 70 + let (mut config, config_warning) =
90 match oxwm::config::parse_lua_config(&config_string, config_directory) { 71 match oxwm::config::parse_lua_config(&config_string, config_directory) {
91 Ok(config) => (config, None), 72 Ok(config) => (config, None),
92 - Err(error) => { 73 + Err(warning) => {
93 - let template = include_str!("../../templates/config.lua"); 74 + let config = match oxwm::config::parse_lua_config(TEMPLATE, None) {
94 - let config = oxwm::config::parse_lua_config(template, None).map_err(|error| { 75 + Ok(c) => c,
95 - format!("Failed to parse default template config: {}", error) 76 + Err(e) => return Err(MainError::FailedReadConfigTemplate(e)),
96 - })?; 77 + };
97 - (config, Some(format!("{}", error))) 78 + (config, Some(warning))
98 } 79 }
99 }; 80 };
100 - 81 + config.path = Some(path);
101 - config.path = Some(config_path); 82 + Ok((config, config_warning))
102 -
103 - Ok((config, config_error))
104 } 83 }
105 84
106 -fn init_config() -> Result<(), Box<dyn std::error::Error>> { 85 +fn init_config() -> Result<(), MainError> {
107 - let config_directory = get_config_path(); 86 + let config_directory = get_config_path()?;
108 - std::fs::create_dir_all(&config_directory)?; 87 + if let Err(e) = std::fs::create_dir_all(&config_directory) {
88 + return Err(MainError::CouldNotCreateConfigDir(e));
89 + }
109 90
110 - let config_template = include_str!("../../templates/config.lua"); 91 + let config_template = TEMPLATE;
111 - let config_path = config_directory.join("config.lua"); 92 + let config_path = config_directory.join(CONFIG_FILE);
112 - std::fs::write(&config_path, config_template)?; 93 + if let Err(e) = std::fs::write(&config_path, config_template) {
94 + return Err(MainError::CouldNotWriteConfig(e));
95 + }
113 96
114 println!("✓ Config created at {:?}", config_path); 97 println!("✓ Config created at {:?}", config_path);
115 println!(" Edit the file and reload with Mod+Shift+R"); 98 println!(" Edit the file and reload with Mod+Shift+R");
@@ -118,10 +101,11 @@ fn init_config() -> Result<(), Box<dyn std::error::Error>> {
118 Ok(()) 101 Ok(())
119 } 102 }
120 103
121 -fn get_config_path() -> PathBuf { 104 +fn get_config_path() -> Result<PathBuf, MainError> {
122 - dirs::config_dir() 105 + match dirs::config_dir() {
123 - .expect("Could not find config directory") 106 + Some(p) => Ok(p.join("oxwm")),
124 - .join("oxwm") 107 + None => Err(MainError::NoConfigDir),
108 + }
125 } 109 }
126 110
127 fn print_help() { 111 fn print_help() {
@@ -142,3 +126,77 @@ fn print_help() {
142 println!(" Run 'oxwm --init' to create a config file"); 126 println!(" Run 'oxwm --init' to create a config file");
143 println!(" Or just start oxwm and it will create one automatically\n"); 127 println!(" Or just start oxwm and it will create one automatically\n");
144 } 128 }
129 +
130 +fn process_args() -> Args {
131 + let mut args = std::env::args();
132 + let name = match args.next() {
133 + Some(n) => n,
134 + None => return Args::Error(MainError::NoProgramName),
135 + };
136 + let switch = args.next();
137 + let path = args.next();
138 +
139 + let switch = match switch {
140 + Some(s) => s,
141 + None => return Args::Arguments(vec![name]),
142 + };
143 +
144 + match switch.as_str() {
145 + "--version" => {
146 + println!("{name} {}", env!("CARGO_PKG_VERSION"));
147 + Args::Exit
148 + }
149 + "--help" => {
150 + print_help();
151 + Args::Exit
152 + }
153 + "--init" => match init_config() {
154 + Ok(_) => Args::Exit,
155 + Err(e) => Args::Error(e),
156 + },
157 + "--config" => match check_custom_config(path) {
158 + Ok(p) => Args::Arguments(vec![name, switch, p]),
159 + Err(e) => Args::Error(e),
160 + },
161 + _ => Args::Error(MainError::InvalidArguments),
162 + }
163 +}
164 +
165 +fn check_custom_config(path: Option<String>) -> Result<String, MainError> {
166 + let path = match path {
167 + Some(p) => p,
168 + None => {
169 + return Err(MainError::NoConfigPath);
170 + }
171 + };
172 +
173 + match std::fs::exists(&path) {
174 + Ok(b) => match b {
175 + true => Ok(path),
176 + false => Err(MainError::BadConfigPath),
177 + },
178 + Err(e) => Err(MainError::FailedCheckExist(e)),
179 + }
180 +}
181 +
182 +fn check_convert(path: &Path) -> Result<(), MainError> {
183 + let config_directory = get_config_path()?;
184 +
185 + if !path.exists() {
186 + let ron_path = config_directory.join("config.ron");
187 + let had_ron_config = ron_path.exists();
188 +
189 + println!("No config found at {:?}", config_directory);
190 + println!("Creating default Lua config...");
191 + init_config()?;
192 +
193 + if had_ron_config {
194 + println!("\n NOTICE: OXWM has migrated to Lua configuration.");
195 + println!(" Your old config.ron has been preserved, but is no longer used.");
196 + println!(" Your settings have been reset to defaults.");
197 + println!(" Please manually port your configuration to the new Lua format.");
198 + println!(" See the new config.lua template for examples.\n");
199 + }
200 + }
201 + Ok(())
202 +}
+37 −8 src/errors.rs
@@ -40,6 +40,21 @@ pub enum BlockError {
40 CommandFailed(String), 40 CommandFailed(String),
41 } 41 }
42 42
43 +pub enum MainError {
44 + CouldNotCreateConfigDir(std::io::Error),
45 + CouldNotWriteConfig(std::io::Error),
46 + FailedCheckExist(std::io::Error),
47 + FailedReadConfig(std::io::Error),
48 + FailedReadConfigTemplate(ConfigError),
49 + CouldNotStartWm(WmError),
50 + BadRestartStatus(WmError),
51 + BadConfigPath,
52 + NoConfigPath,
53 + InvalidArguments,
54 + NoProgramName,
55 + NoConfigDir,
56 +}
57 +
43 impl std::fmt::Display for WmError { 58 impl std::fmt::Display for WmError {
44 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 59 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
45 match self { 60 match self {
@@ -56,8 +71,6 @@ impl std::fmt::Display for WmError {
56 } 71 }
57 } 72 }
58 73
59 -impl std::error::Error for WmError {}
60 -
61 impl std::fmt::Display for X11Error { 74 impl std::fmt::Display for X11Error {
62 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 75 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
63 match self { 76 match self {
@@ -72,8 +85,6 @@ impl std::fmt::Display for X11Error {
72 } 85 }
73 } 86 }
74 87
75 -impl std::error::Error for X11Error {}
76 -
77 impl std::fmt::Display for ConfigError { 88 impl std::fmt::Display for ConfigError {
78 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 89 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
79 match self { 90 match self {
@@ -90,8 +101,6 @@ impl std::fmt::Display for ConfigError {
90 } 101 }
91 } 102 }
92 103
93 -impl std::error::Error for ConfigError {}
94 -
95 impl std::fmt::Display for BlockError { 104 impl std::fmt::Display for BlockError {
96 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 105 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
97 match self { 106 match self {
@@ -104,8 +113,6 @@ impl std::fmt::Display for BlockError {
104 } 113 }
105 } 114 }
106 115
107 -impl std::error::Error for BlockError {}
108 -
109 impl<T: Into<X11Error>> From<T> for WmError { 116 impl<T: Into<X11Error>> From<T> for WmError {
110 fn from(value: T) -> Self { 117 fn from(value: T) -> Self {
111 Self::X11(value.into()) 118 Self::X11(value.into())
@@ -181,3 +188,25 @@ impl<T> LuaResultExt<T> for Result<T, mlua::Error> {
181 self.map_err(|e| ConfigError::LuaError(format!("{}: {}", context, e))) 188 self.map_err(|e| ConfigError::LuaError(format!("{}: {}", context, e)))
182 } 189 }
183 } 190 }
191 +
192 +impl std::fmt::Debug for MainError {
193 + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
194 + use MainError::*;
195 +
196 + match self {
197 + CouldNotCreateConfigDir(e)
198 + | CouldNotWriteConfig(e)
199 + | FailedCheckExist(e)
200 + | FailedReadConfig(e) => {
201 + write!(f, "{e}")
202 + }
203 + FailedReadConfigTemplate(e) => write!(f, "{e}"),
204 + CouldNotStartWm(e) | BadRestartStatus(e) => write!(f, "{e}"),
205 + BadConfigPath => write!(f, "Given config path does not exist"),
206 + NoConfigPath => write!(f, "The --config switch requires a path value"),
207 + InvalidArguments => write!(f, "The arguments given are invalid try --help"),
208 + NoProgramName => write!(f, "Could not get the program name from the environment"),
209 + NoConfigDir => write!(f, "Could not get the config dir"),
210 + }
211 + }
212 +}
+4 −3 src/window_manager.rs
@@ -1,7 +1,7 @@
1 use crate::Config; 1 use crate::Config;
2 use crate::bar::Bar; 2 use crate::bar::Bar;
3 use crate::client::{Client, TagMask}; 3 use crate::client::{Client, TagMask};
4 -use crate::errors::WmError; 4 +use crate::errors::{ConfigError, WmError};
5 use crate::keyboard::{self, Arg, KeyAction, handlers}; 5 use crate::keyboard::{self, Arg, KeyAction, handlers};
6 use crate::layout::GapConfig; 6 use crate::layout::GapConfig;
7 use crate::layout::tiling::TilingLayout; 7 use crate::layout::tiling::TilingLayout;
@@ -312,17 +312,18 @@ impl WindowManager {
312 Ok(window_manager) 312 Ok(window_manager)
313 } 313 }
314 314
315 - pub fn show_startup_config_error(&mut self, error: &str) { 315 + pub fn show_startup_config_error(&mut self, error: ConfigError) {
316 let monitor = &self.monitors[self.selected_monitor]; 316 let monitor = &self.monitors[self.selected_monitor];
317 let monitor_x = monitor.screen_x as i16; 317 let monitor_x = monitor.screen_x as i16;
318 let monitor_y = monitor.screen_y as i16; 318 let monitor_y = monitor.screen_y as i16;
319 let screen_width = monitor.screen_width as u16; 319 let screen_width = monitor.screen_width as u16;
320 let screen_height = monitor.screen_height as u16; 320 let screen_height = monitor.screen_height as u16;
321 + let error = format!("{error}");
321 322
322 if let Err(e) = self.overlay.show_error( 323 if let Err(e) = self.overlay.show_error(
323 &self.connection, 324 &self.connection,
324 &self.font, 325 &self.font,
325 - error, 326 + error.as_str(),
326 monitor_x, 327 monitor_x,
327 monitor_y, 328 monitor_y,
328 screen_width, 329 screen_width,