openmw-config 1.0.0

A library for interacting with the Openmw Configuration system.
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
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
// SPDX-License-Identifier: MIT OR Apache-2.0
// Copyright (c) 2025 Dave Corley (S3kshun8)

//! Parser, resolver, and serializer for `OpenMW` configuration chains.
//!
//! `OpenMW` loads one or more `openmw.cfg` files in a chain: the root config can reference
//! additional configs via `config=` entries, and each file can accumulate or override settings
//! from its parent.  This crate walks that chain, resolves token substitutions
//! (`?local?`, `?global?`, `?userdata?`, `?userconfig?`), normalises paths, and exposes the composed result as
//! [`OpenMWConfiguration`].
//!
//! # Quick start
//!
//! ```no_run
//! use openmw_config::OpenMWConfiguration;
//!
//! // Load from the platform-default location (or OPENMW_CONFIG / OPENMW_CONFIG_DIR env vars)
//! let config = OpenMWConfiguration::from_env()?;
//!
//! // Iterate content files in load order
//! for plugin in config.content_files_iter() {
//!     println!("{}", plugin.value());
//! }
//! # Ok::<(), openmw_config::ConfigError>(())
//! ```
//!
//! # Configuration sources
//!
//! See the [OpenMW path documentation](https://openmw.readthedocs.io/en/latest/reference/modding/paths.html)
//! for platform-specific default locations.  The environment variables `OPENMW_CONFIG` (path to
//! an `openmw.cfg` file) and `OPENMW_CONFIG_DIR` (directory containing `openmw.cfg`) override the
//! platform default.

mod config;
#[cfg(feature = "lua")]
pub mod lua;
mod platform_paths;

pub use config::{
    ConfigChainEntry, ConfigChainStatus, OpenMWConfiguration,
    directorysetting::DirectorySetting,
    encodingsetting::{EncodingSetting, EncodingType},
    error::ConfigError,
    filesetting::FileSetting,
    gamesetting::GameSettingType,
    genericsetting::GenericSetting,
};

#[cfg(feature = "lua")]
pub use lua::create_lua_module;

pub(crate) trait GameSetting: std::fmt::Display {
    fn meta(&self) -> &GameSettingMeta;
}

/// Source-tracking metadata attached to every setting value.
///
/// Records which config file defined the setting and any comment lines that
/// immediately preceded it in the file, so that [`OpenMWConfiguration`]'s
/// `Display` implementation can round-trip comments faithfully.
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct GameSettingMeta {
    source_config: std::path::PathBuf,
    comment: String,
}

impl GameSettingMeta {
    #[must_use]
    pub fn source_config(&self) -> &std::path::Path {
        &self.source_config
    }

    #[must_use]
    pub fn comment(&self) -> &str {
        &self.comment
    }
}

const NO_CONFIG_DIR: &str = "FAILURE: COULD NOT READ CONFIG DIRECTORY";
const NO_LOCAL_DIR: &str = "FAILURE: COULD NOT READ LOCAL DIRECTORY";
const NO_GLOBAL_DIR: &str = "FAILURE: COULD NOT READ GLOBAL DIRECTORY";
const DEFAULT_FLATPAK_APP_ID: &str = "org.openmw.OpenMW";

fn has_flatpak_info_file() -> bool {
    use std::sync::OnceLock;

    static HAS_FLATPAK_INFO: OnceLock<bool> = OnceLock::new();
    *HAS_FLATPAK_INFO.get_or_init(|| std::path::Path::new("/.flatpak-info").exists())
}

fn flatpak_mode_enabled() -> bool {
    #[cfg(not(target_os = "linux"))]
    {
        return false;
    }

    #[cfg(target_os = "linux")]
    {
        if std::env::var_os("OPENMW_CONFIG_USING_FLATPAK").is_some() {
            return true;
        }

        std::env::var_os("FLATPAK_ID").is_some() || has_flatpak_info_file()
    }
}

fn flatpak_app_id() -> String {
    std::env::var("OPENMW_FLATPAK_ID")
        .ok()
        .filter(|value| !value.trim().is_empty())
        .or_else(|| {
            std::env::var("FLATPAK_ID")
                .ok()
                .filter(|value| !value.trim().is_empty())
        })
        .unwrap_or_else(|| DEFAULT_FLATPAK_APP_ID.to_string())
}

