gpui-rhai 0.1.8

A Rhai-authored declarative UI runtime for GPUI
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
use std::collections::{BTreeMap, BTreeSet, btree_map::Entry};
use std::sync::{Arc, RwLock};

use thiserror::Error;

use super::{
    ChartDataset, ChartFormatSpec, ChartGeoPoint, ChartGeoProjection, ChartMark, ChartMarkGeometry,
    ChartPoint, ChartRect, ChartScale, ChartSeriesSpec, ChartTheme,
};

pub enum ChartCustomCoordinateContext<'a> {
    Cartesian {
        x: &'a ChartScale,
        y: &'a ChartScale,
    },
    Polar {
        center: ChartPoint,
        radius: f64,
        value_domain: (f64, f64),
    },
    Geo {
        projection: Option<&'a dyn ChartGeoProjection>,
        scale: (f64, f64, f64),
    },
}

impl ChartCustomCoordinateContext<'_> {
    #[must_use]
    pub fn project_geo(&self, longitude: f64, latitude: f64) -> Option<ChartPoint> {
        let Self::Geo { projection, scale } = self else {
            return None;
        };
        let point = projection.map_or(
            Some(ChartGeoPoint {
                x: longitude,
                y: latitude,
            }),
            |projection| projection.project(longitude, latitude),
        )?;
        Some(ChartPoint {
            x: point.x * scale.0 + scale.1,
            y: point.y * scale.0 + scale.2,
        })
    }
}

pub struct ChartCustomSeriesContext<'a> {
    pub spec: &'a ChartSeriesSpec,
    pub dataset: &'a ChartDataset,
    pub bounds: ChartRect,
    pub theme: &'a ChartTheme,
    pub x_scale: Option<&'a ChartScale>,
    pub y_scale: Option<&'a ChartScale>,
    pub coordinate: ChartCustomCoordinateContext<'a>,
}

/// Compile-time trusted Rust custom series extension.
///
/// Returned marks enter the same paint, hit-test, tooltip, semantic, motion,
/// Inspector, and export scene as built-in series.
pub trait HostChartSeries: Send + Sync {
    /// Produce validated public chart marks for one prepared series.
    ///
    /// # Errors
    ///
    /// Returns an application-facing diagnostic; the candidate scene is then
    /// rejected or reports the bounded series error.
    fn layout(&self, context: ChartCustomSeriesContext<'_>) -> Result<Vec<ChartMark>, String>;
}

#[derive(Clone, Default)]
pub struct ChartSeriesRegistry {
    inner: Arc<RwLock<BTreeMap<String, Arc<dyn HostChartSeries>>>>,
}

impl std::fmt::Debug for ChartSeriesRegistry {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let registered = self
            .inner
            .read()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .keys()
            .cloned()
            .collect::<Vec<_>>();
        formatter
            .debug_struct("ChartSeriesRegistry")
            .field("registered", &registered)
            .finish()
    }
}

impl ChartSeriesRegistry {
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Register a renderer under a stable compile-time ID.
    ///
    /// # Errors
    ///
    /// Returns for an unsafe or duplicate ID or a poisoned registry.
    pub fn register(
        &self,
        id: impl Into<String>,
        renderer: impl HostChartSeries + 'static,
    ) -> Result<(), ChartSeriesExtensionError> {
        let id = id.into();
        if !valid_identifier(&id) {
            return Err(ChartSeriesExtensionError::InvalidId(id));
        }
        let mut registry = self
            .inner
            .write()
            .map_err(|_| ChartSeriesExtensionError::Poisoned)?;
        match registry.entry(id.clone()) {
            Entry::Vacant(entry) => {
                entry.insert(Arc::new(renderer));
            }
            Entry::Occupied(_) => return Err(ChartSeriesExtensionError::Duplicate(id)),
        }
        Ok(())
    }

