alma 0.1.1

A Bevy-native modal text editor with Vim-style navigation.
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
//! Typed application configuration and schema validation.

mod error;

use crate::{
    fs_utils::{DEFAULT_MAX_FILE_BYTES, FilesystemConfig},
    plugin::{PluginRegistryConfig, ValidatedPluginRegistry},
    presentation::{ResolvedTheme, TransparencyMode},
    vim::{
        LeaderConfig, VimConfig,
        config::{KeymapSet, MotionConfig, VimOptions},
    },
};
use bevy::prelude::Resource;
use schemars::{JsonSchema, schema_for};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::{
    env,
    path::{Path, PathBuf},
};

pub use error::{ConfigLoadError, ConfigProjectionError};

/// Environment variable that points at an explicit Alma JSON config file.
pub const CONFIG_ENV_VAR: &str = "ALMA_CONFIG";

/// Workspace-local config path used when present.
pub const WORKSPACE_CONFIG_PATH: &str = ".alma/config.json";

/// Root application configuration.
#[derive(Clone, Debug, Default, Deserialize, Eq, JsonSchema, PartialEq, Resource, Serialize)]
#[serde(default, deny_unknown_fields)]
pub struct AppConfig {
    /// Window and presentation configuration.
    pub window: WindowConfig,
    /// Filesystem policy configuration.
    pub filesystem: AppFilesystemConfig,
    /// Vim subsystem configuration.
    pub vim: AppVimConfig,
    /// Wasm plugin registry configuration.
    #[serde(rename = "plugins")]
    plugin_registry: PluginRegistryConfig,
    /// Validated Wasm plugin registry for runtime consumers.
    #[serde(skip)]
    #[schemars(skip)]
    plugins: ValidatedPluginRegistry,
}

impl AppConfig {
    /// Loads user configuration when available, otherwise returns typed defaults.
    ///
    /// # Errors
    ///
    /// Returns [`ConfigLoadError`] when an explicit or discovered config exists but cannot be
    /// read, parsed, validated, or deserialized.
    pub fn load_or_default() -> Result<Self, ConfigLoadError> {
        let current_dir =
            env::current_dir().map_err(|source| ConfigLoadError::CurrentDir { source })?;
        Self::load_or_default_from(&current_dir)
    }

    /// Loads config using `current_dir` as the workspace-local search root.
    ///
    /// # Errors
    ///
    /// Returns [`ConfigLoadError`] when config loading fails.
    pub fn load_or_default_from(current_dir: &Path) -> Result<Self, ConfigLoadError> {
        if let Some(path) = env::var_os(CONFIG_ENV_VAR).map(PathBuf::from) {
            return Self::load_path(&path);
        }

        let workspace_path = current_dir.join(WORKSPACE_CONFIG_PATH);
        if workspace_path.exists() {
            return Self::load_path(&workspace_path);
        }

        Ok(Self::default())
    }

    /// Loads config from an explicit JSON path.
    ///
    /// # Errors
    ///
    /// Returns [`ConfigLoadError`] when the file cannot be loaded as valid Alma config.
    pub fn load_path(path: &Path) -> Result<Self, ConfigLoadError> {
        let bytes = std::fs::read(path).map_err(|source| ConfigLoadError::Read {
            path: path.to_owned(),
            source,
        })?;
        Self::from_json_slice(&bytes, path)
    }

    /// Parses, schema-validates, and deserializes a JSON config document.
    ///
    /// # Errors
    ///
    /// Returns [`ConfigLoadError`] when JSON parsing, schema validation, or deserialization fails.
    pub fn from_json_slice(bytes: &[u8], path: &Path) -> Result<Self, ConfigLoadError> {
        let value =
            serde_json::from_slice::<Value>(bytes).map_err(|source| ConfigLoadError::Parse {
                path: path.to_owned(),
                source,
            })?;
        validate_config_value(&value, path)?;
        let mut config = serde_json::from_value::<Self>(value).map_err(|source| {
            ConfigLoadError::Deserialize {
                path: path.to_owned(),
                source,
            }
        })?;
        config.plugins = config.plugin_registry.validate().map_err(|source| {
            ConfigLoadError::PluginRegistry {
                path: path.to_owned(),
                source,
            }
        })?;
        Ok(config)
    }