fn flatpak_userconfig_path() -> Result<std::path::PathBuf, ConfigError> {
    platform_paths::home_dir().map(|home| {
        home.join(".var")
            .join("app")
            .join(flatpak_app_id())
            .join("config")
            .join("openmw")
    })
}

fn flatpak_userdata_path() -> Result<std::path::PathBuf, ConfigError> {
    platform_paths::home_dir().map(|home| {
        home.join(".var")
            .join("app")
            .join(flatpak_app_id())
            .join("data")
            .join("openmw")
    })
}

/// Fallible variant of [`default_config_path`].
///
/// Resolution precedence:
/// 1. Flatpak mode path (`$HOME/.var/app/<app-id>/config/openmw`) when Flatpak mode is enabled.
/// 2. Platform default path from platform-specific resolvers.
///
/// On Linux, Flatpak mode is enabled when `OPENMW_CONFIG_USING_FLATPAK` is set to any value, or
/// auto-detected via `FLATPAK_ID` / `/.flatpak-info`.
///
/// # Errors
/// Returns [`ConfigError::PlatformPathUnavailable`] if no platform config directory can be discovered.
pub fn try_default_config_path() -> Result<std::path::PathBuf, ConfigError> {
    #[cfg(target_os = "android")]
    return Ok(std::path::PathBuf::from(
        "/storage/emulated/0/Alpha3/config",
    ));

    #[cfg(not(target_os = "android"))]
    {
        if flatpak_mode_enabled() {
            return flatpak_userconfig_path();
        }

        platform_paths::config_dir().map_err(|_| ConfigError::PlatformPathUnavailable("config"))
    }
}

/// Path to input bindings and core configuration
/// These functions are not expected to fail and should they fail, indicate either:
/// a severe issue with the system
/// or that an unsupported system is being used.
///
/// # Panics
/// Panics if the platform config directory cannot be determined (unsupported system).
#[must_use]
pub fn default_config_path() -> std::path::PathBuf {
    try_default_config_path().expect(NO_CONFIG_DIR)
}

/// Fallible variant of [`default_userdata_path`].
///
/// Resolution precedence:
/// 1. Flatpak mode path (`$HOME/.var/app/<app-id>/data/openmw`) when Flatpak mode is enabled.
/// 2. Platform default path from platform-specific resolvers.
///
/// On Linux, Flatpak mode is enabled when `OPENMW_CONFIG_USING_FLATPAK` is set to any value, or
/// auto-detected via `FLATPAK_ID` / `/.flatpak-info`.
///
/// # Errors
/// Returns [`ConfigError::PlatformPathUnavailable`] if no platform userdata directory can be discovered.
pub fn try_default_userdata_path() -> Result<std::path::PathBuf, ConfigError> {
    #[cfg(target_os = "android")]
    return Ok(std::path::PathBuf::from("/storage/emulated/0/Alpha3"));

    #[cfg(not(target_os = "android"))]
    {
        if flatpak_mode_enabled() {
            return flatpak_userdata_path();
        }

        platform_paths::data_dir().map_err(|_| ConfigError::PlatformPathUnavailable("userdata"))
    }
}

/// Path to save storage, screenshots, navmeshdb, and data-local
/// These functions are not expected to fail and should they fail, indicate either:
/// a severe issue with the system
/// or that an unsupported system is being used.
///
/// # Panics
/// Panics if the platform data directory cannot be determined (unsupported system).
#[must_use]
pub fn default_userdata_path() -> std::path::PathBuf {
    try_default_userdata_path().expect("FAILURE: COULD NOT READ USERDATA DIRECTORY")
}

/// Path to the `data-local` directory as defined by the engine's defaults.
///
/// This directory is loaded last and therefore overrides all other data sources
/// in the VFS load order.
#[must_use]
pub fn default_data_local_path() -> std::path::PathBuf {
    default_userdata_path().join("data")
}

