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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
//! Preference merger
//!
//! This module provides functionality to merge Firefox preferences from
//! multiple sources (built-in defaults, global defaults, and user preferences)
//! with proper precedence handling.

use crate::error::{Error, Result};
use crate::firefox_locator;
use crate::omni_extractor::{ExtractConfig, OmniExtractor};
use crate::parser::parse_prefs_js_file;
use crate::types::{MergedPreferences, PrefEntry, PrefSource};
use std::collections::HashMap;
use std::path::Path;

/// Configuration for preference merging
///
/// Controls which sources are included and how errors are handled.
///
/// # Example
///
/// ```rust,no_run
/// use ffcv::MergeConfig;
///
/// let config = MergeConfig {
///     include_builtins: true,
///     include_globals: true,
///     include_user: true,
///     continue_on_error: true,
/// };
/// ```
#[derive(Debug, Clone)]
pub struct MergeConfig {
    /// Include built-in defaults from omni.ja
    pub include_builtins: bool,
    /// Include global defaults from greprefs.js
    pub include_globals: bool,
    /// Include user preferences from prefs.js
    pub include_user: bool,
    /// Continue even if some sources fail to load
    pub continue_on_error: bool,
}

impl Default for MergeConfig {
    fn default() -> Self {
        Self {
            include_builtins: true,
            include_globals: true,
            include_user: true,
            continue_on_error: true,
        }
    }
}

/// Merge preferences from multiple sources
///
/// This function loads preferences from built-in defaults (omni.ja),
/// global defaults (greprefs.js), and user preferences (prefs.js),
/// then merges them with proper precedence:
///
/// 1. Built-in defaults (lowest precedence)
/// 2. Global defaults (medium precedence)
/// 3. User preferences (highest precedence)
///
/// # Arguments
///
/// * `profile_path` - Path to Firefox profile directory
/// * `install_path` - Optional path to Firefox installation (auto-detected if None)
/// * `config` - Merge configuration
///
/// # Returns
///
/// - `Ok(merged)` - Merged preferences with metadata
/// - `Err(_)` - Error during merging (only if continue_on_error is false)
///
/// # Example
///
/// ```rust,no_run
/// use ffcv::{merge_all_preferences, MergeConfig};
/// use std::path::PathBuf;
///
/// let profile_path = PathBuf::from("/home/user/.mozilla/firefox/default");
/// let merged = merge_all_preferences(&profile_path, None, &MergeConfig::default()).unwrap();
///
/// println!("Loaded {} preferences", merged.entries.len());
/// println!("Sources: {:?}", merged.loaded_sources);
/// ```
pub fn merge_all_preferences(
    profile_path: &Path,
    install_path: Option<&Path>,
    config: &MergeConfig,
) -> Result<MergedPreferences> {
    let mut warnings = Vec::new();
    let mut loaded_sources = Vec::new();
    let mut pref_map: HashMap<String, PrefEntry> = HashMap::new();

    // Auto-detect Firefox installation if not provided
    let resolved_install_path = if let Some(path) = install_path {
        Some(path.to_path_buf())
    } else if config.include_builtins || config.include_globals {
        match firefox_locator::find_firefox_installation() {
            Ok(Some(install)) => {
                loaded_sources.push(PrefSource::BuiltIn);
                Some(install.path)
            }
            Ok(None) => {
                warnings.push("Firefox installation not found".to_string());
                None
            }
            Err(e) => {
                warnings.push(format!("Failed to locate Firefox: {}", e));
                None
            }
        }
    } else {
        None
    };

    // Load built-in defaults from omni.ja (lowest precedence)
    if config.include_builtins {
        if let Some(ref install) = resolved_install_path {
            match load_builtin_preferences(install, &mut warnings) {
                Ok(builtins) => {
                    for pref in builtins {
                        pref_map.insert(pref.key.clone(), pref);
                    }
                    loaded_sources.push(PrefSource::BuiltIn);
                }
                Err(e) => {
                    let msg = format!("Failed to load built-in preferences: {}", e);
                    warnings.push(msg.clone());
                    if !config.continue_on_error {
                        return Err(Error::OmniJaError(msg));
                    }
                }
            }
        }
    }

    // Load global defaults from greprefs.js (medium precedence)
    if config.include_globals {
        if let Some(ref install) = resolved_install_path {
            match load_global_preferences(install, &mut warnings) {
                Ok(globals) => {
                    for pref in globals {
                        pref_map.insert(pref.key.clone(), pref);
                    }
                    loaded_sources.push(PrefSource::GlobalDefault);
                }
                Err(e) => {
                    let msg = format!("Failed to load global preferences: {}", e);
                    warnings.push(msg);
                    if !config.continue_on_error {
                        return Err(Error::PrefFileNotFound {
                            file: "greprefs.js".to_string(),
                        });
                    }
                }
            }
        }
    }

    // Load user preferences from prefs.js (highest precedence)
    if config.include_user {
        let prefs_js_path = profile_path.join("prefs.js");

        match load_user_preferences(&prefs_js_path, &mut warnings) {
            Ok(user_prefs) => {
                for pref in user_prefs {
                    pref_map.insert(pref.key.clone(), pref);
                }
                loaded_sources.push(PrefSource::User);
            }
            Err(e) => {
                let msg = format!("Failed to load user preferences: {}", e);
                warnings.push(msg);
                if !config.continue_on_error {
                    return Err(e);
                }
            }
        }
    }

    // Convert HashMap to Vec
    let mut entries: Vec<PrefEntry> = pref_map.into_values().collect();
    entries.sort_by(|a, b| a.key.cmp(&b.key));

    Ok(MergedPreferences {
        entries,
        install_path: resolved_install_path,
        profile_path: profile_path.to_path_buf(),
        loaded_sources,
        warnings,
    })
}