    /// Returns Alma's generated JSON Schema.
    #[must_use]
    ///
    /// # Panics
    ///
    /// Panics only if schemars produces a schema value that cannot be represented as JSON.
    pub fn json_schema() -> Value {
        serde_json::to_value(schema_for!(Self)).expect("generated config schema is JSON")
    }

    /// Projects app config into filesystem runtime config.
    ///
    /// # Errors
    ///
    /// Returns [`ConfigProjectionError`] when the configured workspace root is invalid.
    pub fn filesystem_config(&self) -> Result<FilesystemConfig, ConfigProjectionError> {
        self.filesystem.to_filesystem_config()
    }

    /// Returns the validated plugin registry runtime code should consume.
    #[must_use]
    pub const fn plugins(&self) -> &ValidatedPluginRegistry {
        &self.plugins
    }
}

/// Window and presentation configuration.
#[derive(Clone, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
#[serde(default, deny_unknown_fields)]
pub struct WindowConfig {
    /// Fullscreen/windowing strategy.
    pub fullscreen_mode: FullscreenMode,
    /// Platform compositor transparency strategy.
    pub transparency_mode: TransparencyMode,
}

impl Default for WindowConfig {
    fn default() -> Self {
        Self {
            fullscreen_mode: FullscreenMode::BorderlessWindowedFullscreen,
            transparency_mode: TransparencyMode::Opaque,
        }
    }
}

impl WindowConfig {
    /// Projects window presentation settings into a resolved theme.
    #[must_use]
    pub fn resolved_theme(&self) -> ResolvedTheme {
        ResolvedTheme::default().with_transparency_mode(self.transparency_mode)
    }
}

/// Fullscreen/windowing strategies supported by Alma.
#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum FullscreenMode {
    /// Use the platform-native fullscreen behavior.
    NativeFullscreen,
    /// Use an undecorated window sized to the primary monitor.
    #[default]
    BorderlessWindowedFullscreen,
}

/// Filesystem policy configuration supplied by app config.
#[derive(Clone, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
#[serde(default, deny_unknown_fields)]
pub struct AppFilesystemConfig {
    /// Trusted root under which file-backed buffers may be opened or written.
    pub workspace_root: Option<PathBuf>,
    /// Maximum number of bytes accepted when reading a file into a buffer.
    pub max_file_bytes: u64,
}

impl AppFilesystemConfig {
    /// Projects into filesystem runtime config.
    ///
    /// # Errors
    ///
    /// Returns [`ConfigProjectionError`] when workspace root discovery or validation fails.
    pub fn to_filesystem_config(&self) -> Result<FilesystemConfig, ConfigProjectionError> {
        let mut config = self
            .workspace_root
            .as_ref()
            .map_or_else(
                FilesystemConfig::discover,
                FilesystemConfig::from_workspace_root,
            )
            .map_err(ConfigProjectionError::Filesystem)?;
        config.max_file_bytes = self.max_file_bytes;
        Ok(config)
    }
}

impl Default for AppFilesystemConfig {
    fn default() -> Self {
        Self {
            workspace_root: None,
            max_file_bytes: DEFAULT_MAX_FILE_BYTES,
        }
    }
}

/// Vim subsystem configuration supplied by app config.
#[derive(Clone, Debug, Default, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
#[serde(default, deny_unknown_fields)]
pub struct AppVimConfig {
    /// User-visible Vim options.
    pub options: AppVimOptions,
}

impl From<AppVimConfig> for VimConfig {
    fn from(config: AppVimConfig) -> Self {
        Self {
            keymaps: KeymapSet::default(),
            options: config.options.into(),
            motions: MotionConfig::default(),
            leader: LeaderConfig::default(),
        }
    }
}

