ffcv 1.1.1

Firefox Configuration Viewer - Parse and query Firefox preference files
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
//! Firefox installation locator
//!
//! This module provides functionality to locate Firefox installations
//! across different platforms (Linux, macOS, Windows).

use crate::error::{Error, Result};
use crate::types::FirefoxInstallation;
use std::fs;
use std::path::{Path, PathBuf};

/// Platform-specific Firefox installation search paths
#[cfg(target_os = "linux")]
const FIREFOX_SEARCH_PATHS: &[&str] = &[
    "/usr/lib/firefox",
    "/usr/lib64/firefox",
    "/opt/firefox",
    "/usr/local/firefox",
    "/opt/firefox-beta",
    "/opt/firefox-esr",
];

#[cfg(target_os = "macos")]
const FIREFOX_SEARCH_PATHS: &[&str] = &[
    "/Applications/Firefox.app/Contents/Resources",
    "/Applications/Firefox Beta.app/Contents/Resources",
    "/Applications/Firefox Developer Edition.app/Contents/Resources",
    "/Applications/Firefox ESR.app/Contents/Resources",
];

#[cfg(target_os = "windows")]
const FIREFOX_SEARCH_PATHS: &[&str] = &[
    r"C:\Program Files\Mozilla Firefox",
    r"C:\Program Files\Firefox Beta",
    r"C:\Program Files\Firefox ESR",
    r"C:\Program Files\Mozilla Firefox ESR",
    r"C:\Program Files (x86)\Mozilla Firefox",
    r"C:\Program Files (x86)\Firefox Beta",
    r"C:\Program Files (x86)\Firefox ESR",
    r"C:\Program Files (x86)\Mozilla Firefox ESR",
    r"C:\Program Files\Mozilla Firefox Developer Edition",
];

/// Additional search paths for NixOS
#[cfg(target_os = "linux")]
const NIX_STORE_PATHS: &[&str] = &[
    "/nix/var/nix/profiles/default/bin/firefox",
    "/run/current-system/sw/bin/firefox",
    // User-specific profile paths (we'll search /etc/profiles too)
    "/etc/profiles",
];

/// Find the first valid Firefox installation on the system
///
/// This function searches common Firefox installation paths for the current
/// platform and returns the first valid installation found.
///
/// # Returns
///
/// - `Ok(Some(installation))` - Firefox installation found
/// - `Ok(None)` - No Firefox installation found
/// - `Err(_)` - Error while searching (e.g., permission denied)
///
/// # Example
///
/// ```rust,no_run
/// use ffcv::find_firefox_installation;
///
/// match find_firefox_installation() {
///     Ok(Some(install)) => println!("Found Firefox {} at {:?}", install.version, install.path),
///     Ok(None) => println!("Firefox not found"),
///     Err(e) => eprintln!("Error: {}", e),
/// }
/// ```
pub fn find_firefox_installation() -> Result<Option<FirefoxInstallation>> {
    let search_paths = get_all_search_paths();

    for path in search_paths {
        if let Ok(install) = validate_installation(&path) {
            return Ok(Some(install));
        }
    }

    Ok(None)
}

/// Find all Firefox installations on the system
///
/// This function searches all common Firefox installation paths and returns
/// all valid installations found.
///
/// # Returns
///
/// - `Ok(installations)` - Vector of all Firefox installations found (may be empty)
/// - `Err(_)` - Error while searching (e.g., permission denied)
///
/// # Example
///
/// ```rust,no_run
/// use ffcv::find_all_firefox_installations;
///
/// match find_all_firefox_installations() {
///     Ok(installations) => {
///         for install in installations {
///             println!("Found Firefox {} at {:?}", install.version, install.path);
///         }
///     }
///     Err(e) => eprintln!("Error: {}", e),
/// }
/// ```
pub fn find_all_firefox_installations() -> Result<Vec<FirefoxInstallation>> {
    let mut installations = Vec::new();
    let search_paths = get_all_search_paths();

    for path in search_paths {
        if let Ok(install) = validate_installation(&path) {
            installations.push(install);
        }
    }

    Ok(installations)
}