/// Get the effective value for a preference key
///
/// Returns the highest-precedence preference entry matching the given key.
///
/// # Arguments
///
/// * `prefs` - Slice of preference entries
/// * `key` - Preference key to look up
///
/// # Returns
///
/// - `Some(entry)` - Found preference entry
/// - `None` - Preference not found
///
/// # Example
///
/// ```rust
/// use ffcv::get_effective_pref;
/// use ffcv::{parse_prefs_js, PrefEntry};
///
/// let content = r#"user_pref("test", true);"#;
/// let prefs = parse_prefs_js(content).unwrap();
///
/// if let Some(entry) = get_effective_pref(&prefs, "test") {
///     println!("Found: {:?}", entry.value);
/// }
/// ```
pub fn get_effective_pref<'a>(prefs: &'a [PrefEntry], key: &str) -> Option<&'a PrefEntry> {
    prefs.iter().find(|e| e.key == key)
}

/// Load built-in preferences from omni.ja
fn load_builtin_preferences(
    install_path: &Path,
    warnings: &mut Vec<String>,
) -> Result<Vec<PrefEntry>> {
    // Find omni.ja (try browser/ subdirectory first, then root)
    let omni_paths = [
        install_path.join("browser/omni.ja"),
        install_path.join("omni.ja"),
    ];

    let omni_path = omni_paths.iter().find(|p| p.exists()).ok_or_else(|| {
        warnings.push("omni.ja not found in Firefox installation".to_string());
        Error::PrefFileNotFound {
            file: "omni.ja".to_string(),
        }
    })?;

    // Only extract preference files, not all JavaScript files
    let config = ExtractConfig {
        target_files: vec![
            "defaults/preferences/*.js".to_string(),
            "defaults/pref/*.js".to_string(),
        ],
        ..Default::default()
    };
    let extractor = OmniExtractor::with_config(omni_path.clone(), config)?;
    let extracted_files = extractor.extract_prefs()?;

    let mut all_prefs = Vec::new();

    for file_path in extracted_files {
        match parse_prefs_js_file(&file_path) {
            Ok(mut prefs) => {
                // Update source information for each preference
                for pref in &mut prefs {
                    pref.source = Some(PrefSource::BuiltIn);
                    if let Ok(file_name) = file_path.strip_prefix(install_path) {
                        pref.source_file = Some(format!("omni.ja:{}", file_name.display()));
                    }
                }
                all_prefs.extend(prefs);
            }
            Err(e) => {
                // Skip files that fail to parse (likely non-pref .js files)
                // Don't warn about firefox.js as it may have non-standard content
                let file_name = file_path
                    .file_name()
                    .and_then(|n| n.to_str())
                    .unwrap_or("unknown");
                if file_name != "firefox.js" {
                    warnings.push(format!("Failed to parse {}: {}", file_path.display(), e));
                }
            }
        }
    }

    Ok(all_prefs)
}

