tony / oxwm

Branch: 7fc1259
Switch branches/tags
master
Scott DeJong Fixed a bug where I was calling std::fs twice and cleaned up error handling a little bit. 7fc1259 2025-12-17
193 lines · 6.3 KB Raw Blame History
1 use std::path::Path;
2 use std::path::PathBuf;
3
4 static CONFIG_FILE: &str = "config.lua";
5 static TEMPLATE: &str = include_str!("../../templates/config.lua");
6
7 enum Args {
8 Exit,
9 Arguments(Vec<String>),
10 Error(String),
11 }
12
13 fn main() {
14 let arguments = match process_args() {
15 Args::Exit => return,
16 Args::Arguments(v) => v,
17 Args::Error(e) => panic!("Error: Could not get valid arguments:\n{}", e),
18 };
19
20 let (config, had_broken_config) = match load_config(arguments.get(2)) {
21 Ok((c, hbc)) => (c, hbc),
22 Err(e) => panic!("Error: Could not load config:\n{}", e),
23 };
24
25 let mut window_manager = match oxwm::window_manager::WindowManager::new(config) {
26 Ok(wm) => wm,
27 Err(e) => panic!("Error: Could not start window manager:\n{}", e),
28 };
29
30 if had_broken_config {
31 window_manager.show_migration_overlay();
32 }
33
34 let should_restart = match window_manager.run() {
35 Ok(sr) => sr,
36 Err(e) => panic!("Error: Could not determine restart\n{}", e),
37 };
38
39 drop(window_manager);
40
41 if should_restart {
42 use std::os::unix::process::CommandExt;
43 let error = std::process::Command::new(&arguments[0])
44 .args(&arguments[1..])
45 .exec();
46 eprintln!("Error: Failed to restart: {}", error);
47 }
48 }
49
50 fn load_config(
51 config_path: Option<&String>,
52 ) -> Result<(oxwm::Config, bool), Box<dyn std::error::Error>> {
53 let path = match config_path {
54 None => {
55 let config_path = get_config_path().join(CONFIG_FILE);
56 check_convert(&config_path)
57 .map_err(|error| format!("Error: Failed to check old config:\n{}", error))?;
58 config_path
59 }
60 Some(p) => PathBuf::from(p),
61 };
62
63 let config_string = std::fs::read_to_string(&path)
64 .map_err(|error| format!("Error: Failed to read config file:\n{}", error))?;
65
66 let config_directory = path.parent();
67
68 match oxwm::config::parse_lua_config(&config_string, config_directory) {
69 Ok(config) => Ok((config, false)),
70 Err(_error) => {
71 let config = oxwm::config::parse_lua_config(TEMPLATE, None).map_err(|error| {
72 format!("Error: Failed to parse default template config:\n{}", error)
73 })?;
74 Ok((config, true))
75 }
76 }
77 }
78
79 fn init_config() -> Result<(), Box<dyn std::error::Error>> {
80 let config_directory = get_config_path();
81 std::fs::create_dir_all(&config_directory)?;
82
83 let config_template = TEMPLATE;
84 let config_path = config_directory.join(CONFIG_FILE);
85 std::fs::write(&config_path, config_template)?;
86
87 println!("✓ Config created at {:?}", config_path);
88 println!(" Edit the file and reload with Mod+Shift+R");
89 println!(" No compilation needed - changes take effect immediately!");
90
91 Ok(())
92 }
93
94 fn get_config_path() -> PathBuf {
95 dirs::config_dir()
96 .expect("Could not find config directory")
97 .join("oxwm")
98 }
99
100 fn print_help() {
101 println!("OXWM - A dynamic window manager written in Rust\n");
102 println!("USAGE:");
103 println!(" oxwm [OPTIONS]\n");
104 println!("OPTIONS:");
105 println!(" --init Create default config in ~/.config/oxwm/config.lua");
106 println!(" --config <PATH> Use custom config file");
107 println!(" --version Print version information");
108 println!(" --help Print this help message\n");
109 println!("CONFIG:");
110 println!(" Location: ~/.config/oxwm/config.lua");
111 println!(" Edit the config file and use Mod+Shift+R to reload");
112 println!(" No compilation needed - instant hot-reload!");
113 println!(" LSP support included with oxwm.lua type definitions\n");
114 println!("FIRST RUN:");
115 println!(" Run 'oxwm --init' to create a config file");
116 println!(" Or just start oxwm and it will create one automatically\n");
117 }
118
119 fn process_args() -> Args {
120 let mut args = std::env::args();
121 let name = match args.next() {
122 Some(n) => n,
123 None => return Args::Error("Error: Program name can't be extracted from args".to_string()),
124 };
125 let switch = args.next();
126 let path = args.next();
127
128 let switch = match switch {
129 Some(s) => s,
130 None => return Args::Arguments(vec![name]),
131 };
132
133 match switch.as_str() {
134 "--version" => {
135 println!("{name} {}", env!("CARGO_PKG_VERSION"));
136 Args::Exit
137 }
138 "--help" => {
139 print_help();
140 Args::Exit
141 }
142 "--init" => match init_config() {
143 Ok(_) => Args::Exit,
144 Err(e) => Args::Error(format!("Error: Failed to create default config:\n{e}")),
145 },
146 "--config" => match check_custom_config(path) {
147 Ok(p) => Args::Arguments(vec![name, switch, p]),
148 Err(e) => Args::Error(e),
149 },
150 _ => Args::Error(format!("Error: {switch} is an unknown argument")),
151 }
152 }
153
154 fn check_custom_config(path: Option<String>) -> Result<String, String> {
155 let path = match path {
156 Some(p) => p,
157 None => {
158 return Err("Error: --config requires a valid path argument".to_string());
159 }
160 };
161
162 match std::fs::exists(&path) {
163 Ok(b) => match b {
164 true => Ok(path),
165 false => Err(format!("Error: {path} does not exist")),
166 },
167 Err(e) => Err(format!("Error: Failed to check config exists:\n{e}")),
168 }
169 }
170
171 fn check_convert(path: &Path) -> Result<(), &str> {
172 let config_directory = get_config_path();
173
174 if !path.exists() {
175 let ron_path = config_directory.join("config.ron");
176 let had_ron_config = ron_path.exists();
177
178 println!("No config found at {:?}", config_directory);
179 println!("Creating default Lua config...");
180 if init_config().is_err() {
181 return Err("Error: Failed to create default lua");
182 }
183
184 if had_ron_config {
185 println!("\n NOTICE: OXWM has migrated to Lua configuration.");
186 println!(" Your old config.ron has been preserved, but is no longer used.");
187 println!(" Your settings have been reset to defaults.");
188 println!(" Please manually port your configuration to the new Lua format.");
189 println!(" See the new config.lua template for examples.\n");
190 }
191 }
192 Ok(())
193 }