/// Get the Firefox version from an installation directory
///
/// This function reads the `application.ini` or `platform.ini` file from
/// the Firefox installation directory and extracts the version string.
///
/// # Arguments
///
/// * `install_path` - Path to Firefox installation directory
///
/// # Returns
///
/// - `Ok(version)` - Firefox version string (e.g., "128.0")
/// - `Err(_)` - Error reading or parsing version file
///
/// # Example
///
/// ```rust,no_run
/// use ffcv::get_firefox_version;
/// use std::path::Path;
///
/// let path = Path::new("/usr/lib/firefox");
/// match get_firefox_version(&path) {
///     Ok(version) => println!("Firefox version: {}", version),
///     Err(e) => eprintln!("Error: {}", e),
/// }
/// ```
pub fn get_firefox_version(install_path: &Path) -> Result<String> {
    // Try application.ini first (standard location)
    let app_ini = install_path.join("application.ini");

    if app_ini.exists() {
        return extract_version_from_ini(&app_ini);
    }

    // Fallback to platform.ini (some distributions use this)
    let platform_ini = install_path.join("platform.ini");

    if platform_ini.exists() {
        return extract_version_from_ini(&platform_ini);
    }

    // For macOS .app bundles, check Contents/Resources
    #[cfg(target_os = "macos")]
    {
        let resources_ini = install_path.join("application.ini");
        if resources_ini.exists() {
            return extract_version_from_ini(&resources_ini);
        }
    }

    // Check parent directory for macOS .app structure
    #[cfg(target_os = "macos")]
    {
        if let Some(parent) = install_path.parent() {
            let browser_ini = parent.join("browserconfig.properties");
            if browser_ini.exists() {
                if let Ok(content) = fs::read_to_string(&browser_ini) {
                    for line in content.lines() {
                        if line.contains("version") {
                            if let Some(version) = line.split('=').nth(1) {
                                return Ok(version.trim().to_string());
                            }
                        }
                    }
                }
            }
        }
    }

    Err(Error::FirefoxNotFound {
        searched_paths: format!("{} (no version info found)", install_path.display()),
    })
}

/// Validate that a path contains a valid Firefox installation
///
/// Checks for the presence of omni.ja and/or greprefs.js, and extracts
/// version information if available.
///
/// # Arguments
///
/// * `path` - Path to validate
///
/// # Returns
///
/// - `Ok(installation)` - Valid Firefox installation
/// - `Err(_)` - Not a valid Firefox installation or error reading files
fn validate_installation(path: &str) -> Result<FirefoxInstallation> {
    let install_path = PathBuf::from(path);

    if !install_path.exists() {
        return Err(Error::FirefoxNotFound {
            searched_paths: path.to_string(),
        });
    }

    // Check for omni.ja (in browser/ or root)
    let omni_ja_paths = [
        install_path.join("browser/omni.ja"),
        install_path.join("omni.ja"),
    ];

    let has_omni_ja = omni_ja_paths.iter().any(|p| p.exists());

    // Check for greprefs.js
    let greprefs_paths = [
        install_path.join("greprefs.js"),
        install_path.join("browser/greprefs.js"),
    ];

    let has_greprefs = greprefs_paths.iter().any(|p| p.exists());

    // At least one of these files should exist for a valid installation
    if !has_omni_ja && !has_greprefs {
        return Err(Error::FirefoxNotFound {
            searched_paths: format!("{} (no omni.ja or greprefs.js found)", path),
        });
    }

    // Try to get version
    let version = get_firefox_version(&install_path).unwrap_or_else(|_| "unknown".to_string());

    Ok(FirefoxInstallation {
        version,
        path: install_path,
        has_greprefs,
        has_omni_ja,
    })
}

/// Extract version from an .ini file
///
/// Parses standard INI format files to find the Version field.
fn extract_version_from_ini(ini_path: &Path) -> Result<String> {
    let content = fs::read_to_string(ini_path).map_err(|e| Error::FirefoxNotFound {
        searched_paths: format!("{} (cannot read: {})", ini_path.display(), e),
    })?;

    for line in content.lines() {
        let line = line.trim();

        // Look for "Version=X.Y.Z" format
        if line.starts_with("Version=") || line.starts_with("Version =") {
            if let Some(version) = line.split('=').nth(1) {
                return Ok(version.trim().to_string());
            }
        }
    }

    Err(Error::FirefoxNotFound {
        searched_paths: format!("{} (no version found)", ini_path.display()),
    })
}