    pub(crate) fn layout(
        &self,
        id: &str,
        context: ChartCustomSeriesContext<'_>,
    ) -> Result<Vec<ChartMark>, ChartSeriesExtensionError> {
        let renderer = self
            .inner
            .read()
            .map_err(|_| ChartSeriesExtensionError::Poisoned)?
            .get(id)
            .cloned()
            .ok_or_else(|| ChartSeriesExtensionError::Unknown(id.to_owned()))?;
        let spec = context.spec.clone();
        let marks =
            renderer
                .layout(context)
                .map_err(|message| ChartSeriesExtensionError::Failed {
                    id: id.to_owned(),
                    message,
                })?;
        validate_custom_marks(&spec, &marks)?;
        Ok(marks)
    }

    #[cfg(feature = "dev-reload")]
    pub(crate) fn copy_from(&self, source: &Self) {
        let source = source
            .inner
            .read()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .clone();
        *self
            .inner
            .write()
            .unwrap_or_else(std::sync::PoisonError::into_inner) = source;
    }
}

fn validate_custom_marks(
    spec: &ChartSeriesSpec,
    marks: &[ChartMark],
) -> Result<(), ChartSeriesExtensionError> {
    if marks.len() > 100_000 {
        return Err(ChartSeriesExtensionError::InvalidMarks {
            series: spec.key.clone(),
            message: "more than 100000 marks".to_owned(),
        });
    }
    let mut keys = BTreeSet::new();
    for mark in marks {
        if mark.series_key != spec.key
            || mark.region_key != spec.coordinate
            || mark.key.is_empty()
            || mark.datum_key.is_empty()
            || (mark.role == super::ChartMarkRole::Data
                && mark.datum.as_ref().is_none_or(|datum| {
                    datum.series != spec.key
                        || datum.dataset != spec.dataset
                        || datum.key != mark.datum_key
                }))
            || !keys.insert(mark.key.clone())
            || !geometry_is_finite(&mark.geometry)
        {
            return Err(ChartSeriesExtensionError::InvalidMarks {
                series: spec.key.clone(),
                message: format!("invalid or duplicate mark `{}`", mark.key),
            });
        }
    }
    Ok(())
}

fn geometry_is_finite(geometry: &ChartMarkGeometry) -> bool {
    match geometry {
        ChartMarkGeometry::Rect(rect) => {
            rect.x.is_finite()
                && rect.y.is_finite()
                && rect.width.is_finite()
                && rect.height.is_finite()
                && rect.width >= 0.0
                && rect.height >= 0.0
        }
        ChartMarkGeometry::Circle { center, radius } => {
            center.x.is_finite() && center.y.is_finite() && radius.is_finite() && *radius >= 0.0
        }
        ChartMarkGeometry::Polyline { points, width } => {
            points.len() >= 2
                && width.is_finite()
                && *width > 0.0
                && points
                    .iter()
                    .all(|point| point.x.is_finite() && point.y.is_finite())
        }
        ChartMarkGeometry::Polygon(points) => {
            points.len() >= 3
                && points
                    .iter()
                    .all(|point| point.x.is_finite() && point.y.is_finite())
        }
        ChartMarkGeometry::CompoundPolygon(rings) => {
            !rings.is_empty()
                && rings.iter().all(|points| {
                    points.len() >= 3
                        && points
                            .iter()
                            .all(|point| point.x.is_finite() && point.y.is_finite())
                })
        }
    }
}

fn valid_identifier(value: &str) -> bool {
    !value.is_empty()
        && value.len() <= 128
        && value
            .chars()
            .next()
            .is_some_and(|character| character.is_ascii_alphabetic())
        && value
            .chars()
            .all(|character| character.is_ascii_alphanumeric() || character == '_')
}

#[derive(Debug, Error, Clone, PartialEq)]
pub enum ChartSeriesExtensionError {
    #[error("chart series renderer ID `{0}` must be a safe identifier")]
    InvalidId(String),
    #[error("chart series renderer `{0}` is already registered")]
    Duplicate(String),
    #[error("chart series renderer `{0}` is not registered")]
    Unknown(String),
    #[error("chart series renderer `{id}` failed: {message}")]
    Failed { id: String, message: String },
    #[error("chart series registry lock was poisoned")]
    Poisoned,
    #[error("custom chart series `{series}` returned invalid marks: {message}")]
    InvalidMarks { series: String, message: String },
}