/// User-visible Vim options supplied by app config.
#[derive(Clone, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
#[serde(default, deny_unknown_fields)]
pub struct AppVimOptions {
    /// Ignore case while searching.
    pub ignore_case: bool,
    /// Re-enable case-sensitive search when the pattern contains uppercase characters.
    pub smart_case: bool,
    /// Wrap searches around file edges.
    pub wrap_scan: bool,
    /// Mapping timeout in milliseconds.
    pub timeout_len_ms: u64,
}

impl Default for AppVimOptions {
    fn default() -> Self {
        let defaults = VimOptions::default();
        Self {
            ignore_case: defaults.ignore_case,
            smart_case: defaults.smart_case,
            wrap_scan: defaults.wrap_scan,
            timeout_len_ms: defaults.timeout_len_ms,
        }
    }
}

impl From<AppVimOptions> for VimOptions {
    fn from(options: AppVimOptions) -> Self {
        Self {
            ignore_case: options.ignore_case,
            smart_case: options.smart_case,
            wrap_scan: options.wrap_scan,
            timeout_len_ms: options.timeout_len_ms,
        }
    }
}

/// Validates parsed JSON against the generated app config schema.
fn validate_config_value(value: &Value, path: &Path) -> Result<(), ConfigLoadError> {
    let schema = AppConfig::json_schema();
    let validator =
        jsonschema::validator_for(&schema).map_err(|error| ConfigLoadError::SchemaCompile {
            message: error.to_string(),
        })?;

    if let Err(error) = validator.validate(value) {
        return Err(ConfigLoadError::Schema {
            path: path.to_owned(),
            message: error.to_string(),
        });
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::{AppConfig, ConfigLoadError, FullscreenMode, WORKSPACE_CONFIG_PATH};
    use crate::{
        fs_utils::DEFAULT_MAX_FILE_BYTES, plugin::PluginIdentity, presentation::TransparencyMode,
        vim::VimConfig,
    };
    use proptest::prelude::*;
    use serde_json::json;
    use std::{error::Error as _, path::Path};

    #[test]
    fn default_config_projects_to_current_runtime_defaults() {
        let config = AppConfig::default();
        let vim_config = VimConfig::from(config.vim.clone());

        assert_eq!(
            config.window.fullscreen_mode,
            FullscreenMode::BorderlessWindowedFullscreen
        );
        assert_eq!(config.window.transparency_mode, TransparencyMode::Opaque);
        assert_eq!(config.filesystem.max_file_bytes, DEFAULT_MAX_FILE_BYTES);
        assert_eq!(vim_config.options, VimConfig::default().options);
    }

    #[test]
    fn checked_in_config_matches_typed_defaults() {
        let config = AppConfig::from_json_slice(
            include_bytes!("../../.alma/config.json"),
            Path::new(".alma/config.json"),
        )
        .expect("checked-in config should be valid");

        assert_eq!(config, AppConfig::default());
    }

    #[test]
    fn generated_schema_contains_root_sections() {
        let schema = AppConfig::json_schema();

        assert!(schema.pointer("/properties/window").is_some());
        assert!(schema.pointer("/properties/filesystem").is_some());
        assert!(schema.pointer("/properties/vim").is_some());
        assert!(schema.pointer("/properties/plugins").is_some());
    }

    #[test]
    fn unknown_fields_are_rejected_by_schema_validation() {
        let error = AppConfig::from_json_slice(br#"{"unknown": true}"#, Path::new("config.json"))
            .expect_err("unknown root field should fail");

        assert!(matches!(error, ConfigLoadError::Schema { .. }));
    }

    #[test]
    fn invalid_enum_values_are_rejected_by_schema_validation() {
        let error = AppConfig::from_json_slice(
            br#"{"window": {"fullscreen_mode": "not_fullscreen"}}"#,
            Path::new("config.json"),
        )
        .expect_err("invalid enum should fail");

        assert!(matches!(error, ConfigLoadError::Schema { .. }));
    }

    #[test]
    fn malformed_json_preserves_parse_source() {
        let error = AppConfig::from_json_slice(br#"{"window": "#, Path::new("config.json"))
            .expect_err("malformed JSON should fail");

        assert!(matches!(error, ConfigLoadError::Parse { .. }));
        assert!(error.source().is_some());
    }

    #[test]
    fn invalid_plugin_registry_fails_config_load() {
        let error = AppConfig::from_json_slice(
            br#"{"plugins": {"plugins": [{"identity": "dup"}, {"identity": "dup"}]}}"#,
            Path::new("config.json"),
        )
        .expect_err("duplicate plugin identities should fail");

        assert!(matches!(error, ConfigLoadError::PluginRegistry { .. }));
        assert!(error.source().is_some());
    }

    #[test]
    fn config_exposes_validated_plugin_registry() {
        let config = AppConfig::from_json_slice(
            br#"{"plugins": {"plugins": [{"identity": "formatter", "enabled": true, "component_path": "plugins/formatter.wasm"}]}}"#,
            Path::new("config.json"),
        )
        .expect("valid plugin registry should load");

        assert!(config.plugins().plugin(&identity("formatter")).is_some());
        assert_eq!(config.plugins().enabled_plugins().count(), 1);
    }

    fn identity(identity: &str) -> PluginIdentity {
        PluginIdentity::try_new(identity).expect("test identity should validate")
    }

    #[test]
    fn explicit_unreadable_config_preserves_read_source() {
        let path =
            std::env::temp_dir().join(format!("alma-missing-config-{}.json", std::process::id()));
        let error = AppConfig::load_path(&path).expect_err("missing explicit config should fail");

        assert!(matches!(error, ConfigLoadError::Read { .. }));
        assert!(error.source().is_some());
    }

    #[test]
    fn invalid_workspace_root_fails_projection() {
        let config = AppConfig::from_json_slice(
            br#"{"filesystem": {"workspace_root": "/definitely/not/alma/workspace"}}"#,
            Path::new("config.json"),
        )
        .expect("schema-valid config should deserialize");

        assert!(config.filesystem_config().is_err());
    }

    #[test]
    fn missing_workspace_config_uses_defaults() {
        let temp = std::env::temp_dir().join(format!("alma-config-missing-{}", std::process::id()));
        std::fs::create_dir_all(&temp).expect("temp dir should be created");
        let config = AppConfig::load_or_default_from(&temp).expect("missing config should default");

        assert_eq!(config, AppConfig::default());
        assert!(!temp.join(WORKSPACE_CONFIG_PATH).exists());
        std::fs::remove_dir_all(temp).expect("temp dir should be removed");
    }

    proptest! {
        #[test]
        fn valid_config_json_round_trips_through_schema(
            fullscreen_mode in prop::sample::select(vec![
                "native_fullscreen",
                "borderless_windowed_fullscreen",
            ]),
            transparency_mode in prop::sample::select(vec![
                "opaque",
                "transparent",
            ]),
            ignore_case in any::<bool>(),
            smart_case in any::<bool>(),
            wrap_scan in any::<bool>(),
            timeout_len_ms in 0_u64..=10_000,
            max_file_bytes in 1_u64..=(64 * 1024 * 1024),
        ) {
            let value = json!({
                "window": {
                    "fullscreen_mode": fullscreen_mode,
                    "transparency_mode": transparency_mode,
                },
                "filesystem": {
                    "max_file_bytes": max_file_bytes,
                },
                "vim": {
                    "options": {
                        "ignore_case": ignore_case,
                        "smart_case": smart_case,
                        "wrap_scan": wrap_scan,
                        "timeout_len_ms": timeout_len_ms,
                    },
                },
            });
            let bytes = serde_json::to_vec(&value).expect("generated JSON should serialize");
            let config = AppConfig::from_json_slice(&bytes, Path::new("config.json"))
                .expect("generated config should validate");

            prop_assert_eq!(config.filesystem.max_file_bytes, max_file_bytes);
            prop_assert_eq!(config.vim.options.ignore_case, ignore_case);
            prop_assert_eq!(config.vim.options.smart_case, smart_case);
            prop_assert_eq!(config.vim.options.wrap_scan, wrap_scan);
            prop_assert_eq!(config.vim.options.timeout_len_ms, timeout_len_ms);
        }

        #[test]
        fn serialized_typed_config_round_trips(
            ignore_case in any::<bool>(),
            smart_case in any::<bool>(),
            wrap_scan in any::<bool>(),
            timeout_len_ms in 0_u64..=10_000,
            max_file_bytes in 1_u64..=(64 * 1024 * 1024),
            use_native_fullscreen in any::<bool>(),
            transparent_window in any::<bool>(),
        ) {
            let config = AppConfig {
                window: super::WindowConfig {
                    fullscreen_mode: if use_native_fullscreen {
                        FullscreenMode::NativeFullscreen
                    } else {
                        FullscreenMode::BorderlessWindowedFullscreen
                    },
                    transparency_mode: if transparent_window {
                        TransparencyMode::Transparent
                    } else {
                        TransparencyMode::Opaque
                    },
                },
                filesystem: super::AppFilesystemConfig {
                    workspace_root: None,
                    max_file_bytes,
                },
                vim: super::AppVimConfig {
                    options: super::AppVimOptions {
                        ignore_case,
                        smart_case,
                        wrap_scan,
                        timeout_len_ms,
                    },
                },
                plugin_registry: crate::plugin::PluginRegistryConfig::default(),
                plugins: crate::plugin::ValidatedPluginRegistry::default(),
            };
            let bytes = serde_json::to_vec(&config).expect("typed config should serialize");
            let round_trip = AppConfig::from_json_slice(&bytes, Path::new("config.json"))
                .expect("serialized typed config should validate");

            prop_assert_eq!(round_trip, config);
        }

        #[test]
        fn window_config_projects_transparency_into_resolved_theme(
            mode in prop::sample::select(vec![
                TransparencyMode::Opaque,
                TransparencyMode::Transparent,
            ]),
            use_native_fullscreen in any::<bool>(),
        ) {
            let window = super::WindowConfig {
                fullscreen_mode: if use_native_fullscreen {
                    FullscreenMode::NativeFullscreen
                } else {
                    FullscreenMode::BorderlessWindowedFullscreen
                },
                transparency_mode: mode,
            };

            prop_assert_eq!(window.resolved_theme().transparency_mode, mode);
        }

        #[test]
        fn unknown_root_fields_fail_schema_validation(
            unknown_key in "[a-z][a-z0-9_]{0,24}",
            value in any::<bool>(),
        ) {
            prop_assume!(unknown_key != "window");
            prop_assume!(unknown_key != "filesystem");
            prop_assume!(unknown_key != "vim");

            let value = json!({ unknown_key: value });
            let bytes = serde_json::to_vec(&value).expect("generated JSON should serialize");
            let error = AppConfig::from_json_slice(&bytes, Path::new("config.json"))
                .expect_err("unknown root key should fail schema validation");

            prop_assert!(
                matches!(error, ConfigLoadError::Schema { .. }),
                "unknown root key should produce schema error"
            );
        }

        #[test]
        fn unknown_nested_fields_fail_schema_validation(
            section in prop::sample::select(vec!["window", "filesystem", "vim"]),
            unknown_key in "[a-z][a-z0-9_]{0,24}",
            value in any::<u64>(),
        ) {
            let known_keys = match section {
                "window" => &["fullscreen_mode", "transparency_mode"][..],
                "filesystem" => &["workspace_root", "max_file_bytes"][..],
                "vim" => &["options"][..],
                _ => unreachable!("sampled section should be known"),
            };
            prop_assume!(!known_keys.contains(&unknown_key.as_str()));

            let value = json!({ section: { unknown_key: value } });
            let bytes = serde_json::to_vec(&value).expect("generated JSON should serialize");
            let error = AppConfig::from_json_slice(&bytes, Path::new("config.json"))
                .expect_err("unknown nested key should fail schema validation");

            prop_assert!(
                matches!(error, ConfigLoadError::Schema { .. }),
                "unknown nested key should produce schema error"
            );
        }
    }
}