/// Get all search paths for the current platform
///
/// Combines standard paths with platform-specific additions like Nix store paths.
fn get_all_search_paths() -> Vec<String> {
    let mut paths: Vec<String> = FIREFOX_SEARCH_PATHS.iter().map(|s| s.to_string()).collect();

    // Add Nix store paths on Linux
    #[cfg(target_os = "linux")]
    {
        for nix_path in NIX_STORE_PATHS {
            let nix_path_buf = PathBuf::from(nix_path);

            // If it's a direct path to a firefox binary, resolve it
            if nix_path_buf.exists() || nix_path_buf.is_symlink() {
                if let Ok(canonical) = nix_path_buf.canonicalize() {
                    // Check if it's a firefox binary
                    if canonical.ends_with("firefox") || canonical.ends_with("firefox-bin") {
                        // This is a binary, get the lib/firefox directory
                        if let Some(bin_dir) = canonical.parent() {
                            if let Some(store_base) = bin_dir.parent() {
                                let lib_firefox = store_base.join("lib/firefox");
                                if lib_firefox.exists() {
                                    paths.push(lib_firefox.to_string_lossy().to_string());
                                }
                            }
                        }
                    }
                }
            }

            // Also check if nix_path itself is a directory (like /etc/profiles)
            // and try to find firefox binaries recursively
            if nix_path_buf.is_dir() {
                // Search recursively for firefox binaries (need depth 4 for /etc/profiles/per-user/USER/bin/firefox)
                let entries = walk_dir_depth(&nix_path_buf, 4);
                for entry in entries {
                    if entry.ends_with("firefox") || entry.ends_with("firefox-bin") {
                        if let Ok(canonical) = entry.canonicalize() {
                            // Get the lib/firefox directory
                            if let Some(bin_dir) = canonical.parent() {
                                if let Some(store_base) = bin_dir.parent() {
                                    let lib_firefox = store_base.join("lib/firefox");
                                    if lib_firefox.exists() {
                                        paths.push(lib_firefox.to_string_lossy().to_string());
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    // Deduplicate paths while preserving order
    let mut seen = std::collections::HashSet::new();
    paths.retain(|p| seen.insert(p.clone()));

    paths
}

/// Walk a directory up to a specified depth, collecting paths that end with "firefox"
#[cfg(target_os = "linux")]
fn walk_dir_depth(dir: &Path, max_depth: usize) -> Vec<PathBuf> {
    let mut results = Vec::new();
    let mut current_dirs = vec![dir.to_path_buf()];

    for _depth in 0..max_depth {
        let mut next_dirs = Vec::new();

        for dir_path in &current_dirs {
            if let Ok(entries) = fs::read_dir(dir_path) {
                for entry in entries.flatten() {
                    let path = entry.path();
                    let file_name = path.file_name();

                    // Check if this is a firefox binary
                    let is_firefox = file_name.is_some() && {
                        let name = file_name.unwrap().to_string_lossy();
                        name == "firefox" || name == "firefox-bin"
                    };

                    // If it's a firefox binary, add it to results
                    if is_firefox {
                        results.push(path.clone());
                    }

                    // If it's a directory, add to next iteration
                    if path.is_dir() {
                        next_dirs.push(path);
                    }
                }
            }
        }

        current_dirs = next_dirs;
        if current_dirs.is_empty() {
            break;
        }
    }

    results
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_get_all_search_paths_not_empty() {
        let paths = get_all_search_paths();
        assert!(!paths.is_empty());
    }

    #[test]
    fn test_validate_nonexistent_path() {
        let result = validate_installation("/nonexistent/firefox/path/xyz123");
        assert!(result.is_err());
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn test_firefox_search_paths_include_standard_locations() {
        let paths = get_all_search_paths();
        assert!(paths.iter().any(|p| p.contains("firefox")));
    }

    #[test]
    fn test_extract_version_from_ini_content() {
        let ini_content = r#"
[App]
Version=128.0
Name=Firefox
"#;
        // This would require creating a temp file and testing extract_version_from_ini
        // For now, we'll just verify the logic structure
        assert!(ini_content.contains("Version=128.0"));
    }
}