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
//! Presentation style model shared by rendering adapters.

use bevy::{
    color::Alpha,
    prelude::{Color, Resource},
};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

/// Fully opaque alpha value in permille.
pub const OPAQUE_ALPHA_PERMILLE: u16 = 1_000;

/// Window compositor transparency mode.
#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum TransparencyMode {
    /// Request an opaque platform window.
    #[default]
    Opaque,
    /// Request a platform-transparent window.
    Transparent,
}

impl TransparencyMode {
    /// Returns whether this mode needs Bevy's transparent window flag.
    #[must_use]
    pub const fn is_window_transparent(self) -> bool {
        matches!(self, Self::Transparent)
    }
}

/// A bounded alpha channel represented as permille to keep config deterministic.
#[derive(Clone, Copy, Debug, Eq, JsonSchema, PartialEq)]
pub struct BoundedAlpha(u16);

impl BoundedAlpha {
    /// Creates a bounded alpha value.
    ///
    /// # Errors
    ///
    /// Returns [`StylePolicyError`] when `permille` is above 1000.
    pub const fn try_new(permille: u16) -> Result<Self, StylePolicyError> {
        if permille > OPAQUE_ALPHA_PERMILLE {
            return Err(StylePolicyError::AlphaOutOfRange { permille });
        }
        Ok(Self(permille))
    }

    /// Returns an opaque alpha value.
    #[must_use]
    pub const fn opaque() -> Self {
        Self(OPAQUE_ALPHA_PERMILLE)
    }

    /// Returns this alpha value as permille.
    #[must_use]
    pub const fn as_permille(self) -> u16 {
        self.0
    }

    /// Returns this alpha value as the `0.0..=1.0` Bevy channel.
    #[must_use]
    pub fn as_f32(self) -> f32 {
        f32::from(self.0) / f32::from(OPAQUE_ALPHA_PERMILLE)
    }
}

impl Default for BoundedAlpha {
    fn default() -> Self {
        Self::opaque()
    }
}

/// A UI or render surface that can receive resolved style.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum SurfaceRole {
    /// Main editor text.
    EditorText,
    /// Background behind the editor scene.
    EditorBackground,
    /// Cursor highlight cell.
    Cursor,
    /// Text rendered inside the cursor cell.
    CursorText,
    /// Visual selection highlight.
    Selection,
    /// Search match highlight.
    SearchMatch,
    /// Bottom status/chrome surface.
    StatusBar,
    /// Non-error status text.
    StatusText,
    /// Error status text.
    StatusErrorText,
}

/// Style for a single resolved presentation surface.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct SurfaceStyle {
    /// Tint applied by the adapter for this surface.
    pub tint: Color,
    /// Surface alpha.
    pub alpha: BoundedAlpha,
    /// Blur radius in logical pixels, reserved for future adapters.
    pub blur_px: u16,
}

impl SurfaceStyle {
    /// Creates a surface style with an opaque tint.
    #[must_use]
    pub const fn opaque(tint: Color) -> Self {
        Self {
            tint,
            alpha: BoundedAlpha::opaque(),
            blur_px: 0,
        }
    }

    /// Returns this style's tint with its bounded alpha applied.
    #[must_use]
    pub fn color(self) -> Color {
        self.tint.with_alpha(self.alpha.as_f32())
    }
}

/// Host policy for dynamic style changes.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct StylePolicy {
    /// Lowest alpha a dynamic style proposal may set.
    pub minimum_alpha: BoundedAlpha,
    /// Highest blur a dynamic style proposal may set.
    pub maximum_blur_px: u16,
}

impl Default for StylePolicy {
    fn default() -> Self {
        Self {
            minimum_alpha: BoundedAlpha(250),
            maximum_blur_px: 48,
        }
    }
}

/// A validated dynamic style proposal.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct SurfaceStyleProposal {
    /// Target surface role.
    pub role: SurfaceRole,
    /// Proposed style.
    pub style: SurfaceStyle,
}

