@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,204 @@
1
+ use std::{env, error::Error, fs, io, path::PathBuf};
2
+
3
+ enum Mode {
4
+ Run,
5
+ /// `--dev <ir>`: development launch connected to `mun dev`.
6
+ Dev,
7
+ Smoke,
8
+ /// Offscreen realization: `--render <ir> <out.png> [script.json]`.
9
+ Render {
10
+ output: PathBuf,
11
+ script: Option<PathBuf>,
12
+ },
13
+ /// Headless dev measurement: `--dev-replay <ir> <updates.ndjson>` applies
14
+ /// recorded `mun dev` updates offscreen and prints per-stage timings.
15
+ DevReplay {
16
+ updates: PathBuf,
17
+ },
18
+ }
19
+
20
+ fn usage(message: &str) -> io::Error {
21
+ io::Error::new(io::ErrorKind::InvalidInput, message.to_owned())
22
+ }
23
+
24
+ /// Resources of a packaged application, located relative to the executable:
25
+ /// `App.app/Contents/MacOS/<exe>` uses `Contents/Resources`; a portable
26
+ /// directory uses `Resources` next to the executable. Never the CWD.
27
+ fn bundled_program() -> Result<PathBuf, io::Error> {
28
+ let executable = env::current_exe()?.canonicalize()?;
29
+ let directory = executable
30
+ .parent()
31
+ .ok_or_else(|| usage("executable has no parent directory"))?;
32
+ let candidates = [
33
+ directory.join("../Resources/program.mun.ir.json"),
34
+ directory.join("Resources/program.mun.ir.json"),
35
+ ];
36
+ let macos_bundle = directory.ends_with("Contents/MacOS");
37
+ candidates
38
+ .into_iter()
39
+ .skip(if macos_bundle { 0 } else { 1 })
40
+ .find(|path| path.is_file())
41
+ .ok_or_else(|| {
42
+ usage(
43
+ "usage: mun-native [--dev | --smoke | --render <out.png> [script.json]] <semantic-ui-ir.json>\n\
44
+ (no packaged Resources/program.mun.ir.json next to this executable)",
45
+ )
46
+ })
47
+ }
48
+
49
+ fn program_path() -> Result<(PathBuf, Mode), io::Error> {
50
+ let mut arguments = env::args_os().skip(1).collect::<Vec<_>>().into_iter();
51
+ let Some(first) = arguments.next() else {
52
+ // No arguments: packaged application mode.
53
+ return Ok((bundled_program()?, Mode::Run));
54
+ };
55
+ let (path, mode) = if first == "--smoke" {
56
+ let path = arguments
57
+ .next()
58
+ .ok_or_else(|| usage("--smoke requires an IR path"))?;
59
+ (path, Mode::Smoke)
60
+ } else if first == "--dev" {
61
+ let path = arguments
62
+ .next()
63
+ .ok_or_else(|| usage("--dev requires an IR path"))?;
64
+ (path, Mode::Dev)
65
+ } else if first == "--render" {
66
+ let path = arguments
67
+ .next()
68
+ .ok_or_else(|| usage("--render requires an IR path"))?;
69
+ let output = arguments
70
+ .next()
71
+ .ok_or_else(|| usage("--render requires an output PNG path"))?;
72
+ let script = arguments.next().map(PathBuf::from);
73
+ (
74
+ path,
75
+ Mode::Render {
76
+ output: PathBuf::from(output),
77
+ script,
78
+ },
79
+ )
80
+ } else if first == "--dev-replay" {
81
+ let path = arguments
82
+ .next()
83
+ .ok_or_else(|| usage("--dev-replay requires an IR path"))?;
84
+ let updates = arguments
85
+ .next()
86
+ .ok_or_else(|| usage("--dev-replay requires an updates (NDJSON) path"))?;
87
+ (
88
+ path,
89
+ Mode::DevReplay {
90
+ updates: PathBuf::from(updates),
91
+ },
92
+ )
93
+ } else if first.to_string_lossy().starts_with("-psn_") {
94
+ // Finder/LaunchServices may pass a process serial number on old macOS.
95
+ return Ok((bundled_program()?, Mode::Run));
96
+ } else {
97
+ (first, Mode::Run)
98
+ };
99
+ if arguments.next().is_some() {
100
+ return Err(usage("mun-native accepts exactly one Semantic UI IR path"));
101
+ }
102
+ Ok((PathBuf::from(path), mode))
103
+ }
104
+
105
+ /// Machine-readable host identity used by release assembly and launchers to
106
+ /// reject a host built for another package version or IR contract.
107
+ fn host_info() -> String {
108
+ format!(
109
+ "{{\"name\":\"mun-native\",\"crateVersion\":\"{}\",\"semanticUiIrVersion\":{},\"os\":\"{}\",\"arch\":\"{}\",\"profile\":\"{}\"}}",
110
+ env!("CARGO_PKG_VERSION"),
111
+ mun_runtime::SEMANTIC_UI_IR_VERSION,
112
+ env::consts::OS,
113
+ env::consts::ARCH,
114
+ if cfg!(debug_assertions) {
115
+ "debug"
116
+ } else {
117
+ "release"
118
+ },
119
+ )
120
+ }
121
+
122
+ fn main() -> Result<(), Box<dyn Error>> {
123
+ if env::args_os()
124
+ .nth(1)
125
+ .is_some_and(|argument| argument == "--host-info")
126
+ {
127
+ println!("{}", host_info());
128
+ return Ok(());
129
+ }
130
+ let (path, mode) = program_path()?;
131
+ let source = fs::read_to_string(&path).map_err(|error| {
132
+ io::Error::new(
133
+ error.kind(),
134
+ format!(
135
+ "failed to read Mün Semantic UI IR from {}: {error}",
136
+ path.display()
137
+ ),
138
+ )
139
+ })?;
140
+ let failed = |error: mun_native::NativeBackendError| -> Box<dyn Error> {
141
+ io::Error::new(
142
+ io::ErrorKind::InvalidData,
143
+ format!(
144
+ "failed to run Mün Semantic UI IR from {}: {error}",
145
+ path.display()
146
+ ),
147
+ )
148
+ .into()
149
+ };
150
+ match mode {
151
+ Mode::Run => mun_native::run_program(&source).map_err(failed),
152
+ Mode::Dev => {
153
+ // The endpoint is honored only in this explicit development mode;
154
+ // production launches ignore these variables entirely.
155
+ let endpoint = env::var("MUN_DEV_ENDPOINT")
156
+ .map_err(|_| usage("--dev requires MUN_DEV_ENDPOINT (started by mun dev)"))?;
157
+ let token = env::var("MUN_DEV_TOKEN")
158
+ .map_err(|_| usage("--dev requires MUN_DEV_TOKEN (started by mun dev)"))?;
159
+ mun_native::run_program_dev(&source, &endpoint, &token).map_err(failed)
160
+ }
161
+ Mode::Smoke => mun_native::smoke_program(&source).map_err(failed),
162
+ Mode::Render { output, script } => {
163
+ let script = match script {
164
+ Some(script) => serde_json::from_str(&fs::read_to_string(script)?)?,
165
+ None => serde_json::Value::Array(Vec::new()),
166
+ };
167
+ let size = |name: &str, fallback: f32| {
168
+ env::var(name)
169
+ .ok()
170
+ .and_then(|value| value.parse::<f32>().ok())
171
+ .unwrap_or(fallback)
172
+ };
173
+ let (png, report) = mun_native::render_program_png(
174
+ &source,
175
+ &script,
176
+ size("MUN_RENDER_WIDTH", 640.0),
177
+ size("MUN_RENDER_HEIGHT", 420.0),
178
+ size("MUN_RENDER_SCALE", 2.0),
179
+ )
180
+ .map_err(failed)?;
181
+ fs::write(&output, png)?;
182
+ println!("{}", serde_json::to_string_pretty(&report)?);
183
+ Ok(())
184
+ }
185
+ Mode::DevReplay { updates } => {
186
+ let size = |name: &str, fallback: f32| {
187
+ env::var(name)
188
+ .ok()
189
+ .and_then(|value| value.parse::<f32>().ok())
190
+ .unwrap_or(fallback)
191
+ };
192
+ let report = mun_native::replay_dev_updates(
193
+ &source,
194
+ &fs::read_to_string(updates)?,
195
+ size("MUN_RENDER_WIDTH", 640.0),
196
+ size("MUN_RENDER_HEIGHT", 420.0),
197
+ size("MUN_RENDER_SCALE", 2.0),
198
+ )
199
+ .map_err(failed)?;
200
+ println!("{}", serde_json::to_string(&report)?);
201
+ Ok(())
202
+ }
203
+ }
204
+ }
@@ -0,0 +1,393 @@
1
+ //! Headless realization through the production renderer.
2
+ //!
3
+ //! An `OffscreenSession` drives the same `Runtime` semantics and the same
4
+ //! wgpu/glyphon realization as a window, but targets a texture. It exists for
5
+ //! pixel-level verification (caret, selection, preedit, scrollbars, clipping)
6
+ //! and for deterministic resource/timing measurement. It does not bypass or
7
+ //! re-implement any runtime semantics: steps are ordinary semantic input events.
8
+ use std::{rc::Rc, time::Instant};
9
+
10
+ use glyphon::FontSystem;
11
+ use mun_runtime::{
12
+ ButtonState, InputEvent, InputPoint, KeyState, LogicalKey, Modifiers, PhysicalKey,
13
+ PlatformConventions, PointerButton, PointerId, Runtime, ScrollDelta, ScrollPhase,
14
+ text_edit::{Composition, TextEdit},
15
+ };
16
+ use serde_json::Value;
17
+
18
+ use crate::{
19
+ FrameStatus, GpuError, GpuRenderer, NativeBackendError, RenderTimings, RendererStats,
20
+ text::TextShaping,
21
+ };
22
+
23
+ pub struct OffscreenSession {
24
+ runtime: Runtime,
25
+ renderer: GpuRenderer,
26
+ shaping: Rc<TextShaping>,
27
+ logical_width: f32,
28
+ logical_height: f32,
29
+ scale_factor: f32,
30
+ modifiers: Modifiers,
31
+ }
32
+
33
+ /// Measured cost of one representative frame.
34
+ #[derive(Clone, Copy, Debug, Default)]
35
+ pub struct FrameTiming {
36
+ pub build_micros: u128,
37
+ pub render_micros: u128,
38
+ }
39
+
40
+ impl OffscreenSession {
41
+ pub fn new(
42
+ program: &str,
43
+ logical_width: f32,
44
+ logical_height: f32,
45
+ scale_factor: f32,
46
+ ) -> Result<Self, NativeBackendError> {
47
+ let mut runtime = Runtime::from_json(program)?;
48
+ let shaping = Rc::new(TextShaping::new(FontSystem::new()));
49
+ runtime.set_intrinsic_measurer(shaping.clone());
50
+ runtime.set_platform_conventions(PlatformConventions::native());
51
+ let renderer = pollster::block_on(GpuRenderer::new_offscreen(
52
+ (logical_width * scale_factor).round() as u32,
53
+ (logical_height * scale_factor).round() as u32,
54
+ shaping.clone(),
55
+ ))
56
+ .map_err(NativeBackendError::Gpu)?;
57
+ Ok(Self {
58
+ runtime,
59
+ renderer,
60
+ shaping,
61
+ logical_width,
62
+ logical_height,
63
+ scale_factor,
64
+ modifiers: Modifiers::default(),
65
+ })
66
+ }
67
+
68
+ pub fn runtime(&self) -> &Runtime {
69
+ &self.runtime
70
+ }
71
+
72
+ pub fn runtime_mut(&mut self) -> &mut Runtime {
73
+ &mut self.runtime
74
+ }
75
+
76
+ pub fn renderer_stats(&self) -> RendererStats {
77
+ self.renderer.stats()
78
+ }
79
+
80
+ pub fn shaped_line_count(&self) -> u64 {
81
+ self.shaping.shaped_line_count()
82
+ }
83
+
84
+ pub fn cached_line_count(&self) -> usize {
85
+ self.shaping.cached_line_count()
86
+ }
87
+
88
+ /// Disable renderer culling of fully clipped primitives (differential
89
+ /// tests compare culled and unculled framebuffers).
90
+ #[doc(hidden)]
91
+ pub fn set_culling(&mut self, enabled: bool) {
92
+ self.renderer.culling = enabled;
93
+ }
94
+
95
+ /// The shaped line the runtime and renderer use for `text` (whatever fonts
96
+ /// this system resolves it to).
97
+ pub fn shaped_line(&self, text: &str, font_size: f32) -> mun_runtime::TextLineLayout {
98
+ mun_runtime::IntrinsicMeasurer::text_line(self.shaping.as_ref(), text, font_size)
99
+ }
100
+
101
+ pub fn size(&self) -> (u32, u32) {
102
+ (self.renderer.config.width, self.renderer.config.height)
103
+ }
104
+
105
+ /// Resize in logical points and/or change the device scale factor, as a
106
+ /// window moving between displays would.
107
+ pub fn resize(&mut self, logical_width: f32, logical_height: f32, scale_factor: f32) {
108
+ self.logical_width = logical_width;
109
+ self.logical_height = logical_height;
110
+ self.scale_factor = scale_factor;
111
+ self.renderer.resize(
112
+ (logical_width * scale_factor).round() as u32,
113
+ (logical_height * scale_factor).round() as u32,
114
+ );
115
+ }
116
+
117
+ pub fn input(&mut self, event: InputEvent) -> Result<(), GpuError> {
118
+ if let InputEvent::ModifiersChanged(modifiers) = &event {
119
+ self.modifiers = *modifiers;
120
+ }
121
+ self.runtime
122
+ .handle_input(event, self.logical_width, self.logical_height)
123
+ .map_err(|error| GpuError::new("layout", error))?;
124
+ // Clipboard requests are acknowledged as unavailable in headless runs so
125
+ // the runtime never waits on a host that cannot answer.
126
+ for request in self.runtime.take_clipboard_requests() {
127
+ let response = match request {
128
+ mun_runtime::input::ClipboardRequest::Write(_) => None,
129
+ mun_runtime::input::ClipboardRequest::Cut { request, .. } => {
130
+ Some(InputEvent::ClipboardWriteCompleted {
131
+ request,
132
+ success: false,
133
+ })
134
+ }
135
+ mun_runtime::input::ClipboardRequest::Read { request, .. } => {
136
+ Some(InputEvent::ClipboardReadCompleted {
137
+ request,
138
+ text: None,
139
+ })
140
+ }
141
+ };
142
+ if let Some(response) = response {
143
+ self.runtime
144
+ .handle_input(response, self.logical_width, self.logical_height)
145
+ .map_err(|error| GpuError::new("layout", error))?;
146
+ }
147
+ }
148
+ self.runtime.take_ime_requests();
149
+ Ok(())
150
+ }
151
+
152
+ pub fn render(&mut self) -> Result<FrameTiming, GpuError> {
153
+ let start = Instant::now();
154
+ let frame = self
155
+ .runtime
156
+ .build_frame(self.logical_width, self.logical_height)
157
+ .map_err(|error| GpuError::new("layout", error))?;
158
+ let built = Instant::now();
159
+ let status = self.renderer.render(&frame.scene, self.scale_factor);
160
+ self.shaping.end_frame();
161
+ let done = Instant::now();
162
+ if status != FrameStatus::Presented {
163
+ return Err(GpuError::new(
164
+ "surface",
165
+ format!("offscreen frame {status:?}"),
166
+ ));
167
+ }
168
+ if let Some(reason) = self.renderer.device_lost() {
169
+ return Err(GpuError::new("device", reason));
170
+ }
171
+ Ok(FrameTiming {
172
+ build_micros: (built - start).as_micros(),
173
+ render_micros: (done - built).as_micros(),
174
+ })
175
+ }
176
+
177
+ pub fn rgba(&self) -> Option<Vec<u8>> {
178
+ self.renderer.read_offscreen_rgba()
179
+ }
180
+
181
+ /// Stage costs of the most recent [`Self::render`].
182
+ pub fn last_render_timings(&self) -> RenderTimings {
183
+ self.renderer.last_timings
184
+ }
185
+
186
+ /// Block until submitted GPU work finishes; returns the wait in microseconds.
187
+ /// Submission is asynchronous, so this is where GPU execution time shows up.
188
+ pub fn wait_for_gpu(&self) -> u64 {
189
+ let started = Instant::now();
190
+ let _ = self
191
+ .renderer
192
+ .device
193
+ .poll(wgpu::PollType::wait_indefinitely());
194
+ u64::try_from(started.elapsed().as_micros()).unwrap_or(u64::MAX)
195
+ }
196
+
197
+ /// Apply one scripted semantic step (see `apply_script`).
198
+ pub fn apply_step(&mut self, step: &Value) -> Result<(), String> {
199
+ let text = |key: &str| step.get(key).and_then(Value::as_str).map(str::to_owned);
200
+ let number = |value: &Value| value.as_f64().map(|value| value as f32);
201
+ let point = |key: &str| {
202
+ let array = step.get(key)?.as_array()?;
203
+ Some(InputPoint::new(
204
+ number(array.first()?)?,
205
+ number(array.get(1)?)?,
206
+ ))
207
+ };
208
+ let gpu = |error: GpuError| error.to_string();
209
+ if let Some(id) = text("focus") {
210
+ if !self.runtime.focus_action(&id) {
211
+ return Err(format!("cannot focus '{id}'"));
212
+ }
213
+ self.runtime.take_ime_requests();
214
+ } else if let Some(id) = text("activate") {
215
+ self.runtime.activate_interactive(&id);
216
+ } else if let Some(value) = text("type") {
217
+ self.input(InputEvent::TextInput { text: value })
218
+ .map_err(gpu)?;
219
+ } else if let Some(value) = text("preedit") {
220
+ let selection = step
221
+ .get("selection")
222
+ .and_then(Value::as_array)
223
+ .and_then(|range| {
224
+ Some((
225
+ range.first()?.as_u64()? as usize,
226
+ range.get(1)?.as_u64()? as usize,
227
+ ))
228
+ });
229
+ self.input(InputEvent::TextEdit(TextEdit::CompositionUpdate(
230
+ Composition {
231
+ text: value,
232
+ selection,
233
+ },
234
+ )))
235
+ .map_err(gpu)?;
236
+ } else if let Some(value) = text("commit") {
237
+ self.input(InputEvent::TextEdit(TextEdit::CompositionCommit(value)))
238
+ .map_err(gpu)?;
239
+ } else if let Some(name) = text("key") {
240
+ let logical = match name.as_str() {
241
+ "Tab" => LogicalKey::Tab,
242
+ "Enter" => LogicalKey::Enter,
243
+ "Space" => LogicalKey::Space,
244
+ "Escape" => LogicalKey::Escape,
245
+ "ArrowUp" => LogicalKey::ArrowUp,
246
+ "ArrowDown" => LogicalKey::ArrowDown,
247
+ "ArrowLeft" => LogicalKey::ArrowLeft,
248
+ "ArrowRight" => LogicalKey::ArrowRight,
249
+ "Home" => LogicalKey::Home,
250
+ "End" => LogicalKey::End,
251
+ "PageUp" => LogicalKey::PageUp,
252
+ "PageDown" => LogicalKey::PageDown,
253
+ "Backspace" => LogicalKey::Backspace,
254
+ "Delete" => LogicalKey::Delete,
255
+ other => LogicalKey::Character(other.to_owned()),
256
+ };
257
+ let flag = |key: &str| step.get(key).and_then(Value::as_bool).unwrap_or(false);
258
+ let modifiers = Modifiers {
259
+ shift: flag("shift"),
260
+ control: flag("control"),
261
+ alt: flag("alt"),
262
+ meta: flag("meta"),
263
+ };
264
+ if modifiers != self.modifiers {
265
+ self.input(InputEvent::ModifiersChanged(modifiers))
266
+ .map_err(gpu)?;
267
+ }
268
+ for state in [KeyState::Pressed, KeyState::Released] {
269
+ self.input(InputEvent::Key {
270
+ logical: logical.clone(),
271
+ physical: PhysicalKey::Other,
272
+ state,
273
+ repeat: false,
274
+ })
275
+ .map_err(gpu)?;
276
+ }
277
+ } else if let Some(position) = point("press") {
278
+ self.input(InputEvent::PointerMoved {
279
+ pointer: PointerId::MOUSE,
280
+ position,
281
+ })
282
+ .map_err(gpu)?;
283
+ self.input(InputEvent::PointerButton {
284
+ pointer: PointerId::MOUSE,
285
+ button: PointerButton::Primary,
286
+ state: ButtonState::Pressed,
287
+ })
288
+ .map_err(gpu)?;
289
+ } else if let Some(position) = point("move") {
290
+ self.input(InputEvent::PointerMoved {
291
+ pointer: PointerId::MOUSE,
292
+ position,
293
+ })
294
+ .map_err(gpu)?;
295
+ } else if step.get("release").is_some() {
296
+ self.input(InputEvent::PointerButton {
297
+ pointer: PointerId::MOUSE,
298
+ button: PointerButton::Primary,
299
+ state: ButtonState::Released,
300
+ })
301
+ .map_err(gpu)?;
302
+ } else if let Some(delta) = point("scroll") {
303
+ self.input(InputEvent::Scroll {
304
+ pointer: Some(PointerId::MOUSE),
305
+ delta: ScrollDelta::Pixels {
306
+ x: delta.x,
307
+ y: delta.y,
308
+ },
309
+ phase: ScrollPhase::Changed,
310
+ })
311
+ .map_err(gpu)?;
312
+ } else if let Some(seconds) = step.get("step").and_then(Value::as_f64) {
313
+ let mut remaining = seconds as f32;
314
+ while remaining > 0.0 {
315
+ let dt = remaining.min(1.0 / 60.0);
316
+ self.runtime.step(dt);
317
+ remaining -= dt;
318
+ }
319
+ } else if let Some(size) = step.get("resize").and_then(Value::as_array) {
320
+ let value = |index: usize| size.get(index).and_then(number);
321
+ self.resize(
322
+ value(0).ok_or("resize width")?,
323
+ value(1).ok_or("resize height")?,
324
+ value(2).unwrap_or(self.scale_factor),
325
+ );
326
+ } else {
327
+ return Err(format!("unknown offscreen step {step}"));
328
+ }
329
+ Ok(())
330
+ }
331
+
332
+ pub fn apply_script(&mut self, script: &Value) -> Result<(), String> {
333
+ for step in script.as_array().ok_or("script must be a JSON array")? {
334
+ self.apply_step(step)?;
335
+ }
336
+ Ok(())
337
+ }
338
+ }
339
+
340
+ /// Minimal PNG encoder (RGBA8, stored deflate blocks); no image dependency.
341
+ pub fn encode_png(width: u32, height: u32, rgba: &[u8]) -> Vec<u8> {
342
+ fn crc32(bytes: &[u8]) -> u32 {
343
+ let mut crc = 0xffff_ffffu32;
344
+ for byte in bytes {
345
+ crc ^= u32::from(*byte);
346
+ for _ in 0..8 {
347
+ crc = if crc & 1 != 0 {
348
+ 0xedb8_8320 ^ (crc >> 1)
349
+ } else {
350
+ crc >> 1
351
+ };
352
+ }
353
+ }
354
+ !crc
355
+ }
356
+ fn chunk(output: &mut Vec<u8>, kind: &[u8; 4], data: &[u8]) {
357
+ output.extend_from_slice(&(data.len() as u32).to_be_bytes());
358
+ let mut body = kind.to_vec();
359
+ body.extend_from_slice(data);
360
+ output.extend_from_slice(&body);
361
+ output.extend_from_slice(&crc32(&body).to_be_bytes());
362
+ }
363
+ let mut raw = Vec::with_capacity((width * 4 + 1) as usize * height as usize);
364
+ for row in rgba.chunks((width * 4) as usize) {
365
+ raw.push(0);
366
+ raw.extend_from_slice(row);
367
+ }
368
+ let mut zlib = vec![0x78, 0x01];
369
+ let blocks = raw.chunks(65_535).collect::<Vec<_>>();
370
+ for (index, block) in blocks.iter().enumerate() {
371
+ zlib.push(u8::from(index + 1 == blocks.len()));
372
+ let len = block.len() as u16;
373
+ zlib.extend_from_slice(&len.to_le_bytes());
374
+ zlib.extend_from_slice(&(!len).to_le_bytes());
375
+ zlib.extend_from_slice(block);
376
+ }
377
+ let (mut a, mut b) = (1u32, 0u32);
378
+ for byte in &raw {
379
+ a = (a + u32::from(*byte)) % 65_521;
380
+ b = (b + a) % 65_521;
381
+ }
382
+ zlib.extend_from_slice(&((b << 16) | a).to_be_bytes());
383
+
384
+ let mut output = b"\x89PNG\r\n\x1a\n".to_vec();
385
+ let mut header = Vec::new();
386
+ header.extend_from_slice(&width.to_be_bytes());
387
+ header.extend_from_slice(&height.to_be_bytes());
388
+ header.extend_from_slice(&[8, 6, 0, 0, 0]);
389
+ chunk(&mut output, b"IHDR", &header);
390
+ chunk(&mut output, b"IDAT", &zlib);
391
+ chunk(&mut output, b"IEND", &[]);
392
+ output
393
+ }
@@ -0,0 +1,63 @@
1
+ struct VertexOut {
2
+ @builtin(position) position: vec4<f32>,
3
+ @location(0) color: vec4<f32>,
4
+ @location(1) local_position: vec2<f32>,
5
+ @location(2) rect_size: vec2<f32>,
6
+ @location(3) corner_radius: f32,
7
+ };
8
+
9
+ @vertex
10
+ fn vs_main(
11
+ @location(0) position: vec2<f32>,
12
+ @location(1) color: vec4<f32>,
13
+ @location(2) local_position: vec2<f32>,
14
+ @location(3) rect_size: vec2<f32>,
15
+ @location(4) corner_radius: f32,
16
+ ) -> VertexOut {
17
+ var out: VertexOut;
18
+ out.position = vec4<f32>(position, 0.0, 1.0);
19
+ out.color = color;
20
+ out.local_position = local_position;
21
+ out.rect_size = rect_size;
22
+ out.corner_radius = corner_radius;
23
+ return out;
24
+ }
25
+
26
+ // Scene colors are authored in sRGB and interpolated in sRGB (matching the web
27
+ // adapter). An sRGB render target encodes on write, so decode to linear first.
28
+ override SRGB_TARGET: bool = true;
29
+
30
+ fn srgb_to_linear(value: vec3<f32>) -> vec3<f32> {
31
+ let low = value / 12.92;
32
+ let high = pow((value + vec3<f32>(0.055)) / 1.055, vec3<f32>(2.4));
33
+ return select(high, low, value <= vec3<f32>(0.04045));
34
+ }
35
+
36
+ fn output_color(color: vec4<f32>) -> vec3<f32> {
37
+ if (SRGB_TARGET) {
38
+ return srgb_to_linear(color.rgb);
39
+ }
40
+ return color.rgb;
41
+ }
42
+
43
+ @fragment
44
+ fn fs_main(in: VertexOut) -> @location(0) vec4<f32> {
45
+ let radius = clamp(
46
+ in.corner_radius,
47
+ 0.0,
48
+ max(0.0, min(in.rect_size.x, in.rect_size.y) * 0.5),
49
+ );
50
+ if (radius <= 0.0) {
51
+ return vec4<f32>(output_color(in.color), in.color.a);
52
+ }
53
+
54
+ let half_size = in.rect_size * 0.5;
55
+ let point = in.local_position - half_size;
56
+ let q = abs(point) - half_size + vec2<f32>(radius);
57
+ let distance = length(max(q, vec2<f32>(0.0)))
58
+ + min(max(q.x, q.y), 0.0)
59
+ - radius;
60
+ let antialias = max(fwidth(distance), 0.5);
61
+ let coverage = 1.0 - smoothstep(-antialias, antialias, distance);
62
+ return vec4<f32>(output_color(in.color), in.color.a * coverage);
63
+ }