tony / oxwm

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