@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,2843 @@
1
+ mod accessibility;
2
+ pub mod dev;
3
+ mod host_services;
4
+ pub mod offscreen;
5
+ mod text;
6
+
7
+ pub use offscreen::{FrameTiming, OffscreenSession, encode_png};
8
+
9
+ use std::{collections::HashMap, error::Error, fmt, rc::Rc, sync::Arc, time::Instant};
10
+
11
+ use accessibility::{AccessibilityHost, NativeEvent};
12
+ use accesskit::ActionRequest;
13
+ use bytemuck::{Pod, Zeroable};
14
+ use glyphon::{
15
+ Buffer, Cache, Color as GlyphColor, FontSystem, Metrics, Resolution, Shaping, SwashCache,
16
+ TextArea, TextAtlas, TextBounds, TextRenderer, Viewport, Wrap,
17
+ };
18
+ use mun_runtime::scene::{Rect, ScenePresentation, SceneTransform};
19
+ use mun_runtime::{
20
+ ButtonState as MunButtonState, Color, ImeRequest, InputEvent, InputPoint,
21
+ KeyState as MunKeyState, LogicalKey, Modifiers, PhysicalKey as MunPhysicalKey,
22
+ PlatformConventions, PointerButton as MunPointerButton, PointerId, Runtime, RuntimeLoadError,
23
+ Scene, SceneTextStyle, ScrollDelta, ScrollPhase,
24
+ };
25
+ use text::{LINE_HEIGHT_FACTOR, TextShaping};
26
+ use winit::{
27
+ application::ApplicationHandler,
28
+ dpi::{LogicalPosition, LogicalSize, PhysicalPosition},
29
+ event::{ElementState, Ime, MouseButton, MouseScrollDelta, TouchPhase, WindowEvent},
30
+ event_loop::{ActiveEventLoop, EventLoop, EventLoopProxy},
31
+ keyboard::{Key, KeyCode, ModifiersState, NamedKey, PhysicalKey as WinitPhysicalKey},
32
+ window::{Window, WindowId},
33
+ };
34
+
35
+ /// Failure while preparing or running Mün's desktop-native backend.
36
+ #[derive(Debug)]
37
+ pub enum NativeBackendError {
38
+ Program(RuntimeLoadError),
39
+ EventLoop(winit::error::EventLoopError),
40
+ /// Native window creation failed.
41
+ Window(winit::error::OsError),
42
+ /// GPU initialization failed or the device was lost; names the subsystem.
43
+ Gpu(GpuError),
44
+ /// The development link to `mun dev` could not be established.
45
+ DevLink(std::io::Error),
46
+ }
47
+
48
+ impl fmt::Display for NativeBackendError {
49
+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
50
+ match self {
51
+ Self::Program(error) => write!(formatter, "{error}"),
52
+ Self::EventLoop(error) => write!(formatter, "{error}"),
53
+ Self::Window(error) => write!(formatter, "Mün window creation failed: {error}"),
54
+ Self::Gpu(error) => write!(formatter, "{error}"),
55
+ Self::DevLink(error) => write!(formatter, "Mün dev link failed: {error}"),
56
+ }
57
+ }
58
+ }
59
+
60
+ impl Error for NativeBackendError {
61
+ fn source(&self) -> Option<&(dyn Error + 'static)> {
62
+ match self {
63
+ Self::Program(error) => Some(error),
64
+ Self::EventLoop(error) => Some(error),
65
+ Self::Window(error) => Some(error),
66
+ Self::Gpu(error) => Some(error),
67
+ Self::DevLink(error) => Some(error),
68
+ }
69
+ }
70
+ }
71
+
72
+ impl From<RuntimeLoadError> for NativeBackendError {
73
+ fn from(error: RuntimeLoadError) -> Self {
74
+ Self::Program(error)
75
+ }
76
+ }
77
+
78
+ impl From<winit::error::EventLoopError> for NativeBackendError {
79
+ fn from(error: winit::error::EventLoopError) -> Self {
80
+ Self::EventLoop(error)
81
+ }
82
+ }
83
+
84
+ #[repr(C)]
85
+ #[derive(Clone, Copy, Pod, Zeroable)]
86
+ struct Vertex {
87
+ position: [f32; 2],
88
+ color: [f32; 4],
89
+ local_position: [f32; 2],
90
+ rect_size: [f32; 2],
91
+ corner_radius: f32,
92
+ }
93
+
94
+ impl Vertex {
95
+ fn layout() -> wgpu::VertexBufferLayout<'static> {
96
+ wgpu::VertexBufferLayout {
97
+ array_stride: std::mem::size_of::<Self>() as wgpu::BufferAddress,
98
+ step_mode: wgpu::VertexStepMode::Vertex,
99
+ attributes: &[
100
+ wgpu::VertexAttribute {
101
+ offset: 0,
102
+ shader_location: 0,
103
+ format: wgpu::VertexFormat::Float32x2,
104
+ },
105
+ wgpu::VertexAttribute {
106
+ offset: std::mem::size_of::<[f32; 2]>() as wgpu::BufferAddress,
107
+ shader_location: 1,
108
+ format: wgpu::VertexFormat::Float32x4,
109
+ },
110
+ wgpu::VertexAttribute {
111
+ offset: (std::mem::size_of::<[f32; 2]>() + std::mem::size_of::<[f32; 4]>())
112
+ as wgpu::BufferAddress,
113
+ shader_location: 2,
114
+ format: wgpu::VertexFormat::Float32x2,
115
+ },
116
+ wgpu::VertexAttribute {
117
+ offset: (std::mem::size_of::<[f32; 2]>() * 2 + std::mem::size_of::<[f32; 4]>())
118
+ as wgpu::BufferAddress,
119
+ shader_location: 3,
120
+ format: wgpu::VertexFormat::Float32x2,
121
+ },
122
+ wgpu::VertexAttribute {
123
+ offset: (std::mem::size_of::<[f32; 2]>() * 3 + std::mem::size_of::<[f32; 4]>())
124
+ as wgpu::BufferAddress,
125
+ shader_location: 4,
126
+ format: wgpu::VertexFormat::Float32,
127
+ },
128
+ ],
129
+ }
130
+ }
131
+ }
132
+
133
+ const INITIAL_RECT_VERTEX_BUFFER_BYTES: u64 = 4096;
134
+
135
+ fn rect_vertex_buffer_capacity(required_bytes: u64) -> u64 {
136
+ required_bytes
137
+ .max(INITIAL_RECT_VERTEX_BUFFER_BYTES)
138
+ .checked_next_power_of_two()
139
+ .unwrap_or(required_bytes)
140
+ }
141
+
142
+ struct CachedTextBuffer {
143
+ buffer: Buffer,
144
+ text: String,
145
+ font_size: f32,
146
+ wrap_width: Option<f32>,
147
+ style: SceneTextStyle,
148
+ /// Shaped content bounds in logical points (may span multiple lines).
149
+ width: f32,
150
+ height: f32,
151
+ }
152
+
153
+ fn shaped_width(buffer: &Buffer) -> f32 {
154
+ buffer
155
+ .layout_runs()
156
+ .map(|run| run.line_w)
157
+ .fold(0.0, f32::max)
158
+ }
159
+
160
+ fn shaped_height(buffer: &Buffer, font_size: f32) -> f32 {
161
+ buffer.layout_runs().count().max(1) as f32 * font_size * LINE_HEIGHT_FACTOR
162
+ }
163
+
164
+ /// Visible height of a buffer limited to `line_limit` lines; cosmic-text stops
165
+ /// laying out runs below the buffer height, which is how `.lineLimit` clips.
166
+ fn limited_height(style: SceneTextStyle, font_size: f32) -> Option<f32> {
167
+ style
168
+ .line_limit
169
+ .map(|limit| limit.max(1) as f32 * font_size * LINE_HEIGHT_FACTOR + 1.0)
170
+ }
171
+
172
+ fn line_align(style: SceneTextStyle) -> Option<glyphon::cosmic_text::Align> {
173
+ use glyphon::cosmic_text::Align;
174
+ match style.alignment {
175
+ mun_runtime::ir::UiTextAlignment::Leading => None,
176
+ mun_runtime::ir::UiTextAlignment::Center => Some(Align::Center),
177
+ mun_runtime::ir::UiTextAlignment::Trailing => Some(Align::Right),
178
+ }
179
+ }
180
+
181
+ impl CachedTextBuffer {
182
+ fn configure(
183
+ buffer: &mut Buffer,
184
+ text: &str,
185
+ font_size: f32,
186
+ wrap_width: Option<f32>,
187
+ style: SceneTextStyle,
188
+ ) {
189
+ // Ordinary Text uses the same proposal used during intrinsic layout.
190
+ // Editing and control labels intentionally keep unbounded single lines.
191
+ buffer.set_wrap(if wrap_width.is_some() {
192
+ Wrap::WordOrGlyph
193
+ } else {
194
+ Wrap::None
195
+ });
196
+ buffer.set_size(wrap_width, limited_height(style, font_size));
197
+ buffer.set_text(
198
+ text,
199
+ &text::styled_attrs(style.text_style(font_size)),
200
+ Shaping::Advanced,
201
+ None,
202
+ );
203
+ let align = line_align(style);
204
+ for line in &mut buffer.lines {
205
+ line.set_align(align);
206
+ }
207
+ }
208
+
209
+ fn new(
210
+ font_system: &mut FontSystem,
211
+ text: &str,
212
+ font_size: f32,
213
+ wrap_width: Option<f32>,
214
+ style: SceneTextStyle,
215
+ ) -> Self {
216
+ let mut buffer = Buffer::new(
217
+ font_system,
218
+ Metrics::new(font_size, font_size * LINE_HEIGHT_FACTOR),
219
+ );
220
+ Self::configure(&mut buffer, text, font_size, wrap_width, style);
221
+ buffer.shape_until_scroll(font_system, false);
222
+ Self {
223
+ width: shaped_width(&buffer),
224
+ height: shaped_height(&buffer, font_size),
225
+ buffer,
226
+ text: text.to_owned(),
227
+ font_size,
228
+ wrap_width,
229
+ style,
230
+ }
231
+ }
232
+
233
+ fn update(
234
+ &mut self,
235
+ font_system: &mut FontSystem,
236
+ text: &str,
237
+ font_size: f32,
238
+ wrap_width: Option<f32>,
239
+ style: SceneTextStyle,
240
+ ) -> bool {
241
+ if self.font_size.to_bits() == font_size.to_bits()
242
+ && self.text == text
243
+ && self.wrap_width == wrap_width
244
+ && self.style == style
245
+ {
246
+ return false;
247
+ }
248
+ if self.font_size.to_bits() != font_size.to_bits() {
249
+ self.buffer
250
+ .set_metrics(Metrics::new(font_size, font_size * LINE_HEIGHT_FACTOR));
251
+ self.font_size = font_size;
252
+ }
253
+ Self::configure(&mut self.buffer, text, font_size, wrap_width, style);
254
+ self.text.clear();
255
+ self.text.push_str(text);
256
+ self.wrap_width = wrap_width;
257
+ self.style = style;
258
+ self.buffer.shape_until_scroll(font_system, false);
259
+ self.width = shaped_width(&self.buffer);
260
+ self.height = shaped_height(&self.buffer, font_size);
261
+ true
262
+ }
263
+ }
264
+
265
+ struct TextBatchRenderer {
266
+ viewport: Viewport,
267
+ renderer: TextRenderer,
268
+ }
269
+
270
+ #[derive(Clone, Copy, Debug, PartialEq)]
271
+ struct TextTransformPlan {
272
+ raster_scale: f32,
273
+ virtual_width: u32,
274
+ virtual_height: u32,
275
+ viewport_x: f32,
276
+ viewport_y: f32,
277
+ viewport_width: f32,
278
+ viewport_height: f32,
279
+ }
280
+
281
+ #[derive(Clone, Copy, Debug, PartialEq, Eq)]
282
+ struct ScissorRect {
283
+ x: u32,
284
+ y: u32,
285
+ width: u32,
286
+ height: u32,
287
+ }
288
+
289
+ #[derive(Clone, Copy, Debug, PartialEq, Eq)]
290
+ struct RectDrawBatch {
291
+ start: u32,
292
+ end: u32,
293
+ scissor: ScissorRect,
294
+ }
295
+
296
+ #[derive(Clone, Copy, Debug)]
297
+ struct PreparedTextBatch {
298
+ slot: usize,
299
+ plan: TextTransformPlan,
300
+ scissor: ScissorRect,
301
+ }
302
+
303
+ /// Where a frame is realized: a window surface or an offscreen texture used for
304
+ /// pixel-level verification and headless measurement.
305
+ enum RenderTarget {
306
+ Surface(wgpu::Surface<'static>),
307
+ Offscreen(wgpu::Texture),
308
+ }
309
+
310
+ /// GPU realization counters for resource-growth measurement.
311
+ #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
312
+ pub struct RendererStats {
313
+ pub text_buffers: usize,
314
+ pub text_batch_renderers: usize,
315
+ pub rect_vertex_capacity_bytes: u64,
316
+ pub frames: u64,
317
+ pub skipped_frames: u64,
318
+ pub surface_reconfigurations: u64,
319
+ pub text_reshapes: u64,
320
+ /// Rects and texts of the last frame skipped because they lie entirely
321
+ /// outside their clip (e.g. scrolled out of a ScrollView) or the surface.
322
+ pub culled_primitives: usize,
323
+ }
324
+
325
+ /// Wall-clock cost of the stages of the last rendered frame, in microseconds.
326
+ #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
327
+ pub struct RenderTimings {
328
+ /// Scene geometry, vertex upload, text shaping and glyph preparation.
329
+ pub prepare_micros: u64,
330
+ /// Acquiring the swapchain texture (may wait on the compositor/vsync).
331
+ pub acquire_micros: u64,
332
+ /// Command encoding and queue submission.
333
+ pub submit_micros: u64,
334
+ /// Handing the frame to the platform presentation engine.
335
+ pub present_micros: u64,
336
+ }
337
+
338
+ fn micros_since(started: Instant) -> u64 {
339
+ u64::try_from(started.elapsed().as_micros()).unwrap_or(u64::MAX)
340
+ }
341
+
342
+ struct GpuRenderer {
343
+ last_timings: RenderTimings,
344
+ device: wgpu::Device,
345
+ queue: wgpu::Queue,
346
+ target: RenderTarget,
347
+ config: wgpu::SurfaceConfiguration,
348
+ rect_pipeline: wgpu::RenderPipeline,
349
+ rect_vertex_buffer: wgpu::Buffer,
350
+ rect_vertex_capacity: u64,
351
+ shaping: Rc<TextShaping>,
352
+ swash_cache: SwashCache,
353
+ cache: Cache,
354
+ atlas: TextAtlas,
355
+ text_batches: Vec<TextBatchRenderer>,
356
+ text_buffers: HashMap<String, CachedTextBuffer>,
357
+ device_lost: Arc<std::sync::Mutex<Option<String>>>,
358
+ stats: RendererStats,
359
+ mirrored_text_reported: bool,
360
+ /// Skip fully clipped primitives (always on; off only for differential tests).
361
+ pub(crate) culling: bool,
362
+ }
363
+
364
+ /// Outcome of one frame realization. Recoverable surface states never panic.
365
+ #[derive(Clone, Copy, Debug, PartialEq, Eq)]
366
+ enum FrameStatus {
367
+ Presented,
368
+ /// Surface temporarily unavailable (occluded, timeout, zero-sized); retry later.
369
+ Skipped,
370
+ /// Surface was reconfigured or recreated; a redraw should follow.
371
+ Reconfigured,
372
+ }
373
+
374
+ impl GpuRenderer {
375
+ async fn new(
376
+ window: Arc<Window>,
377
+ event_loop: &ActiveEventLoop,
378
+ shaping: Rc<TextShaping>,
379
+ ) -> Result<Self, GpuError> {
380
+ let size = window.inner_size();
381
+ let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_with_display_handle(
382
+ Box::new(event_loop.owned_display_handle()),
383
+ ));
384
+ let surface = instance
385
+ .create_surface(window)
386
+ .map_err(|error| GpuError::new("surface", error))?;
387
+ let adapter = instance
388
+ .request_adapter(&wgpu::RequestAdapterOptions {
389
+ compatible_surface: Some(&surface),
390
+ ..Default::default()
391
+ })
392
+ .await
393
+ .map_err(|error| GpuError::new("adapter", error))?;
394
+ let mut config = surface
395
+ .get_default_config(&adapter, size.width.max(1), size.height.max(1))
396
+ .ok_or_else(|| GpuError::new("surface", "adapter cannot present to this window"))?;
397
+ config.present_mode = wgpu::PresentMode::Fifo;
398
+ let (device, queue) = adapter
399
+ .request_device(&wgpu::DeviceDescriptor::default())
400
+ .await
401
+ .map_err(|error| GpuError::new("device", error))?;
402
+ surface.configure(&device, &config);
403
+ Ok(Self::with_device(
404
+ device,
405
+ queue,
406
+ RenderTarget::Surface(surface),
407
+ config,
408
+ shaping,
409
+ ))
410
+ }
411
+
412
+ /// Offscreen renderer with the same pipelines, for pixel verification.
413
+ async fn new_offscreen(
414
+ width: u32,
415
+ height: u32,
416
+ shaping: Rc<TextShaping>,
417
+ ) -> Result<Self, GpuError> {
418
+ let instance = wgpu::Instance::default();
419
+ let adapter = instance
420
+ .request_adapter(&wgpu::RequestAdapterOptions::default())
421
+ .await
422
+ .map_err(|error| GpuError::new("adapter", error))?;
423
+ let (device, queue) = adapter
424
+ .request_device(&wgpu::DeviceDescriptor::default())
425
+ .await
426
+ .map_err(|error| GpuError::new("device", error))?;
427
+ let config = wgpu::SurfaceConfiguration {
428
+ usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
429
+ format: wgpu::TextureFormat::Rgba8UnormSrgb,
430
+ width: width.max(1),
431
+ height: height.max(1),
432
+ present_mode: wgpu::PresentMode::Fifo,
433
+ desired_maximum_frame_latency: 2,
434
+ alpha_mode: wgpu::CompositeAlphaMode::Opaque,
435
+ view_formats: Vec::new(),
436
+ color_space: Default::default(),
437
+ };
438
+ let texture = Self::offscreen_texture(&device, &config);
439
+ Ok(Self::with_device(
440
+ device,
441
+ queue,
442
+ RenderTarget::Offscreen(texture),
443
+ config,
444
+ shaping,
445
+ ))
446
+ }
447
+
448
+ fn offscreen_texture(
449
+ device: &wgpu::Device,
450
+ config: &wgpu::SurfaceConfiguration,
451
+ ) -> wgpu::Texture {
452
+ device.create_texture(&wgpu::TextureDescriptor {
453
+ label: Some("Mün offscreen target"),
454
+ size: wgpu::Extent3d {
455
+ width: config.width,
456
+ height: config.height,
457
+ depth_or_array_layers: 1,
458
+ },
459
+ mip_level_count: 1,
460
+ sample_count: 1,
461
+ dimension: wgpu::TextureDimension::D2,
462
+ format: config.format,
463
+ usage: config.usage,
464
+ view_formats: &[],
465
+ })
466
+ }
467
+
468
+ fn with_device(
469
+ device: wgpu::Device,
470
+ queue: wgpu::Queue,
471
+ target: RenderTarget,
472
+ config: wgpu::SurfaceConfiguration,
473
+ shaping: Rc<TextShaping>,
474
+ ) -> Self {
475
+ let device_lost = Arc::new(std::sync::Mutex::new(None));
476
+ let lost = device_lost.clone();
477
+ device.set_device_lost_callback(move |reason, message| {
478
+ if let Ok(mut slot) = lost.lock() {
479
+ *slot = Some(format!("{reason:?}: {message}"));
480
+ }
481
+ });
482
+ let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
483
+ label: Some("Mün retained-scene shader"),
484
+ source: wgpu::ShaderSource::Wgsl(include_str!("rect.wgsl").into()),
485
+ });
486
+ let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
487
+ label: Some("Mün retained-scene pipeline layout"),
488
+ bind_group_layouts: &[],
489
+ immediate_size: 0,
490
+ });
491
+ let rect_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
492
+ label: Some("Mün retained-scene pipeline"),
493
+ layout: Some(&pipeline_layout),
494
+ vertex: wgpu::VertexState {
495
+ module: &shader,
496
+ entry_point: Some("vs_main"),
497
+ compilation_options: Default::default(),
498
+ buffers: &[Some(Vertex::layout())],
499
+ },
500
+ fragment: Some(wgpu::FragmentState {
501
+ module: &shader,
502
+ entry_point: Some("fs_main"),
503
+ compilation_options: wgpu::PipelineCompilationOptions {
504
+ constants: &[(
505
+ "SRGB_TARGET",
506
+ if config.format.is_srgb() { 1.0 } else { 0.0 },
507
+ )],
508
+ ..Default::default()
509
+ },
510
+ targets: &[Some(wgpu::ColorTargetState {
511
+ format: config.format,
512
+ blend: Some(wgpu::BlendState::ALPHA_BLENDING),
513
+ write_mask: wgpu::ColorWrites::ALL,
514
+ })],
515
+ }),
516
+ primitive: wgpu::PrimitiveState::default(),
517
+ depth_stencil: None,
518
+ multisample: wgpu::MultisampleState::default(),
519
+ multiview_mask: None,
520
+ cache: None,
521
+ });
522
+
523
+ let rect_vertex_capacity = INITIAL_RECT_VERTEX_BUFFER_BYTES;
524
+ let rect_vertex_buffer = device.create_buffer(&wgpu::BufferDescriptor {
525
+ label: Some("Mün retained-scene vertices"),
526
+ size: rect_vertex_capacity,
527
+ usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
528
+ mapped_at_creation: false,
529
+ });
530
+
531
+ let swash_cache = SwashCache::new();
532
+ let cache = Cache::new(&device);
533
+ let atlas = TextAtlas::new(&device, &queue, &cache, config.format);
534
+
535
+ Self {
536
+ device,
537
+ queue,
538
+ target,
539
+ config,
540
+ rect_pipeline,
541
+ rect_vertex_buffer,
542
+ rect_vertex_capacity,
543
+ shaping,
544
+ swash_cache,
545
+ cache,
546
+ atlas,
547
+ text_batches: Vec::new(),
548
+ text_buffers: HashMap::new(),
549
+ device_lost,
550
+ stats: RendererStats {
551
+ rect_vertex_capacity_bytes: rect_vertex_capacity,
552
+ ..Default::default()
553
+ },
554
+ last_timings: RenderTimings::default(),
555
+ mirrored_text_reported: false,
556
+ culling: true,
557
+ }
558
+ }
559
+
560
+ /// Device loss is unrecoverable for this renderer instance; the host reports
561
+ /// it as a structured GPU diagnostic.
562
+ fn device_lost(&self) -> Option<String> {
563
+ self.device_lost.lock().ok().and_then(|slot| slot.clone())
564
+ }
565
+
566
+ fn stats(&self) -> RendererStats {
567
+ RendererStats {
568
+ text_buffers: self.text_buffers.len(),
569
+ text_batch_renderers: self.text_batches.len(),
570
+ rect_vertex_capacity_bytes: self.rect_vertex_capacity,
571
+ ..self.stats
572
+ }
573
+ }
574
+
575
+ /// Zero-sized (minimized) surfaces keep their previous configuration; the
576
+ /// next non-zero size reconfigures. Safe before and after initialization.
577
+ fn resize(&mut self, width: u32, height: u32) {
578
+ if width == 0 || height == 0 {
579
+ return;
580
+ }
581
+ if self.config.width == width && self.config.height == height {
582
+ return;
583
+ }
584
+ self.config.width = width;
585
+ self.config.height = height;
586
+ match &mut self.target {
587
+ RenderTarget::Surface(surface) => surface.configure(&self.device, &self.config),
588
+ RenderTarget::Offscreen(texture) => {
589
+ *texture = Self::offscreen_texture(&self.device, &self.config)
590
+ }
591
+ }
592
+ self.stats.surface_reconfigurations += 1;
593
+ }
594
+
595
+ fn ensure_rect_vertex_capacity(&mut self, required_bytes: u64) {
596
+ if required_bytes <= self.rect_vertex_capacity {
597
+ return;
598
+ }
599
+
600
+ let next_capacity = rect_vertex_buffer_capacity(required_bytes);
601
+ let next_buffer = self.device.create_buffer(&wgpu::BufferDescriptor {
602
+ label: Some("Mün retained-scene vertices"),
603
+ size: next_capacity,
604
+ usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
605
+ mapped_at_creation: false,
606
+ });
607
+ let previous = std::mem::replace(&mut self.rect_vertex_buffer, next_buffer);
608
+ previous.destroy();
609
+ self.rect_vertex_capacity = next_capacity;
610
+ }
611
+
612
+ fn ensure_text_batch(&mut self, slot: usize) {
613
+ while self.text_batches.len() <= slot {
614
+ let viewport = Viewport::new(&self.device, &self.cache);
615
+ let renderer = TextRenderer::new(
616
+ &mut self.atlas,
617
+ &self.device,
618
+ wgpu::MultisampleState::default(),
619
+ None,
620
+ );
621
+ self.text_batches
622
+ .push(TextBatchRenderer { viewport, renderer });
623
+ }
624
+ }
625
+
626
+ fn render(&mut self, scene: &Scene, scale_factor: f32) -> FrameStatus {
627
+ self.render_presented(scene, &scene.presentation, scale_factor)
628
+ }
629
+
630
+ fn render_presented(
631
+ &mut self,
632
+ scene: &Scene,
633
+ presentation: &ScenePresentation,
634
+ scale_factor: f32,
635
+ ) -> FrameStatus {
636
+ self.last_timings = RenderTimings::default();
637
+ if !scale_factor.is_finite() || scale_factor <= 0.0 {
638
+ self.stats.skipped_frames += 1;
639
+ return FrameStatus::Skipped;
640
+ }
641
+ let stage = Instant::now();
642
+ let surface_width = self.config.width.max(1);
643
+ let surface_height = self.config.height.max(1);
644
+ let physical_width = surface_width as f32;
645
+ let physical_height = surface_height as f32;
646
+
647
+ let (vertices, rect_batches, culled_rects) = scene_geometry(
648
+ scene,
649
+ presentation,
650
+ surface_width,
651
+ surface_height,
652
+ scale_factor,
653
+ self.culling,
654
+ );
655
+ if !vertices.is_empty() {
656
+ let bytes = bytemuck::cast_slice(&vertices);
657
+ self.ensure_rect_vertex_capacity(bytes.len() as u64);
658
+ self.queue.write_buffer(&self.rect_vertex_buffer, 0, bytes);
659
+ }
660
+
661
+ let shaping = self.shaping.clone();
662
+ let mut font_system = shaping.font_system();
663
+ // Retained buffers for primitives that left the scene are released so
664
+ // repeated insertion/removal cannot grow shaping memory without bound.
665
+ if self.text_buffers.len() > scene.texts.len() {
666
+ let live = scene
667
+ .texts
668
+ .iter()
669
+ .map(|text| text.id.as_str())
670
+ .collect::<std::collections::HashSet<_>>();
671
+ self.text_buffers.retain(|id, _| live.contains(id.as_str()));
672
+ }
673
+ // A text whose line box (plus a one-em margin for overhang) lies
674
+ // outside its clip draws nothing: it is neither reshaped nor prepared.
675
+ // Its horizontal extent is known only once it has been shaped.
676
+ let mut culled_texts = 0;
677
+ let visible = scene
678
+ .texts
679
+ .iter()
680
+ .map(|text| {
681
+ let Some(scissor) = scissor_for_clip(
682
+ presentation.clip_for(&text.id),
683
+ surface_width,
684
+ surface_height,
685
+ scale_factor,
686
+ ) else {
687
+ return false;
688
+ };
689
+ let transform = presentation.transform_for(&text.id);
690
+ let margin = text.font_size;
691
+ let cached = self.text_buffers.get(&text.id).filter(|cached| {
692
+ cached.text == text.text
693
+ && cached.font_size.to_bits() == text.font_size.to_bits()
694
+ && cached.wrap_width == text.wrap_width
695
+ && cached.style == text.style
696
+ });
697
+ let width = cached.map(|cached| cached.width);
698
+ // A not-yet-shaped wrapped text may reach below its first
699
+ // line; don't cull it using a one-line height estimate.
700
+ let height = cached.map(|cached| cached.height).unwrap_or_else(|| {
701
+ if text.wrap_width.is_some() {
702
+ self.config.height as f32
703
+ } else {
704
+ text.font_size * LINE_HEIGHT_FACTOR
705
+ }
706
+ });
707
+ let bottom = text.y + height + margin;
708
+ let (left, top) = transform.transform_point(text.x - margin, text.y - margin);
709
+ let (right, bottom) =
710
+ transform.transform_point(text.x + width.unwrap_or(0.0) + margin, bottom);
711
+ let overlaps = !self.culling
712
+ || overlaps_scissor(
713
+ width.map(|_| (left, right)),
714
+ (top, bottom),
715
+ scale_factor,
716
+ scissor,
717
+ 1.0,
718
+ );
719
+ culled_texts += usize::from(!overlaps);
720
+ overlaps
721
+ })
722
+ .collect::<Vec<_>>();
723
+ self.stats.culled_primitives = culled_rects + culled_texts;
724
+ for (text, _) in scene
725
+ .texts
726
+ .iter()
727
+ .zip(&visible)
728
+ .filter(|(_, visible)| **visible)
729
+ {
730
+ match self.text_buffers.get_mut(&text.id) {
731
+ Some(cached) => {
732
+ if cached.update(
733
+ &mut font_system,
734
+ &text.text,
735
+ text.font_size,
736
+ text.wrap_width,
737
+ text.style,
738
+ ) {
739
+ self.stats.text_reshapes += 1;
740
+ }
741
+ }
742
+ None => {
743
+ self.stats.text_reshapes += 1;
744
+ self.text_buffers.insert(
745
+ text.id.clone(),
746
+ CachedTextBuffer::new(
747
+ &mut font_system,
748
+ &text.text,
749
+ text.font_size,
750
+ text.wrap_width,
751
+ text.style,
752
+ ),
753
+ );
754
+ }
755
+ }
756
+ }
757
+
758
+ let mut groups = Vec::new();
759
+ let mut start = 0;
760
+ while start < scene.texts.len() {
761
+ if !visible[start] {
762
+ start += 1;
763
+ continue;
764
+ }
765
+ let text = &scene.texts[start];
766
+ let transform = presentation.transform_for(&text.id);
767
+ let Some(scissor) = scissor_for_clip(
768
+ presentation.clip_for(&text.id),
769
+ surface_width,
770
+ surface_height,
771
+ scale_factor,
772
+ ) else {
773
+ start += 1;
774
+ continue;
775
+ };
776
+ let mut end = start + 1;
777
+ while end < scene.texts.len() {
778
+ let next = &scene.texts[end];
779
+ if !visible[end]
780
+ || presentation.transform_for(&next.id) != transform
781
+ || scissor_for_clip(
782
+ presentation.clip_for(&next.id),
783
+ surface_width,
784
+ surface_height,
785
+ scale_factor,
786
+ ) != Some(scissor)
787
+ {
788
+ break;
789
+ }
790
+ end += 1;
791
+ }
792
+ groups.push((start, end, transform, scissor));
793
+ start = end;
794
+ }
795
+
796
+ let mut prepared_batches = Vec::with_capacity(groups.len());
797
+ for (start, end, transform, scissor) in groups {
798
+ let plan = match text_transform_plan(
799
+ transform,
800
+ physical_width,
801
+ physical_height,
802
+ scale_factor,
803
+ ) {
804
+ Ok(Some(plan)) => plan,
805
+ // Collapsed (zero-scale) text has no visible extent.
806
+ Ok(None) => continue,
807
+ Err(reason) => {
808
+ // Supported-contract diagnostic: glyph rasterization here is
809
+ // axis-aligned and non-mirrored. Report once, never draw wrongly.
810
+ if !self.mirrored_text_reported {
811
+ eprintln!(
812
+ "Mün renderer: skipped text with unsupported transform ({reason}): {transform:?}"
813
+ );
814
+ self.mirrored_text_reported = true;
815
+ }
816
+ continue;
817
+ }
818
+ };
819
+
820
+ let slot = prepared_batches.len();
821
+ self.ensure_text_batch(slot);
822
+
823
+ let device = &self.device;
824
+ let queue = &self.queue;
825
+ let font_system = &mut *font_system;
826
+ let atlas = &mut self.atlas;
827
+ let swash_cache = &mut self.swash_cache;
828
+ let batch = &mut self.text_batches[slot];
829
+
830
+ batch.viewport.update(
831
+ queue,
832
+ Resolution {
833
+ width: plan.virtual_width,
834
+ height: plan.virtual_height,
835
+ },
836
+ );
837
+
838
+ let text_buffers = &self.text_buffers;
839
+ let text_areas = scene.texts[start..end].iter().filter_map(|text| {
840
+ let cached = text_buffers.get(&text.id)?;
841
+ let rgba = text
842
+ .color
843
+ .0
844
+ .map(|value| (value.clamp(0.0, 1.0) * 255.0).round() as u8);
845
+ Some(TextArea {
846
+ buffer: &cached.buffer,
847
+ left: text.x * plan.raster_scale,
848
+ top: text.y * plan.raster_scale,
849
+ scale: plan.raster_scale,
850
+ bounds: TextBounds {
851
+ left: 0,
852
+ top: 0,
853
+ right: plan.virtual_width.min(i32::MAX as u32) as i32,
854
+ bottom: plan.virtual_height.min(i32::MAX as u32) as i32,
855
+ },
856
+ default_color: GlyphColor::rgba(rgba[0], rgba[1], rgba[2], rgba[3]),
857
+ custom_glyphs: &[],
858
+ })
859
+ });
860
+
861
+ if let Err(error) = batch.renderer.prepare(
862
+ device,
863
+ queue,
864
+ font_system,
865
+ atlas,
866
+ &batch.viewport,
867
+ text_areas,
868
+ swash_cache,
869
+ ) {
870
+ // Atlas exhaustion is recoverable: drop this batch for the frame;
871
+ // trimming below frees unused glyphs for the next one.
872
+ eprintln!("Mün renderer: text preparation failed: {error}");
873
+ continue;
874
+ }
875
+ prepared_batches.push(PreparedTextBatch {
876
+ slot,
877
+ plan,
878
+ scissor,
879
+ });
880
+ }
881
+ drop(font_system);
882
+ self.last_timings.prepare_micros = micros_since(stage);
883
+ let stage = Instant::now();
884
+
885
+ let (frame, view) = match &self.target {
886
+ RenderTarget::Surface(surface) => {
887
+ let acquired = surface.get_current_texture();
888
+ self.last_timings.acquire_micros = micros_since(stage);
889
+ let frame = match acquired {
890
+ wgpu::CurrentSurfaceTexture::Success(frame) => frame,
891
+ wgpu::CurrentSurfaceTexture::Timeout
892
+ | wgpu::CurrentSurfaceTexture::Occluded => {
893
+ self.stats.skipped_frames += 1;
894
+ return FrameStatus::Skipped;
895
+ }
896
+ wgpu::CurrentSurfaceTexture::Suboptimal(_)
897
+ | wgpu::CurrentSurfaceTexture::Outdated
898
+ | wgpu::CurrentSurfaceTexture::Lost
899
+ | wgpu::CurrentSurfaceTexture::Validation => {
900
+ // Reconfigure and redraw; a persistently lost device is
901
+ // reported through the device-lost diagnostic instead.
902
+ surface.configure(&self.device, &self.config);
903
+ self.stats.surface_reconfigurations += 1;
904
+ return FrameStatus::Reconfigured;
905
+ }
906
+ };
907
+ let view = frame
908
+ .texture
909
+ .create_view(&wgpu::TextureViewDescriptor::default());
910
+ (Some(frame), view)
911
+ }
912
+ RenderTarget::Offscreen(texture) => (
913
+ None,
914
+ texture.create_view(&wgpu::TextureViewDescriptor::default()),
915
+ ),
916
+ };
917
+ let stage = Instant::now();
918
+ let mut encoder = self
919
+ .device
920
+ .create_command_encoder(&wgpu::CommandEncoderDescriptor {
921
+ label: Some("Mün frame encoder"),
922
+ });
923
+
924
+ {
925
+ let clear = Color::WINDOW.0;
926
+ let srgb = self.config.format.is_srgb();
927
+ let channel = |value: f32| -> f64 {
928
+ let value = value as f64;
929
+ if !srgb {
930
+ value
931
+ } else if value <= 0.04045 {
932
+ value / 12.92
933
+ } else {
934
+ ((value + 0.055) / 1.055).powf(2.4)
935
+ }
936
+ };
937
+ let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
938
+ label: Some("Mün retained scene"),
939
+ color_attachments: &[Some(wgpu::RenderPassColorAttachment {
940
+ view: &view,
941
+ depth_slice: None,
942
+ resolve_target: None,
943
+ ops: wgpu::Operations {
944
+ load: wgpu::LoadOp::Clear(wgpu::Color {
945
+ r: channel(clear[0]),
946
+ g: channel(clear[1]),
947
+ b: channel(clear[2]),
948
+ a: clear[3] as f64,
949
+ }),
950
+ store: wgpu::StoreOp::Store,
951
+ },
952
+ })],
953
+ depth_stencil_attachment: None,
954
+ timestamp_writes: None,
955
+ occlusion_query_set: None,
956
+ multiview_mask: None,
957
+ });
958
+
959
+ if !rect_batches.is_empty() {
960
+ pass.set_pipeline(&self.rect_pipeline);
961
+ pass.set_vertex_buffer(0, self.rect_vertex_buffer.slice(..));
962
+ for batch in rect_batches {
963
+ pass.set_scissor_rect(
964
+ batch.scissor.x,
965
+ batch.scissor.y,
966
+ batch.scissor.width,
967
+ batch.scissor.height,
968
+ );
969
+ pass.draw(batch.start..batch.end, 0..1);
970
+ }
971
+ }
972
+
973
+ for prepared in prepared_batches {
974
+ let batch = &self.text_batches[prepared.slot];
975
+ pass.set_scissor_rect(
976
+ prepared.scissor.x,
977
+ prepared.scissor.y,
978
+ prepared.scissor.width,
979
+ prepared.scissor.height,
980
+ );
981
+ pass.set_viewport(
982
+ prepared.plan.viewport_x,
983
+ prepared.plan.viewport_y,
984
+ prepared.plan.viewport_width,
985
+ prepared.plan.viewport_height,
986
+ 0.0,
987
+ 1.0,
988
+ );
989
+ if let Err(error) = batch
990
+ .renderer
991
+ .render(&self.atlas, &batch.viewport, &mut pass)
992
+ {
993
+ eprintln!("Mün renderer: text realization failed: {error}");
994
+ }
995
+ }
996
+ }
997
+
998
+ self.queue.submit(Some(encoder.finish()));
999
+ self.last_timings.submit_micros = micros_since(stage);
1000
+ let stage = Instant::now();
1001
+ if let Some(frame) = frame {
1002
+ self.queue.present(frame);
1003
+ }
1004
+ self.last_timings.present_micros = micros_since(stage);
1005
+ self.atlas.trim();
1006
+ self.stats.frames += 1;
1007
+ FrameStatus::Presented
1008
+ }
1009
+
1010
+ /// Read back the offscreen target as tightly packed RGBA8 rows.
1011
+ fn read_offscreen_rgba(&self) -> Option<Vec<u8>> {
1012
+ let RenderTarget::Offscreen(texture) = &self.target else {
1013
+ return None;
1014
+ };
1015
+ let width = self.config.width;
1016
+ let height = self.config.height;
1017
+ let padded_row = (width * 4).div_ceil(wgpu::COPY_BYTES_PER_ROW_ALIGNMENT)
1018
+ * wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;
1019
+ let buffer = self.device.create_buffer(&wgpu::BufferDescriptor {
1020
+ label: Some("Mün offscreen readback"),
1021
+ size: u64::from(padded_row) * u64::from(height),
1022
+ usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
1023
+ mapped_at_creation: false,
1024
+ });
1025
+ let mut encoder = self
1026
+ .device
1027
+ .create_command_encoder(&wgpu::CommandEncoderDescriptor {
1028
+ label: Some("Mün offscreen readback"),
1029
+ });
1030
+ encoder.copy_texture_to_buffer(
1031
+ texture.as_image_copy(),
1032
+ wgpu::TexelCopyBufferInfo {
1033
+ buffer: &buffer,
1034
+ layout: wgpu::TexelCopyBufferLayout {
1035
+ offset: 0,
1036
+ bytes_per_row: Some(padded_row),
1037
+ rows_per_image: Some(height),
1038
+ },
1039
+ },
1040
+ wgpu::Extent3d {
1041
+ width,
1042
+ height,
1043
+ depth_or_array_layers: 1,
1044
+ },
1045
+ );
1046
+ self.queue.submit(Some(encoder.finish()));
1047
+ let slice = buffer.slice(..);
1048
+ slice.map_async(wgpu::MapMode::Read, |_| {});
1049
+ self.device.poll(wgpu::PollType::wait_indefinitely()).ok()?;
1050
+ let data = slice.get_mapped_range().ok()?;
1051
+ let mut output = Vec::with_capacity((width * height * 4) as usize);
1052
+ for row in data.chunks(padded_row as usize) {
1053
+ output.extend_from_slice(&row[..(width * 4) as usize]);
1054
+ }
1055
+ Some(output)
1056
+ }
1057
+ }
1058
+
1059
+ /// Structured GPU diagnostic naming the failing subsystem.
1060
+ #[derive(Debug)]
1061
+ pub struct GpuError {
1062
+ pub subsystem: &'static str,
1063
+ pub message: String,
1064
+ }
1065
+
1066
+ impl GpuError {
1067
+ fn new(subsystem: &'static str, error: impl fmt::Display) -> Self {
1068
+ Self {
1069
+ subsystem,
1070
+ message: error.to_string(),
1071
+ }
1072
+ }
1073
+ }
1074
+
1075
+ impl fmt::Display for GpuError {
1076
+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1077
+ write!(
1078
+ formatter,
1079
+ "Mün GPU {} initialization failed: {}",
1080
+ self.subsystem, self.message
1081
+ )
1082
+ }
1083
+ }
1084
+
1085
+ impl Error for GpuError {}
1086
+
1087
+ fn text_transform_plan(
1088
+ transform: SceneTransform,
1089
+ physical_width: f32,
1090
+ physical_height: f32,
1091
+ device_scale: f32,
1092
+ ) -> Result<Option<TextTransformPlan>, &'static str> {
1093
+ if !physical_width.is_finite()
1094
+ || !physical_height.is_finite()
1095
+ || !device_scale.is_finite()
1096
+ || physical_width <= 0.0
1097
+ || physical_height <= 0.0
1098
+ || device_scale <= 0.0
1099
+ || !transform.scale_x.is_finite()
1100
+ || !transform.scale_y.is_finite()
1101
+ || !transform.translation_x.is_finite()
1102
+ || !transform.translation_y.is_finite()
1103
+ || transform.scale_x < 0.0
1104
+ || transform.scale_y < 0.0
1105
+ {
1106
+ return Err("invalid text transform");
1107
+ }
1108
+
1109
+ if transform.scale_x <= f32::EPSILON || transform.scale_y <= f32::EPSILON {
1110
+ return Ok(None);
1111
+ }
1112
+
1113
+ let max_axis_scale = transform.scale_x.max(transform.scale_y).max(1.0);
1114
+ let raster_scale = device_scale * max_axis_scale;
1115
+ let logical_width = physical_width / device_scale;
1116
+ let logical_height = physical_height / device_scale;
1117
+ let virtual_width = (logical_width * raster_scale)
1118
+ .ceil()
1119
+ .clamp(1.0, i32::MAX as f32) as u32;
1120
+ let virtual_height = (logical_height * raster_scale)
1121
+ .ceil()
1122
+ .clamp(1.0, i32::MAX as f32) as u32;
1123
+
1124
+ Ok(Some(TextTransformPlan {
1125
+ raster_scale,
1126
+ virtual_width,
1127
+ virtual_height,
1128
+ viewport_x: transform.translation_x * device_scale,
1129
+ viewport_y: transform.translation_y * device_scale,
1130
+ viewport_width: physical_width * transform.scale_x,
1131
+ viewport_height: physical_height * transform.scale_y,
1132
+ }))
1133
+ }
1134
+
1135
+ fn scissor_for_clip(
1136
+ clip: Option<Rect>,
1137
+ surface_width: u32,
1138
+ surface_height: u32,
1139
+ scale: f32,
1140
+ ) -> Option<ScissorRect> {
1141
+ if surface_width == 0 || surface_height == 0 || !scale.is_finite() || scale <= 0.0 {
1142
+ return None;
1143
+ }
1144
+ let Some(clip) = clip else {
1145
+ return Some(ScissorRect {
1146
+ x: 0,
1147
+ y: 0,
1148
+ width: surface_width,
1149
+ height: surface_height,
1150
+ });
1151
+ };
1152
+ if !clip.x.is_finite()
1153
+ || !clip.y.is_finite()
1154
+ || !clip.width.is_finite()
1155
+ || !clip.height.is_finite()
1156
+ || clip.width <= 0.0
1157
+ || clip.height <= 0.0
1158
+ {
1159
+ return None;
1160
+ }
1161
+
1162
+ let max_x = surface_width as f32;
1163
+ let max_y = surface_height as f32;
1164
+ let left = (clip.x * scale).floor().clamp(0.0, max_x);
1165
+ let top = (clip.y * scale).floor().clamp(0.0, max_y);
1166
+ let right = ((clip.x + clip.width) * scale).ceil().clamp(0.0, max_x);
1167
+ let bottom = ((clip.y + clip.height) * scale).ceil().clamp(0.0, max_y);
1168
+ if right <= left || bottom <= top {
1169
+ return None;
1170
+ }
1171
+
1172
+ Some(ScissorRect {
1173
+ x: left as u32,
1174
+ y: top as u32,
1175
+ width: (right - left) as u32,
1176
+ height: (bottom - top) as u32,
1177
+ })
1178
+ }
1179
+
1180
+ fn scene_geometry(
1181
+ scene: &Scene,
1182
+ presentation: &ScenePresentation,
1183
+ surface_width: u32,
1184
+ surface_height: u32,
1185
+ scale: f32,
1186
+ cull: bool,
1187
+ ) -> (Vec<Vertex>, Vec<RectDrawBatch>, usize) {
1188
+ let width = surface_width.max(1) as f32;
1189
+ let height = surface_height.max(1) as f32;
1190
+ let mut vertices = Vec::with_capacity(scene.rects.len() * 6);
1191
+ let mut batches: Vec<RectDrawBatch> = Vec::new();
1192
+ let mut culled = 0;
1193
+ for item in &scene.rects {
1194
+ let Some(scissor) = scissor_for_clip(
1195
+ presentation.clip_for(&item.id),
1196
+ surface_width,
1197
+ surface_height,
1198
+ scale,
1199
+ ) else {
1200
+ continue;
1201
+ };
1202
+ let transform = presentation.transform_for(&item.id);
1203
+ let (left, top) = transform.transform_point(item.rect.x, item.rect.y);
1204
+ let (right, bottom) = transform.transform_point(
1205
+ item.rect.x + item.rect.width,
1206
+ item.rect.y + item.rect.height,
1207
+ );
1208
+ if cull && !overlaps_scissor(Some((left, right)), (top, bottom), scale, scissor, 1.0) {
1209
+ culled += 1;
1210
+ continue;
1211
+ }
1212
+ let x0 = left * scale / width * 2.0 - 1.0;
1213
+ let x1 = right * scale / width * 2.0 - 1.0;
1214
+ let y0 = 1.0 - top * scale / height * 2.0;
1215
+ let y1 = 1.0 - bottom * scale / height * 2.0;
1216
+ let gradient = scene.gradient_for(&item.id);
1217
+ let rect_size = [item.rect.width, item.rect.height];
1218
+ let radius = item.corner_radius.max(0.0);
1219
+ let color_at = |local_position: [f32; 2]| {
1220
+ let Some(gradient) = gradient else {
1221
+ return item.color.0;
1222
+ };
1223
+ let point = [
1224
+ if item.rect.width > 0.0 {
1225
+ local_position[0] / item.rect.width
1226
+ } else {
1227
+ 0.0
1228
+ },
1229
+ if item.rect.height > 0.0 {
1230
+ local_position[1] / item.rect.height
1231
+ } else {
1232
+ 0.0
1233
+ },
1234
+ ];
1235
+ let dx = gradient.end_point[0] - gradient.start_point[0];
1236
+ let dy = gradient.end_point[1] - gradient.start_point[1];
1237
+ let denominator = dx * dx + dy * dy;
1238
+ let t = if denominator <= f32::EPSILON {
1239
+ 0.0
1240
+ } else {
1241
+ (((point[0] - gradient.start_point[0]) * dx
1242
+ + (point[1] - gradient.start_point[1]) * dy)
1243
+ / denominator)
1244
+ .clamp(0.0, 1.0)
1245
+ };
1246
+ std::array::from_fn(|index| {
1247
+ gradient.start.0[index] + (gradient.end.0[index] - gradient.start.0[index]) * t
1248
+ })
1249
+ };
1250
+ let vertex = |position, local_position| Vertex {
1251
+ position,
1252
+ color: color_at(local_position),
1253
+ local_position,
1254
+ rect_size,
1255
+ corner_radius: radius,
1256
+ };
1257
+ let start = vertices.len() as u32;
1258
+ vertices.extend_from_slice(&[
1259
+ vertex([x0, y0], [0.0, 0.0]),
1260
+ vertex([x1, y0], [item.rect.width, 0.0]),
1261
+ vertex([x1, y1], [item.rect.width, item.rect.height]),
1262
+ vertex([x0, y0], [0.0, 0.0]),
1263
+ vertex([x1, y1], [item.rect.width, item.rect.height]),
1264
+ vertex([x0, y1], [0.0, item.rect.height]),
1265
+ ]);
1266
+ let end = vertices.len() as u32;
1267
+ if let Some(previous) = batches.last_mut() {
1268
+ if previous.scissor == scissor && previous.end == start {
1269
+ previous.end = end;
1270
+ continue;
1271
+ }
1272
+ }
1273
+ batches.push(RectDrawBatch {
1274
+ start,
1275
+ end,
1276
+ scissor,
1277
+ });
1278
+ }
1279
+ (vertices, batches, culled)
1280
+ }
1281
+
1282
+ /// Whether a primitive's transformed logical extent (`x` is `None` when the
1283
+ /// horizontal extent is unknown) can produce pixels inside `scissor`. The
1284
+ /// physical `margin` keeps anti-aliasing and glyph overhang conservative.
1285
+ fn overlaps_scissor(
1286
+ x: Option<(f32, f32)>,
1287
+ y: (f32, f32),
1288
+ scale: f32,
1289
+ scissor: ScissorRect,
1290
+ margin: f32,
1291
+ ) -> bool {
1292
+ let within = |a: f32, b: f32, start: u32, length: u32| {
1293
+ let (low, high) = (a.min(b) * scale - margin, a.max(b) * scale + margin);
1294
+ // NaN extents fail closed (drawn), never culled.
1295
+ !(high < start as f32 || low > (start + length) as f32)
1296
+ };
1297
+ x.is_none_or(|(left, right)| within(left, right, scissor.x, scissor.width))
1298
+ && within(y.0, y.1, scissor.y, scissor.height)
1299
+ }
1300
+
1301
+ #[cfg(test)]
1302
+ fn scene_vertices(
1303
+ scene: &Scene,
1304
+ presentation: &ScenePresentation,
1305
+ width: f32,
1306
+ height: f32,
1307
+ scale: f32,
1308
+ ) -> Vec<Vertex> {
1309
+ scene_geometry(
1310
+ scene,
1311
+ presentation,
1312
+ width.max(1.0) as u32,
1313
+ height.max(1.0) as u32,
1314
+ scale,
1315
+ false,
1316
+ )
1317
+ .0
1318
+ }
1319
+
1320
+ #[cfg(test)]
1321
+ mod tests {
1322
+ use super::*;
1323
+ use mun_runtime::scene::SceneRect;
1324
+
1325
+ #[test]
1326
+ fn platform_key_mapping_stays_inside_the_native_adapter() {
1327
+ assert_eq!(
1328
+ input_logical_key(&Key::Named(NamedKey::Tab)),
1329
+ LogicalKey::Tab
1330
+ );
1331
+ assert_eq!(
1332
+ input_logical_key(&Key::Character("x".into())),
1333
+ LogicalKey::Character("x".into())
1334
+ );
1335
+ assert_eq!(
1336
+ input_physical_key(WinitPhysicalKey::Code(KeyCode::Enter)),
1337
+ MunPhysicalKey::Enter
1338
+ );
1339
+ }
1340
+
1341
+ #[test]
1342
+ fn touch_pointer_namespace_never_aliases_mouse_or_u64_local_ids() {
1343
+ assert_ne!(PointerId::touch(0), PointerId::MOUSE);
1344
+ assert_ne!(PointerId::touch(u64::MAX), PointerId(u64::MAX as u128));
1345
+ assert_ne!(PointerId::touch(7), PointerId(7));
1346
+ }
1347
+
1348
+ #[test]
1349
+ fn touch_events_translate_to_canonical_pointer_capture_sequence() {
1350
+ let pointer = PointerId::touch(42);
1351
+ assert_eq!(
1352
+ input_touch_events(
1353
+ 42,
1354
+ TouchPhase::Started,
1355
+ PhysicalPosition::new(20.0, 40.0),
1356
+ 2.0,
1357
+ ),
1358
+ vec![
1359
+ InputEvent::PointerMoved {
1360
+ pointer,
1361
+ position: InputPoint::new(10.0, 20.0),
1362
+ },
1363
+ InputEvent::PointerButton {
1364
+ pointer,
1365
+ button: MunPointerButton::Primary,
1366
+ state: MunButtonState::Pressed,
1367
+ },
1368
+ ]
1369
+ );
1370
+
1371
+ assert_eq!(
1372
+ input_touch_events(
1373
+ 42,
1374
+ TouchPhase::Ended,
1375
+ PhysicalPosition::new(24.0, 44.0),
1376
+ 2.0,
1377
+ ),
1378
+ vec![
1379
+ InputEvent::PointerMoved {
1380
+ pointer,
1381
+ position: InputPoint::new(12.0, 22.0),
1382
+ },
1383
+ InputEvent::PointerButton {
1384
+ pointer,
1385
+ button: MunPointerButton::Primary,
1386
+ state: MunButtonState::Released,
1387
+ },
1388
+ InputEvent::Cancel {
1389
+ pointer: Some(pointer),
1390
+ },
1391
+ ]
1392
+ );
1393
+
1394
+ assert_eq!(
1395
+ input_touch_events(
1396
+ 42,
1397
+ TouchPhase::Cancelled,
1398
+ PhysicalPosition::new(0.0, 0.0),
1399
+ 2.0,
1400
+ ),
1401
+ vec![InputEvent::Cancel {
1402
+ pointer: Some(pointer),
1403
+ }]
1404
+ );
1405
+ }
1406
+
1407
+ #[test]
1408
+ fn platform_scroll_phase_preserves_trackpad_gesture_boundaries() {
1409
+ assert_eq!(input_scroll_phase(TouchPhase::Started), ScrollPhase::Began);
1410
+ assert_eq!(input_scroll_phase(TouchPhase::Moved), ScrollPhase::Changed);
1411
+ assert_eq!(input_scroll_phase(TouchPhase::Ended), ScrollPhase::Ended);
1412
+ assert_eq!(
1413
+ input_scroll_phase(TouchPhase::Cancelled),
1414
+ ScrollPhase::Cancelled
1415
+ );
1416
+ }
1417
+
1418
+ #[test]
1419
+ fn platform_scroll_pixels_are_normalized_to_logical_points() {
1420
+ let delta = input_scroll_delta(
1421
+ MouseScrollDelta::PixelDelta(PhysicalPosition::new(20.0, -10.0)),
1422
+ 2.0,
1423
+ );
1424
+ assert_eq!(delta, ScrollDelta::Pixels { x: 10.0, y: -5.0 });
1425
+ }
1426
+
1427
+ #[test]
1428
+ fn rect_vertex_buffer_capacity_reuses_small_buffers_and_grows_geometrically() {
1429
+ assert_eq!(
1430
+ rect_vertex_buffer_capacity(1),
1431
+ INITIAL_RECT_VERTEX_BUFFER_BYTES
1432
+ );
1433
+ assert_eq!(
1434
+ rect_vertex_buffer_capacity(INITIAL_RECT_VERTEX_BUFFER_BYTES),
1435
+ INITIAL_RECT_VERTEX_BUFFER_BYTES
1436
+ );
1437
+ assert_eq!(
1438
+ rect_vertex_buffer_capacity(INITIAL_RECT_VERTEX_BUFFER_BYTES + 1),
1439
+ INITIAL_RECT_VERTEX_BUFFER_BYTES * 2
1440
+ );
1441
+ }
1442
+
1443
+ #[test]
1444
+ fn scissor_for_clip_rounds_outward_and_intersects_surface() {
1445
+ assert_eq!(
1446
+ scissor_for_clip(None, 20, 10, 2.0),
1447
+ Some(ScissorRect {
1448
+ x: 0,
1449
+ y: 0,
1450
+ width: 20,
1451
+ height: 10,
1452
+ })
1453
+ );
1454
+ assert_eq!(
1455
+ scissor_for_clip(
1456
+ Some(Rect {
1457
+ x: -0.25,
1458
+ y: 1.25,
1459
+ width: 10.5,
1460
+ height: 4.1,
1461
+ }),
1462
+ 20,
1463
+ 10,
1464
+ 2.0,
1465
+ ),
1466
+ Some(ScissorRect {
1467
+ x: 0,
1468
+ y: 2,
1469
+ width: 20,
1470
+ height: 8,
1471
+ })
1472
+ );
1473
+ assert_eq!(
1474
+ scissor_for_clip(
1475
+ Some(Rect {
1476
+ x: 30.0,
1477
+ y: 0.0,
1478
+ width: 5.0,
1479
+ height: 5.0,
1480
+ }),
1481
+ 20,
1482
+ 10,
1483
+ 1.0,
1484
+ ),
1485
+ None
1486
+ );
1487
+ }
1488
+
1489
+ #[test]
1490
+ fn scene_geometry_batches_equal_clips() {
1491
+ let item = |id: &str| SceneRect {
1492
+ id: id.into(),
1493
+ rect: Rect {
1494
+ x: 0.0,
1495
+ y: 0.0,
1496
+ width: 10.0,
1497
+ height: 10.0,
1498
+ },
1499
+ color: Color([1.0; 4]),
1500
+ corner_radius: 0.0,
1501
+ };
1502
+ let scene = Scene {
1503
+ rects: vec![item("a"), item("b")],
1504
+ ..Default::default()
1505
+ };
1506
+ let mut presentation = ScenePresentation::default();
1507
+ let clip = presentation.push_clip(
1508
+ None,
1509
+ Rect {
1510
+ x: 5.0,
1511
+ y: 6.0,
1512
+ width: 20.0,
1513
+ height: 10.0,
1514
+ },
1515
+ None,
1516
+ );
1517
+ presentation.bind_clip("a", clip);
1518
+ presentation.bind_clip("b", clip);
1519
+
1520
+ let (vertices, batches, _) = scene_geometry(&scene, &presentation, 100, 80, 2.0, false);
1521
+ assert_eq!(vertices.len(), 12);
1522
+ assert_eq!(batches.len(), 1);
1523
+ assert_eq!(batches[0].start, 0);
1524
+ assert_eq!(batches[0].end, 12);
1525
+ assert_eq!(
1526
+ batches[0].scissor,
1527
+ ScissorRect {
1528
+ x: 10,
1529
+ y: 12,
1530
+ width: 40,
1531
+ height: 20
1532
+ }
1533
+ );
1534
+ }
1535
+
1536
+ #[test]
1537
+ fn retained_text_buffer_reshapes_only_when_text_or_size_change() {
1538
+ // The window size is deliberately not an input: resizing never reshapes.
1539
+ let mut font_system = FontSystem::new();
1540
+ let mut cached = CachedTextBuffer::new(
1541
+ &mut font_system,
1542
+ "Hello",
1543
+ 16.0,
1544
+ None,
1545
+ SceneTextStyle::default(),
1546
+ );
1547
+
1548
+ assert!(!cached.update(
1549
+ &mut font_system,
1550
+ "Hello",
1551
+ 16.0,
1552
+ None,
1553
+ SceneTextStyle::default()
1554
+ ));
1555
+ assert!(cached.update(
1556
+ &mut font_system,
1557
+ "World",
1558
+ 16.0,
1559
+ None,
1560
+ SceneTextStyle::default()
1561
+ ));
1562
+ assert!(!cached.update(
1563
+ &mut font_system,
1564
+ "World",
1565
+ 16.0,
1566
+ None,
1567
+ SceneTextStyle::default()
1568
+ ));
1569
+ assert!(cached.update(
1570
+ &mut font_system,
1571
+ "World",
1572
+ 18.0,
1573
+ None,
1574
+ SceneTextStyle::default()
1575
+ ));
1576
+ }
1577
+
1578
+ #[test]
1579
+ fn scene_vertices_preserve_rounded_rect_geometry() {
1580
+ let scene = Scene {
1581
+ rects: vec![SceneRect {
1582
+ id: "rounded".into(),
1583
+ rect: Rect {
1584
+ x: 10.0,
1585
+ y: 20.0,
1586
+ width: 40.0,
1587
+ height: 20.0,
1588
+ },
1589
+ color: Color([0.25, 0.5, 0.75, 1.0]),
1590
+ corner_radius: 6.0,
1591
+ }],
1592
+ ..Default::default()
1593
+ };
1594
+
1595
+ let vertices = scene_vertices(&scene, &ScenePresentation::default(), 200.0, 120.0, 2.0);
1596
+
1597
+ assert_eq!(vertices.len(), 6);
1598
+ assert_eq!(vertices[0].local_position, [0.0, 0.0]);
1599
+ assert_eq!(vertices[2].local_position, [40.0, 20.0]);
1600
+ assert_eq!(vertices[0].rect_size, [40.0, 20.0]);
1601
+ assert_eq!(vertices[0].color, [0.25, 0.5, 0.75, 1.0]);
1602
+ assert_eq!(vertices[0].corner_radius, 6.0);
1603
+ }
1604
+
1605
+ #[test]
1606
+ fn scene_vertices_interpolate_linear_gradient_colors() {
1607
+ let scene = Scene {
1608
+ rects: vec![SceneRect {
1609
+ id: "gradient".into(),
1610
+ rect: Rect {
1611
+ x: 0.0,
1612
+ y: 0.0,
1613
+ width: 40.0,
1614
+ height: 20.0,
1615
+ },
1616
+ color: Color([1.0, 0.0, 0.0, 1.0]),
1617
+ corner_radius: 0.0,
1618
+ }],
1619
+ gradients: vec![mun_runtime::scene::SceneGradient {
1620
+ id: "gradient".into(),
1621
+ gradient: mun_runtime::scene::LinearGradient {
1622
+ start: Color([1.0, 0.0, 0.0, 1.0]),
1623
+ end: Color([0.0, 0.0, 1.0, 1.0]),
1624
+ start_point: [0.0, 0.5],
1625
+ end_point: [1.0, 0.5],
1626
+ },
1627
+ }],
1628
+ ..Default::default()
1629
+ };
1630
+
1631
+ let vertices = scene_vertices(&scene, &ScenePresentation::default(), 100.0, 80.0, 1.0);
1632
+
1633
+ assert_eq!(vertices.len(), 6);
1634
+ assert_eq!(vertices[0].local_position, [0.0, 0.0]);
1635
+ assert_eq!(vertices[0].color, [1.0, 0.0, 0.0, 1.0]);
1636
+ assert_eq!(vertices[2].local_position, [40.0, 20.0]);
1637
+ assert_eq!(vertices[2].color, [0.0, 0.0, 1.0, 1.0]);
1638
+ }
1639
+
1640
+ #[test]
1641
+ fn scene_vertices_apply_non_uniform_presentation_transform() {
1642
+ let scene = Scene {
1643
+ rects: vec![SceneRect {
1644
+ id: "box".into(),
1645
+ rect: Rect {
1646
+ x: 10.0,
1647
+ y: 20.0,
1648
+ width: 40.0,
1649
+ height: 20.0,
1650
+ },
1651
+ color: Color([1.0, 1.0, 1.0, 1.0]),
1652
+ corner_radius: 4.0,
1653
+ }],
1654
+ ..Default::default()
1655
+ };
1656
+ let mut presentation = ScenePresentation::default();
1657
+ let transform = presentation.push_transform(
1658
+ None,
1659
+ SceneTransform {
1660
+ scale_x: 0.5,
1661
+ scale_y: 2.0,
1662
+ translation_x: 5.0,
1663
+ translation_y: -10.0,
1664
+ },
1665
+ );
1666
+ presentation.bind("box", transform);
1667
+
1668
+ let vertices = scene_vertices(&scene, &presentation, 200.0, 120.0, 2.0);
1669
+
1670
+ assert!((vertices[0].position[0] - -0.8).abs() < 0.0001);
1671
+ assert!(vertices[0].position[1].abs() < 0.0001);
1672
+ assert!((vertices[2].position[0] - -0.4).abs() < 0.0001);
1673
+ assert!((vertices[2].position[1] - -1.3333334).abs() < 0.0001);
1674
+ assert_eq!(vertices[2].local_position, [40.0, 20.0]);
1675
+ assert_eq!(vertices[0].rect_size, [40.0, 20.0]);
1676
+ assert_eq!(vertices[0].corner_radius, 4.0);
1677
+ }
1678
+
1679
+ #[test]
1680
+ fn non_uniform_text_plan_rasterizes_at_largest_axis() {
1681
+ let plan = text_transform_plan(
1682
+ SceneTransform {
1683
+ scale_x: 2.0,
1684
+ scale_y: 0.5,
1685
+ translation_x: 3.0,
1686
+ translation_y: -4.0,
1687
+ },
1688
+ 200.0,
1689
+ 120.0,
1690
+ 2.0,
1691
+ )
1692
+ .unwrap()
1693
+ .unwrap();
1694
+
1695
+ assert_eq!(plan.raster_scale, 4.0);
1696
+ assert_eq!(plan.virtual_width, 400);
1697
+ assert_eq!(plan.virtual_height, 240);
1698
+ assert_eq!(plan.viewport_x, 6.0);
1699
+ assert_eq!(plan.viewport_y, -8.0);
1700
+ assert_eq!(plan.viewport_width, 400.0);
1701
+ assert_eq!(plan.viewport_height, 60.0);
1702
+ }
1703
+
1704
+ #[test]
1705
+ fn text_plan_skips_collapsed_axes_and_rejects_mirroring() {
1706
+ assert!(
1707
+ text_transform_plan(SceneTransform::scale(0.0, 1.0), 200.0, 120.0, 2.0)
1708
+ .unwrap()
1709
+ .is_none()
1710
+ );
1711
+ assert!(text_transform_plan(SceneTransform::scale(-1.0, 1.0), 200.0, 120.0, 2.0).is_err());
1712
+ }
1713
+ }
1714
+
1715
+ fn input_button_state(state: ElementState) -> MunButtonState {
1716
+ match state {
1717
+ ElementState::Pressed => MunButtonState::Pressed,
1718
+ ElementState::Released => MunButtonState::Released,
1719
+ }
1720
+ }
1721
+
1722
+ fn input_mouse_button(button: MouseButton) -> MunPointerButton {
1723
+ match button {
1724
+ MouseButton::Left => MunPointerButton::Primary,
1725
+ MouseButton::Right => MunPointerButton::Secondary,
1726
+ MouseButton::Middle => MunPointerButton::Middle,
1727
+ MouseButton::Back => MunPointerButton::Back,
1728
+ MouseButton::Forward => MunPointerButton::Forward,
1729
+ MouseButton::Other(button) => MunPointerButton::Other(button),
1730
+ }
1731
+ }
1732
+
1733
+ fn input_logical_key(key: &Key) -> LogicalKey {
1734
+ match key {
1735
+ Key::Named(NamedKey::Tab) => LogicalKey::Tab,
1736
+ Key::Named(NamedKey::Enter) => LogicalKey::Enter,
1737
+ Key::Named(NamedKey::Space) => LogicalKey::Space,
1738
+ Key::Named(NamedKey::Escape) => LogicalKey::Escape,
1739
+ Key::Named(NamedKey::ArrowUp) => LogicalKey::ArrowUp,
1740
+ Key::Named(NamedKey::ArrowDown) => LogicalKey::ArrowDown,
1741
+ Key::Named(NamedKey::ArrowLeft) => LogicalKey::ArrowLeft,
1742
+ Key::Named(NamedKey::ArrowRight) => LogicalKey::ArrowRight,
1743
+ Key::Named(NamedKey::Home) => LogicalKey::Home,
1744
+ Key::Named(NamedKey::End) => LogicalKey::End,
1745
+ Key::Named(NamedKey::PageUp) => LogicalKey::PageUp,
1746
+ Key::Named(NamedKey::PageDown) => LogicalKey::PageDown,
1747
+ Key::Named(NamedKey::Backspace) => LogicalKey::Backspace,
1748
+ Key::Named(NamedKey::Delete) => LogicalKey::Delete,
1749
+ Key::Character(value) => LogicalKey::Character(value.to_string()),
1750
+ _ => LogicalKey::Unidentified,
1751
+ }
1752
+ }
1753
+
1754
+ /// With Command/Control held, letter shortcuts are identified by their
1755
+ /// physical key: a non-Latin input source (e.g. Korean 2-Set reports `ㅁ` for
1756
+ /// the A key) must not disable Cmd+A, Cmd+Z, Cmd+C and friends.
1757
+ fn shortcut_key(modifiers: &Modifiers, key: WinitPhysicalKey) -> Option<LogicalKey> {
1758
+ if !(modifiers.meta || modifiers.control) {
1759
+ return None;
1760
+ }
1761
+ let WinitPhysicalKey::Code(code) = key else {
1762
+ return None;
1763
+ };
1764
+ let name = format!("{code:?}");
1765
+ let letter = name.strip_prefix("Key")?;
1766
+ (letter.len() == 1).then(|| LogicalKey::Character(letter.to_ascii_lowercase()))
1767
+ }
1768
+
1769
+ fn input_physical_key(key: WinitPhysicalKey) -> MunPhysicalKey {
1770
+ match key {
1771
+ WinitPhysicalKey::Code(KeyCode::Tab) => MunPhysicalKey::Tab,
1772
+ WinitPhysicalKey::Code(KeyCode::Enter) => MunPhysicalKey::Enter,
1773
+ WinitPhysicalKey::Code(KeyCode::Space) => MunPhysicalKey::Space,
1774
+ WinitPhysicalKey::Code(KeyCode::Escape) => MunPhysicalKey::Escape,
1775
+ WinitPhysicalKey::Code(KeyCode::ArrowUp) => MunPhysicalKey::ArrowUp,
1776
+ WinitPhysicalKey::Code(KeyCode::ArrowDown) => MunPhysicalKey::ArrowDown,
1777
+ WinitPhysicalKey::Code(KeyCode::ArrowLeft) => MunPhysicalKey::ArrowLeft,
1778
+ WinitPhysicalKey::Code(KeyCode::ArrowRight) => MunPhysicalKey::ArrowRight,
1779
+ WinitPhysicalKey::Code(KeyCode::Home) => MunPhysicalKey::Home,
1780
+ WinitPhysicalKey::Code(KeyCode::End) => MunPhysicalKey::End,
1781
+ WinitPhysicalKey::Code(KeyCode::PageUp) => MunPhysicalKey::PageUp,
1782
+ WinitPhysicalKey::Code(KeyCode::PageDown) => MunPhysicalKey::PageDown,
1783
+ WinitPhysicalKey::Code(KeyCode::Backspace) => MunPhysicalKey::Backspace,
1784
+ WinitPhysicalKey::Code(KeyCode::Delete) => MunPhysicalKey::Delete,
1785
+ WinitPhysicalKey::Code(_) => MunPhysicalKey::Other,
1786
+ WinitPhysicalKey::Unidentified(_) => MunPhysicalKey::Unidentified,
1787
+ }
1788
+ }
1789
+
1790
+ fn input_modifiers(state: ModifiersState) -> Modifiers {
1791
+ Modifiers {
1792
+ shift: state.shift_key(),
1793
+ control: state.control_key(),
1794
+ alt: state.alt_key(),
1795
+ meta: state.super_key(),
1796
+ }
1797
+ }
1798
+
1799
+ fn input_scroll_delta(delta: MouseScrollDelta, scale_factor: f64) -> ScrollDelta {
1800
+ match delta {
1801
+ MouseScrollDelta::LineDelta(x, y) => ScrollDelta::Lines { x, y },
1802
+ MouseScrollDelta::PixelDelta(position) => ScrollDelta::Pixels {
1803
+ x: (position.x / scale_factor) as f32,
1804
+ y: (position.y / scale_factor) as f32,
1805
+ },
1806
+ }
1807
+ }
1808
+
1809
+ fn input_scroll_phase(phase: TouchPhase) -> ScrollPhase {
1810
+ match phase {
1811
+ TouchPhase::Started => ScrollPhase::Began,
1812
+ TouchPhase::Moved => ScrollPhase::Changed,
1813
+ TouchPhase::Ended => ScrollPhase::Ended,
1814
+ TouchPhase::Cancelled => ScrollPhase::Cancelled,
1815
+ }
1816
+ }
1817
+
1818
+ fn input_touch_events(
1819
+ id: u64,
1820
+ phase: TouchPhase,
1821
+ position: PhysicalPosition<f64>,
1822
+ scale_factor: f64,
1823
+ ) -> Vec<InputEvent> {
1824
+ let pointer = PointerId::touch(id);
1825
+ let position = InputPoint::new(
1826
+ (position.x / scale_factor) as f32,
1827
+ (position.y / scale_factor) as f32,
1828
+ );
1829
+ let moved = InputEvent::PointerMoved { pointer, position };
1830
+
1831
+ match phase {
1832
+ TouchPhase::Started => vec![
1833
+ moved,
1834
+ InputEvent::PointerButton {
1835
+ pointer,
1836
+ button: MunPointerButton::Primary,
1837
+ state: MunButtonState::Pressed,
1838
+ },
1839
+ ],
1840
+ TouchPhase::Moved => vec![moved],
1841
+ TouchPhase::Ended => vec![
1842
+ moved,
1843
+ InputEvent::PointerButton {
1844
+ pointer,
1845
+ button: MunPointerButton::Primary,
1846
+ state: MunButtonState::Released,
1847
+ },
1848
+ InputEvent::Cancel {
1849
+ pointer: Some(pointer),
1850
+ },
1851
+ ],
1852
+ TouchPhase::Cancelled => vec![InputEvent::Cancel {
1853
+ pointer: Some(pointer),
1854
+ }],
1855
+ }
1856
+ }
1857
+
1858
+ struct WindowState {
1859
+ runtime: Runtime,
1860
+ renderer: GpuRenderer,
1861
+ accessibility: AccessibilityHost,
1862
+ last_frame: Instant,
1863
+ clipboard: Option<arboard::Clipboard>,
1864
+ modifiers: Modifiers,
1865
+ ime_composing: bool,
1866
+ ime_allowed: bool,
1867
+ ime_cursor_area: Option<mun_runtime::Rect>,
1868
+ /// `MUN_NATIVE_TRACE=1`: JSON-lines trace of platform input and resulting
1869
+ /// semantic state on stderr, for verifying manual platform sessions.
1870
+ trace: bool,
1871
+ minimum_size: MinimumSizeSync,
1872
+ window: Arc<Window>,
1873
+ }
1874
+
1875
+ /// Keeps the window's minimum inner size at the layout-derived minimum
1876
+ /// (`Runtime::minimum_window_size`). The minimum is recomputed only when the
1877
+ /// runtime's state revision changes, when motion starts or settles (animated
1878
+ /// sizes are read at their presentation values), or after a hot update; never
1879
+ /// per frame. Sizes are logical, so a scale-factor change needs nothing.
1880
+ #[derive(Default)]
1881
+ struct MinimumSizeSync {
1882
+ key: Option<(u64, bool)>,
1883
+ applied: Option<(f32, f32)>,
1884
+ }
1885
+
1886
+ impl MinimumSizeSync {
1887
+ /// Recompute on the next sync (the program itself was replaced).
1888
+ fn invalidate(&mut self) {
1889
+ self.key = None;
1890
+ }
1891
+
1892
+ fn sync(&mut self, window: &Window, runtime: &Runtime) {
1893
+ let key = (runtime.revision(), runtime.has_active_motion());
1894
+ if self.key == Some(key) {
1895
+ return;
1896
+ }
1897
+ self.key = Some(key);
1898
+ let (width, height) = runtime.minimum_window_size();
1899
+ if self.applied.is_some_and(|(applied_width, applied_height)| {
1900
+ (applied_width - width).abs() < 0.5 && (applied_height - height).abs() < 0.5
1901
+ }) {
1902
+ return;
1903
+ }
1904
+ self.applied = Some((width, height));
1905
+ let (width, height) = (width as f64, height as f64);
1906
+ window.set_min_inner_size(Some(LogicalSize::new(width, height)));
1907
+ // A minimum only limits later resizes: grow a window that is already
1908
+ // smaller (initial size below the minimum, or content that grew).
1909
+ let current = window.inner_size().to_logical::<f64>(window.scale_factor());
1910
+ if current.width < width || current.height < height {
1911
+ let _ = window.request_inner_size(LogicalSize::new(
1912
+ current.width.max(width),
1913
+ current.height.max(height),
1914
+ ));
1915
+ }
1916
+ }
1917
+ }
1918
+
1919
+ /// Drop the platform input method's marked text after the runtime deliberately
1920
+ /// committed or cancelled a composition (pointer relocation, focus change).
1921
+ /// winit's `set_ime_allowed(false)` only clears its own copy on macOS; the
1922
+ /// system input context must be told explicitly or the IME keeps composing.
1923
+ #[cfg(target_os = "macos")]
1924
+ fn discard_platform_marked_text() {
1925
+ if let Some(mtm) = objc2_foundation::MainThreadMarker::new() {
1926
+ // SAFETY: called on the main thread (checked by `MainThreadMarker`).
1927
+ if let Some(context) =
1928
+ unsafe { objc2_app_kit::NSTextInputContext::currentInputContext(mtm) }
1929
+ {
1930
+ context.discardMarkedText();
1931
+ }
1932
+ }
1933
+ }
1934
+
1935
+ #[cfg(not(target_os = "macos"))]
1936
+ fn discard_platform_marked_text() {
1937
+ // Windows (IMM/TSF) and X11/Wayland input methods are reset by the
1938
+ // allowed-state toggle performed in `sync_text_input`.
1939
+ }
1940
+
1941
+ impl WindowState {
1942
+ async fn new(
1943
+ window: Arc<Window>,
1944
+ event_loop: &ActiveEventLoop,
1945
+ mut runtime: Runtime,
1946
+ proxy: EventLoopProxy<NativeEvent>,
1947
+ ) -> Result<Self, GpuError> {
1948
+ let shaping = Rc::new(TextShaping::new(FontSystem::new()));
1949
+ runtime.set_intrinsic_measurer(shaping.clone());
1950
+ runtime.set_platform_conventions(PlatformConventions::native());
1951
+ runtime.set_host_services(Box::new(host_services::DesktopHostServices));
1952
+ // Needs the real text measurer installed above; the window is still
1953
+ // hidden, so clamping the initial size up is not visible.
1954
+ let mut minimum_size = MinimumSizeSync::default();
1955
+ minimum_size.sync(&window, &runtime);
1956
+ let scale_factor = window.scale_factor() as f32;
1957
+ let size = window.inner_size();
1958
+ let logical_width = size.width.max(1) as f32 / scale_factor;
1959
+ let logical_height = size.height.max(1) as f32 / scale_factor;
1960
+ let tree = runtime
1961
+ .build_accessibility_tree(logical_width, logical_height)
1962
+ .map_err(|error| GpuError::new("layout", error))?;
1963
+ let accessibility = AccessibilityHost::new(event_loop, &window, tree, scale_factor, proxy);
1964
+ // The platform IME is routed only while an editable field owns focus.
1965
+ window.set_ime_allowed(false);
1966
+ window.set_visible(true);
1967
+ let renderer = GpuRenderer::new(window.clone(), event_loop, shaping).await?;
1968
+ Ok(Self {
1969
+ runtime,
1970
+ renderer,
1971
+ accessibility,
1972
+ last_frame: Instant::now(),
1973
+ clipboard: None,
1974
+ modifiers: Modifiers::default(),
1975
+ ime_composing: false,
1976
+ ime_allowed: false,
1977
+ ime_cursor_area: None,
1978
+ trace: std::env::var_os("MUN_NATIVE_TRACE").is_some_and(|value| value == "1"),
1979
+ minimum_size,
1980
+ window,
1981
+ })
1982
+ }
1983
+
1984
+ /// Trace a platform event and the semantic editing/focus state after it.
1985
+ fn trace_event(&self, platform: &str) {
1986
+ if !self.trace {
1987
+ return;
1988
+ }
1989
+ let focused = self.runtime.focused_action();
1990
+ let editor = self.runtime.focused_text_editor();
1991
+ let entry = serde_json::json!({
1992
+ "platform": platform,
1993
+ "focused": focused,
1994
+ "text": editor.map(|editor| editor.text()),
1995
+ "selection": editor.map(|editor| [editor.anchor(), editor.cursor()]),
1996
+ "preedit": editor.and_then(|editor| editor.composition()).map(|composition| &composition.text),
1997
+ "imeAllowed": self.ime_allowed,
1998
+ "imeArea": self.ime_cursor_area.map(|area| [area.x, area.y, area.width, area.height]),
1999
+ });
2000
+ eprintln!("MUN_TRACE {entry}");
2001
+ }
2002
+
2003
+ fn logical_size(&self) -> (f32, f32) {
2004
+ let scale = self.window.scale_factor() as f32;
2005
+ (
2006
+ self.renderer.config.width as f32 / scale,
2007
+ self.renderer.config.height as f32 / scale,
2008
+ )
2009
+ }
2010
+
2011
+ fn dispatch_input(&mut self, event: InputEvent) {
2012
+ let (width, height) = self.logical_size();
2013
+ let outcome = match self.runtime.handle_input(event, width, height) {
2014
+ Ok(outcome) => outcome,
2015
+ Err(error) => {
2016
+ // Layout failures are reported, never a crash of the host.
2017
+ eprintln!("{}", GpuError::new("layout", error));
2018
+ return;
2019
+ }
2020
+ };
2021
+ if outcome.needs_redraw {
2022
+ self.window.request_redraw();
2023
+ }
2024
+ self.service_clipboard();
2025
+ self.sync_text_input();
2026
+ }
2027
+
2028
+ /// Service runtime clipboard requests through the OS clipboard. Every cut and
2029
+ /// read is acknowledged, including failures, so the runtime never guesses.
2030
+ fn service_clipboard(&mut self) {
2031
+ use mun_runtime::input::ClipboardRequest;
2032
+ let (width, height) = self.logical_size();
2033
+ loop {
2034
+ let requests = self.runtime.take_clipboard_requests();
2035
+ if requests.is_empty() {
2036
+ return;
2037
+ }
2038
+ for request in requests {
2039
+ if self.clipboard.is_none() {
2040
+ match arboard::Clipboard::new() {
2041
+ Ok(clipboard) => self.clipboard = Some(clipboard),
2042
+ Err(error) => eprintln!("Mün clipboard unavailable: {error}"),
2043
+ }
2044
+ }
2045
+ let response = match (request, self.clipboard.as_mut()) {
2046
+ (ClipboardRequest::Write(text), Some(clipboard)) => {
2047
+ if let Err(error) = clipboard.set_text(text) {
2048
+ eprintln!("Mün clipboard write failed: {error}");
2049
+ }
2050
+ None
2051
+ }
2052
+ (ClipboardRequest::Write(_), None) => None,
2053
+ (ClipboardRequest::Cut { request, text }, clipboard) => {
2054
+ let success = match clipboard.map(|clipboard| clipboard.set_text(text)) {
2055
+ Some(Ok(())) => true,
2056
+ Some(Err(error)) => {
2057
+ eprintln!("Mün clipboard cut failed: {error}");
2058
+ false
2059
+ }
2060
+ None => false,
2061
+ };
2062
+ Some(InputEvent::ClipboardWriteCompleted { request, success })
2063
+ }
2064
+ (ClipboardRequest::Read { request, .. }, clipboard) => {
2065
+ let text = match clipboard.map(|clipboard| clipboard.get_text()) {
2066
+ Some(Ok(text)) => Some(text),
2067
+ Some(Err(error)) => {
2068
+ eprintln!("Mün clipboard read unavailable: {error}");
2069
+ None
2070
+ }
2071
+ None => None,
2072
+ };
2073
+ Some(InputEvent::ClipboardReadCompleted { request, text })
2074
+ }
2075
+ };
2076
+ if let Some(response) = response {
2077
+ match self.runtime.handle_input(response, width, height) {
2078
+ Ok(outcome) if outcome.needs_redraw || outcome.activated => {
2079
+ self.window.request_redraw();
2080
+ }
2081
+ Ok(_) => {}
2082
+ Err(error) => eprintln!("{}", GpuError::new("layout", error)),
2083
+ }
2084
+ }
2085
+ }
2086
+ }
2087
+ }
2088
+
2089
+ /// Keep the platform input method aligned with runtime-owned editing state.
2090
+ fn sync_text_input(&mut self) {
2091
+ let mut reset = false;
2092
+ for request in self.runtime.take_ime_requests() {
2093
+ match request {
2094
+ ImeRequest::DiscardComposition => {
2095
+ discard_platform_marked_text();
2096
+ self.ime_composing = false;
2097
+ reset = true;
2098
+ }
2099
+ }
2100
+ }
2101
+ let wants = self.runtime.wants_text_input();
2102
+ if reset && self.ime_allowed {
2103
+ // Clears winit's preedit copy (and on Windows/X11 ends the platform
2104
+ // composition); re-enabled below when an editable field keeps focus.
2105
+ self.window.set_ime_allowed(false);
2106
+ self.ime_allowed = false;
2107
+ }
2108
+ if wants != self.ime_allowed {
2109
+ self.window.set_ime_allowed(wants);
2110
+ self.ime_allowed = wants;
2111
+ if !wants {
2112
+ self.ime_composing = false;
2113
+ self.ime_cursor_area = None;
2114
+ }
2115
+ }
2116
+ }
2117
+
2118
+ fn update_ime_cursor_area(&mut self, area: Option<mun_runtime::Rect>) {
2119
+ if !self.ime_allowed || area == self.ime_cursor_area {
2120
+ return;
2121
+ }
2122
+ self.ime_cursor_area = area;
2123
+ if let Some(area) = area {
2124
+ self.window.set_ime_cursor_area(
2125
+ LogicalPosition::new(area.x as f64, area.y as f64),
2126
+ LogicalSize::new(area.width.max(1.0) as f64, area.height.max(1.0) as f64),
2127
+ );
2128
+ }
2129
+ }
2130
+
2131
+ fn handle_accessibility_action(&mut self, request: ActionRequest) {
2132
+ let Some((id, action)) = self.accessibility.semantic_request(&request) else {
2133
+ return;
2134
+ };
2135
+ let outcome = self.runtime.handle_accessibility_action(&id, action);
2136
+ if outcome.needs_redraw {
2137
+ self.window.request_redraw();
2138
+ }
2139
+ self.sync_text_input();
2140
+ }
2141
+
2142
+ fn redraw(&mut self) -> Option<FrameReport> {
2143
+ let size = self.window.inner_size();
2144
+ if size.width == 0 || size.height == 0 {
2145
+ return None;
2146
+ }
2147
+ let now = Instant::now();
2148
+ let dt = (now - self.last_frame).as_secs_f32().min(0.05);
2149
+ self.last_frame = now;
2150
+ self.runtime.step(dt);
2151
+ let step_micros = micros_since(now);
2152
+ self.minimum_size.sync(&self.window, &self.runtime);
2153
+
2154
+ let stage = Instant::now();
2155
+ let (width, height) = self.logical_size();
2156
+ let frame = match self.runtime.build_frame(width, height) {
2157
+ Ok(frame) => frame,
2158
+ Err(error) => {
2159
+ eprintln!("{}", GpuError::new("layout", error));
2160
+ return None;
2161
+ }
2162
+ };
2163
+ let layout_micros = micros_since(stage);
2164
+ let stage = Instant::now();
2165
+ self.update_ime_cursor_area(frame.ime_cursor_area);
2166
+ self.accessibility
2167
+ .update(frame.accessibility, self.window.scale_factor() as f32);
2168
+ let accessibility_micros = micros_since(stage);
2169
+ let status = self
2170
+ .renderer
2171
+ .render(&frame.scene, self.window.scale_factor() as f32);
2172
+ self.renderer.shaping.end_frame();
2173
+ if status == FrameStatus::Reconfigured || self.runtime.has_active_motion() {
2174
+ self.window.request_redraw();
2175
+ }
2176
+ Some(FrameReport {
2177
+ status,
2178
+ step_micros,
2179
+ layout_micros,
2180
+ accessibility_micros,
2181
+ render: self.renderer.last_timings,
2182
+ layout_sync: self.runtime.last_layout_sync(),
2183
+ culled_primitives: self.renderer.stats.culled_primitives,
2184
+ })
2185
+ }
2186
+ }
2187
+
2188
+ struct Application {
2189
+ state: Option<WindowState>,
2190
+ failure: Option<NativeBackendError>,
2191
+ proxy: EventLoopProxy<NativeEvent>,
2192
+ runtime: Option<Runtime>,
2193
+ smoke_frames: Option<u32>,
2194
+ dev: Option<dev::DevLink>,
2195
+ dev_program: Option<dev::DevProgram>,
2196
+ /// The latest applied dev revision not yet shown on screen.
2197
+ pending_presentation: Option<PendingPresentation>,
2198
+ }
2199
+
2200
+ /// Tell the toolchain when a hot update first reaches the screen, with the
2201
+ /// frame's stage costs. Skipped frames (occluded/minimized window) are counted
2202
+ /// and the update stays pending until a frame is actually presented.
2203
+ fn report_presentation(
2204
+ link: &dev::DevLink,
2205
+ pending: &mut Option<PendingPresentation>,
2206
+ report: &FrameReport,
2207
+ ) {
2208
+ let Some(waiting) = pending.as_mut() else {
2209
+ return;
2210
+ };
2211
+ if report.status != FrameStatus::Presented {
2212
+ waiting.skipped_frames += 1;
2213
+ return;
2214
+ }
2215
+ let waiting = pending.take().expect("pending presentation checked above");
2216
+ link.send(&serde_json::json!({
2217
+ "type": "update-presented",
2218
+ "revision": waiting.revision,
2219
+ "receiveToPresentMicros": micros_since(waiting.received),
2220
+ "applyToPresentMicros": micros_since(waiting.applied),
2221
+ "skippedFrames": waiting.skipped_frames,
2222
+ "supersededRevisions": waiting.superseded,
2223
+ "frame": {
2224
+ "stepMicros": report.step_micros,
2225
+ "layoutMicros": report.layout_micros,
2226
+ "accessibilityMicros": report.accessibility_micros,
2227
+ "prepareMicros": report.render.prepare_micros,
2228
+ "acquireMicros": report.render.acquire_micros,
2229
+ "submitMicros": report.render.submit_micros,
2230
+ "presentMicros": report.render.present_micros,
2231
+ "layoutNodes": report.layout_sync.live,
2232
+ "layoutInvalidated": report.layout_sync.invalidated(),
2233
+ "culledPrimitives": report.culled_primitives,
2234
+ },
2235
+ }));
2236
+ }
2237
+
2238
+ /// Measured cost of one windowed frame (development instrumentation).
2239
+ struct FrameReport {
2240
+ status: FrameStatus,
2241
+ step_micros: u64,
2242
+ /// `Runtime::build_frame`: layout and scene/accessibility construction.
2243
+ layout_micros: u64,
2244
+ accessibility_micros: u64,
2245
+ render: RenderTimings,
2246
+ layout_sync: mun_runtime::layout_cache::LayoutSyncStats,
2247
+ culled_primitives: usize,
2248
+ }
2249
+
2250
+ /// A hot update waiting for its first presented frame (development only).
2251
+ struct PendingPresentation {
2252
+ revision: u64,
2253
+ received: Instant,
2254
+ applied: Instant,
2255
+ /// Frames skipped (occluded/timeout) while waiting.
2256
+ skipped_frames: u32,
2257
+ /// Older applied revisions this one superseded before any was presented.
2258
+ superseded: u32,
2259
+ }
2260
+
2261
+ impl Application {
2262
+ fn new(proxy: EventLoopProxy<NativeEvent>, runtime: Runtime) -> Self {
2263
+ Self {
2264
+ state: None,
2265
+ failure: None,
2266
+ proxy,
2267
+ runtime: Some(runtime),
2268
+ smoke_frames: None,
2269
+ dev: None,
2270
+ dev_program: None,
2271
+ pending_presentation: None,
2272
+ }
2273
+ }
2274
+
2275
+ fn runtime_mut(&mut self) -> Option<&mut Runtime> {
2276
+ match &mut self.state {
2277
+ Some(state) => Some(&mut state.runtime),
2278
+ None => self.runtime.as_mut(),
2279
+ }
2280
+ }
2281
+
2282
+ /// Report runtime contract diagnostics to the dev toolchain.
2283
+ fn forward_diagnostics(&mut self) {
2284
+ let Some(link) = self.dev.clone() else { return };
2285
+ let Some(runtime) = self.runtime_mut() else {
2286
+ return;
2287
+ };
2288
+ for diagnostic in runtime.take_diagnostics() {
2289
+ link.send(&serde_json::json!({
2290
+ "type": "diagnostic",
2291
+ "severity": "error",
2292
+ "message": format!("{diagnostic:?}"),
2293
+ "node": match &diagnostic {
2294
+ mun_runtime::RuntimeDiagnostic::RejectedTransaction { action, .. } => action.clone(),
2295
+ _ => None,
2296
+ },
2297
+ }));
2298
+ }
2299
+ }
2300
+
2301
+ fn handle_dev(&mut self, event_loop: &ActiveEventLoop, command: dev::DevCommand) {
2302
+ let Some(link) = self.dev.clone() else { return };
2303
+ match command {
2304
+ dev::DevCommand::Update {
2305
+ id,
2306
+ base_revision,
2307
+ revision,
2308
+ body,
2309
+ preserve,
2310
+ received,
2311
+ } => {
2312
+ let Some(mut dev_program) = self.dev_program.take() else {
2313
+ return;
2314
+ };
2315
+ let result = match self.runtime_mut() {
2316
+ Some(runtime) => dev_program.apply(
2317
+ runtime,
2318
+ base_revision,
2319
+ revision,
2320
+ body,
2321
+ &preserve,
2322
+ received,
2323
+ ),
2324
+ None => Err(dev::UpdateRejection {
2325
+ code: "runtime-unavailable",
2326
+ message: "native host has no runtime".into(),
2327
+ current_revision: dev_program.revision(),
2328
+ }),
2329
+ };
2330
+ self.dev_program = Some(dev_program);
2331
+ match result {
2332
+ Ok((report, timings)) => {
2333
+ if let Some(state) = &mut self.state {
2334
+ state.window.set_title(state.runtime.title());
2335
+ state.minimum_size.invalidate();
2336
+ state.sync_text_input();
2337
+ state.window.request_redraw();
2338
+ }
2339
+ let superseded = self
2340
+ .pending_presentation
2341
+ .as_ref()
2342
+ .map_or(0, |pending| pending.superseded + 1);
2343
+ self.pending_presentation = Some(PendingPresentation {
2344
+ revision,
2345
+ received: received.at,
2346
+ applied: Instant::now(),
2347
+ skipped_frames: 0,
2348
+ superseded,
2349
+ });
2350
+ link.send(&serde_json::json!({
2351
+ "type": "update-applied",
2352
+ "id": id,
2353
+ "revision": revision,
2354
+ "applyMicros": timings.apply_micros,
2355
+ "timings": timings.to_json(),
2356
+ "preservedStates": report.preserved_states,
2357
+ "resetStates": report.reset_states,
2358
+ "insertedNodes": report.inserted_nodes,
2359
+ "removedNodes": report.removed_nodes,
2360
+ "lifecycleMutations": report.lifecycle_mutations,
2361
+ }));
2362
+ }
2363
+ Err(rejection) => link.send(&serde_json::json!({
2364
+ "type": "update-rejected",
2365
+ "id": id,
2366
+ "code": rejection.code,
2367
+ "currentRevision": rejection.current_revision,
2368
+ "message": rejection.message,
2369
+ })),
2370
+ }
2371
+ self.forward_diagnostics();
2372
+ }
2373
+ dev::DevCommand::Inspect { id, include_values } => {
2374
+ let size = self
2375
+ .state
2376
+ .as_ref()
2377
+ .map(|state| state.logical_size())
2378
+ .unwrap_or((640.0, 420.0));
2379
+ let Some(runtime) = self.runtime_mut() else {
2380
+ return;
2381
+ };
2382
+ let snapshot = runtime.inspect(size.0, size.1, include_values);
2383
+ link.send(
2384
+ &serde_json::json!({ "type": "snapshot", "id": id, "snapshot": snapshot }),
2385
+ );
2386
+ }
2387
+ // The toolchain owns a dev app: when it goes away, so does the app.
2388
+ dev::DevCommand::Disconnected(_) => event_loop.exit(),
2389
+ }
2390
+ }
2391
+ }
2392
+
2393
+ impl ApplicationHandler<NativeEvent> for Application {
2394
+ fn resumed(&mut self, event_loop: &ActiveEventLoop) {
2395
+ if self.state.is_some() {
2396
+ return;
2397
+ }
2398
+
2399
+ let runtime = self
2400
+ .runtime
2401
+ .take()
2402
+ .expect("Mün runtime must be available before the native window is created");
2403
+ let (width, height) = runtime.initial_window_size();
2404
+ let window = match event_loop.create_window(
2405
+ Window::default_attributes()
2406
+ .with_title(runtime.title())
2407
+ .with_visible(false)
2408
+ .with_inner_size(LogicalSize::new(width as f64, height as f64)),
2409
+ ) {
2410
+ Ok(window) => Arc::new(window),
2411
+ Err(error) => {
2412
+ self.failure = Some(NativeBackendError::Window(error));
2413
+ event_loop.exit();
2414
+ return;
2415
+ }
2416
+ };
2417
+ match pollster::block_on(WindowState::new(
2418
+ window,
2419
+ event_loop,
2420
+ runtime,
2421
+ self.proxy.clone(),
2422
+ )) {
2423
+ Ok(state) => self.state = Some(state),
2424
+ Err(error) => {
2425
+ self.failure = Some(NativeBackendError::Gpu(error));
2426
+ event_loop.exit();
2427
+ }
2428
+ }
2429
+ }
2430
+
2431
+ fn window_event(
2432
+ &mut self,
2433
+ event_loop: &ActiveEventLoop,
2434
+ _window_id: WindowId,
2435
+ event: WindowEvent,
2436
+ ) {
2437
+ let Some(state) = &mut self.state else { return };
2438
+ state.accessibility.process_event(&state.window, &event);
2439
+ let traced = state.trace.then(|| match &event {
2440
+ WindowEvent::Ime(ime) => Some(format!("{ime:?}")),
2441
+ WindowEvent::KeyboardInput { event, .. } => Some(format!(
2442
+ "Key {:?} {:?} text={:?}",
2443
+ event.logical_key, event.state, event.text
2444
+ )),
2445
+ WindowEvent::MouseWheel { delta, phase, .. } => {
2446
+ Some(format!("Wheel {delta:?} {phase:?}"))
2447
+ }
2448
+ WindowEvent::MouseInput { state, button, .. } => {
2449
+ Some(format!("Mouse {button:?} {state:?}"))
2450
+ }
2451
+ WindowEvent::Focused(focused) => Some(format!("WindowFocused {focused}")),
2452
+ WindowEvent::ScaleFactorChanged { scale_factor, .. } => {
2453
+ Some(format!("Scale {scale_factor}"))
2454
+ }
2455
+ _ => None,
2456
+ });
2457
+ match event {
2458
+ WindowEvent::CloseRequested => event_loop.exit(),
2459
+ WindowEvent::Resized(size) => {
2460
+ state.renderer.resize(size.width, size.height);
2461
+ state.window.request_redraw();
2462
+ }
2463
+ WindowEvent::ScaleFactorChanged { .. } => {
2464
+ let size = state.window.inner_size();
2465
+ state.renderer.resize(size.width, size.height);
2466
+ // The cached candidate area is logical; the platform position
2467
+ // it maps to changed with the scale, so send it again.
2468
+ state.ime_cursor_area = None;
2469
+ state.window.request_redraw();
2470
+ }
2471
+ WindowEvent::ModifiersChanged(modifiers) => {
2472
+ state.modifiers = input_modifiers(modifiers.state());
2473
+ state.dispatch_input(InputEvent::ModifiersChanged(input_modifiers(
2474
+ modifiers.state(),
2475
+ )));
2476
+ }
2477
+ WindowEvent::CursorMoved {
2478
+ position: PhysicalPosition { x, y },
2479
+ ..
2480
+ } => {
2481
+ let scale = state.window.scale_factor();
2482
+ state.dispatch_input(InputEvent::PointerMoved {
2483
+ pointer: PointerId::MOUSE,
2484
+ position: InputPoint::new((x / scale) as f32, (y / scale) as f32),
2485
+ });
2486
+ }
2487
+ WindowEvent::CursorLeft { .. } => {
2488
+ state.dispatch_input(InputEvent::Cancel {
2489
+ pointer: Some(PointerId::MOUSE),
2490
+ });
2491
+ }
2492
+ WindowEvent::MouseInput {
2493
+ state: button_state,
2494
+ button,
2495
+ ..
2496
+ } => {
2497
+ state.dispatch_input(InputEvent::PointerButton {
2498
+ pointer: PointerId::MOUSE,
2499
+ button: input_mouse_button(button),
2500
+ state: input_button_state(button_state),
2501
+ });
2502
+ }
2503
+ WindowEvent::MouseWheel { delta, phase, .. } => {
2504
+ state.dispatch_input(InputEvent::Scroll {
2505
+ pointer: Some(PointerId::MOUSE),
2506
+ delta: input_scroll_delta(delta, state.window.scale_factor()),
2507
+ phase: input_scroll_phase(phase),
2508
+ });
2509
+ }
2510
+ WindowEvent::Touch(touch) => {
2511
+ for event in input_touch_events(
2512
+ touch.id,
2513
+ touch.phase,
2514
+ touch.location,
2515
+ state.window.scale_factor(),
2516
+ ) {
2517
+ state.dispatch_input(event);
2518
+ }
2519
+ }
2520
+ WindowEvent::KeyboardInput { event, .. } => {
2521
+ let text = if event.state == ElementState::Pressed
2522
+ && !state.ime_composing
2523
+ && !state.modifiers.control
2524
+ && !state.modifiers.meta
2525
+ {
2526
+ event
2527
+ .text
2528
+ .as_ref()
2529
+ .map(|text| {
2530
+ text.chars()
2531
+ .filter(|ch| !ch.is_control())
2532
+ .collect::<String>()
2533
+ })
2534
+ .filter(|text| !text.is_empty())
2535
+ } else {
2536
+ None
2537
+ };
2538
+ state.dispatch_input(InputEvent::Key {
2539
+ logical: shortcut_key(&state.modifiers, event.physical_key)
2540
+ .unwrap_or_else(|| input_logical_key(&event.logical_key)),
2541
+ physical: input_physical_key(event.physical_key),
2542
+ state: match event.state {
2543
+ ElementState::Pressed => MunKeyState::Pressed,
2544
+ ElementState::Released => MunKeyState::Released,
2545
+ },
2546
+ repeat: event.repeat,
2547
+ });
2548
+ if let Some(text) = text {
2549
+ state.dispatch_input(InputEvent::TextInput { text });
2550
+ }
2551
+ }
2552
+ WindowEvent::Ime(event) => {
2553
+ use mun_runtime::text_edit::{Composition, TextEdit};
2554
+ let edit = match event {
2555
+ Ime::Enabled => None,
2556
+ Ime::Preedit(text, selection) => {
2557
+ state.ime_composing = !text.is_empty();
2558
+ if text.is_empty() {
2559
+ Some(TextEdit::CompositionCancel)
2560
+ } else {
2561
+ // winit preedit offsets are UTF-8 bytes. Normalize at the adapter.
2562
+ let scalar = |byte: usize| {
2563
+ text.char_indices()
2564
+ .take_while(|(index, _)| *index < byte)
2565
+ .count()
2566
+ };
2567
+ let selection = selection.map(|(a, b)| (scalar(a), scalar(b)));
2568
+ Some(TextEdit::CompositionUpdate(Composition { text, selection }))
2569
+ }
2570
+ }
2571
+ Ime::Commit(text) => {
2572
+ state.ime_composing = false;
2573
+ Some(TextEdit::CompositionCommit(text))
2574
+ }
2575
+ Ime::Disabled => {
2576
+ state.ime_composing = false;
2577
+ Some(TextEdit::CompositionCancel)
2578
+ }
2579
+ };
2580
+ if let Some(edit) = edit {
2581
+ state.dispatch_input(InputEvent::TextEdit(edit));
2582
+ }
2583
+ }
2584
+ WindowEvent::Focused(focused) => {
2585
+ if !focused {
2586
+ state.modifiers = Modifiers::default();
2587
+ state.ime_composing = false;
2588
+ }
2589
+ state.dispatch_input(InputEvent::WindowFocusChanged(focused));
2590
+ }
2591
+ WindowEvent::RedrawRequested => {
2592
+ let report = state.redraw();
2593
+ if let (Some(report), Some(link)) = (report, &self.dev) {
2594
+ report_presentation(link, &mut self.pending_presentation, &report);
2595
+ }
2596
+ if let Some(reason) = state.renderer.device_lost() {
2597
+ self.failure = Some(NativeBackendError::Gpu(GpuError {
2598
+ subsystem: "device",
2599
+ message: format!("GPU device lost: {reason}"),
2600
+ }));
2601
+ event_loop.exit();
2602
+ return;
2603
+ }
2604
+ if let Some(frames) = &mut self.smoke_frames {
2605
+ *frames = frames.saturating_sub(1);
2606
+ if *frames == 0 {
2607
+ event_loop.exit();
2608
+ } else {
2609
+ state.window.request_redraw();
2610
+ }
2611
+ }
2612
+ }
2613
+ _ => {}
2614
+ }
2615
+ if let (Some(Some(platform)), Some(state)) = (traced, &self.state) {
2616
+ state.trace_event(&platform);
2617
+ }
2618
+ self.forward_diagnostics();
2619
+ }
2620
+
2621
+ fn user_event(&mut self, event_loop: &ActiveEventLoop, event: NativeEvent) {
2622
+ match event {
2623
+ NativeEvent::Dev(command) => self.handle_dev(event_loop, command),
2624
+ NativeEvent::AccessibilityAction(request) => {
2625
+ let Some(state) = &mut self.state else { return };
2626
+ let platform = format!("AccessKit {:?} {:?}", request.action, request.data);
2627
+ state.handle_accessibility_action(request);
2628
+ state.trace_event(&platform);
2629
+ self.forward_diagnostics();
2630
+ }
2631
+ }
2632
+ }
2633
+ }
2634
+
2635
+ /// Run an initialized Mün semantic runtime in the desktop native backend.
2636
+ pub fn run_runtime(runtime: Runtime) -> Result<(), NativeBackendError> {
2637
+ let event_loop = EventLoop::<NativeEvent>::with_user_event().build()?;
2638
+ let proxy = event_loop.create_proxy();
2639
+ let mut application = Application::new(proxy, runtime);
2640
+ event_loop.run_app(&mut application)?;
2641
+ application.failure.map_or(Ok(()), Err)
2642
+ }
2643
+
2644
+ /// Render compiler-produced IR offscreen through the production renderer after
2645
+ /// applying a semantic input script; returns PNG bytes and a JSON report.
2646
+ pub fn render_program_png(
2647
+ program: &str,
2648
+ script: &serde_json::Value,
2649
+ logical_width: f32,
2650
+ logical_height: f32,
2651
+ scale_factor: f32,
2652
+ ) -> Result<(Vec<u8>, serde_json::Value), NativeBackendError> {
2653
+ let mut session = OffscreenSession::new(program, logical_width, logical_height, scale_factor)?;
2654
+ session.render().map_err(NativeBackendError::Gpu)?;
2655
+ session.apply_script(script).map_err(|message| {
2656
+ NativeBackendError::Gpu(GpuError {
2657
+ subsystem: "script",
2658
+ message,
2659
+ })
2660
+ })?;
2661
+ let timing = session.render().map_err(NativeBackendError::Gpu)?;
2662
+ let (width, height) = session.size();
2663
+ let rgba = session.rgba().ok_or_else(|| {
2664
+ NativeBackendError::Gpu(GpuError {
2665
+ subsystem: "readback",
2666
+ message: "offscreen target could not be read".into(),
2667
+ })
2668
+ })?;
2669
+ let frame = session
2670
+ .runtime()
2671
+ .build_frame(logical_width, logical_height)
2672
+ .map_err(|error| NativeBackendError::Gpu(GpuError::new("layout", error)))?;
2673
+ let stats = session.renderer_stats();
2674
+ let report = serde_json::json!({
2675
+ "width": width,
2676
+ "height": height,
2677
+ "focused": session.runtime().focused_action(),
2678
+ "imeCursorArea": frame.ime_cursor_area.map(|area| [area.x, area.y, area.width, area.height]),
2679
+ "rects": frame.scene.rects.iter().map(|item| serde_json::json!({
2680
+ "id": item.id,
2681
+ "rect": [item.rect.x, item.rect.y, item.rect.width, item.rect.height],
2682
+ })).collect::<Vec<_>>(),
2683
+ "texts": frame.scene.texts.iter().map(|item| serde_json::json!({
2684
+ "id": item.id, "text": item.text, "x": item.x, "y": item.y,
2685
+ })).collect::<Vec<_>>(),
2686
+ "retainedNodes": session.runtime().retained_tree().len(),
2687
+ "textBuffers": stats.text_buffers,
2688
+ "textReshapes": stats.text_reshapes,
2689
+ "buildMicros": timing.build_micros,
2690
+ "renderMicros": timing.render_micros,
2691
+ });
2692
+ Ok((encode_png(width, height, &rgba), report))
2693
+ }
2694
+
2695
+ /// Headless development measurement: apply a recorded stream of dev updates
2696
+ /// (one `update`/`patch` message per line, as `mun dev` sends them) through the
2697
+ /// same [`dev::DevProgram::apply`] path the windowed host uses, rendering one
2698
+ /// offscreen frame through the production renderer after each. Returns a JSON
2699
+ /// report with per-update stage timings. Opens no window.
2700
+ pub fn replay_dev_updates(
2701
+ program: &str,
2702
+ updates: &str,
2703
+ logical_width: f32,
2704
+ logical_height: f32,
2705
+ scale_factor: f32,
2706
+ ) -> Result<serde_json::Value, NativeBackendError> {
2707
+ let failure = |subsystem: &'static str, message: String| {
2708
+ NativeBackendError::Gpu(GpuError { subsystem, message })
2709
+ };
2710
+ let mut session = OffscreenSession::new(program, logical_width, logical_height, scale_factor)?;
2711
+ let initial = session.render().map_err(NativeBackendError::Gpu)?;
2712
+ let initial_gpu = session.wait_for_gpu();
2713
+ let mut dev_program = dev::DevProgram::new(
2714
+ serde_json::from_str(program).map_err(|error| failure("replay", error.to_string()))?,
2715
+ );
2716
+ let mut records = Vec::new();
2717
+ for (index, line) in updates
2718
+ .lines()
2719
+ .enumerate()
2720
+ .filter(|(_, line)| !line.trim().is_empty())
2721
+ {
2722
+ let started = Instant::now();
2723
+ let message: serde_json::Value = serde_json::from_str(line)
2724
+ .map_err(|error| failure("replay", format!("update {}: {error}", index + 1)))?;
2725
+ let received = dev::Received {
2726
+ decode_micros: micros_since(started),
2727
+ at: Instant::now(),
2728
+ };
2729
+ let Ok(dev::DevCommand::Update {
2730
+ base_revision,
2731
+ revision,
2732
+ body,
2733
+ preserve,
2734
+ ..
2735
+ }) = dev::parse_command(message, received)
2736
+ else {
2737
+ return Err(failure(
2738
+ "replay",
2739
+ format!("update {} is not an update/patch message", index + 1),
2740
+ ));
2741
+ };
2742
+ let kind = if matches!(body, dev::UpdateBody::Patch(_)) {
2743
+ "patch"
2744
+ } else {
2745
+ "update"
2746
+ };
2747
+ let (report, timings) = dev_program
2748
+ .apply(
2749
+ session.runtime_mut(),
2750
+ base_revision,
2751
+ revision,
2752
+ body,
2753
+ &preserve,
2754
+ received,
2755
+ )
2756
+ .map_err(|rejection| {
2757
+ failure(
2758
+ "replay",
2759
+ format!(
2760
+ "update {} rejected ({}): {}",
2761
+ index + 1,
2762
+ rejection.code,
2763
+ rejection.message
2764
+ ),
2765
+ )
2766
+ })?;
2767
+ let frame = session.render().map_err(NativeBackendError::Gpu)?;
2768
+ let render = session.last_render_timings();
2769
+ let gpu_micros = session.wait_for_gpu();
2770
+ records.push(serde_json::json!({
2771
+ "revision": revision,
2772
+ "type": kind,
2773
+ "update": timings.to_json(),
2774
+ "insertedNodes": report.inserted_nodes,
2775
+ "removedNodes": report.removed_nodes,
2776
+ "frame": {
2777
+ "layoutMicros": frame.build_micros,
2778
+ "prepareMicros": render.prepare_micros,
2779
+ "submitMicros": render.submit_micros,
2780
+ "gpuMicros": gpu_micros,
2781
+ "layoutNodes": session.runtime().last_layout_sync().live,
2782
+ "layoutInvalidated": session.runtime().last_layout_sync().invalidated(),
2783
+ "culledPrimitives": session.renderer_stats().culled_primitives,
2784
+ "reusedForEach": session.runtime().last_reused_for_each_count(),
2785
+ },
2786
+ "totalMicros": micros_since(started),
2787
+ }));
2788
+ }
2789
+ Ok(serde_json::json!({
2790
+ "initial": { "layoutMicros": initial.build_micros, "renderMicros": initial.render_micros, "gpuMicros": initial_gpu },
2791
+ "retainedNodes": session.runtime().retained_tree().len(),
2792
+ "updates": records,
2793
+ }))
2794
+ }
2795
+
2796
+ /// Bounded real-window/GPU/accesskit smoke path; failures remain fatal.
2797
+ pub fn smoke_program(program: &str) -> Result<(), NativeBackendError> {
2798
+ let runtime = Runtime::from_json(program)?;
2799
+ let event_loop = EventLoop::<NativeEvent>::with_user_event().build()?;
2800
+ let mut application = Application::new(event_loop.create_proxy(), runtime);
2801
+ application.smoke_frames = Some(3);
2802
+ event_loop.run_app(&mut application)?;
2803
+ application.failure.map_or(Ok(()), Err)
2804
+ }
2805
+
2806
+ /// Development launch: run the program and accept hot updates/inspection from
2807
+ /// the `mun dev` toolchain at a loopback `endpoint`. Never used by packaged apps.
2808
+ pub fn run_program_dev(
2809
+ program: &str,
2810
+ endpoint: &str,
2811
+ token: &str,
2812
+ ) -> Result<(), NativeBackendError> {
2813
+ let runtime = Runtime::from_json(program)?;
2814
+ let dev_program = dev::DevProgram::new(
2815
+ serde_json::from_str(program)
2816
+ .expect("Runtime::from_json accepted a program that serde_json then rejected"),
2817
+ );
2818
+ let event_loop = EventLoop::<NativeEvent>::with_user_event().build()?;
2819
+ let proxy = event_loop.create_proxy();
2820
+ let link = dev::DevLink::connect(endpoint, token, proxy.clone())
2821
+ .map_err(NativeBackendError::DevLink)?;
2822
+ let mut application = Application::new(proxy, runtime);
2823
+ application.dev = Some(link);
2824
+ application.dev_program = Some(dev_program);
2825
+ event_loop.run_app(&mut application)?;
2826
+ application.failure.map_or(Ok(()), Err)
2827
+ }
2828
+
2829
+ /// Parse compiler-produced Mün Semantic UI IR and run it in the desktop native backend.
2830
+ pub fn run_program(program: &str) -> Result<(), NativeBackendError> {
2831
+ run_runtime(Runtime::from_json(program)?)
2832
+ }
2833
+
2834
+ #[cfg(test)]
2835
+ mod backend_tests {
2836
+ use super::*;
2837
+
2838
+ #[test]
2839
+ fn invalid_program_fails_before_platform_startup() {
2840
+ let error = run_program("{").expect_err("invalid IR must fail before opening a window");
2841
+ assert!(matches!(error, NativeBackendError::Program(_)));
2842
+ }
2843
+ }