/// Trusted Rust formatter for application-specific numeric conventions.
pub trait HostChartFormatter: Send + Sync {
    /// Format one finite value for a declared locale and format specification.
    ///
    /// # Errors
    ///
    /// Returns an application-facing diagnostic; the built-in label is kept.
    fn format(&self, value: f64, locale: &str, spec: &ChartFormatSpec) -> Result<String, String>;
}

#[derive(Clone, Default)]
pub struct ChartFormatterRegistry {
    inner: Arc<RwLock<BTreeMap<String, Arc<dyn HostChartFormatter>>>>,
}

impl std::fmt::Debug for ChartFormatterRegistry {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let registered = self
            .inner
            .read()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .keys()
            .cloned()
            .collect::<Vec<_>>();
        formatter
            .debug_struct("ChartFormatterRegistry")
            .field("registered", &registered)
            .finish()
    }
}

impl ChartFormatterRegistry {
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Register a formatter under a stable compile-time ID.
    ///
    /// # Errors
    ///
    /// Returns for an unsafe/duplicate ID or poisoned registry.
    pub fn register(
        &self,
        id: impl Into<String>,
        formatter: impl HostChartFormatter + 'static,
    ) -> Result<(), ChartFormatterError> {
        let id = id.into();
        if !valid_identifier(&id) {
            return Err(ChartFormatterError::InvalidId(id));
        }
        let mut registry = self
            .inner
            .write()
            .map_err(|_| ChartFormatterError::Poisoned)?;
        match registry.entry(id.clone()) {
            Entry::Vacant(entry) => {
                entry.insert(Arc::new(formatter));
            }
            Entry::Occupied(_) => return Err(ChartFormatterError::Duplicate(id)),
        }
        Ok(())
    }

    pub(crate) fn format(
        &self,
        id: &str,
        value: f64,
        locale: &str,
        spec: &ChartFormatSpec,
    ) -> Result<String, ChartFormatterError> {
        let handler = self
            .inner
            .read()
            .map_err(|_| ChartFormatterError::Poisoned)?
            .get(id)
            .cloned()
            .ok_or_else(|| ChartFormatterError::Unknown(id.to_owned()))?;
        let formatted =
            handler
                .format(value, locale, spec)
                .map_err(|message| ChartFormatterError::Failed {
                    id: id.to_owned(),
                    message,
                })?;
        if formatted.len() > 1_024 || formatted.contains('\n') || formatted.contains('\r') {
            return Err(ChartFormatterError::InvalidOutput(id.to_owned()));
        }
        Ok(formatted)
    }

    #[cfg(feature = "dev-reload")]
    pub(crate) fn copy_from(&self, source: &Self) {
        let source = source
            .inner
            .read()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .clone();
        *self
            .inner
            .write()
            .unwrap_or_else(std::sync::PoisonError::into_inner) = source;
    }
}

#[derive(Debug, Error, Clone, PartialEq)]
pub enum ChartFormatterError {
    #[error("chart formatter ID `{0}` must be a safe identifier")]
    InvalidId(String),
    #[error("chart formatter `{0}` is already registered")]
    Duplicate(String),
    #[error("chart formatter `{0}` is not registered")]
    Unknown(String),
    #[error("chart formatter `{id}` failed: {message}")]
    Failed { id: String, message: String },
    #[error("chart formatter registry lock was poisoned")]
    Poisoned,
    #[error("chart formatter `{0}` returned an overlong or multiline label")]
    InvalidOutput(String),
}

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

    struct CurrencyFormatter;

    impl HostChartFormatter for CurrencyFormatter {
        fn format(&self, value: f64, locale: &str, _: &ChartFormatSpec) -> Result<String, String> {
            Ok(format!("{locale}:{value:.2}"))
        }
    }

    #[test]
    fn host_formatter_registry_is_typed_and_duplicate_safe() {
        let registry = ChartFormatterRegistry::new();
        registry.register("currency", CurrencyFormatter).unwrap();
        assert_eq!(
            registry
                .format("currency", 12.5, "zh-CN", &ChartFormatSpec::default())
                .unwrap(),
            "zh-CN:12.50"
        );
        assert!(matches!(
            registry.register("currency", CurrencyFormatter),
            Err(ChartFormatterError::Duplicate(_))
        ));
    }
}