tony / oxwm

Branch: 18f19a1
Switch branches/tags
master
tonybtw Fixed main.rs to just launch with sane defaults and accomdate for rare situation where user will not have a Cargo.toml but will have a config.rs... 18f19a1 2025-10-13
272 lines · 7.5 KB Raw Blame History
1 use anyhow::Result;
2 use std::path::PathBuf;
3 use std::process::Command;
4
5 fn main() -> Result<()> {
6 let args: Vec<String> = std::env::args().collect();
7
8 match args.get(1).map(|s| s.as_str()) {
9 Some("--init") => return init_config(),
10 Some("--recompile") => return recompile_config(),
11 Some("--version") => {
12 println!("oxwm {}", env!("CARGO_PKG_VERSION"));
13 return Ok(());
14 }
15 Some("--help") => {
16 print_help();
17 return Ok(());
18 }
19 _ => {}
20 }
21
22 let config_path = get_config_path().join("config.rs");
23 let cache_binary = get_cache_binary_path();
24
25 if !config_path.exists() {
26 init_config()?;
27 notify(
28 "OXWM First Run",
29 "Config created at ~/.config/oxwm/config.rs\nEdit and reload with Mod+Shift+R",
30 );
31 } else {
32 let config_dir = get_config_path();
33 if !config_dir.join("Cargo.toml").exists() || !config_dir.join("main.rs").exists() {
34 ensure_build_files(&config_dir)?;
35 }
36 }
37
38 if !cache_binary.exists() || should_recompile(&config_path, &cache_binary)? {
39 if let Err(e) = recompile_config() {
40 eprintln!("\nCompilation failed: {}", e);
41 eprintln!("\nYour config may be incompatible with this version of OXWM.");
42 eprintln!("Options:");
43 eprintln!(" 1. Fix the errors in ~/.config/oxwm/config.rs");
44 eprintln!(" 2. Run 'oxwm --init' to regenerate default config");
45 eprintln!("\nBackup your config first if you have customizations!");
46 std::process::exit(1);
47 }
48 }
49
50 use std::os::unix::process::CommandExt;
51 let err = Command::new(&cache_binary).args(&args[1..]).exec();
52 eprintln!("Failed to exec: {}", err);
53 std::process::exit(1);
54 }
55
56 #[derive(Debug)]
57 enum BuildMethod {
58 NixFlake,
59 NixBuild,
60 Cargo,
61 }
62
63 fn detect_build_method() -> BuildMethod {
64 let config_dir = get_config_path();
65
66 if config_dir.join("flake.nix").exists() {
67 println!("Detected flake.nix, will use nix flake for recompilation");
68 return BuildMethod::NixFlake;
69 }
70
71 if config_dir.join("default.nix").exists() || config_dir.join("shell.nix").exists() {
72 println!("Detected nix files, will use nix-shell for recompilation");
73 return BuildMethod::NixBuild;
74 }
75
76 println!("Will use cargo for recompilation");
77 BuildMethod::Cargo
78 }
79
80 fn init_config() -> Result<()> {
81 let config_dir = get_config_path();
82 std::fs::create_dir_all(&config_dir)?;
83
84 let config_template = include_str!("../../templates/config.rs");
85 std::fs::write(config_dir.join("config.rs"), config_template)?;
86
87 ensure_build_files(&config_dir)?;
88
89 Ok(())
90 }
91
92 fn ensure_build_files(config_dir: &PathBuf) -> Result<()> {
93 let main_template = include_str!("../../templates/main.rs");
94 std::fs::write(config_dir.join("main.rs"), main_template)?;
95
96 let cargo_toml = r#"[package]
97 name = "oxwm-user"
98 version = "0.1.0"
99 edition = "2024"
100
101 [dependencies]
102 oxwm = { git = "https://github.com/tonybanters/oxwm" }
103 anyhow = "1"
104
105 [[bin]]
106 name = "oxwm-user"
107 path = "main.rs"
108 "#;
109
110 std::fs::write(config_dir.join("Cargo.toml"), cargo_toml)?;
111 std::fs::write(config_dir.join(".gitignore"), "target/\nCargo.lock\n")?;
112
113 if is_nixos() {
114 let shell_nix = r#"{ pkgs ? import <nixpkgs> {} }:
115 pkgs.mkShell {
116 buildInputs = with pkgs; [
117 rustc
118 cargo
119 pkg-config
120 xorg.libX11
121 xorg.libXft
122 xorg.libXrender
123 freetype
124 fontconfig
125 ];
126 }
127 "#;
128 std::fs::write(config_dir.join("shell.nix"), shell_nix)?;
129 }
130
131 Ok(())
132 }
133
134 fn recompile_config() -> Result<()> {
135 let config_dir = get_config_path();
136
137 if !config_dir.join("config.rs").exists() {
138 anyhow::bail!("No config found. Run: oxwm --init");
139 }
140
141 println!("Compiling oxwm configuration...");
142
143 let build_method = detect_build_method();
144
145 let output = match build_method {
146 BuildMethod::NixFlake => {
147 println!("Using nix flake build...");
148 Command::new("nix")
149 .args(&["build", ".#", "--no-link"])
150 .current_dir(&config_dir)
151 .output()?
152 }
153 BuildMethod::NixBuild => {
154 println!("Using nix-shell...");
155 Command::new("nix-shell")
156 .args(&["--run", "cargo build --release"])
157 .current_dir(&config_dir)
158 .output()?
159 }
160 BuildMethod::Cargo => Command::new("cargo")
161 .args(&["build", "--release"])
162 .current_dir(&config_dir)
163 .output()?,
164 };
165
166 if !output.status.success() {
167 let stderr = String::from_utf8_lossy(&output.stderr);
168 eprintln!("\nāŒ Compilation failed:\n{}", stderr);
169
170 notify_error("OXWM Compile Error", "Check terminal for details");
171
172 anyhow::bail!("Failed to compile configuration");
173 }
174
175 let source = config_dir.join("target/release/oxwm-user");
176 let dest = get_cache_binary_path();
177
178 std::fs::create_dir_all(dest.parent().unwrap())?;
179
180 match std::fs::copy(&source, &dest) {
181 Ok(_) => {}
182 Err(e) if e.raw_os_error() == Some(26) => {
183 let temp_dest = dest.with_extension("new");
184 std::fs::copy(&source, &temp_dest)?;
185 std::fs::rename(&temp_dest, &dest)?;
186 }
187 Err(e) => return Err(e.into()),
188 }
189
190 println!("āœ“ Compiled successfully");
191
192 notify(
193 "OXWM",
194 "Configuration recompiled! Hit Mod+Shift+R to restart.",
195 );
196
197 Ok(())
198 }
199
200 fn is_nixos() -> bool {
201 std::path::Path::new("/etc/NIXOS").exists()
202 || std::path::Path::new("/run/current-system/nixos-version").exists()
203 || std::env::var("NIX_PATH").is_ok()
204 }
205
206 fn should_recompile(config: &PathBuf, binary: &PathBuf) -> Result<bool> {
207 if !config.exists() {
208 return Ok(false);
209 }
210
211 let config_dir = get_config_path();
212 let binary_time = std::fs::metadata(binary)?.modified()?;
213
214 let watch_files = [
215 "config.rs",
216 "main.rs",
217 "Cargo.toml",
218 "flake.nix",
219 "shell.nix",
220 ];
221
222 for filename in &watch_files {
223 let path = config_dir.join(filename);
224 if !path.exists() {
225 continue;
226 }
227
228 let file_time = std::fs::metadata(&path)?.modified()?;
229 if file_time > binary_time {
230 return Ok(true);
231 }
232 }
233
234 Ok(false)
235 }
236
237 fn get_config_path() -> PathBuf {
238 dirs::config_dir()
239 .expect("Could not find config directory")
240 .join("oxwm")
241 }
242
243 fn get_cache_binary_path() -> PathBuf {
244 dirs::cache_dir()
245 .expect("Could not find cache directory")
246 .join("oxwm/oxwm-binary")
247 }
248
249 fn notify(title: &str, body: &str) {
250 let _ = Command::new("notify-send").args(&[title, body]).spawn();
251 }
252
253 fn notify_error(title: &str, body: &str) {
254 let _ = Command::new("notify-send")
255 .args(&["-u", "critical", title, body])
256 .spawn();
257 }
258
259 fn print_help() {
260 println!("OXWM - A dynamic window manager written in Rust\n");
261 println!("USAGE:");
262 println!(" oxwm [OPTIONS]\n");
263 println!("OPTIONS:");
264 println!(" --init Recreate config template in ~/.config/oxwm");
265 println!(" --recompile Manually recompile configuration");
266 println!(" --version Print version information");
267 println!(" --help Print this help message\n");
268 println!("FIRST RUN:");
269 println!(" Just run 'oxwm' - config will be auto-generated at:");
270 println!(" ~/.config/oxwm/config.rs");
271 println!("\n Edit your config and reload with Mod+Shift+R\n");
272 }