@mun-ui/ui 0.0.0-stage → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (176) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +114 -2
  3. package/bin/compile.mjs +38 -0
  4. package/bin/desktop.mjs +143 -0
  5. package/bin/dev-protocol.mjs +94 -0
  6. package/bin/formatter.mjs +109 -0
  7. package/bin/hot-reload.mjs +38 -0
  8. package/bin/mun.mjs +538 -0
  9. package/bin/native.mjs +133 -0
  10. package/bin/pnpm-workspace.mjs +58 -0
  11. package/bin/program-patch.mjs +104 -0
  12. package/bin/project.mjs +322 -0
  13. package/bin/watch.mjs +316 -0
  14. package/bin/workflow.mjs +261 -0
  15. package/dist/astro.d.ts +3 -0
  16. package/dist/astro.d.ts.map +1 -0
  17. package/dist/astro.js +3 -0
  18. package/dist/astro.js.map +1 -0
  19. package/dist/closures.d.ts +2 -0
  20. package/dist/closures.d.ts.map +1 -0
  21. package/dist/closures.js +2 -0
  22. package/dist/closures.js.map +1 -0
  23. package/dist/compiler/index.d.ts +2 -0
  24. package/dist/compiler/index.d.ts.map +1 -0
  25. package/dist/compiler/index.js +2 -0
  26. package/dist/compiler/index.js.map +1 -0
  27. package/dist/core.d.ts +3 -0
  28. package/dist/core.d.ts.map +1 -0
  29. package/dist/core.js +3 -0
  30. package/dist/core.js.map +1 -0
  31. package/dist/experimental.d.ts +2 -0
  32. package/dist/experimental.d.ts.map +1 -0
  33. package/dist/experimental.js +2 -0
  34. package/dist/experimental.js.map +1 -0
  35. package/dist/index.d.ts +3 -0
  36. package/dist/index.d.ts.map +1 -0
  37. package/dist/index.js +3 -0
  38. package/dist/index.js.map +1 -0
  39. package/dist/jsx-dev-runtime.d.ts +2 -0
  40. package/dist/jsx-dev-runtime.d.ts.map +1 -0
  41. package/dist/jsx-dev-runtime.js +2 -0
  42. package/dist/jsx-dev-runtime.js.map +1 -0
  43. package/dist/jsx-runtime.d.ts +2 -0
  44. package/dist/jsx-runtime.d.ts.map +1 -0
  45. package/dist/jsx-runtime.js +2 -0
  46. package/dist/jsx-runtime.js.map +1 -0
  47. package/dist/legacy.d.ts +3 -0
  48. package/dist/legacy.d.ts.map +1 -0
  49. package/dist/legacy.js +3 -0
  50. package/dist/legacy.js.map +1 -0
  51. package/dist/mun.d.ts +5 -0
  52. package/dist/mun.d.ts.map +1 -0
  53. package/dist/mun.js +4 -0
  54. package/dist/mun.js.map +1 -0
  55. package/dist/progressive-blur/index.d.ts +8 -0
  56. package/dist/progressive-blur/index.d.ts.map +1 -0
  57. package/dist/progressive-blur/index.js +8 -0
  58. package/dist/progressive-blur/index.js.map +1 -0
  59. package/dist/progressive-blur/plan.d.ts +3 -0
  60. package/dist/progressive-blur/plan.d.ts.map +1 -0
  61. package/dist/progressive-blur/plan.js +3 -0
  62. package/dist/progressive-blur/plan.js.map +1 -0
  63. package/dist/react-types.d.ts +2 -0
  64. package/dist/react-types.d.ts.map +1 -0
  65. package/dist/react-types.js +2 -0
  66. package/dist/react-types.js.map +1 -0
  67. package/dist/rendering-quality.d.ts +4 -0
  68. package/dist/rendering-quality.d.ts.map +1 -0
  69. package/dist/rendering-quality.js +4 -0
  70. package/dist/rendering-quality.js.map +1 -0
  71. package/dist/state.d.ts +2 -0
  72. package/dist/state.d.ts.map +1 -0
  73. package/dist/state.js +2 -0
  74. package/dist/state.js.map +1 -0
  75. package/dist/types.d.ts +2 -0
  76. package/dist/types.d.ts.map +1 -0
  77. package/dist/types.js +2 -0
  78. package/dist/types.js.map +1 -0
  79. package/dist/vite.d.ts +2 -0
  80. package/dist/vite.d.ts.map +1 -0
  81. package/dist/vite.js +2 -0
  82. package/dist/vite.js.map +1 -0
  83. package/editors/install.mjs +102 -0
  84. package/editors/lsp/mun-lsp.mjs +123 -0
  85. package/editors/lsp/service.mjs +306 -0
  86. package/editors/lsp/source.mjs +58 -0
  87. package/editors/vscode/client.mjs +40 -0
  88. package/editors/vscode/dev-client.mjs +83 -0
  89. package/editors/vscode/discovery.mjs +46 -0
  90. package/editors/vscode/export.mjs +42 -0
  91. package/editors/vscode/extension.cjs +226 -0
  92. package/editors/vscode/language-configuration.json +15 -0
  93. package/editors/vscode/package.json +119 -0
  94. package/editors/vscode/protocol.mjs +29 -0
  95. package/editors/vscode/syntaxes/mun.tmLanguage.json +130 -0
  96. package/native/Cargo.lock +3581 -0
  97. package/native/Cargo.toml +21 -0
  98. package/native/README.md +21 -0
  99. package/native/mun-native/Cargo.toml +23 -0
  100. package/native/mun-native/src/accessibility.rs +738 -0
  101. package/native/mun-native/src/dev.rs +604 -0
  102. package/native/mun-native/src/host_services.rs +202 -0
  103. package/native/mun-native/src/lib.rs +2843 -0
  104. package/native/mun-native/src/main.rs +204 -0
  105. package/native/mun-native/src/offscreen.rs +393 -0
  106. package/native/mun-native/src/rect.wgsl +63 -0
  107. package/native/mun-native/src/text.rs +401 -0
  108. package/native/mun-native/tests/offscreen_rendering.rs +161 -0
  109. package/native/mun-native/tests/stress.rs +408 -0
  110. package/native/mun-native/tests/window_lifecycle.rs +183 -0
  111. package/native/mun-runtime/Cargo.toml +13 -0
  112. package/native/mun-runtime/src/accessibility.rs +193 -0
  113. package/native/mun-runtime/src/collection.rs +1090 -0
  114. package/native/mun-runtime/src/gesture.rs +1070 -0
  115. package/native/mun-runtime/src/input.rs +325 -0
  116. package/native/mun-runtime/src/ir.rs +852 -0
  117. package/native/mun-runtime/src/kinetics.rs +500 -0
  118. package/native/mun-runtime/src/layout.rs +258 -0
  119. package/native/mun-runtime/src/layout_cache.rs +209 -0
  120. package/native/mun-runtime/src/lib.rs +52 -0
  121. package/native/mun-runtime/src/motion.rs +1162 -0
  122. package/native/mun-runtime/src/retained.rs +574 -0
  123. package/native/mun-runtime/src/runtime.rs +7449 -0
  124. package/native/mun-runtime/src/scene.rs +567 -0
  125. package/native/mun-runtime/src/scroll.rs +521 -0
  126. package/native/mun-runtime/src/scroll_view.rs +220 -0
  127. package/native/mun-runtime/src/text_edit.rs +670 -0
  128. package/native/mun-runtime/src/timeline.rs +1534 -0
  129. package/native/mun-runtime/src/validate.rs +677 -0
  130. package/native/mun-runtime/tests/accessibility_semantics.rs +168 -0
  131. package/native/mun-runtime/tests/compiler_contract.rs +110 -0
  132. package/native/mun-runtime/tests/flexible_frames.rs +47 -0
  133. package/native/mun-runtime/tests/host_services.rs +107 -0
  134. package/native/mun-runtime/tests/hot_update.rs +367 -0
  135. package/native/mun-runtime/tests/incremental_runtime.rs +323 -0
  136. package/native/mun-runtime/tests/ir_validation.rs +167 -0
  137. package/native/mun-runtime/tests/keyed_collections.rs +251 -0
  138. package/native/mun-runtime/tests/minimum_window_size.rs +80 -0
  139. package/native/mun-runtime/tests/native_controls_style.rs +491 -0
  140. package/native/mun-runtime/tests/native_demo.rs +285 -0
  141. package/native/mun-runtime/tests/native_layout_style.rs +175 -0
  142. package/native/mun-runtime/tests/native_settings_pane.rs +152 -0
  143. package/native/mun-runtime/tests/priority_proposals.rs +69 -0
  144. package/native/mun-runtime/tests/scroll_view.rs +403 -0
  145. package/native/mun-runtime/tests/text_editing.rs +491 -0
  146. package/native/mun-runtime/tests/text_proposals.rs +42 -0
  147. package/native/mun-runtime/tests/typography.rs +63 -0
  148. package/package.json +213 -3
  149. package/schemas/README.md +19 -0
  150. package/schemas/semantic-ui-ir-v1.schema.json +2061 -0
  151. package/templates/desktop/gitignore +5 -0
  152. package/templates/desktop/package.json +10 -0
  153. package/templates/desktop/src-tauri/Cargo.toml +14 -0
  154. package/templates/desktop/src-tauri/build.rs +1 -0
  155. package/templates/desktop/src-tauri/capabilities/main.json +12 -0
  156. package/templates/desktop/src-tauri/icons/icon.icns +0 -0
  157. package/templates/desktop/src-tauri/icons/icon.ico +0 -0
  158. package/templates/desktop/src-tauri/icons/icon.png +0 -0
  159. package/templates/desktop/src-tauri/src/main.rs +2 -0
  160. package/templates/desktop/src-tauri/tauri.conf.json +42 -0
  161. package/templates/desktop/vite.config.ts +10 -0
  162. package/templates/native/App.mun +15 -0
  163. package/templates/native/gitignore +3 -0
  164. package/templates/native/mun.toml +8 -0
  165. package/templates/project/gitignore +5 -0
  166. package/templates/project/index.html +13 -0
  167. package/templates/project/package.json +24 -0
  168. package/templates/project/src/App.mun +13 -0
  169. package/templates/project/src/index.css +30 -0
  170. package/templates/project/src/main.ts +5 -0
  171. package/templates/project/tsconfig.json +20 -0
  172. package/templates/project/vite.config.ts +6 -0
  173. package/templates/vite/src/App.css +134 -0
  174. package/templates/vite/src/App.tsx +91 -0
  175. package/templates/vite/src/index.css +23 -0
  176. package/templates/vite/vite.config.ts +10 -0