/// Style proposal validation failure.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum StylePolicyError {
    /// Alpha was outside the supported `0..=1000` range.
    AlphaOutOfRange {
        /// Rejected alpha permille.
        permille: u16,
    },
    /// Proposed alpha is below the host minimum.
    AlphaBelowMinimum {
        /// Proposed alpha permille.
        permille: u16,
        /// Minimum accepted alpha permille.
        minimum: u16,
    },
    /// Proposed blur exceeded host policy.
    BlurTooLarge {
        /// Proposed blur radius.
        blur_px: u16,
        /// Maximum accepted blur radius.
        maximum: u16,
    },
}

/// Resolved theme consumed by Bevy and haalka adapters.
#[derive(Clone, Debug, PartialEq, Resource)]
pub struct ResolvedTheme {
    /// Window compositor transparency mode.
    pub transparency_mode: TransparencyMode,
    /// Main editor text surface.
    pub editor_text: SurfaceStyle,
    /// Editor background surface.
    pub editor_background: SurfaceStyle,
    /// Cursor cell surface.
    pub cursor: SurfaceStyle,
    /// Text inside cursor cell.
    pub cursor_text: SurfaceStyle,
    /// Visual selection surface.
    pub selection: SurfaceStyle,
    /// Search match surface.
    pub search_match: SurfaceStyle,
    /// Status bar background.
    pub status_bar: SurfaceStyle,
    /// Status line text.
    pub status_text: SurfaceStyle,
    /// Status line error text.
    pub status_error_text: SurfaceStyle,
}

impl ResolvedTheme {
    /// Resolves Alma's default opaque theme.
    #[must_use]
    pub const fn default_opaque() -> Self {
        Self {
            transparency_mode: TransparencyMode::Opaque,
            editor_text: SurfaceStyle::opaque(Color::srgb(0.610_009_9, 0.759_212_6, 0.763_073_15)),
            editor_background: SurfaceStyle::opaque(Color::srgb_u8(0x00, 0x1E, 0x27)),
            cursor: SurfaceStyle::opaque(Color::srgb(0.954_751_13, 0.293_346_46, 0.0)),
            cursor_text: SurfaceStyle::opaque(Color::srgb(0.0, 0.155_759_26, 0.193_701_39)),
            selection: SurfaceStyle::opaque(Color::srgb(0.049_706_57, 0.355_832_28, 0.392_785_07)),
            search_match: SurfaceStyle::opaque(Color::srgb(0.38, 0.30, 0.04)),
            status_bar: SurfaceStyle::opaque(Color::srgb(0.0, 0.12, 0.15)),
            status_text: SurfaceStyle::opaque(Color::srgb_u8(0xD8, 0xF3, 0xF8)),
            status_error_text: SurfaceStyle::opaque(Color::srgb_u8(0xff, 0x66, 0x66)),
        }
    }

    /// Returns the style for one role.
    #[must_use]
    pub const fn surface(&self, role: SurfaceRole) -> SurfaceStyle {
        match role {
            SurfaceRole::EditorText => self.editor_text,
            SurfaceRole::EditorBackground => self.editor_background,
            SurfaceRole::Cursor => self.cursor,
            SurfaceRole::CursorText => self.cursor_text,
            SurfaceRole::Selection => self.selection,
            SurfaceRole::SearchMatch => self.search_match,
            SurfaceRole::StatusBar => self.status_bar,
            SurfaceRole::StatusText => self.status_text,
            SurfaceRole::StatusErrorText => self.status_error_text,
        }
    }

    /// Returns a copy with a different compositor transparency mode.
    #[must_use]
    pub const fn with_transparency_mode(mut self, transparency_mode: TransparencyMode) -> Self {
        self.transparency_mode = transparency_mode;
        self
    }

