tony / oxwm

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