tony / oxwm

Branch: e22d139
Switch branches/tags
master
Scott DeJong Additional cleanup and logic improvement e22d139 2025-12-16
181 lines · 5.8 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!("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!("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!("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!("{}", 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!("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!("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!("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)
72 .map_err(|error| format!("Failed to parse default template config:\n{}", error))?;
73 Ok((config, true))
74 }
75 }
76 }
77
78 fn init_config() -> Result<(), Box<dyn std::error::Error>> {
79 let config_directory = get_config_path();
80 std::fs::create_dir_all(&config_directory)?;
81
82 let config_template = TEMPLATE;
83 let config_path = config_directory.join(CONFIG_FILE);
84 std::fs::write(&config_path, config_template)?;
85
86 println!("✓ Config created at {:?}", config_path);
87 println!(" Edit the file and reload with Mod+Shift+R");
88 println!(" No compilation needed - changes take effect immediately!");
89
90 Ok(())
91 }
92
93 fn get_config_path() -> PathBuf {
94 dirs::config_dir()
95 .expect("Could not find config directory")
96 .join("oxwm")
97 }
98
99 fn print_help() {
100 println!("OXWM - A dynamic window manager written in Rust\n");
101 println!("USAGE:");
102 println!(" oxwm [OPTIONS]\n");
103 println!("OPTIONS:");
104 println!(" --init Create default config in ~/.config/oxwm/config.lua");
105 println!(" --config <PATH> Use custom config file");
106 println!(" --version Print version information");
107 println!(" --help Print this help message\n");
108 println!("CONFIG:");
109 println!(" Location: ~/.config/oxwm/config.lua");
110 println!(" Edit the config file and use Mod+Shift+R to reload");
111 println!(" No compilation needed - instant hot-reload!");
112 println!(" LSP support included with oxwm.lua type definitions\n");
113 println!("FIRST RUN:");
114 println!(" Run 'oxwm --init' to create a config file");
115 println!(" Or just start oxwm and it will create one automatically\n");
116 }
117
118 fn process_args() -> Args {
119 let mut args = std::env::args();
120 let name = match args.next() {
121 Some(n) => n,
122 None => return Args::Error("Program name can't be extracted from args".to_string()),
123 };
124 let switch = args.next();
125 let path = args.next();
126
127 let switch = match switch {
128 Some(s) => s,
129 None => return Args::Arguments(vec![name]),
130 };
131
132 match switch.as_str() {
133 "--version" => {
134 println!("{name} {}", env!("CARGO_PKG_VERSION"));
135 Args::Exit
136 }
137 "--help" => {
138 print_help();
139 Args::Exit
140 }
141 "--init" => match init_config() {
142 Ok(_) => Args::Exit,
143 Err(e) => Args::Error(format!("Failed to create default config:\n{e}")),
144 },
145 "--config" => {
146 if let Some(path) = path
147 && std::fs::exists(&path).is_ok()
148 && std::fs::exists(&path).unwrap()
149 {
150 Args::Arguments(vec![name, switch, path])
151 } else {
152 Args::Error("Error: --config requires a valid path argument".to_string())
153 }
154 }
155 _ => Args::Error(format!("Error: {switch} is an unknown argument")),
156 }
157 }
158
159 fn check_convert(path: &Path) -> Result<(), &str> {
160 let config_directory = get_config_path();
161
162 if !path.exists() {
163 let ron_path = config_directory.join("config.ron");
164 let had_ron_config = ron_path.exists();
165
166 println!("No config found at {:?}", config_directory);
167 println!("Creating default Lua config...");
168 if init_config().is_err() {
169 return Err("Failed to create default lua");
170 }
171
172 if had_ron_config {
173 println!("\n NOTICE: OXWM has migrated to Lua configuration.");
174 println!(" Your old config.ron has been preserved, but is no longer used.");
175 println!(" Your settings have been reset to defaults.");
176 println!(" Please manually port your configuration to the new Lua format.");
177 println!(" See the new config.lua template for examples.\n");
178 }
179 }
180 Ok(())
181 }