/// Load global preferences from greprefs.js
fn load_global_preferences(
    install_path: &Path,
    warnings: &mut Vec<String>,
) -> Result<Vec<PrefEntry>> {
    // First try to find greprefs.js directly in the filesystem
    let greprefs_paths = [
        install_path.join("greprefs.js"),
        install_path.join("browser/greprefs.js"),
    ];

    let greprefs_path = if let Some(path) = greprefs_paths.iter().find(|p| p.exists()) {
        path.clone()
    } else {
        // If not found, try to extract from omni.ja
        let omni_paths = [
            install_path.join("omni.ja"),
            install_path.join("browser/omni.ja"),
        ];

        let omni_path = omni_paths.iter().find(|p| p.exists()).ok_or_else(|| {
            warnings.push("greprefs.js not found and omni.ja not found".to_string());
            Error::PrefFileNotFound {
                file: "greprefs.js".to_string(),
            }
        })?;

        // Extract greprefs.js from omni.ja
        let config = ExtractConfig {
            target_files: vec!["greprefs.js".to_string()],
            ..Default::default()
        };

        let extractor = OmniExtractor::with_config(omni_path.clone(), config)?;

        let extracted_files = match extractor.extract_prefs() {
            Ok(files) => files,
            Err(e) => {
                warnings.push(format!("Failed to extract greprefs.js from omni.ja: {}", e));
                return Err(Error::PrefFileNotFound {
                    file: "greprefs.js".to_string(),
                });
            }
        };

        if extracted_files.is_empty() {
            warnings.push("greprefs.js not found in omni.ja".to_string());
            return Err(Error::PrefFileNotFound {
                file: "greprefs.js".to_string(),
            });
        }

        // Copy to a temp file that won't be deleted when extractor is dropped
        let temp_dir = tempfile::tempdir()?;
        let temp_path = temp_dir.path().join("greprefs.js");
        std::fs::copy(&extracted_files[0], &temp_path)?;

        // Keep temp_dir alive by leaking it (not ideal but works for now)
        let _ = Box::leak(Box::new(temp_dir));

        temp_path
    };

    let mut prefs = parse_prefs_js_file(&greprefs_path).unwrap_or_default();

    // Update source information
    let source_file = if greprefs_path.to_string_lossy().contains("omni") {
        "omni.ja:greprefs.js".to_string()
    } else {
        "greprefs.js".to_string()
    };

    for pref in &mut prefs {
        pref.source = Some(PrefSource::GlobalDefault);
        pref.source_file = Some(source_file.clone());
    }

    Ok(prefs)
}

/// Load user preferences from prefs.js
fn load_user_preferences(
    prefs_js_path: &Path,
    warnings: &mut Vec<String>,
) -> Result<Vec<PrefEntry>> {
    if !prefs_js_path.exists() {
        warnings.push(format!("prefs.js not found at {}", prefs_js_path.display()));
        return Err(Error::PrefFileNotFound {
            file: prefs_js_path.display().to_string(),
        });
    }

    parse_prefs_js_file(prefs_js_path)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::types::{PrefType, PrefValue};
    use std::fs::write;
    use tempfile::TempDir;

    #[test]
    fn test_merge_config_default() {
        let config = MergeConfig::default();
        assert!(config.include_builtins);
        assert!(config.include_globals);
        assert!(config.include_user);
        assert!(config.continue_on_error);
    }

    #[test]
    fn test_get_effective_pref() {
        let prefs = vec![PrefEntry {
            key: "test.pref".to_string(),
            value: PrefValue::Bool(true),
            pref_type: PrefType::User,
            explanation: None,
            source: Some(PrefSource::User),
            source_file: Some("prefs.js".to_string()),
            locked: None,
        }];

        assert!(get_effective_pref(&prefs, "test.pref").is_some());
        assert!(get_effective_pref(&prefs, "nonexistent").is_none());
    }

    #[test]
    fn test_load_user_preferences() {
        let temp_dir = TempDir::new().unwrap();
        let prefs_path = temp_dir.path().join("prefs.js");

        let content = r#"
            user_pref("test.pref", true);
            user_pref("another.pref", "value");
        "#;

        write(&prefs_path, content).unwrap();

        let mut warnings = Vec::new();
        let prefs = load_user_preferences(&prefs_path, &mut warnings).unwrap();

        assert_eq!(prefs.len(), 2);
        assert!(warnings.is_empty());
    }

    #[test]
    fn test_load_user_preferences_not_found() {
        let temp_dir = TempDir::new().unwrap();
        let prefs_path = temp_dir.path().join("nonexistent.js");

        let mut warnings = Vec::new();
        let result = load_user_preferences(&prefs_path, &mut warnings);

        assert!(result.is_err());
        assert!(!warnings.is_empty());
    }
}