/// Fallible variant of [`default_local_path`].
///
/// Resolves the `?local?` token target.
///
/// - On macOS app bundles, this is the `Contents/Resources` directory.
/// - On other platforms, this is the directory containing the running executable.
///
/// # Errors
/// Returns [`ConfigError::PlatformPathUnavailable`] if the local path cannot be determined.
pub fn try_default_local_path() -> Result<std::path::PathBuf, ConfigError> {
    let exe = std::env::current_exe()?;

    #[cfg(target_os = "macos")]
    {
        if let Some(macos_dir) = exe.parent()
            && macos_dir.file_name() == Some(std::ffi::OsStr::new("MacOS"))
            && let Some(contents_dir) = macos_dir.parent()
            && contents_dir.file_name() == Some(std::ffi::OsStr::new("Contents"))
        {
            return Ok(contents_dir.join("Resources"));
        }
    }

    exe.parent()
        .map(std::path::Path::to_path_buf)
        .ok_or(ConfigError::PlatformPathUnavailable("local"))
}

/// Path that backs the `?local?` token.
///
/// # Panics
/// Panics if the local path cannot be determined.
#[must_use]
pub fn default_local_path() -> std::path::PathBuf {
    try_default_local_path().expect(NO_LOCAL_DIR)
}

/// Fallible variant of [`default_global_path`].
///
/// Resolves the `?global?` token target.
///
/// Resolution order:
/// 1. `OPENMW_GLOBAL_PATH` when set.
/// 2. Flatpak default (`/app/share/games`) when Flatpak mode is active.
/// 3. Platform default (`/usr/share/games` on Unix-like systems, `/Library/Application Support` on macOS).
///
/// Flatpak app id selection is: `OPENMW_FLATPAK_ID` > `FLATPAK_ID` > `org.openmw.OpenMW`.
///
/// # Errors
/// Returns [`ConfigError::PlatformPathUnavailable`] on unsupported platforms.
pub fn try_default_global_path() -> Result<std::path::PathBuf, ConfigError> {
    if let Ok(value) = std::env::var("OPENMW_GLOBAL_PATH")
        && !value.trim().is_empty()
    {
        return Ok(std::path::PathBuf::from(value));
    }

    if cfg!(windows) {
        return Err(ConfigError::PlatformPathUnavailable("global"));
    }

    // NOTE: Flatpak path behavior is intentionally Linux-only.
    // We are not fully certain whether OpenMW Flatpak builds should prefer a global
    // or local config path in all packaging variants, so we keep this conservative:
    // only Linux Flatpak mode maps ?global? to /app/share/games.
    if flatpak_mode_enabled() {
        return Ok(std::path::PathBuf::from("/app/share/games"));
    }

    if cfg!(target_os = "macos") {
        return Ok(std::path::PathBuf::from("/Library/Application Support"));
    }

    Ok(std::path::PathBuf::from("/usr/share/games"))
}

