@mun-ui/ui 0.0.0-stage → 0.2.0

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