@@ -0,0 +1,401 @@
1
+ //! Shaped text metrics shared by layout, editing geometry and rendering.
2
+ //!
3
+ //! One cosmic-text `FontSystem` serves both the runtime's measurement boundary
4
+ //! and glyphon realization, so caret stops, pointer mapping and drawn glyphs come
5
+ //! from the same shaping. This module exposes geometry only; editing state stays
6
+ //! in `mun-runtime`.
7
+ use std::{
8
+ cell::{Cell, RefCell, RefMut},
9
+ collections::HashMap,
10
+ };
11
+
12
+ use glyphon::{Attrs, Buffer, Family, FontSystem, Metrics, Shaping, Style, Weight, Wrap};
13
+ use mun_runtime::{IntrinsicMeasurer, IntrinsicSize, TextLineLayout, TextStyle, ir::UiFontDesign};
14
+ use unicode_segmentation::UnicodeSegmentation;
15
+
16
+ /// Line height factor shared with the renderer's glyphon buffers.
17
+ pub const LINE_HEIGHT_FACTOR: f32 = 1.25;
18
+ const TEXT_FONT_SIZE: f32 = 24.0;
19
+ const CONTROL_FONT_SIZE: f32 = 16.0;
20
+ /// Hard cap on lines shaped within one frame generation (memory safety net).
21
+ const LINE_CACHE_LIMIT: usize = 65_536;
22
+
23
+ /// cosmic-text attributes for a Mün text style (family, weight, slant).
24
+ pub fn styled_attrs(style: TextStyle) -> Attrs<'static> {
25
+ let family = match style.design {
26
+ UiFontDesign::Default | UiFontDesign::Rounded => Family::SansSerif,
27
+ UiFontDesign::Monospaced => Family::Monospace,
28
+ UiFontDesign::Serif => Family::Serif,
29
+ };
30
+ Attrs::new()
31
+ .family(family)
32
+ .weight(Weight(style.weight.clamp(1, 1000)))
33
+ .style(if style.italic {
34
+ Style::Italic
35
+ } else {
36
+ Style::Normal
37
+ })
38
+ }
39
+
40
+ /// Cache key of a text style: size bits, weight, slant and family.
41
+ type StyleKey = (u32, u16, bool, u8);
42
+
43
+ fn style_key(style: TextStyle) -> StyleKey {
44
+ (
45
+ style.size.to_bits(),
46
+ style.weight,
47
+ style.italic,
48
+ style.design as u8,
49
+ )
50
+ }
51
+
52
+ /// Shaped lines are memoized in two frame generations: a line used during
53
+ /// the current or previous frame stays cached, a line unused for a whole frame
54
+ /// is dropped at the next [`TextShaping::end_frame`]. The cache therefore
55
+ /// tracks the live text set however large it is, instead of thrashing once a
56
+ /// fixed capacity is exceeded.
57
+ pub struct TextShaping {
58
+ font_system: RefCell<FontSystem>,
59
+ lines: RefCell<LineCache>,
60
+ previous: RefCell<LineCache>,
61
+ shaped_lines: Cell<u64>,
62
+ }
63
+
64
+ /// Font size bits -> text -> shaped line. Keyed so that a hit is looked up by
65
+ /// `&str` without allocating.
66
+ #[derive(Default)]
67
+ struct LineCache {
68
+ sizes: HashMap<StyleKey, HashMap<String, TextLineLayout>>,
69
+ len: usize,
70
+ }
71
+
72
+ impl LineCache {
73
+ fn get(&self, text: &str, size: StyleKey) -> Option<&TextLineLayout> {
74
+ self.sizes.get(&size)?.get(text)
75
+ }
76
+
77
+ fn remove(&mut self, text: &str, size: StyleKey) -> Option<TextLineLayout> {
78
+ let line = self.sizes.get_mut(&size)?.remove(text)?;
79
+ self.len -= 1;
80
+ Some(line)
81
+ }
82
+
83
+ fn insert(&mut self, text: &str, size: StyleKey, line: TextLineLayout) {
84
+ if self
85
+ .sizes
86
+ .entry(size)
87
+ .or_default()
88
+ .insert(text.to_owned(), line)
89
+ .is_none()
90
+ {
91
+ self.len += 1;
92
+ }
93
+ }
94
+
95
+ fn clear(&mut self) {
96
+ self.sizes.clear();
97
+ self.len = 0;
98
+ }
99
+ }
100
+
101
+ impl TextShaping {
102
+ pub fn new(font_system: FontSystem) -> Self {
103
+ Self {
104
+ font_system: RefCell::new(font_system),
105
+ lines: RefCell::new(LineCache::default()),
106
+ previous: RefCell::new(LineCache::default()),
107
+ shaped_lines: Cell::new(0),
108
+ }
109
+ }
110
+
111
+ pub fn font_system(&self) -> RefMut<'_, FontSystem> {
112
+ self.font_system.borrow_mut()
113
+ }
114
+
115
+ /// Number of line shapings performed for measurement (cache misses).
116
+ pub fn shaped_line_count(&self) -> u64 {
117
+ self.shaped_lines.get()
118
+ }
119
+
120
+ pub fn cached_line_count(&self) -> usize {
121
+ self.lines.borrow().len + self.previous.borrow().len
122
+ }
123
+
124
+ /// Frame boundary: lines not used since the previous boundary are dropped.
125
+ pub fn end_frame(&self) {
126
+ let current = std::mem::take(&mut *self.lines.borrow_mut());
127
+ *self.previous.borrow_mut() = current;
128
+ }
129
+
130
+ fn shape_line(&self, text: &str, font_size: f32) -> TextLineLayout {
131
+ self.with_line(text, TextStyle::body(font_size), TextLineLayout::clone)
132
+ }
133
+
134
+ /// Borrow the (cached) shaped line without copying its caret stops.
135
+ fn with_line<R>(
136
+ &self,
137
+ text: &str,
138
+ style: TextStyle,
139
+ read: impl FnOnce(&TextLineLayout) -> R,
140
+ ) -> R {
141
+ let size = style_key(style);
142
+ if let Some(line) = self.lines.borrow().get(text, size) {
143
+ return read(line);
144
+ }
145
+ let line = match self.previous.borrow_mut().remove(text, size) {
146
+ Some(line) => line,
147
+ None => {
148
+ self.shaped_lines.set(self.shaped_lines.get() + 1);
149
+ shape_styled_line(&mut self.font_system.borrow_mut(), text, style)
150
+ }
151
+ };
152
+ let result = read(&line);
153
+ let mut lines = self.lines.borrow_mut();
154
+ if lines.len >= LINE_CACHE_LIMIT {
155
+ lines.clear();
156
+ }
157
+ lines.insert(text, size, line);
158
+ result
159
+ }
160
+ }
161
+
162
+ /// Shape one unwrapped line and derive a caret stop for every grapheme boundary.
163
+ ///
164
+ /// Glyph clusters come from cosmic-text (`start..end` UTF-8 ranges in logical
165
+ /// order, `x/w` in visual space, bidi level per glyph). A boundary at a cluster
166
+ /// start maps to the cluster's leading edge (left for LTR, right for RTL);
167
+ /// boundaries inside a multi-grapheme cluster (ligatures) are interpolated across
168
+ /// the cluster's graphemes; the end of text maps to the last cluster's trailing edge.
169
+ #[cfg(test)]
170
+ pub fn shape_line(font_system: &mut FontSystem, text: &str, font_size: f32) -> TextLineLayout {
171
+ shape_styled_line(font_system, text, TextStyle::body(font_size))
172
+ }
173
+
174
+ pub fn shape_styled_line(
175
+ font_system: &mut FontSystem,
176
+ text: &str,
177
+ style: TextStyle,
178
+ ) -> TextLineLayout {
179
+ let font_size = style.size;
180
+ let line_height = font_size * LINE_HEIGHT_FACTOR;
181
+ let mut buffer = Buffer::new(font_system, Metrics::new(font_size, line_height));
182
+ buffer.set_wrap(Wrap::None);
183
+ buffer.set_size(None, None);
184
+ buffer.set_text(text, &styled_attrs(style), Shaping::Advanced, None);
185
+ buffer.shape_until_scroll(font_system, false);
186
+
187
+ // Merge glyphs that share a cluster range (e.g. base + combining mark glyphs).
188
+ let mut clusters: Vec<(usize, usize, f32, f32, bool)> = Vec::new();
189
+ let mut cluster_index: HashMap<(usize, usize), usize> = HashMap::new();
190
+ let mut width = 0.0_f32;
191
+ for run in buffer.layout_runs() {
192
+ width = width.max(run.line_w);
193
+ for glyph in run.glyphs {
194
+ let (left, right) = (glyph.x, glyph.x + glyph.w);
195
+ match cluster_index.get(&(glyph.start, glyph.end)) {
196
+ Some(&index) => {
197
+ let cluster = &mut clusters[index];
198
+ cluster.2 = cluster.2.min(left);
199
+ cluster.3 = cluster.3.max(right);
200
+ }
201
+ None => {
202
+ cluster_index.insert((glyph.start, glyph.end), clusters.len());
203
+ clusters.push((glyph.start, glyph.end, left, right, glyph.level.is_rtl()));
204
+ }
205
+ }
206
+ }
207
+ }
208
+ clusters.sort_by_key(|cluster| cluster.0);
209
+
210
+ let mut carets = Vec::new();
211
+ let mut scalar = 0;
212
+ let mut byte = 0;
213
+ let mut previous_x = 0.0;
214
+ let mut boundaries = text
215
+ .grapheme_indices(true)
216
+ .map(|(index, _)| index)
217
+ .collect::<Vec<_>>();
218
+ boundaries.push(text.len());
219
+ for boundary in boundaries {
220
+ scalar += text[byte..boundary].chars().count();
221
+ byte = boundary;
222
+ let x = if boundary == text.len() {
223
+ clusters
224
+ .last()
225
+ .map(|cluster| if cluster.4 { cluster.2 } else { cluster.3 })
226
+ } else {
227
+ clusters
228
+ .iter()
229
+ .find(|cluster| cluster.0 <= boundary && boundary < cluster.1)
230
+ .map(|cluster| {
231
+ let cluster_text = &text[cluster.0..cluster.1];
232
+ let total = cluster_text.graphemes(true).count().max(1) as f32;
233
+ let before = text[cluster.0..boundary].graphemes(true).count() as f32;
234
+ let fraction = before / total;
235
+ if cluster.4 {
236
+ cluster.3 - fraction * (cluster.3 - cluster.2)
237
+ } else {
238
+ cluster.2 + fraction * (cluster.3 - cluster.2)
239
+ }
240
+ })
241
+ }
242
+ .unwrap_or(previous_x);
243
+ previous_x = x;
244
+ carets.push((scalar, x));
245
+ }
246
+ TextLineLayout {
247
+ carets,
248
+ width,
249
+ line_height,
250
+ }
251
+ }
252
+
253
+ impl IntrinsicMeasurer for TextShaping {
254
+ fn measure_text(&self, text: &str) -> IntrinsicSize {
255
+ self.measure_styled_text(text, TextStyle::body(TEXT_FONT_SIZE), None, None)
256
+ }
257
+
258
+ fn measure_text_for_width(&self, text: &str, available_width: Option<f32>) -> IntrinsicSize {
259
+ self.measure_styled_text(text, TextStyle::body(TEXT_FONT_SIZE), available_width, None)
260
+ }
261
+
262
+ fn measure_styled_text(
263
+ &self,
264
+ text: &str,
265
+ style: TextStyle,
266
+ available_width: Option<f32>,
267
+ line_limit: Option<usize>,
268
+ ) -> IntrinsicSize {
269
+ // 3pt top inset used by the retained scene plus the shaped line box.
270
+ let natural = self.with_line(text, style, |line| {
271
+ IntrinsicSize::new(line.width.ceil(), (line.line_height + 2.0).ceil())
272
+ });
273
+ let Some(width) = available_width.filter(|width| width.is_finite() && *width > 0.0) else {
274
+ return natural;
275
+ };
276
+ if width >= natural.width {
277
+ return natural;
278
+ }
279
+ // Use the same cosmic-text word/glyph breaks and line metrics as the
280
+ // drawing buffer. A one-line intrinsic height cannot size a narrow View.
281
+ let line_height = style.size * LINE_HEIGHT_FACTOR;
282
+ let mut fonts = self.font_system.borrow_mut();
283
+ let mut buffer = Buffer::new(&mut fonts, Metrics::new(style.size, line_height));
284
+ buffer.set_wrap(Wrap::WordOrGlyph);
285
+ buffer.set_size(Some(width), None);
286
+ buffer.set_text(text, &styled_attrs(style), Shaping::Advanced, None);
287
+ buffer.shape_until_scroll(&mut fonts, false);
288
+ let (line_width, line_count) = buffer
289
+ .layout_runs()
290
+ .fold((0.0_f32, 0usize), |(longest, count), line| {
291
+ (longest.max(line.line_w), count + 1)
292
+ });
293
+ let lines = match line_limit {
294
+ Some(limit) => line_count.clamp(1, limit.max(1)),
295
+ None => line_count.max(1),
296
+ };
297
+ IntrinsicSize::new(
298
+ line_width.min(width).ceil(),
299
+ (lines as f32 * line_height + 2.0).ceil(),
300
+ )
301
+ }
302
+
303
+ fn measure_action(&self, label: &str) -> IntrinsicSize {
304
+ self.with_line(label, TextStyle::body(CONTROL_FONT_SIZE), |line| {
305
+ IntrinsicSize::new((line.width + 34.0).ceil().max(92.0), 38.0)
306
+ })
307
+ }
308
+
309
+ fn measure_panel(&self) -> IntrinsicSize {
310
+ IntrinsicSize::new(160.0, 96.0)
311
+ }
312
+
313
+ fn text_line(&self, text: &str, font_size: f32) -> TextLineLayout {
314
+ self.shape_line(text, font_size)
315
+ }
316
+ }
317
+
318
+ #[cfg(test)]
319
+ mod tests {
320
+ use super::*;
321
+ use std::sync::{Mutex, OnceLock};
322
+
323
+ fn font_system() -> std::sync::MutexGuard<'static, FontSystem> {
324
+ static FONTS: OnceLock<Mutex<FontSystem>> = OnceLock::new();
325
+ FONTS
326
+ .get_or_init(|| Mutex::new(FontSystem::new()))
327
+ .lock()
328
+ .expect("font system")
329
+ }
330
+
331
+ fn assert_monotonic(line: &TextLineLayout, text: &str) {
332
+ let boundaries = mun_runtime::text_edit::grapheme_boundaries(text);
333
+ assert_eq!(
334
+ line.carets
335
+ .iter()
336
+ .map(|(offset, _)| *offset)
337
+ .collect::<Vec<_>>(),
338
+ boundaries,
339
+ "one caret stop per grapheme boundary for {text:?}"
340
+ );
341
+ for pair in line.carets.windows(2) {
342
+ assert!(
343
+ pair[1].1 >= pair[0].1,
344
+ "LTR stops advance for {text:?}: {line:?}"
345
+ );
346
+ }
347
+ assert!(
348
+ (line.carets.last().unwrap().1 - line.width).abs() < 0.5,
349
+ "{text:?}"
350
+ );
351
+ }
352
+
353
+ #[test]
354
+ fn constrained_text_measures_multiple_shaped_lines() {
355
+ let shaping = TextShaping::new(FontSystem::new());
356
+ let text = "A line of text that must wrap when the proposed width is small.";
357
+ let natural = shaping.measure_text(text);
358
+ let narrow = shaping.measure_text_for_width(text, Some(110.0));
359
+ assert!(narrow.width <= 110.0);
360
+ assert!(
361
+ narrow.height > natural.height,
362
+ "narrow text needs multiple lines"
363
+ );
364
+ assert_eq!(shaping.measure_text_for_width(text, None), natural);
365
+ }
366
+
367
+ #[test]
368
+ fn shaped_caret_stops_follow_real_glyph_advances() {
369
+ let mut fonts = font_system();
370
+ // Proportional shaping: "i" is narrower than "W" in any sans-serif face,
371
+ // so a uniform per-character estimate cannot satisfy this.
372
+ let line = shape_line(&mut fonts, "iW", 16.0);
373
+ assert_monotonic(&line, "iW");
374
+ let narrow = line.carets[1].1 - line.carets[0].1;
375
+ let wide = line.carets[2].1 - line.carets[1].1;
376
+ assert!(narrow < wide, "{line:?}");
377
+
378
+ for text in [
379
+ "한국어 Mixed 😀",
380
+ "e\u{301}a\u{308}",
381
+ "\u{1112}\u{1161}\u{11AB}\u{1100}\u{1173}\u{11AF}",
382
+ "👩‍👩‍👧‍👦👍🏽🇰🇷",
383
+ ] {
384
+ let line = shape_line(&mut fonts, text, 16.0);
385
+ assert_monotonic(&line, text);
386
+ }
387
+ let empty = shape_line(&mut fonts, "", 16.0);
388
+ assert_eq!(empty.carets, vec![(0, 0.0)]);
389
+ }
390
+
391
+ #[test]
392
+ fn measurement_cache_avoids_reshaping_identical_lines() {
393
+ let shaping = TextShaping::new(FontSystem::new());
394
+ let first = shaping.text_line("반복 shaping", 16.0);
395
+ let second = shaping.text_line("반복 shaping", 16.0);
396
+ assert_eq!(first, second);
397
+ assert_eq!(shaping.shaped_line_count(), 1);
398
+ shaping.text_line("반복 shaping", 18.0);
399
+ assert_eq!(shaping.shaped_line_count(), 2);
400
+ }
401
+ }
@@ -0,0 +1,161 @@
1
+ //! Pixel-level checks through the production wgpu/glyphon renderer.
2
+ use mun_native::OffscreenSession;
3
+ use mun_runtime::text_edit::{Composition, TextEdit};
4
+ use mun_runtime::{InputEvent, IntrinsicMeasurer};
5
+
6
+ const FIELD: &str = r##"{"version":1,"sourceLanguage":"mun","entry":"Pixels","states":[{"name":"name","initial":"한국어 text"}],"root":{"kind":"window","id":"window","title":"Pixels","child":{"kind":"column","id":"stack","layout":{"alignment":"leading","padding":10,"maxWidth":"infinity","maxHeight":"infinity"},"visual":{"background":"#101018"},"children":[{"kind":"textField","id":"field","state":"name","layout":{"width":{"kind":"literal","value":260},"height":{"kind":"literal","value":40}},"visual":{"background":"#202030"}}]}}}"##;
7
+
8
+ fn pixel(session: &OffscreenSession, rgba: &[u8], x: f32, y: f32, scale: f32) -> [u8; 4] {
9
+ let (width, _) = session.size();
10
+ let index = (((y * scale) as u32 * width + (x * scale) as u32) * 4) as usize;
11
+ [
12
+ rgba[index],
13
+ rgba[index + 1],
14
+ rgba[index + 2],
15
+ rgba[index + 3],
16
+ ]
17
+ }
18
+
19
+ fn rect(session: &OffscreenSession, id: &str) -> mun_runtime::Rect {
20
+ let frame = session.runtime().build_frame(320.0, 120.0).unwrap();
21
+ frame
22
+ .scene
23
+ .rects
24
+ .iter()
25
+ .find(|item| item.id == id)
26
+ .unwrap_or_else(|| panic!("scene rect {id}"))
27
+ .rect
28
+ }
29
+
30
+ #[test]
31
+ fn authored_srgb_colors_survive_srgb_render_targets() {
32
+ let mut session = OffscreenSession::new(FIELD, 320.0, 120.0, 2.0).unwrap();
33
+ session.render().unwrap();
34
+ let rgba = session.rgba().unwrap();
35
+ // #101018 container background, not a gamma-brightened value.
36
+ let [r, g, b, _] = pixel(&session, &rgba, 4.0, 100.0, 2.0);
37
+ assert!(
38
+ r.abs_diff(0x10) <= 2 && g.abs_diff(0x10) <= 2 && b.abs_diff(0x18) <= 2,
39
+ "{r} {g} {b}"
40
+ );
41
+ }
42
+
43
+ /// Field origin of `FIELD`'s text: 10pt stack padding + 12pt field inset.
44
+ const TEXT_ORIGIN_X: f32 = 22.0;
45
+
46
+ fn assert_close(actual: f32, expected: f32, what: &str) {
47
+ assert!(
48
+ (actual - expected).abs() < 0.01,
49
+ "{what}: {actual} != shaped {expected}"
50
+ );
51
+ }
52
+
53
+ /// Selection, caret and preedit geometry comes from the same shaping the
54
+ /// renderer draws with, and reaches the framebuffer there. Expectations are
55
+ /// derived from the session's own shaped lines, never from assumed font
56
+ /// metrics: which face covers Hangul (and so the glyph advances) differs per
57
+ /// system, e.g. a Linux image without a CJK font shapes `.notdef` boxes.
58
+ #[test]
59
+ fn caret_selection_and_preedit_reach_the_framebuffer_at_shaped_positions() {
60
+ let scale = 2.0;
61
+ let mut session = OffscreenSession::new(FIELD, 320.0, 120.0, scale).unwrap();
62
+ assert!(session.runtime_mut().focus_action("field"));
63
+ session
64
+ .input(InputEvent::TextEdit(TextEdit::Home { select: false }))
65
+ .unwrap();
66
+ for _ in 0..3 {
67
+ session
68
+ .input(InputEvent::TextEdit(TextEdit::Right { select: true }))
69
+ .unwrap();
70
+ }
71
+ session.render().unwrap();
72
+ let rgba = session.rgba().unwrap();
73
+ let line = session.shaped_line("한국어 text", 16.0);
74
+ // Real shaping, not the uniform per-grapheme headless model: proportional
75
+ // Latin advances differ whatever face is chosen.
76
+ assert_ne!(
77
+ line.carets,
78
+ mun_runtime::FallbackIntrinsicMeasurer
79
+ .text_line("한국어 text", 16.0)
80
+ .carets,
81
+ "the session measures with shaped glyph advances"
82
+ );
83
+ let selection = rect(&session, "field:selection");
84
+ assert_close(
85
+ selection.x,
86
+ TEXT_ORIGIN_X + line.x_for_offset(0),
87
+ "selection start",
88
+ );
89
+ assert_close(
90
+ selection.width,
91
+ line.x_for_offset(3) - line.x_for_offset(0),
92
+ "selection covers the three shaped syllables",
93
+ );
94
+ assert!(
95
+ selection.width > 0.0 && selection.width < 236.0,
96
+ "{selection:?}"
97
+ );
98
+ // Sample just below the glyph area inside the highlight: blue-tinted.
99
+ let [r, g, b, _] = pixel(
100
+ &session,
101
+ &rgba,
102
+ selection.x + 2.0,
103
+ selection.y + selection.height - 1.5,
104
+ scale,
105
+ );
106
+ assert!(b > r + 40 && b > g, "selection highlight pixel {r} {g} {b}");
107
+
108
+ session
109
+ .input(InputEvent::TextEdit(TextEdit::End { select: false }))
110
+ .unwrap();
111
+ session
112
+ .input(InputEvent::TextEdit(TextEdit::CompositionUpdate(
113
+ Composition {
114
+ text: "가".into(),
115
+ selection: None,
116
+ },
117
+ )))
118
+ .unwrap();
119
+ session.render().unwrap();
120
+ let rgba = session.rgba().unwrap();
121
+ let composed = session.shaped_line("한국어 text가", 16.0);
122
+ let committed = "한국어 text".chars().count();
123
+ let caret = rect(&session, "field:caret");
124
+ assert_close(
125
+ caret.x + caret.width * 0.5,
126
+ TEXT_ORIGIN_X + composed.width,
127
+ "caret after the preedit",
128
+ );
129
+ let [r, g, b, _] = pixel(
130
+ &session,
131
+ &rgba,
132
+ caret.x + caret.width * 0.5,
133
+ caret.y + 4.0,
134
+ scale,
135
+ );
136
+ assert!(r > 180 && g > 180 && b > 180, "caret pixel {r} {g} {b}");
137
+ let underline = rect(&session, "field:preedit");
138
+ assert_close(
139
+ underline.x,
140
+ TEXT_ORIGIN_X + composed.x_for_offset(committed),
141
+ "preedit start",
142
+ );
143
+ assert_close(
144
+ underline.width,
145
+ composed.width - composed.x_for_offset(committed),
146
+ "preedit underline spans the composing syllable",
147
+ );
148
+ let [r, _, _, _] = pixel(
149
+ &session,
150
+ &rgba,
151
+ underline.x + underline.width * 0.5,
152
+ underline.y + 0.5,
153
+ scale,
154
+ );
155
+ assert!(r > 150, "preedit underline pixel {r}");
156
+ assert_eq!(
157
+ session.runtime().state_value("name").unwrap(),
158
+ "한국어 text가",
159
+ "the binding shows the in-progress composition"
160
+ );
161
+ }