    /// Applies a host-validated dynamic style proposal.
    ///
    /// # Errors
    ///
    /// Returns [`StylePolicyError`] without mutating the theme when the proposal violates policy.
    pub fn apply_proposal(
        &mut self,
        proposal: SurfaceStyleProposal,
        policy: StylePolicy,
    ) -> Result<(), StylePolicyError> {
        validate_style(proposal.style, policy)?;
        match proposal.role {
            SurfaceRole::EditorText => self.editor_text = proposal.style,
            SurfaceRole::EditorBackground => self.editor_background = proposal.style,
            SurfaceRole::Cursor => self.cursor = proposal.style,
            SurfaceRole::CursorText => self.cursor_text = proposal.style,
            SurfaceRole::Selection => self.selection = proposal.style,
            SurfaceRole::SearchMatch => self.search_match = proposal.style,
            SurfaceRole::StatusBar => self.status_bar = proposal.style,
            SurfaceRole::StatusText => self.status_text = proposal.style,
            SurfaceRole::StatusErrorText => self.status_error_text = proposal.style,
        }
        Ok(())
    }
}

impl Default for ResolvedTheme {
    fn default() -> Self {
        Self::default_opaque()
    }
}

/// Validates one dynamic surface style against host policy.
const fn validate_style(style: SurfaceStyle, policy: StylePolicy) -> Result<(), StylePolicyError> {
    if style.alpha.as_permille() < policy.minimum_alpha.as_permille() {
        return Err(StylePolicyError::AlphaBelowMinimum {
            permille: style.alpha.as_permille(),
            minimum: policy.minimum_alpha.as_permille(),
        });
    }
    if style.blur_px > policy.maximum_blur_px {
        return Err(StylePolicyError::BlurTooLarge {
            blur_px: style.blur_px,
            maximum: policy.maximum_blur_px,
        });
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::{
        BoundedAlpha, ResolvedTheme, StylePolicy, StylePolicyError, SurfaceRole, SurfaceStyle,
        SurfaceStyleProposal, TransparencyMode,
    };
    use bevy::prelude::Color;
    use proptest::prelude::*;

    #[test]
    fn default_theme_preserves_current_opaque_surfaces() {
        let theme = ResolvedTheme::default();

        assert_eq!(theme.transparency_mode, TransparencyMode::Opaque);
        assert_eq!(
            theme.editor_text.color(),
            Color::srgb(0.610_009_9, 0.759_212_6, 0.763_073_15)
        );
        assert_eq!(theme.status_bar.color(), Color::srgb(0.0, 0.12, 0.15));
        assert_eq!(
            theme.cursor.color(),
            Color::srgb(0.954_751_13, 0.293_346_46, 0.0)
        );
    }

    #[test]
    fn surface_alpha_resolves_deterministically_by_role() {
        let theme = ResolvedTheme::default();

        for role in [
            SurfaceRole::EditorText,
            SurfaceRole::EditorBackground,
            SurfaceRole::Cursor,
            SurfaceRole::CursorText,
            SurfaceRole::Selection,
            SurfaceRole::SearchMatch,
            SurfaceRole::StatusBar,
            SurfaceRole::StatusText,
            SurfaceRole::StatusErrorText,
        ] {
            assert_eq!(theme.surface(role).alpha, BoundedAlpha::opaque());
        }
    }

    #[test]
    fn invalid_style_proposal_leaves_theme_unchanged() {
        let mut theme = ResolvedTheme::default();
        let before = theme.clone();
        let proposal = SurfaceStyleProposal {
            role: SurfaceRole::StatusBar,
            style: SurfaceStyle {
                tint: Color::srgb(1.0, 1.0, 1.0),
                alpha: BoundedAlpha::try_new(100).expect("alpha is structurally valid"),
                blur_px: 0,
            },
        };

        let error = theme
            .apply_proposal(proposal, StylePolicy::default())
            .expect_err("proposal below policy minimum should fail");

        assert_eq!(
            error,
            StylePolicyError::AlphaBelowMinimum {
                permille: 100,
                minimum: 250,
            }
        );
        assert_eq!(theme, before);
    }

    fn surface_role_strategy() -> impl Strategy<Value = SurfaceRole> {
        prop::sample::select(vec![
            SurfaceRole::EditorText,
            SurfaceRole::EditorBackground,
            SurfaceRole::Cursor,
            SurfaceRole::CursorText,
            SurfaceRole::Selection,
            SurfaceRole::SearchMatch,
            SurfaceRole::StatusBar,
            SurfaceRole::StatusText,
            SurfaceRole::StatusErrorText,
        ])
    }

    fn bounded_alpha_strategy() -> impl Strategy<Value = BoundedAlpha> {
        (0_u16..=1_000_u16)
            .prop_map(|permille| BoundedAlpha::try_new(permille).expect("generated alpha is valid"))
    }

    fn color_strategy() -> impl Strategy<Value = Color> {
        (0_u8..=255, 0_u8..=255, 0_u8..=255)
            .prop_map(|(red, green, blue)| Color::srgb_u8(red, green, blue))
    }

    fn surface_style_strategy() -> impl Strategy<Value = SurfaceStyle> {
        (color_strategy(), bounded_alpha_strategy(), 0_u16..=96_u16).prop_map(
            |(tint, alpha, blur_px)| SurfaceStyle {
                tint,
                alpha,
                blur_px,
            },
        )
    }

    proptest! {
        #[test]
        fn bounded_alpha_accepts_only_permille_range(permille in any::<u16>()) {
            let result = BoundedAlpha::try_new(permille);

            if permille <= 1_000 {
                prop_assert_eq!(
                    result.expect("alpha in range should validate").as_permille(),
                    permille
                );
            } else {
                prop_assert_eq!(
                    result,
                    Err(StylePolicyError::AlphaOutOfRange { permille })
                );
            }
        }

        #[test]
        fn bounded_alpha_f32_projection_stays_in_unit_interval(alpha in bounded_alpha_strategy()) {
            let value = alpha.as_f32();

            prop_assert!((0.0..=1.0).contains(&value));
            prop_assert_eq!(alpha, BoundedAlpha::try_new(alpha.as_permille()).expect("round trip should validate"));
        }

        #[test]
        fn accepted_style_proposal_changes_only_target_role(
            role in surface_role_strategy(),
            style in surface_style_strategy(),
        ) {
            let alpha = BoundedAlpha::try_new(style.alpha.as_permille().max(250))
                .expect("clamped alpha should be valid");
            let style = SurfaceStyle { alpha, blur_px: style.blur_px.min(48), ..style };
            let mut theme = ResolvedTheme::default();
            let before = theme.clone();

            theme.apply_proposal(
                SurfaceStyleProposal { role, style },
                StylePolicy::default(),
            )
            .expect("policy-compliant proposal should apply");

            for candidate in [
                SurfaceRole::EditorText,
                SurfaceRole::EditorBackground,
                SurfaceRole::Cursor,
                SurfaceRole::CursorText,
                SurfaceRole::Selection,
                SurfaceRole::SearchMatch,
                SurfaceRole::StatusBar,
                SurfaceRole::StatusText,
                SurfaceRole::StatusErrorText,
            ] {
                if candidate == role {
                    prop_assert_eq!(theme.surface(candidate), style);
                } else {
                    prop_assert_eq!(theme.surface(candidate), before.surface(candidate));
                }
            }
        }

        #[test]
        fn rejected_style_proposal_never_mutates_theme(
            role in surface_role_strategy(),
            tint in color_strategy(),
            alpha_permille in 0_u16..250_u16,
            blur_px in 49_u16..=u16::MAX,
            reject_by_alpha in any::<bool>(),
        ) {
            let mut theme = ResolvedTheme::default();
            let before = theme.clone();
            let style = SurfaceStyle {
                tint,
                alpha: if reject_by_alpha {
                    BoundedAlpha::try_new(alpha_permille).expect("generated alpha is valid")
                } else {
                    BoundedAlpha::opaque()
                },
                blur_px: if reject_by_alpha { 0 } else { blur_px },
            };

            let rejected = theme.apply_proposal(
                SurfaceStyleProposal { role, style },
                StylePolicy::default(),
            ).is_err();

            prop_assert!(rejected);
            prop_assert_eq!(theme, before);
        }

        #[test]
        fn transparency_mode_maps_directly_to_window_flag(mode in prop::sample::select(vec![
            TransparencyMode::Opaque,
            TransparencyMode::Transparent,
        ])) {
            prop_assert_eq!(
                mode.is_window_transparent(),
                matches!(mode, TransparencyMode::Transparent)
            );
        }
    }
}