tony / oxwm

Branch: 3fbd72e
Switch branches/tags
master
tonybanters Updated compiler to detect os... 1fb52fe 2025-10-10
266 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 cache_binary = get_cache_binary_path();
23
24 if cache_binary.exists() {
25 let config_path = get_config_path().join("config.rs");
26 if should_recompile(&config_path, &cache_binary)? {
27 println!("Config changed, recompiling...");
28 recompile_config()?;
29 }
30
31 use std::os::unix::process::CommandExt;
32 let err = Command::new(&cache_binary).args(&args[1..]).exec();
33 anyhow::bail!("Failed to exec user binary: {}", err);
34 } else {
35 eprintln!("No configuration found.");
36 eprintln!("Run: oxwm --init");
37 eprintln!("Then add 'exec oxwm' to your ~/.xinitrc");
38 std::process::exit(1);
39 }
40 }
41
42 #[derive(Debug)]
43 enum BuildMethod {
44 NixFlake,
45 NixBuild,
46 Cargo,
47 }
48
49 fn detect_build_method() -> BuildMethod {
50 let config_dir = get_config_path();
51
52 if config_dir.join("flake.nix").exists() {
53 println!("Detected flake.nix, will use nix flake for recompilation");
54 return BuildMethod::NixFlake;
55 }
56
57 if config_dir.join("default.nix").exists() || config_dir.join("shell.nix").exists() {
58 println!("Detected nix files, will use nix-shell for recompilation");
59 return BuildMethod::NixBuild;
60 }
61
62 println!("Will use cargo for recompilation");
63 BuildMethod::Cargo
64 }
65
66 fn init_config() -> Result<()> {
67 let config_dir = get_config_path();
68 std::fs::create_dir_all(&config_dir)?;
69
70 if config_dir.join("config.rs").exists() {
71 eprintln!("Config already exists at ~/.config/oxwm/config.rs");
72 eprintln!("Remove it first if you want to reinitialize.");
73 return Ok(());
74 }
75
76 let config_template = include_str!("../../templates/config.rs");
77 std::fs::write(config_dir.join("config.rs"), config_template)?;
78
79 let main_template = include_str!("../../templates/main.rs");
80 std::fs::write(config_dir.join("main.rs"), main_template)?;
81
82 let cargo_toml = r#"[package]
83 name = "oxwm-user"
84 version = "0.1.0"
85 edition = "2024"
86
87 [dependencies]
88 oxwm = { git = "https://github.com/tonybanters/oxwm" }
89 anyhow = "1"
90
91 [[bin]]
92 name = "oxwm-user"
93 path = "main.rs"
94 "#;
95
96 std::fs::write(config_dir.join("Cargo.toml"), cargo_toml)?;
97 std::fs::write(config_dir.join(".gitignore"), "target/\nCargo.lock\n")?;
98
99 if is_nixos() {
100 let shell_nix = r#"{ pkgs ? import <nixpkgs> {} }:
101 pkgs.mkShell {
102 buildInputs = with pkgs; [
103 rustc
104 cargo
105 pkg-config
106 xorg.libX11
107 xorg.libXft
108 xorg.libXrender
109 freetype
110 fontconfig
111 ];
112 }
113 "#;
114 std::fs::write(config_dir.join("shell.nix"), shell_nix)?;
115 println!("✓ Created shell.nix for NixOS");
116 }
117
118 println!("✓ Created ~/.config/oxwm/config.rs");
119 println!("✓ Created ~/.config/oxwm/main.rs");
120 println!("✓ Edit ~/.config/oxwm/config.rs to customize your setup");
121
122 println!("\nCompiling initial configuration...");
123 recompile_config()?;
124
125 println!("\n✓ Setup complete!");
126 println!(" Add 'exec oxwm' to your ~/.xinitrc");
127 println!(" Reload config anytime with Mod+Shift+R");
128
129 Ok(())
130 }
131
132 fn recompile_config() -> Result<()> {
133 let config_dir = get_config_path();
134
135 if !config_dir.join("config.rs").exists() {
136 anyhow::bail!("No config found. Run: oxwm --init");
137 }
138
139 println!("Compiling oxwm configuration...");
140
141 let build_method = detect_build_method();
142
143 let output = match build_method {
144 BuildMethod::NixFlake => {
145 println!("Using nix flake build...");
146 Command::new("nix")
147 .args(&["build", ".#", "--no-link"])
148 .current_dir(&config_dir)
149 .output()?
150 }
151 BuildMethod::NixBuild => {
152 println!("Using nix-shell...");
153 Command::new("nix-shell")
154 .args(&["--run", "cargo build --release"])
155 .current_dir(&config_dir)
156 .output()?
157 }
158 BuildMethod::Cargo => Command::new("cargo")
159 .args(&["build", "--release"])
160 .current_dir(&config_dir)
161 .output()?,
162 };
163
164 if !output.status.success() {
165 let stderr = String::from_utf8_lossy(&output.stderr);
166 eprintln!("\n❌ Compilation failed:\n{}", stderr);
167
168 let _ = Command::new("notify-send")
169 .args(&[
170 "-u",
171 "critical",
172 "OXWM Compile Error",
173 "Check terminal for details",
174 ])
175 .spawn();
176
177 anyhow::bail!("Failed to compile configuration");
178 }
179
180 let source = config_dir.join("target/release/oxwm-user");
181 let dest = get_cache_binary_path();
182
183 std::fs::create_dir_all(dest.parent().unwrap())?;
184 std::fs::copy(&source, &dest)?;
185
186 println!("✓ Compiled successfully");
187
188 let _ = Command::new("notify-send")
189 .args(&[
190 "OXWM",
191 "Configuration recompiled! Hit Mod+Shift+R to restart.",
192 ])
193 .spawn();
194
195 Ok(())
196 }
197
198 fn is_nixos() -> bool {
199 std::path::Path::new("/etc/NIXOS").exists()
200 || std::path::Path::new("/run/current-system/nixos-version").exists()
201 || std::env::var("NIX_PATH").is_ok()
202 }
203
204 fn should_recompile(config: &PathBuf, binary: &PathBuf) -> Result<bool> {
205 if !config.exists() {
206 return Ok(false);
207 }
208
209 let config_dir = get_config_path();
210 let binary_time = std::fs::metadata(binary)?.modified()?;
211
212 let watch_files = [
213 "config.rs",
214 "main.rs",
215 "Cargo.toml",
216 "flake.nix",
217 "shell.nix",
218 ];
219
220 for filename in &watch_files {
221 let path = config_dir.join(filename);
222 if !path.exists() {
223 continue;
224 }
225
226 let file_time = std::fs::metadata(&path)?.modified()?;
227 if file_time > binary_time {
228 return Ok(true);
229 }
230 }
231
232 Ok(false)
233 }
234
235 fn get_config_path() -> PathBuf {
236 dirs::config_dir()
237 .expect("Could not find config directory")
238 .join("oxwm")
239 }
240
241 fn get_cache_binary_path() -> PathBuf {
242 dirs::cache_dir()
243 .expect("Could not find cache directory")
244 .join("oxwm/oxwm-binary")
245 }
246
247 fn print_help() {
248 println!("OXWM - A dynamic window manager written in Rust\n");
249 println!("USAGE:");
250 println!(" oxwm [OPTIONS]\n");
251 println!("OPTIONS:");
252 println!(" --init Initialize user configuration in ~/.config/oxwm");
253 println!(" --recompile Recompile user configuration");
254 println!(" --version Print version information");
255 println!(" --help Print this help message\n");
256 println!("SETUP:");
257 println!(" 1. Run 'oxwm --init' to create your config");
258 println!(" 2. Edit ~/.config/oxwm/config.rs");
259 println!(" 3. Add 'exec oxwm' to your ~/.xinitrc");
260 println!(" 4. Start X with 'startx'\n");
261 println!("CONFIGURATION:");
262 println!(" Config location: ~/.config/oxwm/config.rs");
263 println!(" Reload hotkey: Mod+Shift+R (auto-recompiles if needed)\n");
264 println!("ADVANCED:");
265 println!(" Create flake.nix or shell.nix in ~/.config/oxwm to use nix builds");
266 }