/// Path that backs the `?global?` token.
///
/// # Panics
/// Panics if the global path cannot be determined.
#[must_use]
pub fn default_global_path() -> std::path::PathBuf {
    try_default_global_path().expect(NO_GLOBAL_DIR)
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::ffi::OsString;
    use std::sync::Mutex;

    static ENV_LOCK: Mutex<()> = Mutex::new(());

    fn snapshot_env(keys: &[&str]) -> Vec<(String, Option<OsString>)> {
        keys.iter()
            .map(|key| ((*key).to_string(), std::env::var_os(key)))
            .collect()
    }

    fn restore_env(snapshot: Vec<(String, Option<OsString>)>) {
        for (key, value) in snapshot {
            // SAFETY: guarded by a process-wide mutex in tests to prevent concurrent env mutation.
            unsafe {
                if let Some(value) = value {
                    std::env::set_var(&key, value);
                } else {
                    std::env::remove_var(&key);
                }
            }
        }
    }

    #[test]
    fn test_default_data_local_path_is_userdata_data_child() {
        let _guard = ENV_LOCK.lock().expect("env lock poisoned");
        let snapshot = snapshot_env(&[
            "OPENMW_CONFIG_USING_FLATPAK",
            "OPENMW_FLATPAK_ID",
            "FLATPAK_ID",
            "OPENMW_GLOBAL_PATH",
        ]);

        // SAFETY: guarded by a process-wide mutex in tests to prevent concurrent env mutation.
        unsafe {
            std::env::remove_var("OPENMW_CONFIG_USING_FLATPAK");
            std::env::remove_var("OPENMW_FLATPAK_ID");
            std::env::remove_var("FLATPAK_ID");
            std::env::remove_var("OPENMW_GLOBAL_PATH");
        }

        assert_eq!(
            default_data_local_path(),
            default_userdata_path().join("data")
        );

        restore_env(snapshot);
    }

    #[test]
    #[cfg(windows)]
    fn test_windows_default_paths_contract() {
        let cfg = default_config_path();
        let cfg_str = cfg.to_string_lossy().to_lowercase();
        assert!(cfg_str.contains("my games"));
        assert!(cfg_str.contains("openmw"));
        assert_eq!(default_userdata_path(), cfg);
    }

    #[test]
    fn test_try_default_config_path_returns_path_or_error() {
        let _guard = ENV_LOCK.lock().expect("env lock poisoned");
        let snapshot = snapshot_env(&[
            "OPENMW_CONFIG_USING_FLATPAK",
            "OPENMW_FLATPAK_ID",
            "FLATPAK_ID",
        ]);
        let _ = try_default_config_path();
        restore_env(snapshot);
    }

    #[test]
    fn test_try_default_local_path_returns_path_or_error() {
        let _guard = ENV_LOCK.lock().expect("env lock poisoned");
        let snapshot = snapshot_env(&[
            "OPENMW_CONFIG_USING_FLATPAK",
            "OPENMW_FLATPAK_ID",
            "FLATPAK_ID",
        ]);
        let _ = try_default_local_path();
        restore_env(snapshot);
    }

    #[test]
    #[cfg(target_os = "linux")]
    fn test_flatpak_env_flag_forces_flatpak_paths() {
        let _guard = ENV_LOCK.lock().expect("env lock poisoned");
        let Ok(home) = platform_paths::home_dir() else {
            return;
        };

        // SAFETY: guarded by a process-wide mutex in tests to prevent concurrent env mutation.
        unsafe {
            std::env::set_var("OPENMW_CONFIG_USING_FLATPAK", "bananas");
            std::env::remove_var("OPENMW_FLATPAK_ID");
            std::env::remove_var("FLATPAK_ID");
        }

        let cfg = try_default_config_path().expect("flatpak config path should resolve");
        let data = try_default_userdata_path().expect("flatpak userdata path should resolve");

        assert_eq!(
            cfg,
            home.join(".var")
                .join("app")
                .join(DEFAULT_FLATPAK_APP_ID)
                .join("config")
                .join("openmw")
        );
        assert_eq!(
            data,
            home.join(".var")
                .join("app")
                .join(DEFAULT_FLATPAK_APP_ID)
                .join("data")
                .join("openmw")
        );

        // SAFETY: guarded by a process-wide mutex in tests to prevent concurrent env mutation.
        unsafe {
            std::env::remove_var("OPENMW_CONFIG_USING_FLATPAK");
        }
    }

    #[test]
    #[cfg(target_os = "linux")]
    fn test_flatpak_app_id_override_precedence() {
        let _guard = ENV_LOCK.lock().expect("env lock poisoned");
        let Ok(home) = platform_paths::home_dir() else {
            return;
        };

        // SAFETY: guarded by a process-wide mutex in tests to prevent concurrent env mutation.
        unsafe {
            std::env::set_var("OPENMW_CONFIG_USING_FLATPAK", "enabled");
            std::env::set_var("OPENMW_FLATPAK_ID", "org.example.Override");
            std::env::set_var("FLATPAK_ID", "org.example.ShouldNotWin");
        }

        let cfg = try_default_config_path().expect("flatpak config path should resolve");
        assert_eq!(
            cfg,
            home.join(".var")
                .join("app")
                .join("org.example.Override")
                .join("config")
                .join("openmw")
        );

        // SAFETY: guarded by a process-wide mutex in tests to prevent concurrent env mutation.
        unsafe {
            std::env::remove_var("OPENMW_CONFIG_USING_FLATPAK");
            std::env::remove_var("OPENMW_FLATPAK_ID");
            std::env::remove_var("FLATPAK_ID");
        }
    }

    #[test]
    #[cfg(target_os = "linux")]
    fn test_flatpak_auto_detect_via_flatpak_id() {
        let _guard = ENV_LOCK.lock().expect("env lock poisoned");
        let Ok(home) = platform_paths::home_dir() else {
            return;
        };

        // SAFETY: guarded by a process-wide mutex in tests to prevent concurrent env mutation.
        unsafe {
            std::env::remove_var("OPENMW_CONFIG_USING_FLATPAK");
            std::env::remove_var("OPENMW_FLATPAK_ID");
            std::env::set_var("FLATPAK_ID", "org.example.AutoDetect");
        }

        let data = try_default_userdata_path().expect("flatpak userdata path should resolve");
        assert_eq!(
            data,
            home.join(".var")
                .join("app")
                .join("org.example.AutoDetect")
                .join("data")
                .join("openmw")
        );

        // SAFETY: guarded by a process-wide mutex in tests to prevent concurrent env mutation.
        unsafe {
            std::env::remove_var("FLATPAK_ID");
        }
    }

    #[test]
    fn test_global_path_env_override_has_precedence() {
        let _guard = ENV_LOCK.lock().expect("env lock poisoned");
        let expected = std::path::PathBuf::from("/opt/openmw/global");

        // SAFETY: guarded by a process-wide mutex in tests to prevent concurrent env mutation.
        unsafe {
            std::env::set_var("OPENMW_GLOBAL_PATH", expected.as_os_str());
        }

        assert_eq!(
            try_default_global_path().expect("global override should be used"),
            expected
        );

        // SAFETY: guarded by a process-wide mutex in tests to prevent concurrent env mutation.
        unsafe {
            std::env::remove_var("OPENMW_GLOBAL_PATH");
        }
    }

    #[test]
    #[cfg(not(windows))]
    fn test_global_path_default_is_platform_or_flatpak_value() {
        let _guard = ENV_LOCK.lock().expect("env lock poisoned");

        // SAFETY: guarded by a process-wide mutex in tests to prevent concurrent env mutation.
        unsafe {
            std::env::remove_var("OPENMW_GLOBAL_PATH");
            std::env::remove_var("OPENMW_CONFIG_USING_FLATPAK");
            std::env::remove_var("FLATPAK_ID");
        }

        if cfg!(target_os = "macos") {
            assert_eq!(
                try_default_global_path().expect("macOS global path should resolve"),
                std::path::PathBuf::from("/Library/Application Support")
            );
        } else if flatpak_mode_enabled() {
            assert_eq!(
                try_default_global_path().expect("flatpak global path should resolve"),
                std::path::PathBuf::from("/app/share/games")
            );
        } else {
            assert_eq!(
                try_default_global_path().expect("unix global path should resolve"),
                std::path::PathBuf::from("/usr/share/games")
            );
        }
    }

    #[test]
    #[cfg(windows)]
    fn test_global_path_is_unavailable_on_windows_without_override() {
        let _guard = ENV_LOCK.lock().expect("env lock poisoned");

        // SAFETY: guarded by a process-wide mutex in tests to prevent concurrent env mutation.
        unsafe {
            std::env::remove_var("OPENMW_GLOBAL_PATH");
            std::env::remove_var("OPENMW_CONFIG_USING_FLATPAK");
            std::env::remove_var("FLATPAK_ID");
        }

        assert!(matches!(
            try_default_global_path(),
            Err(ConfigError::PlatformPathUnavailable("global"))
        ));
    }

    #[test]
    #[cfg(not(target_os = "linux"))]
    fn test_flatpak_mode_is_ignored_off_linux() {
        let _guard = ENV_LOCK.lock().expect("env lock poisoned");

        // SAFETY: guarded by a process-wide mutex in tests to prevent concurrent env mutation.
        unsafe {
            std::env::set_var("OPENMW_CONFIG_USING_FLATPAK", "1");
            std::env::set_var("FLATPAK_ID", "org.example.Flatpak");
            std::env::remove_var("OPENMW_GLOBAL_PATH");
        }

        assert!(!flatpak_mode_enabled());

        assert_eq!(
            try_default_config_path().ok(),
            platform_paths::config_dir().ok()
        );
        assert_eq!(
            try_default_userdata_path().ok(),
            platform_paths::data_dir().ok()
        );

        if cfg!(windows) {
            assert!(matches!(
                try_default_global_path(),
                Err(ConfigError::PlatformPathUnavailable("global"))
            ));
        } else if cfg!(target_os = "macos") {
            assert_eq!(
                try_default_global_path().expect("macOS global path should resolve"),
                std::path::PathBuf::from("/Library/Application Support")
            );
        }

        // SAFETY: guarded by a process-wide mutex in tests to prevent concurrent env mutation.
        unsafe {
            std::env::remove_var("OPENMW_CONFIG_USING_FLATPAK");
            std::env::remove_var("FLATPAK_ID");
            std::env::remove_var("OPENMW_GLOBAL_PATH");
        }
    }
}