@elurjs/universal 0.1.10 → 0.1.11

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 (57) hide show
  1. package/cli/create-app.mjs +4 -2
  2. package/cli/dev.mjs +1 -1
  3. package/cli/elur.mjs +18 -4
  4. package/docs/INSTALACION-Y-DEV.md +7 -4
  5. package/package.json +5 -1
  6. package/targets/linux/CMakeLists.txt +196 -0
  7. package/targets/linux/README.md +422 -0
  8. package/targets/linux/ci/tsan.supp +15 -0
  9. package/targets/linux/generated/elur_module_registrar.cpp +14 -0
  10. package/targets/linux/generated/module_sources.cmake +5 -0
  11. package/targets/linux/src/elur_applicator.cpp +5073 -0
  12. package/targets/linux/src/elur_applicator.h +387 -0
  13. package/targets/linux/src/elur_clip.cpp +76 -0
  14. package/targets/linux/src/elur_clip.h +23 -0
  15. package/targets/linux/src/elur_crypto_module.cpp +121 -0
  16. package/targets/linux/src/elur_events.h +57 -0
  17. package/targets/linux/src/elur_fonts.cpp +106 -0
  18. package/targets/linux/src/elur_fonts.h +31 -0
  19. package/targets/linux/src/elur_host.cpp +1041 -0
  20. package/targets/linux/src/elur_host.h +66 -0
  21. package/targets/linux/src/elur_http_module.cpp +437 -0
  22. package/targets/linux/src/elur_js.h +40 -0
  23. package/targets/linux/src/elur_modules.cpp +453 -0
  24. package/targets/linux/src/elur_modules.h +159 -0
  25. package/targets/linux/src/elur_renderer.h +46 -0
  26. package/targets/linux/src/elur_shot.cpp +64 -0
  27. package/targets/linux/src/elur_shot.h +17 -0
  28. package/targets/linux/src/elur_skia_a11y.cpp +987 -0
  29. package/targets/linux/src/elur_skia_a11y.h +146 -0
  30. package/targets/linux/src/elur_skia_app.cpp +1770 -0
  31. package/targets/linux/src/elur_skia_app.h +18 -0
  32. package/targets/linux/src/elur_state_module.cpp +99 -0
  33. package/targets/linux/src/elur_tck_module.cpp +186 -0
  34. package/targets/linux/src/elur_ui_module.cpp +84 -0
  35. package/targets/linux/src/elur_yoga.cpp +452 -0
  36. package/targets/linux/src/elur_yoga.h +95 -0
  37. package/targets/linux/src/main.cpp +294 -0
  38. package/targets/windows/Package.appxmanifest +28 -0
  39. package/targets/windows/README.md +44 -0
  40. package/targets/windows/elur-windows.vcxproj +133 -0
  41. package/targets/windows/packages.config +10 -0
  42. package/targets/windows/src/elur_crypto_module_win.cpp +106 -0
  43. package/targets/windows/src/elur_events.h +58 -0
  44. package/targets/windows/src/elur_host_win.cpp +645 -0
  45. package/targets/windows/src/elur_host_win.h +75 -0
  46. package/targets/windows/src/elur_http_module_win.cpp +331 -0
  47. package/targets/windows/src/elur_js.h +40 -0
  48. package/targets/windows/src/elur_modules.cpp +460 -0
  49. package/targets/windows/src/elur_modules.h +159 -0
  50. package/targets/windows/src/elur_state_module.cpp +99 -0
  51. package/targets/windows/src/elur_ui_module_win.cpp +75 -0
  52. package/targets/windows/src/elur_uia_host.h +129 -0
  53. package/targets/windows/src/elur_win_applicator.cpp +3118 -0
  54. package/targets/windows/src/elur_win_applicator.h +186 -0
  55. package/targets/windows/src/elur_yoga.cpp +452 -0
  56. package/targets/windows/src/elur_yoga.h +95 -0
  57. package/targets/windows/src/main.cpp +321 -0
@@ -0,0 +1,3118 @@
1
+ // elur_win_applicator.cpp — ver header. M1: tipos box/column/row/
2
+ // text/button/text-input/switch/scroll-view/image/stack (fallback a
3
+ // contenedor); eventos press/input/change/submit/scroll; estilos
4
+ // visuales bg/color/fontSize/fontWeight/borderRadius/borders/opacity/
5
+ // textAlign/padding-visual; resto → warnOnce honesto.
6
+
7
+ #include "elur_win_applicator.h"
8
+
9
+ #include "elur_js.h"
10
+ #include "elur_modules.h"
11
+ #include "elur_yoga.h"
12
+
13
+ #include <algorithm>
14
+ #include <cctype>
15
+ #include <climits>
16
+ #include <cmath>
17
+ #include <cstdio>
18
+ #include <cstdlib>
19
+ #include <fstream>
20
+ #include <winrt/Microsoft.UI.Dispatching.h>
21
+ #include <winrt/Microsoft.UI.Input.h>
22
+ #include <winrt/Microsoft.UI.Text.h>
23
+ #include <winrt/Microsoft.UI.Xaml.Automation.Peers.h>
24
+ #include <winrt/Microsoft.UI.Xaml.Automation.h>
25
+ #include <winrt/Microsoft.UI.Xaml.Controls.Primitives.h>
26
+ #include <winrt/Microsoft.UI.Xaml.Documents.h>
27
+ #include <winrt/Microsoft.UI.Xaml.Input.h>
28
+ #include <winrt/Microsoft.UI.Xaml.Media.Animation.h>
29
+ #include <winrt/Microsoft.UI.Xaml.Media.Imaging.h>
30
+ #include <winrt/Microsoft.UI.Xaml.Media.h>
31
+ #include <winrt/Windows.Foundation.Collections.h>
32
+ #include <winrt/Windows.Foundation.Numerics.h>
33
+ #include <winrt/Windows.Foundation.h>
34
+ #include <winrt/Windows.Security.Cryptography.h>
35
+ #include <winrt/Windows.Storage.Streams.h>
36
+ #include <winrt/Windows.System.h>
37
+ #include <winrt/Windows.UI.Core.h>
38
+ #include <winrt/Windows.UI.h>
39
+ #include <winrt/base.h>
40
+
41
+ namespace wf = winrt::Windows::Foundation;
42
+ namespace wu = winrt::Windows::UI;
43
+ namespace wut = winrt::Microsoft::UI::Text;
44
+ namespace mui = winrt::Microsoft::UI::Input;
45
+ namespace muxd = winrt::Microsoft::UI::Xaml::Documents;
46
+ namespace muxm = winrt::Microsoft::UI::Xaml::Media;
47
+ namespace muxi = winrt::Microsoft::UI::Xaml::Input;
48
+ namespace mud = winrt::Microsoft::UI::Dispatching;
49
+ using winrt::Microsoft::UI::Xaml::Thickness;
50
+ using winrt::Windows::Foundation::Size;
51
+
52
+ void dlog(const char *fmt, ...);
53
+
54
+ namespace elur {
55
+
56
+ WinApplicator g_winapp;
57
+
58
+ namespace {
59
+
60
+ // "#rrggbb" | "#aarrggbb" | "rgb(r,g,b)" → Color. "" → transparent.
61
+ wu::Color parseColor(const std::string &s, bool &ok) {
62
+ ok = false;
63
+ auto hex = [](char c) -> int {
64
+ if (c >= '0' && c <= '9') return c - '0';
65
+ if (c >= 'a' && c <= 'f') return c - 'a' + 10;
66
+ if (c >= 'A' && c <= 'F') return c - 'A' + 10;
67
+ return -1;
68
+ };
69
+ auto dup = [](int h) { return h * 16 + h; };
70
+ if (s.size() == 4 && s[0] == '#') {
71
+ // #rgb shorthand — Color.parseColor (android) y gdk_rgba_parse
72
+ // (GTK) lo aceptan; el wire lo emite verbatim.
73
+ int r = hex(s[1]), g = hex(s[2]), b = hex(s[3]);
74
+ if (r < 0 || g < 0 || b < 0) return {};
75
+ ok = true;
76
+ return wu::Color{255, (uint8_t)dup(r), (uint8_t)dup(g),
77
+ (uint8_t)dup(b)};
78
+ }
79
+ if (s.size() == 5 && s[0] == '#') {
80
+ int a = hex(s[1]), r = hex(s[2]), g = hex(s[3]), b = hex(s[4]);
81
+ if (a < 0 || r < 0 || g < 0 || b < 0) return {};
82
+ ok = true;
83
+ return wu::Color{(uint8_t)dup(a), (uint8_t)dup(r), (uint8_t)dup(g),
84
+ (uint8_t)dup(b)};
85
+ }
86
+ if (s.size() == 7 && s[0] == '#') {
87
+ wu::Color c{255, 0, 0, 0};
88
+ int v[3];
89
+ for (int i = 0; i < 3; i++) {
90
+ int h1 = hex(s[1 + i * 2]), h2 = hex(s[2 + i * 2]);
91
+ if (h1 < 0 || h2 < 0) return {};
92
+ v[i] = h1 * 16 + h2;
93
+ }
94
+ c.R = (uint8_t)v[0]; c.G = (uint8_t)v[1]; c.B = (uint8_t)v[2];
95
+ ok = true;
96
+ return c;
97
+ }
98
+ if (s.size() == 9 && s[0] == '#') {
99
+ wu::Color c;
100
+ int v[4];
101
+ for (int i = 0; i < 4; i++) {
102
+ int h1 = hex(s[1 + i * 2]), h2 = hex(s[2 + i * 2]);
103
+ if (h1 < 0 || h2 < 0) return {};
104
+ v[i] = h1 * 16 + h2;
105
+ }
106
+ c.A = (uint8_t)v[0]; c.R = (uint8_t)v[1]; c.G = (uint8_t)v[2];
107
+ c.B = (uint8_t)v[3];
108
+ ok = true;
109
+ return c;
110
+ }
111
+ if (s.rfind("rgb(", 0) == 0 && s.size() > 5) {
112
+ int r = 0, g = 0, b = 0;
113
+ if (sscanf_s(s.c_str() + 4, "%d,%d,%d", &r, &g, &b) == 3) {
114
+ ok = true;
115
+ return wu::Color{255, (uint8_t)r, (uint8_t)g, (uint8_t)b};
116
+ }
117
+ }
118
+ return {};
119
+ }
120
+
121
+ muxm::Brush brushOf(const std::string &s) {
122
+ bool ok = false;
123
+ wu::Color c = parseColor(s, ok);
124
+ if (!ok)
125
+ return nullptr;
126
+ return muxm::SolidColorBrush(c);
127
+ }
128
+
129
+ winrt::hstring hs(const std::string &s) {
130
+ int n = MultiByteToWideChar(CP_UTF8, 0, s.c_str(), (int)s.size(),
131
+ nullptr, 0);
132
+ std::wstring w((size_t)n, L'\0');
133
+ MultiByteToWideChar(CP_UTF8, 0, s.c_str(), (int)s.size(), w.data(), n);
134
+ return winrt::hstring(w);
135
+ }
136
+
137
+ // Sufijos "px" tolerados (el wire emite números o "12px").
138
+ double pxOf(const std::string &s, double dflt = 0) {
139
+ if (s.empty())
140
+ return dflt;
141
+ return atof(s.c_str());
142
+ }
143
+
144
+ // Xaml no permite reparenting directo (E_INVALIDARG si el elemento ya
145
+ // tiene padre visual; GTK lo toleraba). Hay que quitarlo primero.
146
+ void detachVisual(mux::UIElement const &el) {
147
+ if (!el)
148
+ return;
149
+ auto fe = el.try_as<mux::FrameworkElement>();
150
+ if (!fe)
151
+ return;
152
+ auto parent = fe.Parent();
153
+ if (!parent)
154
+ return;
155
+ if (auto panel = parent.try_as<muxc::Panel>()) {
156
+ auto children = panel.Children();
157
+ uint32_t idx = 0;
158
+ if (children.IndexOf(el, idx))
159
+ children.RemoveAt(idx);
160
+ } else if (auto border = parent.try_as<muxc::Border>()) {
161
+ if (border.Child() == el)
162
+ border.Child(nullptr);
163
+ } else if (auto sv = parent.try_as<muxc::ScrollViewer>()) {
164
+ if (sv.Content() == el)
165
+ sv.Content(nullptr);
166
+ } else if (auto cc = parent.try_as<muxc::ContentControl>()) {
167
+ if (cc.Content() == el)
168
+ cc.Content(nullptr);
169
+ }
170
+ }
171
+
172
+ } // namespace
173
+
174
+ void WinApplicator::warnOnce(std::unordered_map<std::string, int> &m,
175
+ const char *kind, const std::string &what) {
176
+ if (++m[what] == 1)
177
+ fprintf(stderr, "[elur-windows] %s sin soporte aún: %s\n", kind,
178
+ what.c_str());
179
+ }
180
+
181
+ namespace {
182
+
183
+ // VirtualKey → nombre DOM `KeyboardEvent.key` (ADR-0159/0179 — misma
184
+ // tabla que elurDomKeyName en el host GTK: "Return"→"Enter",
185
+ // "Left"→"ArrowLeft"; letras en minúscula, el shift llega en mods).
186
+ std::string domKeyName(winrt::Windows::System::VirtualKey k) {
187
+ namespace vk = winrt::Windows::System;
188
+ switch (k) {
189
+ case vk::VirtualKey::Enter: return "Enter";
190
+ case vk::VirtualKey::Tab: return "Tab";
191
+ case vk::VirtualKey::Back: return "Backspace";
192
+ case vk::VirtualKey::Delete: return "Delete";
193
+ case vk::VirtualKey::Left: return "ArrowLeft";
194
+ case vk::VirtualKey::Right: return "ArrowRight";
195
+ case vk::VirtualKey::Up: return "ArrowUp";
196
+ case vk::VirtualKey::Down: return "ArrowDown";
197
+ case vk::VirtualKey::Home: return "Home";
198
+ case vk::VirtualKey::End: return "End";
199
+ case vk::VirtualKey::PageUp: return "PageUp";
200
+ case vk::VirtualKey::PageDown: return "PageDown";
201
+ case vk::VirtualKey::Escape: return "Escape";
202
+ case vk::VirtualKey::Space: return " ";
203
+ case vk::VirtualKey::Shift:
204
+ case vk::VirtualKey::LeftShift:
205
+ case vk::VirtualKey::RightShift: return "Shift";
206
+ case vk::VirtualKey::Control:
207
+ case vk::VirtualKey::LeftControl:
208
+ case vk::VirtualKey::RightControl: return "Control";
209
+ case vk::VirtualKey::Menu:
210
+ case vk::VirtualKey::LeftMenu:
211
+ case vk::VirtualKey::RightMenu: return "Alt";
212
+ case vk::VirtualKey::LeftWindows:
213
+ case vk::VirtualKey::RightWindows: return "Meta";
214
+ case vk::VirtualKey::Add: return "+";
215
+ default: break;
216
+ }
217
+ int i = (int)k;
218
+ if (i >= 'A' && i <= 'Z')
219
+ return std::string(1, (char)tolower(i));
220
+ if (i >= '0' && i <= '9')
221
+ return std::string(1, (char)i);
222
+ if (i >= 0x70 && i <= 0x87) // F1..F24
223
+ return "F" + std::to_string(i - 0x6f);
224
+ return "";
225
+ }
226
+
227
+ bool modDown(winrt::Windows::System::VirtualKey a,
228
+ winrt::Windows::System::VirtualKey b,
229
+ winrt::Windows::System::VirtualKey c) {
230
+ // InputKeyboardSource (Microsoft.UI.Input) es el API para WinUI 3
231
+ // desktop — CoreWindow.GetForCurrentThread devuelve null en apps de
232
+ // escritorio (solo existe en UWP) y los modificadores no se leen.
233
+ namespace wuc = winrt::Windows::UI::Core;
234
+ auto down = [](winrt::Windows::System::VirtualKey k) {
235
+ return (mui::InputKeyboardSource::GetKeyStateForCurrentThread(k) &
236
+ wuc::CoreVirtualKeyStates::Down) != wuc::CoreVirtualKeyStates::None;
237
+ };
238
+ return down(a) || down(b) || down(c);
239
+ }
240
+
241
+ // Espejo de src/ir/shortcut.ts (ADR-0179): forma canónica
242
+ // `ctrl+alt+shift+meta+tecla`. El host no parsea combos de autor —
243
+ // construye esta forma desde la tecla y compara strings.
244
+ std::string keyToken(std::string k) {
245
+ if (k == " ")
246
+ return "space";
247
+ if (k == "+")
248
+ return "plus";
249
+ for (auto &c : k)
250
+ c = (char)tolower((unsigned char)c);
251
+ return k;
252
+ }
253
+
254
+ std::string comboOf(winrt::Windows::System::VirtualKey k) {
255
+ namespace vk = winrt::Windows::System;
256
+ std::string c;
257
+ if (modDown(vk::VirtualKey::Control, vk::VirtualKey::LeftControl,
258
+ vk::VirtualKey::RightControl))
259
+ c += "ctrl+";
260
+ if (modDown(vk::VirtualKey::Menu, vk::VirtualKey::LeftMenu,
261
+ vk::VirtualKey::RightMenu))
262
+ c += "alt+";
263
+ if (modDown(vk::VirtualKey::Shift, vk::VirtualKey::LeftShift,
264
+ vk::VirtualKey::RightShift))
265
+ c += "shift+";
266
+ if (modDown(vk::VirtualKey::LeftWindows, vk::VirtualKey::RightWindows,
267
+ vk::VirtualKey::LeftWindows))
268
+ c += "meta+";
269
+ return c + keyToken(domKeyName(k));
270
+ }
271
+
272
+ // En edición solo disparan combos con ctrl/alt/meta, Escape o F1-F24
273
+ // (misma regla que el host GTK — el resto se lo queda el TextBox).
274
+ bool firesWhileEditing(const std::string &combo) {
275
+ if (combo.rfind("ctrl+", 0) == 0 || combo.rfind("alt+", 0) == 0 ||
276
+ combo.find("meta+") != std::string::npos)
277
+ return true;
278
+ std::string key = combo.substr(
279
+ combo.rfind('+') == std::string::npos ? 0 : combo.rfind('+') + 1);
280
+ if (key == "escape")
281
+ return true;
282
+ if (key.size() >= 2 && key[0] == 'f') {
283
+ int n = atoi(key.c_str() + 1);
284
+ return n >= 1 && n <= 24 && std::to_string(n) == key.substr(1);
285
+ }
286
+ return false;
287
+ }
288
+
289
+ } // namespace
290
+
291
+ // `variant` del switch (ADR-0216): ToggleSwitch ≠ CheckBox ≠
292
+ // RadioButton — hay que recrear el control, copiar estado y
293
+ // reinsertarlo en el índice que ocupaba el anterior.
294
+ void WinApplicator::swapVariant(WinNode &n, const std::string &v) {
295
+ std::string want = v.empty() ? "switch" : v;
296
+ if (want == n.variant && n.swEl)
297
+ return;
298
+ bool on = false;
299
+ if (n.sw)
300
+ on = n.sw.IsOn();
301
+ else if (n.check)
302
+ on = n.check.IsChecked() && n.check.IsChecked().Value();
303
+ else if (n.radio)
304
+ on = n.radio.IsChecked() && n.radio.IsChecked().Value();
305
+ mux::UIElement fresh{nullptr};
306
+ if (want == "checkbox") {
307
+ if (!n.check)
308
+ n.check = muxc::CheckBox();
309
+ fresh = n.check;
310
+ } else if (want == "radio") {
311
+ if (!n.radio)
312
+ n.radio = muxc::RadioButton();
313
+ fresh = n.radio;
314
+ } else if (want == "switch") {
315
+ if (!n.sw) {
316
+ n.sw = muxc::ToggleSwitch();
317
+ n.sw.OnContent(nullptr);
318
+ n.sw.OffContent(nullptr);
319
+ }
320
+ fresh = n.sw;
321
+ } else {
322
+ warnOnce(unknownProps_, "prop", "variant=" + v + "@switch");
323
+ return;
324
+ }
325
+ // El host (n.el) es permanente — el swap cambia solo su contenido;
326
+ // la geometría vive en el host, no en el control intercambiado.
327
+ if (auto cur = n.host.Content().try_as<mux::UIElement>()) {
328
+ if (cur == fresh)
329
+ return;
330
+ if (auto cf = cur.try_as<mux::FrameworkElement>())
331
+ if (auto nf = fresh.try_as<mux::FrameworkElement>()) {
332
+ nf.Width(cf.Width());
333
+ nf.Height(cf.Height());
334
+ }
335
+ }
336
+ n.host.Content(fresh);
337
+ n.swEl = fresh;
338
+ n.variant = want;
339
+ // Reaplicar estado y label conocidos.
340
+ n.suppressSignal = true;
341
+ if (n.sw)
342
+ n.sw.IsOn(on);
343
+ else if (n.check && n.check == fresh)
344
+ n.check.IsChecked(
345
+ winrt::box_value(on).as<wf::IReference<bool>>());
346
+ else if (n.radio && n.radio == fresh)
347
+ n.radio.IsChecked(
348
+ winrt::box_value(on).as<wf::IReference<bool>>());
349
+ n.suppressSignal = false;
350
+ if (!n.textValue.empty() && n.check && n.check == fresh)
351
+ n.check.Content(winrt::box_value(hs(n.textValue)));
352
+ if (!n.textValue.empty() && n.radio && n.radio == fresh)
353
+ n.radio.Content(winrt::box_value(hs(n.textValue)));
354
+ wireCheckLike(n.id, n);
355
+ yoga::nodeSetText(n.id); // la medida cambia con el control nuevo
356
+ }
357
+
358
+ // Cablea change/input sobre el control switch-like activo
359
+ // (Toggled en ToggleSwitch; Checked/Unchecked en CheckBox/RadioButton).
360
+ // Control interactivo del nodo para foco/tabstop — el específico del
361
+ // tipo si existe; si no, el host (ContentControl sí es Control).
362
+ static muxc::Control innerCtl(WinNode &n) {
363
+ if (n.input)
364
+ return n.input;
365
+ if (n.button)
366
+ return n.button;
367
+ if (n.swEl)
368
+ if (auto c = n.swEl.try_as<muxc::Control>())
369
+ return c;
370
+ if (n.slider)
371
+ return n.slider;
372
+ return n.el ? n.el.try_as<muxc::Control>() : nullptr;
373
+ }
374
+
375
+ void WinApplicator::wireCheckLike(int id, WinNode &n) {
376
+ auto emitChecked = [this, id]() {
377
+ auto i = nodes_.find(id);
378
+ if (i == nodes_.end() || i->second.suppressSignal)
379
+ return;
380
+ WinNode &nn = i->second;
381
+ const char *ev = nn.events.count("change") ? "change" : "input";
382
+ auto eb = nn.events.find(ev);
383
+ if (eb == nn.events.end())
384
+ return;
385
+ bool on = nn.sw ? nn.sw.IsOn()
386
+ : nn.check ? (nn.check.IsChecked() &&
387
+ nn.check.IsChecked().Value())
388
+ : nn.radio ? (nn.radio.IsChecked() &&
389
+ nn.radio.IsChecked().Value())
390
+ : false;
391
+ emitEvent(nn, ev, "user",
392
+ std::string("{\"value\":") + (on ? "true" : "false") + "}",
393
+ eb->second);
394
+ };
395
+ if (n.sw && !n.tokToggle.value)
396
+ n.tokToggle = n.sw.Toggled(
397
+ [emitChecked](auto const &, auto const &) { emitChecked(); });
398
+ if (n.check) {
399
+ if (!n.tokCheckOn.value)
400
+ n.tokCheckOn = n.check.Checked(
401
+ [emitChecked](auto const &, auto const &) { emitChecked(); });
402
+ if (!n.tokCheckOff.value)
403
+ n.tokCheckOff = n.check.Unchecked(
404
+ [emitChecked](auto const &, auto const &) { emitChecked(); });
405
+ }
406
+ if (n.radio) {
407
+ if (!n.tokRadioOn.value)
408
+ n.tokRadioOn = n.radio.Checked(
409
+ [emitChecked](auto const &, auto const &) { emitChecked(); });
410
+ if (!n.tokRadioOff.value)
411
+ n.tokRadioOff = n.radio.Unchecked(
412
+ [emitChecked](auto const &, auto const &) { emitChecked(); });
413
+ }
414
+ }
415
+
416
+ // pull-to-refresh (ADR-0216): RefreshContainer envuelve al
417
+ // ScrollViewer — se crea al primer attach `refresh` / prop
418
+ // `refreshing` para no alterar scrolls sin el gesto.
419
+ void WinApplicator::ensureRefresh(WinNode &n) {
420
+ if (n.refresh || !n.scroll || !n.border)
421
+ return;
422
+ warnOnce(unknownProps_, "prop", "refresh-skip-bisect@scroll-view");
423
+ return;
424
+ auto rc = muxc::RefreshContainer();
425
+ n.border.Child(rc);
426
+ rc.Content(n.scroll);
427
+ n.refresh = rc;
428
+ int id = n.id;
429
+ n.tokRefresh = rc.RefreshRequested(
430
+ [this, id](auto const &, auto const &) {
431
+ auto i = nodes_.find(id);
432
+ if (i == nodes_.end() || i->second.suppressSignal)
433
+ return;
434
+ auto eb = i->second.events.find("refresh");
435
+ if (eb != i->second.events.end())
436
+ emitEvent(i->second, "refresh", "user", "{}", eb->second);
437
+ });
438
+ }
439
+
440
+ // ── Fábrica por tipo IR ────────────────────────────────────────────
441
+
442
+ void WinApplicator::createNode(int id, const std::string &type) {
443
+ WinNode n;
444
+ n.id = id;
445
+ n.type = type;
446
+
447
+ // Todo nodo queda bajo un ElurHost (peer UIA propio — elur_uia_host.h);
448
+ // el contenido visible es el Border de chrome o el control directo.
449
+ // El impl queda retenido como com_ptr: sobre un objeto composable no
450
+ // hay ruta projected→impl (get_self exige produce<D,IRuntimeClass>
451
+ // como base y el runtime class lo aporta el objeto interior).
452
+ auto withHost = [&](mux::UIElement content) {
453
+ auto hostImpl = winrt::make_self<ElurHost>();
454
+ n.host = *hostImpl;
455
+ if (content)
456
+ n.host.Content(content);
457
+ n.el = n.host;
458
+ n.a11y = hostImpl->a11y;
459
+ n.a11y->invoke = [this, id](const char *act) {
460
+ onA11yInvoke(id, act);
461
+ };
462
+ };
463
+ auto withBorder = [&](mux::UIElement content) {
464
+ n.border = muxc::Border();
465
+ if (content)
466
+ n.border.Child(content);
467
+ withHost(n.border);
468
+ };
469
+
470
+ if (type == "text") {
471
+ n.textBlock = muxc::TextBlock();
472
+ n.textBlock.TextWrapping(mux::TextWrapping::Wrap);
473
+ withBorder(n.textBlock);
474
+ } else if (type == "button") {
475
+ n.button = muxc::Button();
476
+ withHost(n.button);
477
+ } else if (type == "text-input") {
478
+ n.input = muxc::TextBox();
479
+ withHost(n.input);
480
+ } else if (type == "switch") {
481
+ n.sw = muxc::ToggleSwitch();
482
+ n.sw.OnContent(nullptr);
483
+ n.sw.OffContent(nullptr);
484
+ n.swEl = n.sw;
485
+ withHost(n.sw);
486
+ } else if (type == "slider") {
487
+ n.slider = muxc::Slider();
488
+ withHost(n.slider);
489
+ } else if (type == "scroll-view" || type == "scroll") {
490
+ n.inner = muxc::Canvas();
491
+ n.scroll = muxc::ScrollViewer();
492
+ n.scroll.Content(n.inner);
493
+ n.scroll.VerticalScrollBarVisibility(
494
+ muxc::ScrollBarVisibility::Auto);
495
+ n.scroll.HorizontalScrollBarVisibility(
496
+ muxc::ScrollBarVisibility::Disabled);
497
+ withBorder(n.scroll);
498
+ } else if (type == "image") {
499
+ n.image = muxc::Image();
500
+ n.image.Stretch(muxm::Stretch::UniformToFill);
501
+ // ADR-0204: resultados materializados en flags; el attach-event de
502
+ // load/error hace replay (el attach llega tras la carga).
503
+ n.tokImgOpen = n.image.ImageOpened(
504
+ [this, id](auto const &, auto const &) {
505
+ auto i = nodes_.find(id);
506
+ if (i == nodes_.end())
507
+ return;
508
+ WinNode &nn = i->second;
509
+ nn.imgLoaded = true;
510
+ nn.imgFailed = false;
511
+ nn.imgW = (int)nn.image.ActualWidth();
512
+ nn.imgH = (int)nn.image.ActualHeight();
513
+ auto eb = nn.events.find("load");
514
+ if (eb != nn.events.end()) {
515
+ char buf[96];
516
+ snprintf(buf, sizeof(buf), "{\"width\":%d,\"height\":%d%s}",
517
+ nn.imgW, nn.imgH,
518
+ nn.imgLoadFallback ? ",\"fallback\":true" : "");
519
+ emitEvent(nn, "load", "program", buf, eb->second);
520
+ }
521
+ });
522
+ n.tokImgFail = n.image.ImageFailed(
523
+ [this, id](auto const &, auto const &) {
524
+ auto i = nodes_.find(id);
525
+ if (i == nodes_.end())
526
+ return;
527
+ WinNode &nn = i->second;
528
+ if (!nn.fallbackSrc.empty() && !nn.imgFailFallback) {
529
+ // fallbackSrc (ADR-0204): primer fallo → reintenta con el
530
+ // respaldo y marca la procedencia para el payload.
531
+ nn.imgFailFallback = true;
532
+ nn.imgLoadFallback = true;
533
+ try {
534
+ muxm::Imaging::BitmapImage fb;
535
+ fb.UriSource(wf::Uri(hs(nn.fallbackSrc)));
536
+ nn.image.Source(fb);
537
+ } catch (...) {
538
+ }
539
+ return;
540
+ }
541
+ nn.imgFailed = true;
542
+ auto eb = nn.events.find("error");
543
+ if (eb != nn.events.end()) {
544
+ std::string d = "{\"message\":\"image load failed\"";
545
+ if (nn.imgFailFallback)
546
+ d += ",\"fallback\":true";
547
+ d += "}";
548
+ emitEvent(nn, "error", "program", d, eb->second);
549
+ }
550
+ });
551
+ withBorder(n.image);
552
+ } else {
553
+ // box/column/row/stack/view/<desconocido> — contenedor con inner.
554
+ n.inner = muxc::Canvas();
555
+ withBorder(n.inner);
556
+ if (type != "box" && type != "column" && type != "row" &&
557
+ type != "stack" && type != "view")
558
+ warnOnce(unknownOps_, "type", type);
559
+ }
560
+ nodes_[id] = n;
561
+ yoga::nodeCreate(id, type);
562
+ }
563
+
564
+ // Superficie de hijos para parentId — mismo contrato que surfaceOf()
565
+ // en el aplicador GTK: 0 o padre desconocido → Canvas raíz; padre con
566
+ // `inner` → su Canvas interno; padre hoja → null (el caller advierte).
567
+ muxc::Canvas WinApplicator::surfaceOf(int parentId) {
568
+ auto it = nodes_.find(parentId);
569
+ if (it == nodes_.end())
570
+ return root_;
571
+ return it->second.inner;
572
+ }
573
+
574
+ void WinApplicator::deleteNode(int id) {
575
+ auto it = nodes_.find(id);
576
+ if (it == nodes_.end())
577
+ return;
578
+ WinNode &n = it->second;
579
+ if (n.button && n.tokClick.value)
580
+ n.button.Click(n.tokClick);
581
+ if (n.input && n.tokText.value)
582
+ n.input.TextChanged(n.tokText);
583
+ if (n.sw && n.tokToggle.value)
584
+ n.sw.Toggled(n.tokToggle);
585
+ if (n.scroll && n.tokView.value)
586
+ n.scroll.ViewChanged(n.tokView);
587
+ if (n.slider && n.tokSlider.value)
588
+ n.slider.ValueChanged(n.tokSlider);
589
+ if (n.check) {
590
+ if (n.tokCheckOn.value)
591
+ n.check.Checked(n.tokCheckOn);
592
+ if (n.tokCheckOff.value)
593
+ n.check.Unchecked(n.tokCheckOff);
594
+ }
595
+ if (n.radio) {
596
+ if (n.tokRadioOn.value)
597
+ n.radio.Checked(n.tokRadioOn);
598
+ if (n.tokRadioOff.value)
599
+ n.radio.Unchecked(n.tokRadioOff);
600
+ }
601
+ if (n.image) {
602
+ if (n.tokImgOpen.value)
603
+ n.image.ImageOpened(n.tokImgOpen);
604
+ if (n.tokImgFail.value)
605
+ n.image.ImageFailed(n.tokImgFail);
606
+ }
607
+ if (n.refresh && n.tokRefresh.value)
608
+ n.refresh.RefreshRequested(n.tokRefresh);
609
+ detachVisual(n.el);
610
+ nodes_.erase(it);
611
+ yoga::nodeDelete(id);
612
+ }
613
+
614
+ // ── Texto / props / estilos ────────────────────────────────────────
615
+
616
+ // UTF-8 → UTF-16: los offsets de `spans` (ADR-0147) son unidades
617
+ // UTF-16 sobre el texto renderizado, igual que hstring/wchar.
618
+ std::wstring ws(const std::string &s) {
619
+ int n = MultiByteToWideChar(CP_UTF8, 0, s.c_str(), (int)s.size(),
620
+ nullptr, 0);
621
+ std::wstring w((size_t)n, L'\0');
622
+ MultiByteToWideChar(CP_UTF8, 0, s.c_str(), (int)s.size(), w.data(), n);
623
+ return w;
624
+ }
625
+
626
+ winrt::hstring hsw(std::wstring_view v) {
627
+ return winrt::hstring(v.data(), (uint32_t)v.size());
628
+ }
629
+
630
+ // Subset TEXT_SPAN_STYLE_KEYS (ADR-0147); backgroundColor no tiene
631
+ // equivalente en Span — se ignora (approx).
632
+ void spanStyle(const WinSpan &sp, muxd::TextElement const &el) {
633
+ namespace wuct = winrt::Windows::UI::Text;
634
+ for (auto const &[k, v] : sp.style) {
635
+ if (k == "color") {
636
+ if (auto b = brushOf(v))
637
+ el.Foreground(b);
638
+ } else if (k == "fontSize") {
639
+ el.FontSize(pxOf(v));
640
+ } else if (k == "fontWeight") {
641
+ int wgt = v == "bold" ? 700 : v == "normal" ? 400 : atoi(v.c_str());
642
+ wuct::FontWeight fw;
643
+ fw.Weight = (uint16_t)std::clamp(wgt, 1, 999);
644
+ el.FontWeight(fw);
645
+ } else if (k == "fontStyle") {
646
+ if (v == "italic")
647
+ el.FontStyle(wuct::FontStyle::Italic);
648
+ else if (v == "oblique")
649
+ el.FontStyle(wuct::FontStyle::Oblique);
650
+ } else if (k == "textDecoration") {
651
+ if (v == "underline")
652
+ el.TextDecorations(wuct::TextDecorations::Underline);
653
+ else if (v == "line-through")
654
+ el.TextDecorations(wuct::TextDecorations::Strikethrough);
655
+ else
656
+ el.TextDecorations(wuct::TextDecorations::None);
657
+ } else if (k == "fontFamily") {
658
+ el.FontFamily(muxm::FontFamily(hs(v)));
659
+ }
660
+ }
661
+ }
662
+
663
+ // Construye el árbol de spans desde la lista plana ordenada
664
+ // (s asc, e desc): los que siguen a un span dentro de su rango son
665
+ // sus hijos — el resto, sus hermanos.
666
+ void treeify(const std::vector<WinSpan> &flat, size_t &i, int lo,
667
+ int hi, std::vector<WinSpan> &dst) {
668
+ while (i < flat.size() && flat[i].s >= lo && flat[i].e <= hi) {
669
+ WinSpan cur = flat[i++];
670
+ treeify(flat, i, cur.s, cur.e, cur.kids);
671
+ dst.push_back(std::move(cur));
672
+ }
673
+ }
674
+
675
+ // Emite Run/Span/Hyperlink en `out` para el rango [lo,hi): huecos
676
+ // como Run plano y cada span como Span (o Hyperlink si href) con sus
677
+ // kids anidados dentro — los rangos se clampean (ADR-0147).
678
+ void emitSpanRange(const std::wstring &t, int lo, int hi,
679
+ const std::vector<WinSpan> &inside,
680
+ muxd::InlineCollection const &out, WinApplicator *self) {
681
+ int pos = lo;
682
+ auto run = [&](int a, int b) {
683
+ auto r = muxd::Run();
684
+ r.Text(hsw(std::wstring_view(t).substr((size_t)a, (size_t)(b - a))));
685
+ out.Append(r);
686
+ };
687
+ for (const WinSpan &sp : inside) {
688
+ int s = std::clamp(sp.s, lo, hi);
689
+ int e = std::clamp(sp.e, s, hi);
690
+ if (s > pos)
691
+ run(pos, s);
692
+ muxd::Span sub{nullptr};
693
+ if (sp.href.empty()) {
694
+ sub = muxd::Span();
695
+ } else {
696
+ // ADR-0133/0147: el handler JS decide interna vs openUrl.
697
+ muxd::Hyperlink hl;
698
+ std::string url = sp.href;
699
+ auto self_ = self;
700
+ hl.Click([self_, url](auto const &,
701
+ muxd::HyperlinkClickEventArgs const &) {
702
+ self_->cb_.callHandlerStr("__elur_span_href", url.c_str());
703
+ });
704
+ sub = hl;
705
+ }
706
+ spanStyle(sp, sub);
707
+ emitSpanRange(t, s, e, sp.kids, sub.Inlines(), self);
708
+ out.Append(sub);
709
+ pos = e;
710
+ }
711
+ if (pos < hi)
712
+ run(pos, hi);
713
+ }
714
+
715
+ void WinApplicator::applySpans(WinNode &n) {
716
+ if (!n.textBlock)
717
+ return;
718
+ auto inlines = n.textBlock.Inlines();
719
+ inlines.Clear();
720
+ if (n.spans.empty()) {
721
+ n.textBlock.Text(hs(n.textValue));
722
+ return;
723
+ }
724
+ std::wstring t = ws(n.textValue);
725
+ emitSpanRange(t, 0, (int)t.size(), n.spans, inlines, this);
726
+ }
727
+
728
+ void WinApplicator::updateText(WinNode &n, const std::string &val) {
729
+ n.textValue = val;
730
+ if (n.textBlock) {
731
+ if (!n.spans.empty())
732
+ applySpans(n);
733
+ else
734
+ n.textBlock.Text(hs(val));
735
+ }
736
+ else if (n.button)
737
+ n.button.Content(winrt::box_value(hs(val)));
738
+ else if (n.input) {
739
+ n.suppressSignal = true;
740
+ n.input.Text(hs(val));
741
+ n.suppressSignal = false;
742
+ } else if (n.sw) {
743
+ n.suppressSignal = true;
744
+ n.sw.IsOn(val == "true" || val == "1");
745
+ n.suppressSignal = false;
746
+ } else if (n.check) {
747
+ n.check.Content(winrt::box_value(hs(val)));
748
+ } else if (n.radio) {
749
+ n.radio.Content(winrt::box_value(hs(val)));
750
+ } else
751
+ warnOnce(unknownOps_, "update-text", n.type);
752
+ yoga::nodeSetText(n.id);
753
+ }
754
+
755
+ void WinApplicator::updateProp(WinNode &n, const std::string &key,
756
+ JSContext *ctx, JSValueConst val) {
757
+ if (key == "value" && n.input) {
758
+ n.suppressSignal = true;
759
+ n.input.Text(hs(jsStr(ctx, val)));
760
+ n.suppressSignal = false;
761
+ return;
762
+ }
763
+ if (key == "placeholder" && n.input) {
764
+ n.input.PlaceholderText(hs(jsStr(ctx, val)));
765
+ return;
766
+ }
767
+ if (key == "src" && n.image) {
768
+ std::string src = jsStr(ctx, val);
769
+ try {
770
+ muxm::Imaging::BitmapImage bi;
771
+ namespace wss = winrt::Windows::Storage::Streams;
772
+ // Image no repinta cuando un stream asignado antes de decodificar
773
+ // completa tarde — con streams la Source se asigna tras el decode
774
+ // (Completed retiene ras+bi; el lookup cubre nodos borrados).
775
+ int nid = n.id;
776
+ auto dq = n.image.DispatcherQueue();
777
+ auto assignDecoded =
778
+ [this, nid, bi, dq](wss::InMemoryRandomAccessStream const &ras) {
779
+ bi.SetSourceAsync(ras).Completed(
780
+ [this, nid, bi, ras, dq](auto const &,
781
+ wf::AsyncStatus st) {
782
+ // Completed puede correr en threadpool (decode
783
+ // asíncrono); Source solo se asigna en UI thread.
784
+ dq.TryEnqueue(mud::DispatcherQueuePriority::Normal,
785
+ mud::DispatcherQueueHandler(
786
+ [this, nid, bi, st]() {
787
+ auto i = nodes_.find(nid);
788
+ if (i == nodes_.end() ||
789
+ !i->second.image)
790
+ return;
791
+ if (st ==
792
+ wf::AsyncStatus::Completed) {
793
+ i->second.image.Source(bi);
794
+ return;
795
+ }
796
+ auto eb = i->second.events.find(
797
+ "error");
798
+ if (eb != i->second.events.end())
799
+ emitEvent(
800
+ i->second, "error",
801
+ "program",
802
+ "{\"message\":\"image load "
803
+ "failed\"}",
804
+ eb->second);
805
+ }));
806
+ });
807
+ };
808
+ // BitmapImage.UriSource no acepta data: URIs (WinUI) — el payload
809
+ // va por stream en memoria, igual que el decode de GTK (ADR-0071).
810
+ if (src.rfind("data:", 0) == 0) {
811
+ auto comma = src.find(',');
812
+ std::string b64 =
813
+ comma == std::string::npos ? "" : src.substr(comma + 1);
814
+ namespace wsc = winrt::Windows::Security::Cryptography;
815
+ wss::InMemoryRandomAccessStream ras;
816
+ ras.WriteAsync(
817
+ wsc::CryptographicBuffer::DecodeFromBase64String(hs(b64)))
818
+ .get();
819
+ ras.Seek(0);
820
+ assignDecoded(ras);
821
+ } else if (src.find(":/") == std::string::npos &&
822
+ src.find(":\\") == std::string::npos) {
823
+ // Sin esquema URI (asset empaquetado o ruta de disco): path
824
+ // relativo al cwd, como gdk_texture_new_from_filename en GTK.
825
+ // UriSource no soporta file:// en apps unpackaged — va por
826
+ // stream, igual que el path data:.
827
+ char abs[MAX_PATH];
828
+ DWORD len = GetFullPathNameA(src.c_str(), MAX_PATH, abs, nullptr);
829
+ if (len == 0 || len >= MAX_PATH)
830
+ throw winrt::hresult_error(E_INVALIDARG);
831
+ std::ifstream f(abs, std::ios::binary);
832
+ std::string bytes((std::istreambuf_iterator<char>(f)),
833
+ std::istreambuf_iterator<char>());
834
+ if (bytes.empty())
835
+ throw winrt::hresult_error(HRESULT_FROM_WIN32(
836
+ ERROR_FILE_NOT_FOUND));
837
+ namespace wsc = winrt::Windows::Security::Cryptography;
838
+ wss::InMemoryRandomAccessStream ras;
839
+ ras.WriteAsync(
840
+ wsc::CryptographicBuffer::CreateFromByteArray(
841
+ winrt::array_view<const uint8_t>(
842
+ reinterpret_cast<const uint8_t *>(
843
+ bytes.data()),
844
+ (uint32_t)bytes.size())))
845
+ .get();
846
+ ras.Seek(0);
847
+ assignDecoded(ras);
848
+ } else {
849
+ bi.UriSource(wf::Uri(hs(src)));
850
+ n.image.Source(bi);
851
+ }
852
+ } catch (...) {
853
+ emitEvent(n, "error", "program",
854
+ "{\"message\":\"image load failed\"}",
855
+ n.events.count("error") ? n.events["error"]
856
+ : EventBind{});
857
+ }
858
+ return;
859
+ }
860
+ if (key == "editable" && n.input) {
861
+ n.input.IsReadOnly(!JS_ToBool(ctx, val));
862
+ return;
863
+ }
864
+ if (key == "readOnly" && n.input) {
865
+ n.input.IsReadOnly(JS_ToBool(ctx, val));
866
+ return;
867
+ }
868
+ if (key == "checked" && n.sw) {
869
+ n.suppressSignal = true;
870
+ n.sw.IsOn(JS_ToBool(ctx, val));
871
+ n.suppressSignal = false;
872
+ return;
873
+ }
874
+ if (key == "checked" && (n.check || n.radio)) {
875
+ n.suppressSignal = true;
876
+ auto b = winrt::box_value(JS_ToBool(ctx, val))
877
+ .as<wf::IReference<bool>>();
878
+ if (n.check)
879
+ n.check.IsChecked(b);
880
+ else
881
+ n.radio.IsChecked(b);
882
+ n.suppressSignal = false;
883
+ return;
884
+ }
885
+ if (key == "variant" && n.type == "switch") {
886
+ swapVariant(n, jsStr(ctx, val));
887
+ return;
888
+ }
889
+ if (key == "value" && n.slider) {
890
+ n.suppressSignal = true;
891
+ double v = 0;
892
+ JS_ToFloat64(ctx, &v, val);
893
+ n.slider.Value(v);
894
+ n.suppressSignal = false;
895
+ return;
896
+ }
897
+ if (key == "min" && n.slider) {
898
+ double v = 0;
899
+ JS_ToFloat64(ctx, &v, val);
900
+ n.slider.Minimum(v);
901
+ return;
902
+ }
903
+ if (key == "max" && n.slider) {
904
+ double v = 0;
905
+ JS_ToFloat64(ctx, &v, val);
906
+ n.slider.Maximum(v);
907
+ return;
908
+ }
909
+ if (key == "fallbackSrc" && n.image) {
910
+ n.fallbackSrc = jsStr(ctx, val);
911
+ return;
912
+ }
913
+ // ─ Estado / foco / a11y genérico (AutomationProperties) ──
914
+ if (key == "disabled") {
915
+ if (n.el) {
916
+ bool b = JS_ToBool(ctx, val);
917
+ n.el.IsHitTestVisible(!b);
918
+ if (auto c = n.el.try_as<muxc::Control>())
919
+ c.IsEnabled(!b);
920
+ }
921
+ return;
922
+ }
923
+ if (key == "focused") {
924
+ // El foco programático va al control interactivo del nodo — el
925
+ // host (ContentControl) no es focusable por sí mismo.
926
+ if (JS_ToBool(ctx, val)) {
927
+ if (auto c = innerCtl(n)) {
928
+ // Focus() exige elemento en el árbol + ventana activa — si el
929
+ // op llega antes del insert/Loaded, difiere a baja prioridad.
930
+ if (!c.Focus(mux::FocusState::Programmatic)) {
931
+ namespace mud = winrt::Microsoft::UI::Dispatching;
932
+ if (auto dq = c.DispatcherQueue())
933
+ dq.TryEnqueue(mud::DispatcherQueuePriority::Low,
934
+ mud::DispatcherQueueHandler([c]() {
935
+ c.Focus(mux::FocusState::Programmatic);
936
+ }));
937
+ }
938
+ }
939
+ }
940
+ return;
941
+ }
942
+ if (key == "focusable") {
943
+ if (auto c = innerCtl(n))
944
+ c.IsTabStop(JS_ToBool(ctx, val));
945
+ return;
946
+ }
947
+ if (key == "label") {
948
+ auto nm = hs(jsStr(ctx, val));
949
+ if (n.el)
950
+ mux::Automation::AutomationProperties::SetName(n.el, nm);
951
+ // El widget real es el control interno (Edit/Button…): el lector
952
+ // de pantalla anuncia su Name, no el del wrapper Custom — igual
953
+ // que gtk_accessible nombre al entry en GTK.
954
+ if (auto ic = innerCtl(n))
955
+ mux::Automation::AutomationProperties::SetName(ic, nm);
956
+ return;
957
+ }
958
+ if (key == "hint") {
959
+ if (n.el)
960
+ mux::Automation::AutomationProperties::SetHelpText(
961
+ n.el, hs(jsStr(ctx, val)));
962
+ return;
963
+ }
964
+ if (key == "live") {
965
+ if (n.el) {
966
+ std::string v = jsStr(ctx, val);
967
+ namespace peers = mux::Automation::Peers;
968
+ mux::Automation::AutomationProperties::SetLiveSetting(
969
+ n.el, v == "assertive"
970
+ ? peers::AutomationLiveSetting::Assertive
971
+ : peers::AutomationLiveSetting::Polite);
972
+ }
973
+ return;
974
+ }
975
+ if (key == "required") {
976
+ if (n.el)
977
+ mux::Automation::AutomationProperties::SetIsRequiredForForm(
978
+ n.el, JS_ToBool(ctx, val));
979
+ return;
980
+ }
981
+ if ((key == "valueMin" || key == "valueMax" || key == "valueNow") &&
982
+ n.slider) {
983
+ // UIA no tiene attached-prop de valor para elementos genéricos —
984
+ // en nodos slider el rango ya lo expone RangeValuePattern;
985
+ // materializan sobre el propio widget.
986
+ double v = 0;
987
+ JS_ToFloat64(ctx, &v, val);
988
+ if (key == "valueMin")
989
+ n.slider.Minimum(v);
990
+ else if (key == "valueMax")
991
+ n.slider.Maximum(v);
992
+ else {
993
+ n.suppressSignal = true;
994
+ n.slider.Value(v);
995
+ n.suppressSignal = false;
996
+ }
997
+ return;
998
+ }
999
+ if (key == "invalid") {
1000
+ // UIA IsDataValidForForm=false ≡ aria-invalid=true (ADR-0152).
1001
+ if (n.el)
1002
+ mux::Automation::AutomationProperties::SetIsDataValidForForm(
1003
+ n.el, !JS_ToBool(ctx, val));
1004
+ return;
1005
+ }
1006
+ if (key == "selected" || key == "expanded" || key == "valueText") {
1007
+ // Estado → ElurA11y del host: el peer lo lee por patrón
1008
+ // (SelectionItem/ExpandCollapse/Value) — elur_uia_host.h.
1009
+ if (!n.a11y)
1010
+ return;
1011
+ bool isNull = JS_IsNull(val) || JS_IsUndefined(val);
1012
+ if (key == "selected") {
1013
+ n.a11y->hasSel = !isNull;
1014
+ n.a11y->sel = !isNull && JS_ToBool(ctx, val);
1015
+ } else if (key == "expanded") {
1016
+ n.a11y->hasExp = !isNull;
1017
+ n.a11y->exp = !isNull && JS_ToBool(ctx, val);
1018
+ } else {
1019
+ n.a11y->hasVal = !isNull;
1020
+ n.a11y->valueText = isNull ? L"" : hs(jsStr(ctx, val));
1021
+ }
1022
+ return;
1023
+ }
1024
+ if (key == "sticky") {
1025
+ // ADR-0150 — translationY por ViewChanged con clamp al padre
1026
+ // (mismo modelo que ElurScrollView en android).
1027
+ float th = 0;
1028
+ bool on = JS_ToBool(ctx, val);
1029
+ if (on && JS_IsNumber(val)) {
1030
+ double d = 0;
1031
+ JS_ToFloat64(ctx, &d, val);
1032
+ th = (float)d;
1033
+ }
1034
+ if (!on) {
1035
+ n.sticky = false;
1036
+ if (n.el)
1037
+ n.el.Translation(winrt::Windows::Foundation::Numerics::float3(
1038
+ 0.f, 0.f, 0.f));
1039
+ if (n.stickyScroll && n.tokSticky.value)
1040
+ n.stickyScroll.ViewChanged(n.tokSticky);
1041
+ n.stickyScroll = nullptr;
1042
+ return;
1043
+ }
1044
+ n.sticky = true;
1045
+ n.stickyTop = th;
1046
+ ensureStickyScroll(n);
1047
+ return;
1048
+ }
1049
+ if (key == "accessible") {
1050
+ bool acc = JS_IsNull(val) || JS_IsUndefined(val) || JS_ToBool(ctx, val);
1051
+ if (n.a11y)
1052
+ n.a11y->hidden = !acc;
1053
+ if (n.el)
1054
+ mux::Automation::AutomationProperties::SetAccessibilityView(
1055
+ n.el, acc ? mux::Automation::Peers::AccessibilityView::Control
1056
+ : mux::Automation::Peers::AccessibilityView::Raw);
1057
+ return;
1058
+ }
1059
+ if (key == "role") {
1060
+ // LocalizedControlType solo anuncia el rol al narrador — no cambia
1061
+ // comportamiento (igual que android role→contentDescription).
1062
+ if (n.el)
1063
+ mux::Automation::AutomationProperties::SetLocalizedControlType(
1064
+ n.el, hs(jsStr(ctx, val)));
1065
+ return;
1066
+ }
1067
+ if (key == "href") {
1068
+ // ADR-0133 — el reconciler ya convirtió href→press/openUrl; el
1069
+ // cursor de enlace no existe en este WASDK (ProtectedCursor ausente).
1070
+ return;
1071
+ }
1072
+ if (key == "as") {
1073
+ // Paridad views/Android/Linux: solo h1–h6 materializan rol
1074
+ // heading; el resto de etiquetas se ignora.
1075
+ std::string v = jsStr(ctx, val);
1076
+ if (n.el && v.size() == 2 && v[0] == 'h' && v[1] >= '1' &&
1077
+ v[1] <= '6')
1078
+ mux::Automation::AutomationProperties::SetHeadingLevel(
1079
+ n.el, (mux::Automation::Peers::AutomationHeadingLevel)(
1080
+ v[1] - '0'));
1081
+ return;
1082
+ }
1083
+ if (key == "spans" && n.textBlock) {
1084
+ // ADR-0147 — array {start,end,style,href} normalizado por el
1085
+ // reconciler (orden s asc/e desc, anidación verificada); aquí solo
1086
+ // se construye el árbol por contención.
1087
+ n.spans.clear();
1088
+ std::vector<WinSpan> flat;
1089
+ int64_t len = 0;
1090
+ JS_GetLength(ctx, val, &len);
1091
+ for (int64_t i = 0; i < len; i++) {
1092
+ JSValue it = JS_GetPropertyInt64(ctx, val, i);
1093
+ WinSpan sp;
1094
+ sp.s = jsInt(ctx, it, "start");
1095
+ sp.e = jsInt(ctx, it, "end");
1096
+ sp.href = jsGetStr(ctx, it, "href");
1097
+ JSValue st = jsGet(ctx, it, "style");
1098
+ JSPropertyEnum *tab = nullptr;
1099
+ uint32_t plen = 0;
1100
+ if (JS_GetOwnPropertyNames(ctx, &tab, &plen, st,
1101
+ JS_GPN_STRING_MASK |
1102
+ JS_GPN_ENUM_ONLY) == 0) {
1103
+ for (uint32_t k = 0; k < plen; k++) {
1104
+ JSValue keyv = JS_AtomToString(ctx, tab[k].atom);
1105
+ std::string skey = jsStr(ctx, keyv);
1106
+ JS_FreeValue(ctx, keyv);
1107
+ JSValue sv = JS_GetProperty(ctx, st, tab[k].atom);
1108
+ sp.style[skey] = jsStr(ctx, sv);
1109
+ JS_FreeValue(ctx, sv);
1110
+ JS_FreeAtom(ctx, tab[k].atom);
1111
+ }
1112
+ js_free(ctx, tab);
1113
+ }
1114
+ JS_FreeValue(ctx, st);
1115
+ flat.push_back(std::move(sp));
1116
+ JS_FreeValue(ctx, it);
1117
+ }
1118
+ std::sort(flat.begin(), flat.end(),
1119
+ [](const WinSpan &a, const WinSpan &b) {
1120
+ return a.s < b.s || (a.s == b.s && a.e > b.e);
1121
+ });
1122
+ size_t idx = 0;
1123
+ treeify(flat, idx, 0, INT_MAX, n.spans);
1124
+ applySpans(n);
1125
+ return;
1126
+ }
1127
+ // ─ TextBlock ──
1128
+ if (key == "selectable" && n.textBlock) {
1129
+ n.textBlock.IsTextSelectionEnabled(JS_ToBool(ctx, val));
1130
+ return;
1131
+ }
1132
+ if (key == "maxLines" && n.textBlock) {
1133
+ double v = 0;
1134
+ JS_ToFloat64(ctx, &v, val);
1135
+ n.textBlock.MaxLines((int)v);
1136
+ return;
1137
+ }
1138
+ if (key == "textOverflow" && n.textBlock) {
1139
+ std::string v = jsStr(ctx, val);
1140
+ n.textBlock.TextTrimming(
1141
+ v == "ellipsis" ? mux::TextTrimming::CharacterEllipsis
1142
+ : v == "clip" ? mux::TextTrimming::Clip
1143
+ : mux::TextTrimming::None);
1144
+ return;
1145
+ }
1146
+ // ─ TextBox ──
1147
+ if (key == "maxlength" && n.input) {
1148
+ double v = 0;
1149
+ JS_ToFloat64(ctx, &v, val);
1150
+ n.input.MaxLength((int)v);
1151
+ return;
1152
+ }
1153
+ if (key == "spellcheck" && n.input) {
1154
+ n.input.IsSpellCheckEnabled(JS_ToBool(ctx, val));
1155
+ return;
1156
+ }
1157
+ if (key == "multiline" && n.input) {
1158
+ bool b = JS_ToBool(ctx, val);
1159
+ n.input.AcceptsReturn(b);
1160
+ if (b)
1161
+ n.input.TextWrapping(mux::TextWrapping::Wrap);
1162
+ return;
1163
+ }
1164
+ if (key == "rows" && n.input) {
1165
+ double v = 0;
1166
+ JS_ToFloat64(ctx, &v, val);
1167
+ if (v > 0) {
1168
+ // Aprox: TextBox no expone filas — MinHeight por línea
1169
+ // (fontSize*1.4 + chrome).
1170
+ double fs = n.fontSizePx > 0 ? n.fontSizePx : 14;
1171
+ n.inputMinH = (float)(v * fs * 1.4 + 16);
1172
+ n.input.MinHeight(n.inputMinH);
1173
+ }
1174
+ return;
1175
+ }
1176
+ if ((key == "keyboard" || key == "autocomplete") && n.input) {
1177
+ // `autocomplete` en desktop no tiene autofill de sistema —
1178
+ // InputScope es el hint más cercano (mismo vocabulario que
1179
+ // `keyboard`: email/tel/url/search/password).
1180
+ std::string v = jsStr(ctx, val);
1181
+ muxi::InputScopeNameValue kv = muxi::InputScopeNameValue::Default;
1182
+ if (v == "number" || v == "decimal")
1183
+ kv = muxi::InputScopeNameValue::Number;
1184
+ else if (v == "phone" || v == "tel")
1185
+ kv = muxi::InputScopeNameValue::TelephoneNumber;
1186
+ else if (v == "email")
1187
+ kv = muxi::InputScopeNameValue::EmailSmtpAddress;
1188
+ else if (v == "url")
1189
+ kv = muxi::InputScopeNameValue::Url;
1190
+ else if (v == "search")
1191
+ kv = muxi::InputScopeNameValue::Search;
1192
+ else if (v == "password" || v == "current-password")
1193
+ kv = muxi::InputScopeNameValue::Password;
1194
+ else if (v == "username")
1195
+ kv = muxi::InputScopeNameValue::NameOrPhoneNumber;
1196
+ else if (v == "name")
1197
+ kv = muxi::InputScopeNameValue::PersonalFullName;
1198
+ muxi::InputScope scope;
1199
+ scope.Names().Append(muxi::InputScopeName(kv));
1200
+ n.input.InputScope(scope);
1201
+ return;
1202
+ }
1203
+ if (key == "selection" && n.input) {
1204
+ // {start,end} objeto o número (caret colapsado).
1205
+ int s = 0, e = 0;
1206
+ if (JS_IsObject(val)) {
1207
+ s = jsInt(ctx, val, "start");
1208
+ e = jsInt(ctx, val, "end", s);
1209
+ } else {
1210
+ double v = 0;
1211
+ JS_ToFloat64(ctx, &v, val);
1212
+ s = e = (int)v;
1213
+ }
1214
+ n.input.SelectionStart(s);
1215
+ n.input.SelectionLength(std::max(0, e - s));
1216
+ return;
1217
+ }
1218
+ // ─ ScrollViewer ──
1219
+ if (key == "scrollTop" && n.scroll) {
1220
+ double v = 0;
1221
+ JS_ToFloat64(ctx, &v, val);
1222
+ n.suppressSignal = true;
1223
+ n.scroll.ChangeView(nullptr, v, nullptr, true);
1224
+ n.suppressSignal = false;
1225
+ return;
1226
+ }
1227
+ if (key == "scrollLeft" && n.scroll) {
1228
+ double v = 0;
1229
+ JS_ToFloat64(ctx, &v, val);
1230
+ n.suppressSignal = true;
1231
+ n.scroll.ChangeView(v, nullptr, nullptr, true);
1232
+ n.suppressSignal = false;
1233
+ return;
1234
+ }
1235
+ if (key == "horizontal" && n.scroll) {
1236
+ bool b = JS_ToBool(ctx, val);
1237
+ n.scroll.HorizontalScrollBarVisibility(
1238
+ b ? muxc::ScrollBarVisibility::Auto
1239
+ : muxc::ScrollBarVisibility::Disabled);
1240
+ return;
1241
+ }
1242
+ if ((key == "refreshing" || key == "refresh") && n.scroll) {
1243
+ ensureRefresh(n);
1244
+ if (key == "refreshing" && JS_ToBool(ctx, val))
1245
+ n.refresh.RequestRefresh();
1246
+ return;
1247
+ }
1248
+ if (key == "dir") {
1249
+ std::string dv = jsStr(ctx, val);
1250
+ yoga::nodeSetDir(n.id, dv == "rtl");
1251
+ // FlowDirection solo en hojas: en contenedores (n.inner = Canvas de
1252
+ // hijos posicionados por Yoga) invierte la interpretación de
1253
+ // Canvas.Left y cancela el RTL que Yoga ya aplicó — doble volteo.
1254
+ // En hojas sí aporta: bidi del texto y alineación start del control.
1255
+ if (!n.inner && n.el)
1256
+ if (auto fe = n.el.try_as<mux::FrameworkElement>())
1257
+ fe.FlowDirection(dv == "rtl"
1258
+ ? mux::FlowDirection::RightToLeft
1259
+ : mux::FlowDirection::LeftToRight);
1260
+ return;
1261
+ }
1262
+ if (key == "visible") {
1263
+ if (n.el)
1264
+ n.el.Visibility(JS_ToBool(ctx, val) ? mux::Visibility::Visible
1265
+ : mux::Visibility::Collapsed);
1266
+ return;
1267
+ }
1268
+ warnOnce(unknownProps_, "prop", key + "@" + n.type);
1269
+ }
1270
+
1271
+ // update-style: isNum decide el carril f64/str (ADR-0050). Los estilos
1272
+ // de layout van al mirror Yoga; los visuales al wrapper/control.
1273
+ void WinApplicator::updateStyle(WinNode &n, JSContext *ctx,
1274
+ JSValueConst style) {
1275
+ JSPropertyEnum *tab = nullptr;
1276
+ uint32_t len = 0;
1277
+ if (JS_GetOwnPropertyNames(ctx, &tab, &len, style,
1278
+ JS_GPN_STRING_MASK | JS_GPN_ENUM_ONLY) < 0)
1279
+ return;
1280
+ for (uint32_t i = 0; i < len; i++) {
1281
+ JSAtom atom = tab[i].atom;
1282
+ JSValue keyv = JS_AtomToString(ctx, atom);
1283
+ std::string key = jsStr(ctx, keyv);
1284
+ JS_FreeValue(ctx, keyv);
1285
+ JSValue val = JS_GetProperty(ctx, style, atom);
1286
+ if (JS_IsNumber(val)) {
1287
+ double num = 0;
1288
+ JS_ToFloat64(ctx, &num, val);
1289
+ yoga::nodeSetStyle(n.id, key, true, num, "");
1290
+ n.visual.erase(key);
1291
+ } else {
1292
+ std::string s = jsStr(ctx, val);
1293
+ yoga::nodeSetStyle(n.id, key, false, 0, s);
1294
+ n.visual[key] = s;
1295
+ }
1296
+ JS_FreeValue(ctx, val);
1297
+ JS_FreeAtom(ctx, atom);
1298
+ }
1299
+ js_free(ctx, tab);
1300
+ applyVisual(n);
1301
+ }
1302
+
1303
+ void WinApplicator::applyVisual(WinNode &n) {
1304
+ auto find = [&](const char *k) -> const std::string * {
1305
+ auto i = n.visual.find(k);
1306
+ return i == n.visual.end() ? nullptr : &i->second;
1307
+ };
1308
+ mux::UIElement target = n.el;
1309
+ if (const std::string *bg = find("backgroundColor")) {
1310
+ if (auto b = brushOf(*bg)) {
1311
+ if (n.border)
1312
+ n.border.Background(b);
1313
+ else if (n.button)
1314
+ n.button.Background(b);
1315
+ else if (n.input)
1316
+ n.input.Background(b);
1317
+ else if (n.sw)
1318
+ n.sw.Background(b);
1319
+ }
1320
+ }
1321
+ if (const std::string *fg = find("color")) {
1322
+ if (auto b = brushOf(*fg)) {
1323
+ if (n.textBlock)
1324
+ n.textBlock.Foreground(b);
1325
+ else if (n.button)
1326
+ n.button.Foreground(b);
1327
+ else if (n.input)
1328
+ n.input.Foreground(b);
1329
+ }
1330
+ }
1331
+ if (const std::string *fs = find("fontSize")) {
1332
+ double px = pxOf(*fs);
1333
+ if (px > 0) {
1334
+ n.fontSizePx = (float)px;
1335
+ if (n.textBlock)
1336
+ n.textBlock.FontSize(px);
1337
+ else if (n.button)
1338
+ n.button.FontSize(px);
1339
+ else if (n.input)
1340
+ n.input.FontSize(px);
1341
+ }
1342
+ }
1343
+ if (const std::string *fw = find("fontWeight")) {
1344
+ auto w = wut::FontWeights::Normal();
1345
+ if (*fw == "bold" || pxOf(*fw) >= 600)
1346
+ w = wut::FontWeights::Bold();
1347
+ if (n.textBlock)
1348
+ n.textBlock.FontWeight(w);
1349
+ else if (n.button)
1350
+ n.button.FontWeight(w);
1351
+ }
1352
+ if (const std::string *ta = find("textAlign")) {
1353
+ n.alignSet = true;
1354
+ mux::TextAlignment a = mux::TextAlignment::Left;
1355
+ if (*ta == "center")
1356
+ a = mux::TextAlignment::Center;
1357
+ else if (*ta == "right" || *ta == "end")
1358
+ a = mux::TextAlignment::Right;
1359
+ else if (*ta == "justify")
1360
+ a = mux::TextAlignment::Justify;
1361
+ if (n.textBlock)
1362
+ n.textBlock.TextAlignment(a);
1363
+ else if (n.input)
1364
+ n.input.TextAlignment(a);
1365
+ }
1366
+ if (n.border) {
1367
+ const std::string *br = find("borderRadius");
1368
+ if (br) {
1369
+ double r = pxOf(*br);
1370
+ n.border.CornerRadius(mux::CornerRadius{r, r, r, r});
1371
+ }
1372
+ const std::string *bc = find("borderColor");
1373
+ const std::string *bw = find("borderWidth");
1374
+ if (bc || bw) {
1375
+ if (bc)
1376
+ if (auto b = brushOf(*bc))
1377
+ n.border.BorderBrush(b);
1378
+ double t = bw ? pxOf(*bw, 1) : 1;
1379
+ n.border.BorderThickness(Thickness{t, t, t, t});
1380
+ }
1381
+ // Padding visual: Yoga lo lleva en el árbol para contenedores;
1382
+ // en hojas con measureFunc lo suma la medida (padVals), como en
1383
+ // GTK — aquí no lo duplicamos.
1384
+ }
1385
+ if (const std::string *op = find("opacity")) {
1386
+ if (n.el)
1387
+ n.el.Opacity(pxOf(*op, 1));
1388
+ }
1389
+ if (const std::string *ov = find("overflow")) {
1390
+ // M1: ScrollViewer ya gestiona scroll; hidden → clip al rect
1391
+ // (XAML recorta hijos por defecto en Canvas si el border tiene
1392
+ // tamaño fijado por el rect Yoga — nada que hacer de momento).
1393
+ if (*ov != "hidden" && *ov != "scroll" && *ov != "auto" &&
1394
+ *ov != "visible")
1395
+ warnOnce(unknownStyles_, "style", "overflow:" + *ov);
1396
+ }
1397
+ }
1398
+
1399
+ // ── Medida de hojas (hook síncrono de yoga) ────────────────────────
1400
+
1401
+ void WinApplicator::measureLeaf(int id, float w, int wMode, float h,
1402
+ int hMode, float &ow, float &oh) {
1403
+ auto it = nodes_.find(id);
1404
+ if (it == nodes_.end()) {
1405
+ ow = oh = 0;
1406
+ return;
1407
+ }
1408
+ WinNode &n = it->second;
1409
+ auto availW = (wMode == YGMeasureModeUndefined || w <= 0)
1410
+ ? std::numeric_limits<float>::infinity()
1411
+ : w;
1412
+ auto availH = (hMode == YGMeasureModeUndefined || h <= 0)
1413
+ ? std::numeric_limits<float>::infinity()
1414
+ : h;
1415
+ if (n.input) {
1416
+ // Measure() sobre un TextBox/RichEditBox detached corrompe el
1417
+ // estado de WinUIEdit (crash 0x80004005 stowed en el siguiente
1418
+ // pase de render — medido en repro mínimo). Se usa el intrínseco
1419
+ // del default style: alto 32 por línea, ancho mínimo 120.
1420
+ ow = wMode == YGMeasureModeUndefined ? 120 : w;
1421
+ float ih = n.inputMinH > 32 ? n.inputMinH : 32;
1422
+ oh = hMode == YGMeasureModeUndefined ? ih : h;
1423
+ return;
1424
+ }
1425
+ mux::UIElement probe{nullptr};
1426
+ if (n.textBlock)
1427
+ probe = n.textBlock;
1428
+ else if (n.button)
1429
+ probe = n.button;
1430
+ else if (n.swEl)
1431
+ probe = n.swEl;
1432
+ else if (n.slider)
1433
+ probe = n.slider;
1434
+ else if (n.image)
1435
+ probe = n.image;
1436
+ if (!probe) {
1437
+ ow = wMode == YGMeasureModeUndefined ? 0 : w;
1438
+ oh = hMode == YGMeasureModeUndefined ? 0 : h;
1439
+ return;
1440
+ }
1441
+ probe.Measure(Size{availW, availH});
1442
+ Size d = probe.DesiredSize();
1443
+ // Controles templated (Button/ToggleSwitch/TextBox) devuelven 0×0
1444
+ // si se miden antes de entrar al visual tree: el template solo se
1445
+ // instancia en load. Sin fallback Yoga les da rect 0 y el control
1446
+ // queda invisible aunque funcione — intrínsecos del default style.
1447
+ if (d.Width <= 0 || d.Height <= 0) {
1448
+ if (n.sw)
1449
+ d = Size{60, 24};
1450
+ else if (n.check || n.radio)
1451
+ d = Size{20, 20};
1452
+ else if (n.input)
1453
+ d = Size{120, 32};
1454
+ else if (n.button)
1455
+ d = Size{88, 32};
1456
+ else if (n.slider)
1457
+ d = Size{120, 32};
1458
+ else if (n.image)
1459
+ d = Size{64, 64};
1460
+ }
1461
+ ow = wMode == YGMeasureModeExactly ? w : std::min(d.Width, availW);
1462
+ oh = hMode == YGMeasureModeExactly ? h : std::min(d.Height, availH);
1463
+ float pl = 0, pt = 0, pr = 0, pb = 0;
1464
+ yoga::padOf(id, pl, pt, pr, pb);
1465
+ ow += pl + pr;
1466
+ oh += pt + pb;
1467
+ }
1468
+
1469
+ // ── Eventos (attach-event → control nativo) ────────────────────────
1470
+
1471
+ void WinApplicator::attachEvent(int id, const std::string &event,
1472
+ const std::string &handler,
1473
+ bool continuous,
1474
+ const std::string &payload) {
1475
+ auto it = nodes_.find(id);
1476
+ if (it == nodes_.end())
1477
+ return;
1478
+ WinNode &n = it->second;
1479
+ n.events[event] = EventBind{handler, continuous, payload};
1480
+
1481
+ if (event == "press") {
1482
+ // ADR-0179: el release que cierra un longPress o un pan disparado
1483
+ // no es press — los consume lpFired/panMoved (una sola vez).
1484
+ auto consumeGesture = [](WinNode &nn) {
1485
+ if (nn.lpFired || nn.panMoved) {
1486
+ nn.lpFired = false;
1487
+ nn.panMoved = false;
1488
+ return true;
1489
+ }
1490
+ return false;
1491
+ };
1492
+ if (n.button) {
1493
+ if (!n.tokClick.value)
1494
+ n.tokClick = n.button.Click(
1495
+ [this, id, consumeGesture](auto const &, auto const &) {
1496
+ auto i = nodes_.find(id);
1497
+ if (i == nodes_.end() || consumeGesture(i->second))
1498
+ return;
1499
+ if (i->second.events.count("press"))
1500
+ emitEvent(i->second, "press", "user", "{}",
1501
+ i->second.events["press"]);
1502
+ });
1503
+ } else if (n.el) {
1504
+ // IsTapEnabled default false en UIElement — sin el flag el Tapped
1505
+ // nunca se genera en la ruta de hit (el hit cae en el Border del
1506
+ // chrome, no en el host ContentControl).
1507
+ if (n.border)
1508
+ n.border.IsTapEnabled(true);
1509
+ n.el.IsTapEnabled(true);
1510
+ n.el.Tapped(
1511
+ [this, id, consumeGesture](auto const &,
1512
+ muxi::TappedRoutedEventArgs const &) {
1513
+ auto i = nodes_.find(id);
1514
+ if (i == nodes_.end() || consumeGesture(i->second))
1515
+ return;
1516
+ if (i->second.events.count("press"))
1517
+ emitEvent(i->second, "press", "user", "{}",
1518
+ i->second.events["press"]);
1519
+ });
1520
+ }
1521
+ return;
1522
+ }
1523
+ if (event == "input" || event == "change") {
1524
+ if (n.input) {
1525
+ if (!n.tokText.value)
1526
+ n.tokText =
1527
+ n.input.TextChanged([this, id](auto const &, auto const &) {
1528
+ auto i = nodes_.find(id);
1529
+ if (i == nodes_.end() || i->second.suppressSignal)
1530
+ return;
1531
+ WinNode &nn = i->second;
1532
+ std::string t = winrt::to_string(nn.input.Text());
1533
+ const char *ev = nn.events.count("input") ? "input"
1534
+ : "change";
1535
+ auto eb = nn.events.find(ev);
1536
+ if (eb != nn.events.end())
1537
+ emitEvent(nn, ev, "user",
1538
+ std::string("{\"value\":") +
1539
+ modules::jsonQuote(t) + "}",
1540
+ eb->second);
1541
+ });
1542
+ } else if (n.swEl) {
1543
+ wireCheckLike(id, n);
1544
+ } else if (n.slider) {
1545
+ if (!n.tokSlider.value)
1546
+ n.tokSlider = n.slider.ValueChanged(
1547
+ [this, id](auto const &,
1548
+ muxc::Primitives::RangeBaseValueChangedEventArgs
1549
+ const &e) {
1550
+ auto i = nodes_.find(id);
1551
+ if (i == nodes_.end() || i->second.suppressSignal)
1552
+ return;
1553
+ WinNode &nn = i->second;
1554
+ const char *ev = nn.events.count("change") ? "change"
1555
+ : "input";
1556
+ auto eb = nn.events.find(ev);
1557
+ if (eb != nn.events.end()) {
1558
+ char buf[48];
1559
+ snprintf(buf, sizeof(buf), "{\"value\":%.4g}",
1560
+ e.NewValue());
1561
+ emitEvent(nn, ev, "user", buf, eb->second);
1562
+ }
1563
+ });
1564
+ } else
1565
+ warnOnce(unknownProps_, "event-pendiente",
1566
+ event + "@" + n.type);
1567
+ return;
1568
+ }
1569
+ if (event == "submit" && n.input) {
1570
+ n.input.KeyDown([this, id](auto const &,
1571
+ muxi::KeyRoutedEventArgs const &e) {
1572
+ if (e.Key() != winrt::Windows::System::VirtualKey::Enter)
1573
+ return;
1574
+ auto i = nodes_.find(id);
1575
+ if (i == nodes_.end())
1576
+ return;
1577
+ auto eb = i->second.events.find("submit");
1578
+ if (eb != i->second.events.end())
1579
+ emitEvent(i->second, "submit", "user",
1580
+ std::string("{\"text\":") +
1581
+ modules::jsonQuote(
1582
+ winrt::to_string(i->second.input.Text())) +
1583
+ "}",
1584
+ eb->second);
1585
+ });
1586
+ return;
1587
+ }
1588
+ if (event == "scroll" && n.scroll) {
1589
+ auto emitMetrics = [this](WinNode &nd) {
1590
+ auto eb = nd.events.find("scroll");
1591
+ if (eb == nd.events.end())
1592
+ return;
1593
+ // {y,x,vh,vw,ch,cw,node} — mismo contrato que emitScrollMetrics
1594
+ // GTK: endReached lo sintetiza el reconciler sobre estos campos.
1595
+ char buf[256];
1596
+ snprintf(buf, sizeof(buf),
1597
+ "{\"y\":%.1f,\"x\":%.1f,\"vh\":%.1f,\"vw\":%.1f,"
1598
+ "\"ch\":%.1f,\"cw\":%.1f,\"node\":%d}",
1599
+ nd.scroll.VerticalOffset(), nd.scroll.HorizontalOffset(),
1600
+ nd.scroll.ViewportHeight(), nd.scroll.ViewportWidth(),
1601
+ nd.scroll.ExtentHeight(), nd.scroll.ExtentWidth(),
1602
+ nd.id);
1603
+ emitEvent(nd, "scroll", "user", buf, eb->second);
1604
+ };
1605
+ if (!n.tokView.value)
1606
+ n.tokView = n.scroll.ViewChanged(
1607
+ [this, id, emitMetrics](auto const &, auto const &) {
1608
+ auto i = nodes_.find(id);
1609
+ if (i == nodes_.end() || i->second.suppressSignal)
1610
+ return;
1611
+ emitMetrics(i->second);
1612
+ });
1613
+ emitMetrics(n); // métricas iniciales — igual que en el attach GTK
1614
+ return;
1615
+ }
1616
+ if (event == "focus" || event == "blur") {
1617
+ auto fire = [this, id](const char *ev) {
1618
+ auto i = nodes_.find(id);
1619
+ if (i == nodes_.end())
1620
+ return;
1621
+ auto eb = i->second.events.find(ev);
1622
+ if (eb != i->second.events.end())
1623
+ emitEvent(i->second, ev, "user", "{}", eb->second);
1624
+ };
1625
+ if (event == "focus")
1626
+ n.el.GotFocus([fire](auto const &, auto const &) { fire("focus"); });
1627
+ else
1628
+ n.el.LostFocus([fire](auto const &, auto const &) { fire("blur"); });
1629
+ return;
1630
+ }
1631
+ if (event == "key" && n.el) {
1632
+ // Paridad GTK/web (tabindex): el nodo se vuelve enfocable y el
1633
+ // PointerPressed le da el foco — sin él el KeyDown nunca llega.
1634
+ if (auto ctl = n.el.try_as<muxc::Control>())
1635
+ ctl.IsTabStop(true);
1636
+ auto grabKeyFocus = [this](mux::UIElement el) {
1637
+ // La asignación de foco por puntero del sistema termina tras el
1638
+ // release y pisa cualquier Focus previo — el diferido en el
1639
+ // release gana la carrera.
1640
+ if (auto dq = mud::DispatcherQueue::GetForCurrentThread())
1641
+ dq.TryEnqueue(
1642
+ mud::DispatcherQueuePriority::Low,
1643
+ mud::DispatcherQueueHandler([el]() {
1644
+ if (auto ctl = el.try_as<muxc::Control>())
1645
+ ctl.Focus(mux::FocusState::Programmatic);
1646
+ }));
1647
+ };
1648
+ muxi::PointerEventHandler onP(
1649
+ [this, id, grabKeyFocus](
1650
+ auto const &, muxi::PointerRoutedEventArgs const &) {
1651
+ auto i = nodes_.find(id);
1652
+ if (i != nodes_.end())
1653
+ grabKeyFocus(i->second.el);
1654
+ });
1655
+ n.el.AddHandler(mux::UIElement::PointerReleasedEvent(),
1656
+ winrt::box_value(onP), true);
1657
+ n.el.KeyDown(
1658
+ [this, id](auto const &, muxi::KeyRoutedEventArgs const &e) {
1659
+ emitKeyFor(id, e.Key());
1660
+ });
1661
+ return;
1662
+ }
1663
+ if (event == "shortcut") {
1664
+ // El reconciler deja el combo canónico en el payload (ADR-0179) —
1665
+ // mismo modelo que GTK: registro de ventana + PreviewKeyDown.
1666
+ modules::Json p;
1667
+ const modules::Json *c =
1668
+ modules::jsonParse(payload, p) ? p.get("combo") : nullptr;
1669
+ std::string combo = c ? c->asStr() : "";
1670
+ if (combo.empty())
1671
+ return;
1672
+ dropHotkeys(id);
1673
+ hotkeys_.push_back({id, combo});
1674
+ ensureHotkeyHook();
1675
+ return;
1676
+ }
1677
+ if (event == "hover" && n.el) {
1678
+ // GTK: hover = solo la fase enter.
1679
+ n.el.PointerEntered(
1680
+ [this, id](auto const &, muxi::PointerRoutedEventArgs const &) {
1681
+ auto i = nodes_.find(id);
1682
+ if (i == nodes_.end())
1683
+ return;
1684
+ auto eb = i->second.events.find("hover");
1685
+ if (eb != i->second.events.end())
1686
+ emitEvent(i->second, "hover", "user", "{}", eb->second);
1687
+ });
1688
+ return;
1689
+ }
1690
+ if (event == "pointer" && n.el) {
1691
+ auto firePt = [this, id](const char *phase, auto const &e) {
1692
+ auto i = nodes_.find(id);
1693
+ if (i == nodes_.end())
1694
+ return;
1695
+ auto eb = i->second.events.find("pointer");
1696
+ if (eb == i->second.events.end())
1697
+ return;
1698
+ auto pt = e.GetCurrentPoint(i->second.el).Position();
1699
+ char buf[128];
1700
+ snprintf(buf, sizeof(buf), "{\"phase\":\"%s\",\"x\":%.1f,\"y\":%.1f}",
1701
+ phase, pt.X, pt.Y);
1702
+ emitEvent(i->second, "pointer", "user", buf, eb->second);
1703
+ };
1704
+ n.el.PointerEntered(
1705
+ [firePt](auto const &,
1706
+ muxi::PointerRoutedEventArgs const &e) { firePt("enter", e); });
1707
+ n.el.PointerMoved(
1708
+ [firePt](auto const &,
1709
+ muxi::PointerRoutedEventArgs const &e) { firePt("move", e); });
1710
+ n.el.PointerExited(
1711
+ [firePt](auto const &,
1712
+ muxi::PointerRoutedEventArgs const &e) { firePt("leave", e); });
1713
+ // down/up sobre un Button llega handled: AddHandler los ve igual.
1714
+ n.el.AddHandler(
1715
+ mux::UIElement::PointerPressedEvent(),
1716
+ winrt::box_value(muxi::PointerEventHandler(
1717
+ [firePt](auto const &,
1718
+ muxi::PointerRoutedEventArgs const &e) {
1719
+ firePt("down", e);
1720
+ })),
1721
+ true);
1722
+ n.el.AddHandler(
1723
+ mux::UIElement::PointerReleasedEvent(),
1724
+ winrt::box_value(muxi::PointerEventHandler(
1725
+ [firePt](auto const &,
1726
+ muxi::PointerRoutedEventArgs const &e) {
1727
+ firePt("up", e);
1728
+ })),
1729
+ true);
1730
+ return;
1731
+ }
1732
+ if (event == "contextMenu" && n.el) {
1733
+ n.el.RightTapped(
1734
+ [this, id](auto const &,
1735
+ muxi::RightTappedRoutedEventArgs const &e) {
1736
+ auto i = nodes_.find(id);
1737
+ if (i == nodes_.end())
1738
+ return;
1739
+ auto eb = i->second.events.find("contextMenu");
1740
+ if (eb == i->second.events.end())
1741
+ return;
1742
+ auto pt = e.GetPosition(i->second.el);
1743
+ char buf[64];
1744
+ snprintf(buf, sizeof(buf), "{\"x\":%.1f,\"y\":%.1f}", pt.X, pt.Y);
1745
+ emitEvent(i->second, "contextMenu", "user", buf, eb->second);
1746
+ });
1747
+ return;
1748
+ }
1749
+ if (event == "longPress" && n.el) {
1750
+ auto fireLp = [this, id](float x, float y) {
1751
+ auto i = nodes_.find(id);
1752
+ if (i == nodes_.end())
1753
+ return;
1754
+ auto eb = i->second.events.find("longPress");
1755
+ if (eb == i->second.events.end())
1756
+ return;
1757
+ char buf[64];
1758
+ snprintf(buf, sizeof(buf), "{\"x\":%.1f,\"y\":%.1f}", x, y);
1759
+ emitEvent(i->second, "longPress", "user", buf, eb->second);
1760
+ };
1761
+ // ADR-0179: umbral del SO — Holding cubre touch/pen; el ratón no
1762
+ // genera Holding en WinUI3, así que lleva un timer propio
1763
+ // (500 ms / cancela a 8 px — el estándar web del ADR). La ruta de
1764
+ // hit pasa por el Border: los flags van en los dos niveles.
1765
+ if (n.border)
1766
+ n.border.IsHoldingEnabled(true);
1767
+ n.el.IsHoldingEnabled(true);
1768
+ n.el.Holding(
1769
+ [this, id, fireLp](auto const &,
1770
+ muxi::HoldingRoutedEventArgs const &e) {
1771
+ if (e.HoldingState() != mui::HoldingState::Started)
1772
+ return;
1773
+ auto i = nodes_.find(id);
1774
+ if (i == nodes_.end())
1775
+ return;
1776
+ i->second.lpFired = true;
1777
+ auto pt = e.GetPosition(i->second.el);
1778
+ fireLp((float)pt.X, (float)pt.Y);
1779
+ });
1780
+ // AddHandler(handledEventsToo): Button marca pressed/released
1781
+ // handled — con += el timer no vería nunca el ciclo del ratón.
1782
+ n.el.AddHandler(
1783
+ mux::UIElement::PointerPressedEvent(),
1784
+ winrt::box_value(muxi::PointerEventHandler(
1785
+ [this, id](auto const &,
1786
+ muxi::PointerRoutedEventArgs const &e) {
1787
+ auto i = nodes_.find(id);
1788
+ if (i == nodes_.end())
1789
+ return;
1790
+ WinNode &nn = i->second;
1791
+ nn.lpFired = false;
1792
+ if (!nn.lpTimer) {
1793
+ nn.lpTimer = mux::DispatcherTimer();
1794
+ nn.lpTimer.Interval(
1795
+ wf::TimeSpan{std::chrono::milliseconds(500)});
1796
+ nn.lpTimer.Tick([this, id](auto const &, auto const &) {
1797
+ auto it = nodes_.find(id);
1798
+ if (it == nodes_.end())
1799
+ return;
1800
+ it->second.lpTimer.Stop();
1801
+ auto eb = it->second.events.find("longPress");
1802
+ if (eb == it->second.events.end())
1803
+ return;
1804
+ it->second.lpFired = true;
1805
+ char buf[64];
1806
+ snprintf(buf, sizeof(buf), "{\"x\":%.1f,\"y\":%.1f}",
1807
+ it->second.lpX, it->second.lpY);
1808
+ emitEvent(it->second, "longPress", "user", buf,
1809
+ eb->second);
1810
+ });
1811
+ }
1812
+ auto pt = e.GetCurrentPoint(nn.el).Position();
1813
+ nn.lpX = (float)pt.X;
1814
+ nn.lpY = (float)pt.Y;
1815
+ nn.lpTimer.Start();
1816
+ })),
1817
+ true);
1818
+ auto cancelLp = [this, id](float mx, float my, bool hard) {
1819
+ auto i = nodes_.find(id);
1820
+ if (i == nodes_.end() || !i->second.lpTimer)
1821
+ return;
1822
+ if (hard ||
1823
+ std::abs(mx - i->second.lpX) > 8.f ||
1824
+ std::abs(my - i->second.lpY) > 8.f)
1825
+ i->second.lpTimer.Stop();
1826
+ };
1827
+ // El gesto reclamado a manipulación con desplazamiento real no es
1828
+ // longPress — ManipulationStarted llega ya en el press (Translate
1829
+ // activo), así que se cancela por distancia, no por el inicio.
1830
+ n.el.ManipulationDelta(
1831
+ [this, id, cancelLp](
1832
+ auto const &,
1833
+ muxi::ManipulationDeltaRoutedEventArgs const &e) {
1834
+ auto cum = e.Cumulative().Translation;
1835
+ if (std::abs((float)cum.X) > 8.f ||
1836
+ std::abs((float)cum.Y) > 8.f)
1837
+ cancelLp(0, 0, true);
1838
+ });
1839
+ n.el.AddHandler(
1840
+ mux::UIElement::PointerMovedEvent(),
1841
+ winrt::box_value(muxi::PointerEventHandler(
1842
+ [this, id, cancelLp](
1843
+ auto const &, muxi::PointerRoutedEventArgs const &e) {
1844
+ auto i = nodes_.find(id);
1845
+ if (i == nodes_.end())
1846
+ return;
1847
+ auto pt = e.GetCurrentPoint(i->second.el).Position();
1848
+ cancelLp((float)pt.X, (float)pt.Y, false);
1849
+ })),
1850
+ true);
1851
+ n.el.AddHandler(
1852
+ mux::UIElement::PointerReleasedEvent(),
1853
+ winrt::box_value(muxi::PointerEventHandler(
1854
+ [this, id, cancelLp](
1855
+ auto const &, muxi::PointerRoutedEventArgs const &) {
1856
+ cancelLp(0, 0, true);
1857
+ })),
1858
+ true);
1859
+ n.el.PointerExited(
1860
+ [this, id, cancelLp](auto const &,
1861
+ muxi::PointerRoutedEventArgs const &) {
1862
+ cancelLp(0, 0, true);
1863
+ });
1864
+ n.el.PointerCaptureLost(
1865
+ [this, id, cancelLp](auto const &,
1866
+ muxi::PointerRoutedEventArgs const &) {
1867
+ cancelLp(0, 0, true);
1868
+ });
1869
+ return;
1870
+ }
1871
+ // El gesture recognizer lo genera el elemento más profundo bajo el
1872
+ // puntero (Button captura el contacto y los PointerMoved no llegan
1873
+ // al wrapper; ManipulationDelta tampoco burbujea — solo Started/
1874
+ // Completed). Pan/pinch escuchan ese elemento, que además necesita
1875
+ // los modos reales: System produce Started/Completed con cum=0.
1876
+ auto gestureEl = [&n]() -> mux::UIElement {
1877
+ if (n.button) return n.button;
1878
+ if (n.input) return n.input;
1879
+ if (n.swEl) return n.swEl;
1880
+ if (n.slider) return n.slider;
1881
+ if (n.image) return n.image;
1882
+ return n.el;
1883
+ };
1884
+ if (event == "pan" && n.el) {
1885
+ auto ge = gestureEl();
1886
+ // Pan por ManipulationDelta en el elemento gestual (ge): el
1887
+ // recognizer vive en el control más profundo — los deltas no
1888
+ // burbujean al host (Started/Completed sí). Slop 8px como
1889
+ // GtkGestureDrag; el reclamo niega longPress (timer) y el press
1890
+ // del release (consumeGesture). Payload {x,y} = posición del
1891
+ // contacto en coords del elemento, {dx,dy} = traslación
1892
+ // acumulada — mismo contrato que GTK.
1893
+ ge.ManipulationMode(
1894
+ (ge.ManipulationMode() & ~muxi::ManipulationModes::System) |
1895
+ muxi::ManipulationModes::TranslateX |
1896
+ muxi::ManipulationModes::TranslateY |
1897
+ muxi::ManipulationModes::Scale);
1898
+ auto emitPan = [this, id](const char *phase, float px, float py,
1899
+ float ox, float oy) {
1900
+ auto i = nodes_.find(id);
1901
+ if (i == nodes_.end())
1902
+ return;
1903
+ auto eb = i->second.events.find("pan");
1904
+ if (eb == i->second.events.end())
1905
+ return;
1906
+ char buf[160];
1907
+ snprintf(buf, sizeof(buf),
1908
+ "{\"phase\":\"%s\",\"x\":%.1f,\"y\":%.1f,"
1909
+ "\"dx\":%.1f,\"dy\":%.1f}",
1910
+ phase, px, py, ox, oy);
1911
+ emitEvent(i->second, "pan", "user", buf, eb->second);
1912
+ };
1913
+ ge.ManipulationStarted(
1914
+ [this, id](auto const &,
1915
+ muxi::ManipulationStartedRoutedEventArgs const &) {
1916
+ auto i = nodes_.find(id);
1917
+ if (i != nodes_.end())
1918
+ i->second.panMoved = false;
1919
+ });
1920
+ ge.ManipulationDelta(
1921
+ [this, id, emitPan](
1922
+ auto const &,
1923
+ muxi::ManipulationDeltaRoutedEventArgs const &e) {
1924
+ auto i = nodes_.find(id);
1925
+ if (i == nodes_.end())
1926
+ return;
1927
+ WinNode &nn = i->second;
1928
+ auto cum = e.Cumulative().Translation;
1929
+ float ox = (float)cum.X, oy = (float)cum.Y;
1930
+ bool first = false;
1931
+ if (!nn.panMoved) {
1932
+ if (std::hypot(ox, oy) <= 8.f)
1933
+ return;
1934
+ nn.panMoved = true;
1935
+ first = true;
1936
+ if (nn.lpTimer)
1937
+ nn.lpTimer.Stop();
1938
+ }
1939
+ auto pos = e.Position();
1940
+ emitPan(first ? "start" : "move", (float)pos.X, (float)pos.Y,
1941
+ ox, oy);
1942
+ });
1943
+ ge.ManipulationCompleted(
1944
+ [this, id, emitPan](
1945
+ auto const &,
1946
+ muxi::ManipulationCompletedRoutedEventArgs const &e) {
1947
+ auto i = nodes_.find(id);
1948
+ if (i == nodes_.end() || !i->second.panMoved)
1949
+ return;
1950
+ auto cum = e.Cumulative().Translation;
1951
+ auto pos = e.Position();
1952
+ emitPan("end", (float)pos.X, (float)pos.Y, (float)cum.X,
1953
+ (float)cum.Y);
1954
+ });
1955
+ // Ratón: la manipulación de WinUI 3 desktop solo se alimenta de
1956
+ // touch/pen — el drag de ratón se mide por PointerMoved con botón
1957
+ // (mismo camino que GtkGestureDrag). panMoved queda tras el end:
1958
+ // consumeGesture lo usa para negar el press del release.
1959
+ ge.AddHandler(
1960
+ mux::UIElement::PointerPressedEvent(),
1961
+ winrt::box_value(muxi::PointerEventHandler(
1962
+ [this, id, ge](auto const &,
1963
+ muxi::PointerRoutedEventArgs const &e) {
1964
+ if (e.Pointer().PointerDeviceType() !=
1965
+ mui::PointerDeviceType::Mouse)
1966
+ return;
1967
+ auto i = nodes_.find(id);
1968
+ if (i == nodes_.end())
1969
+ return;
1970
+ WinNode &nn = i->second;
1971
+ nn.panMouseDown = true;
1972
+ nn.panMoved = false;
1973
+ auto pt = e.GetCurrentPoint(ge).Position();
1974
+ nn.panSX = (float)pt.X;
1975
+ nn.panSY = (float)pt.Y;
1976
+ ge.CapturePointer(e.Pointer());
1977
+ })),
1978
+ true);
1979
+ ge.AddHandler(
1980
+ mux::UIElement::PointerMovedEvent(),
1981
+ winrt::box_value(muxi::PointerEventHandler(
1982
+ [this, id, ge, emitPan](
1983
+ auto const &, muxi::PointerRoutedEventArgs const &e) {
1984
+ auto i = nodes_.find(id);
1985
+ if (i == nodes_.end())
1986
+ return;
1987
+ WinNode &nn = i->second;
1988
+ if (!nn.panMouseDown)
1989
+ return;
1990
+ auto cp = e.GetCurrentPoint(ge);
1991
+ if (!cp.Properties().IsLeftButtonPressed()) {
1992
+ nn.panMouseDown = false;
1993
+ return;
1994
+ }
1995
+ auto pt = cp.Position();
1996
+ float ox = (float)pt.X - nn.panSX;
1997
+ float oy = (float)pt.Y - nn.panSY;
1998
+ if (!nn.panMoved) {
1999
+ if (std::hypot(ox, oy) <= 8.f)
2000
+ return;
2001
+ nn.panMoved = true;
2002
+ if (nn.lpTimer)
2003
+ nn.lpTimer.Stop();
2004
+ emitPan("start", (float)pt.X, (float)pt.Y, ox, oy);
2005
+ } else {
2006
+ emitPan("move", (float)pt.X, (float)pt.Y, ox, oy);
2007
+ }
2008
+ })),
2009
+ true);
2010
+ auto endMousePan = [this, id, ge, emitPan](
2011
+ muxi::PointerRoutedEventArgs const &e) {
2012
+ auto i = nodes_.find(id);
2013
+ if (i == nodes_.end() || !i->second.panMouseDown)
2014
+ return;
2015
+ WinNode &nn = i->second;
2016
+ nn.panMouseDown = false;
2017
+ if (!nn.panMoved)
2018
+ return;
2019
+ auto pt = e.GetCurrentPoint(ge).Position();
2020
+ emitPan("end", (float)pt.X, (float)pt.Y,
2021
+ (float)pt.X - nn.panSX, (float)pt.Y - nn.panSY);
2022
+ };
2023
+ ge.AddHandler(mux::UIElement::PointerReleasedEvent(),
2024
+ winrt::box_value(muxi::PointerEventHandler(
2025
+ [endMousePan](
2026
+ auto const &,
2027
+ muxi::PointerRoutedEventArgs const &e) {
2028
+ endMousePan(e);
2029
+ })),
2030
+ true);
2031
+ ge.AddHandler(mux::UIElement::PointerCaptureLostEvent(),
2032
+ winrt::box_value(muxi::PointerEventHandler(
2033
+ [endMousePan](
2034
+ auto const &,
2035
+ muxi::PointerRoutedEventArgs const &e) {
2036
+ endMousePan(e);
2037
+ })),
2038
+ true);
2039
+ return;
2040
+ }
2041
+ if (event == "pinch" && n.el) {
2042
+ // events.ts {scale,focalX,focalY,phase} — ManipulationDelta con
2043
+ // modo Scale. El delta dispara con CUALQUIER manipulación (un pan
2044
+ // de un dedo también es manipulación): el gesto solo es pinch si
2045
+ // hubo 2+ contactos simultáneos — ptrCount los lleva la cuenta.
2046
+ auto ge = gestureEl();
2047
+ ge.ManipulationMode((ge.ManipulationMode() &
2048
+ ~muxi::ManipulationModes::System) |
2049
+ muxi::ManipulationModes::Scale);
2050
+ // AddHandler(handledEventsToo): los controles marcan pressed
2051
+ // handled; la cuenta de contactos tiene que verlos igual.
2052
+ n.el.AddHandler(
2053
+ mux::UIElement::PointerPressedEvent(),
2054
+ winrt::box_value(muxi::PointerEventHandler(
2055
+ [this, id](auto const &,
2056
+ muxi::PointerRoutedEventArgs const &) {
2057
+ auto i = nodes_.find(id);
2058
+ if (i != nodes_.end())
2059
+ i->second.ptrCount++;
2060
+ })),
2061
+ true);
2062
+ auto dropPtr = [this, id]() {
2063
+ auto i = nodes_.find(id);
2064
+ if (i != nodes_.end() && i->second.ptrCount > 0)
2065
+ i->second.ptrCount--;
2066
+ };
2067
+ n.el.AddHandler(
2068
+ mux::UIElement::PointerReleasedEvent(),
2069
+ winrt::box_value(muxi::PointerEventHandler(
2070
+ [this, id, dropPtr](
2071
+ auto const &, muxi::PointerRoutedEventArgs const &) {
2072
+ dropPtr();
2073
+ })),
2074
+ true);
2075
+ n.el.PointerCaptureLost(
2076
+ [this, id, dropPtr](auto const &,
2077
+ muxi::PointerRoutedEventArgs const &) {
2078
+ dropPtr();
2079
+ });
2080
+ ge.ManipulationStarted(
2081
+ [this, id](auto const &, auto const &) {
2082
+ auto i = nodes_.find(id);
2083
+ if (i != nodes_.end())
2084
+ i->second.pinchActive = false;
2085
+ });
2086
+ ge.ManipulationDelta(
2087
+ [this, id](auto const &,
2088
+ muxi::ManipulationDeltaRoutedEventArgs const &e) {
2089
+ auto i = nodes_.find(id);
2090
+ if (i == nodes_.end() || i->second.ptrCount < 2)
2091
+ return;
2092
+ auto eb = i->second.events.find("pinch");
2093
+ if (eb == i->second.events.end())
2094
+ return;
2095
+ auto pos = e.Position();
2096
+ char buf[160];
2097
+ if (!i->second.pinchActive) {
2098
+ i->second.pinchActive = true;
2099
+ snprintf(buf, sizeof(buf),
2100
+ "{\"phase\":\"start\",\"scale\":1,\"focalX\":%.1f,"
2101
+ "\"focalY\":%.1f}",
2102
+ (float)pos.X, (float)pos.Y);
2103
+ emitEvent(i->second, "pinch", "user", buf, eb->second);
2104
+ }
2105
+ float sc = (float)e.Delta().Scale;
2106
+ if (sc == 1.f || sc != sc)
2107
+ return;
2108
+ auto cum = e.Cumulative().Scale;
2109
+ snprintf(buf, sizeof(buf),
2110
+ "{\"phase\":\"move\",\"scale\":%.3f,"
2111
+ "\"focalX\":%.1f,\"focalY\":%.1f}",
2112
+ (float)cum, (float)pos.X, (float)pos.Y);
2113
+ emitEvent(i->second, "pinch", "user", buf, eb->second);
2114
+ });
2115
+ ge.ManipulationCompleted(
2116
+ [this, id](auto const &, auto const &) {
2117
+ auto i = nodes_.find(id);
2118
+ if (i == nodes_.end() || !i->second.pinchActive)
2119
+ return;
2120
+ i->second.pinchActive = false;
2121
+ auto eb = i->second.events.find("pinch");
2122
+ if (eb == i->second.events.end())
2123
+ return;
2124
+ emitEvent(i->second, "pinch", "user",
2125
+ "{\"phase\":\"end\",\"scale\":1,\"focalX\":0,"
2126
+ "\"focalY\":0}",
2127
+ eb->second);
2128
+ });
2129
+ return;
2130
+ }
2131
+ if (event == "select" && n.input) {
2132
+ n.input.SelectionChanged(
2133
+ [this, id](auto const &, auto const &) {
2134
+ auto i = nodes_.find(id);
2135
+ if (i == nodes_.end() || i->second.suppressSignal)
2136
+ return;
2137
+ WinNode &nn = i->second;
2138
+ auto eb = nn.events.find("select");
2139
+ if (eb == nn.events.end())
2140
+ return;
2141
+ char buf[64];
2142
+ snprintf(buf, sizeof(buf), "{\"start\":%d,\"end\":%d}",
2143
+ nn.input.SelectionStart(),
2144
+ nn.input.SelectionStart() + nn.input.SelectionLength());
2145
+ emitEvent(nn, "select", "user", buf, eb->second);
2146
+ });
2147
+ return;
2148
+ }
2149
+ if (event == "composition" && n.input) {
2150
+ auto fireComp = [this, id](const char *phase) {
2151
+ auto i = nodes_.find(id);
2152
+ if (i == nodes_.end())
2153
+ return;
2154
+ WinNode &nn = i->second;
2155
+ auto eb = nn.events.find("composition");
2156
+ if (eb == nn.events.end())
2157
+ return;
2158
+ emitEvent(nn, "composition", "user",
2159
+ std::string("{\"phase\":\"") + phase + "\",\"text\":" +
2160
+ modules::jsonQuote(winrt::to_string(nn.input.Text())) +
2161
+ "}",
2162
+ eb->second);
2163
+ };
2164
+ n.input.TextCompositionStarted(
2165
+ [fireComp](auto const &, auto const &) { fireComp("start"); });
2166
+ n.input.TextCompositionChanged(
2167
+ [fireComp](auto const &, auto const &) { fireComp("update"); });
2168
+ n.input.TextCompositionEnded(
2169
+ [fireComp](auto const &, auto const &) { fireComp("end"); });
2170
+ return;
2171
+ }
2172
+ if ((event == "load" || event == "error") && n.image) {
2173
+ // Replay ADR-0204: si el bitmap ya resolvió antes del attach, se
2174
+ // reemite el resultado (como imgLoaded/imgFailed en GTK).
2175
+ if (event == "load" && n.imgLoaded) {
2176
+ char buf[96];
2177
+ snprintf(buf, sizeof(buf), "{\"width\":%d,\"height\":%d%s}",
2178
+ n.imgW, n.imgH,
2179
+ n.imgLoadFallback ? ",\"fallback\":true" : "");
2180
+ emitEvent(n, "load", "program", buf, n.events["load"]);
2181
+ } else if (event == "error" && n.imgFailed) {
2182
+ std::string d = "{\"message\":\"image load failed\"";
2183
+ if (n.imgFailFallback)
2184
+ d += ",\"fallback\":true";
2185
+ d += "}";
2186
+ emitEvent(n, "error", "program", d, n.events["error"]);
2187
+ }
2188
+ return;
2189
+ }
2190
+ if (event == "refresh" && n.scroll) {
2191
+ ensureRefresh(n);
2192
+ return;
2193
+ }
2194
+ warnOnce(unknownProps_, "event-pendiente", event + "@" + n.type);
2195
+ }
2196
+
2197
+ void WinApplicator::detachEvent(int id, const std::string &event) {
2198
+ auto it = nodes_.find(id);
2199
+ if (it != nodes_.end())
2200
+ it->second.events.erase(event);
2201
+ if (event == "shortcut")
2202
+ dropHotkeys(id);
2203
+ }
2204
+
2205
+ void WinApplicator::dropHotkeys(int id) {
2206
+ hotkeys_.erase(std::remove_if(hotkeys_.begin(), hotkeys_.end(),
2207
+ [id](const Hotkey &h) { return h.id == id; }),
2208
+ hotkeys_.end());
2209
+ }
2210
+
2211
+ void WinApplicator::ensureHotkeyHook() {
2212
+ if (hotkeyHooked_ || !root_)
2213
+ return;
2214
+ hotkeyHooked_ = true;
2215
+ // Capture en el root: PreviewKeyDown se ve antes que el control
2216
+ // enfocado — mismo rol que el controller GTK_PHASE_CAPTURE.
2217
+ root_.PreviewKeyDown(
2218
+ [this](auto const &, muxi::KeyRoutedEventArgs const &e) {
2219
+ if (e.KeyStatus().WasKeyDown)
2220
+ return; // autorepeat
2221
+ std::string combo = comboOf(e.Key());
2222
+ if (hotkeys_.empty() || combo.empty())
2223
+ return;
2224
+ // Si el foco está en un campo de texto solo disparan los
2225
+ // combos editing-safe (ctrl/alt/meta, Escape, F1-F24).
2226
+ auto focusedObj =
2227
+ root_.XamlRoot()
2228
+ ? muxi::FocusManager::GetFocusedElement(root_.XamlRoot())
2229
+ : nullptr;
2230
+ bool editing =
2231
+ focusedObj &&
2232
+ (focusedObj.try_as<muxc::TextBox>() ||
2233
+ focusedObj.try_as<muxc::RichEditBox>() ||
2234
+ focusedObj.try_as<muxc::PasswordBox>());
2235
+ if (editing && !firesWhileEditing(combo))
2236
+ return;
2237
+ for (auto h = hotkeys_.rbegin(); h != hotkeys_.rend(); ++h) {
2238
+ if (h->combo != combo)
2239
+ continue;
2240
+ auto it = nodes_.find(h->id);
2241
+ if (it == nodes_.end())
2242
+ continue;
2243
+ auto eb = it->second.events.find("shortcut");
2244
+ if (eb == it->second.events.end())
2245
+ continue;
2246
+ emitEvent(it->second, "shortcut", "user", "{}", eb->second);
2247
+ e.Handled(true);
2248
+ return;
2249
+ }
2250
+ });
2251
+ }
2252
+
2253
+ void WinApplicator::ensureStickyScroll(WinNode &n) {
2254
+ if (n.stickyScroll || !n.el)
2255
+ return;
2256
+ // El ancestro scroll se busca por el árbol visual — los nodos no
2257
+ // guardan parentId.
2258
+ auto fe = n.el.try_as<mux::FrameworkElement>();
2259
+ mux::DependencyObject p = fe ? fe.Parent() : nullptr;
2260
+ while (p) {
2261
+ if (auto sv = p.try_as<muxc::ScrollViewer>()) {
2262
+ n.stickyScroll = sv;
2263
+ break;
2264
+ }
2265
+ p = mux::Media::VisualTreeHelper::GetParent(p);
2266
+ }
2267
+ if (!n.stickyScroll) {
2268
+ warnOnce(unknownProps_, "prop-pendiente", "sticky-fuera-de-scroll");
2269
+ n.sticky = false;
2270
+ return;
2271
+ }
2272
+ n.tokSticky = n.stickyScroll.ViewChanged(
2273
+ [this, id = n.id](auto const &, auto const &) { applySticky(id); });
2274
+ applySticky(n.id);
2275
+ }
2276
+
2277
+ void WinApplicator::applySticky(int id) {
2278
+ auto it = nodes_.find(id);
2279
+ if (it == nodes_.end())
2280
+ return;
2281
+ WinNode &n = it->second;
2282
+ if (!n.sticky || !n.stickyScroll || !n.el)
2283
+ return;
2284
+ if (!n.stickyBaseValid) {
2285
+ // Top de contenido = posición dentro del Content del scroll sin
2286
+ // la translation aplicada.
2287
+ auto content = n.stickyScroll.Content()
2288
+ .try_as<mux::UIElement>();
2289
+ if (!content)
2290
+ return;
2291
+ auto t = n.el.TransformToVisual(content);
2292
+ auto pt = t.TransformPoint(
2293
+ winrt::Windows::Foundation::Point(0.f, 0.f));
2294
+ n.stickyBaseY = (float)pt.Y - n.stickyShift;
2295
+ n.stickyBaseValid = true;
2296
+ }
2297
+ float off = (float)n.stickyScroll.VerticalOffset();
2298
+ float shift = off - (n.stickyBaseY - n.stickyTop);
2299
+ // Clamp al containing block (padre visual directo, igual que
2300
+ // android): el nodo no puede salir por abajo de su padre.
2301
+ float maxShift = 3.4e38f;
2302
+ auto pfe = n.el.try_as<mux::FrameworkElement>();
2303
+ if (auto canvas = pfe ? pfe.Parent().try_as<muxc::Canvas>()
2304
+ : nullptr) {
2305
+ double ph = canvas.Height();
2306
+ if (ph == ph && ph > 0)
2307
+ maxShift = (float)ph - n.stickyBaseY - n.layH;
2308
+ }
2309
+ if (shift > maxShift)
2310
+ shift = maxShift;
2311
+ if (shift < 0 || shift != shift)
2312
+ shift = 0;
2313
+ if (shift == n.stickyShift)
2314
+ return;
2315
+ n.stickyShift = shift;
2316
+ n.el.Translation(winrt::Windows::Foundation::Numerics::float3(
2317
+ 0.f, shift, 0.f));
2318
+ }
2319
+
2320
+ void WinApplicator::emitKeyFor(int id,
2321
+ winrt::Windows::System::VirtualKey k) {
2322
+ auto i = nodes_.find(id);
2323
+ if (i == nodes_.end())
2324
+ return;
2325
+ auto eb = i->second.events.find("key");
2326
+ if (eb == i->second.events.end())
2327
+ return;
2328
+ std::string name = domKeyName(k);
2329
+ if (name.empty())
2330
+ return;
2331
+ namespace vk = winrt::Windows::System;
2332
+ std::string d = "{\"key\":\"" + name + "\"";
2333
+ if (modDown(vk::VirtualKey::Control, vk::VirtualKey::LeftControl,
2334
+ vk::VirtualKey::RightControl))
2335
+ d += ",\"ctrl\":true";
2336
+ if (modDown(vk::VirtualKey::Menu, vk::VirtualKey::LeftMenu,
2337
+ vk::VirtualKey::RightMenu))
2338
+ d += ",\"alt\":true";
2339
+ if (modDown(vk::VirtualKey::Shift, vk::VirtualKey::LeftShift,
2340
+ vk::VirtualKey::RightShift))
2341
+ d += ",\"shift\":true";
2342
+ if (modDown(vk::VirtualKey::LeftWindows, vk::VirtualKey::RightWindows,
2343
+ vk::VirtualKey::LeftWindows))
2344
+ d += ",\"meta\":true";
2345
+ emitEvent(i->second, "key", "user", d + "}", eb->second);
2346
+ }
2347
+
2348
+ void WinApplicator::emitEvent(WinNode &n, const char *event,
2349
+ const char *origin,
2350
+ const std::string &dataJson,
2351
+ const EventBind &bind) {
2352
+ (void)n;
2353
+ dlog("[elur] emit %s handler=%s\n", event, bind.handler.c_str());
2354
+ emitHostEvent(cb_, bind, event, origin, dataJson);
2355
+ }
2356
+
2357
+ // AT invoca una acción del peer (select/expand/collapse) → evento
2358
+ // `action` al JS con fallback `press` — mismo contrato que
2359
+ // onA11yAction en GTK (ADR-0190).
2360
+ void WinApplicator::onA11yInvoke(int id, const char *act) {
2361
+ auto it = nodes_.find(id);
2362
+ if (it == nodes_.end())
2363
+ return;
2364
+ WinNode &n = it->second;
2365
+ std::string data = std::string("{\"action\":\"") + act + "\"}";
2366
+ auto eb = n.events.find("action");
2367
+ if (eb != n.events.end()) {
2368
+ emitEvent(n, "action", "user", data, eb->second);
2369
+ return;
2370
+ }
2371
+ if (auto pb = n.events.find("press"); pb != n.events.end())
2372
+ emitEvent(n, "press", "user", "{}", pb->second);
2373
+ }
2374
+
2375
+ // ── Layout ─────────────────────────────────────────────────────────
2376
+
2377
+ void WinApplicator::relayout() {
2378
+ int n = yoga::layoutIfDirty([this](int id, float x, float y, float w,
2379
+ float h) {
2380
+ auto it = nodes_.find(id);
2381
+ if (it == nodes_.end() || !it->second.el)
2382
+ return;
2383
+ WinNode &nd = it->second;
2384
+ nd.layX = x; nd.layY = y; nd.layW = w; nd.layH = h;
2385
+ muxc::Canvas::SetLeft(nd.el, x);
2386
+ muxc::Canvas::SetTop(nd.el, y);
2387
+ if (auto fe = nd.el.try_as<mux::FrameworkElement>()) {
2388
+ if (w >= 0)
2389
+ fe.Width(w);
2390
+ if (h >= 0)
2391
+ fe.Height(h);
2392
+ }
2393
+ // Contenedor vacío: el peer UIA deriva su BoundingRectangle del
2394
+ // sub-árbol visual — un Canvas sin tamaño explícito colapsa a 0
2395
+ // y el nodo queda IsOffscreen (inaccesible para el harness). El
2396
+ // scroll tiene su propia regla abajo (extent = bbox de hijos).
2397
+ if (nd.inner && !nd.scroll && w > 0 && h > 0) {
2398
+ nd.inner.Width(w);
2399
+ nd.inner.Height(h);
2400
+ }
2401
+ if (nd.border && w > 0 && h > 0) {
2402
+ nd.border.Width(w);
2403
+ nd.border.Height(h);
2404
+ }
2405
+ // El inner canvas del scroll necesita su propio tamaño de
2406
+ // contenido: ScrollViewer desplaza, el canvas recibe los rects
2407
+ // de los hijos igual que el GtkFixed interno.
2408
+ });
2409
+ // Canvas no reporta DesiredSize: sin extent el ScrollViewer no
2410
+ // scrollea. Se fija al bbox de los hijos (equivalente al natural
2411
+ // size que GtkFixed da al GtkScrolledWindow en Linux).
2412
+ for (auto &kv : nodes_) {
2413
+ WinNode &nd = kv.second;
2414
+ if (!nd.scroll || !nd.inner)
2415
+ continue;
2416
+ float cw = 0, ch = 0;
2417
+ for (auto const &child : nd.inner.Children()) {
2418
+ auto fe = child.try_as<mux::FrameworkElement>();
2419
+ if (!fe)
2420
+ continue;
2421
+ float x = (float)muxc::Canvas::GetLeft(child) + (float)fe.Width();
2422
+ float y = (float)muxc::Canvas::GetTop(child) + (float)fe.Height();
2423
+ if (x > cw)
2424
+ cw = x;
2425
+ if (y > ch)
2426
+ ch = y;
2427
+ }
2428
+ if (cw > 0)
2429
+ nd.inner.Width(cw);
2430
+ if (ch > 0)
2431
+ nd.inner.Height(ch);
2432
+ }
2433
+ if (trace && n > 0)
2434
+ yoga::dumpRects(stderr);
2435
+ }
2436
+
2437
+ // ── Ops ────────────────────────────────────────────────────────────
2438
+
2439
+ void WinApplicator::applyFrame(JSContext *ctx, JSValueConst v) {
2440
+ applyCycle_++;
2441
+ JSValue ops = jsGet(ctx, v, "ops");
2442
+ if (!JS_IsArray(ops)) {
2443
+ JS_FreeValue(ctx, ops);
2444
+ return;
2445
+ }
2446
+ int64_t len = 0;
2447
+ JS_GetLength(ctx, ops, &len);
2448
+
2449
+ for (int64_t i = 0; i < len; i++) {
2450
+ JSValue op = JS_GetPropertyInt64(ctx, ops, i);
2451
+ std::string name = jsGetStr(ctx, op, "op");
2452
+ int id = jsInt(ctx, op, "id");
2453
+ if (GetEnvironmentVariableA("ELUR_DEBUG", nullptr, 0) > 1) {
2454
+ JSValue js = JS_JSONStringify(ctx, op, JS_UNDEFINED,
2455
+ JS_UNDEFINED);
2456
+ const char *s = JS_ToCString(ctx, js);
2457
+ fprintf(stderr, "[op] %s id=%d %s\n", name.c_str(), id,
2458
+ s ? s : "");
2459
+ dlog("[op] %s id=%d %s\n", name.c_str(), id, s ? s : "");
2460
+ if (s)
2461
+ JS_FreeCString(ctx, s);
2462
+ JS_FreeValue(ctx, js);
2463
+ }
2464
+
2465
+ try {
2466
+ if (name == "create-node") {
2467
+ createNode(id, jsGetStr(ctx, op, "type"));
2468
+ } else if (name == "update-text") {
2469
+ auto it = nodes_.find(id);
2470
+ if (it != nodes_.end())
2471
+ updateText(it->second, jsGetStr(ctx, op, "value"));
2472
+ } else if (name == "update-style") {
2473
+ auto it = nodes_.find(id);
2474
+ if (it != nodes_.end()) {
2475
+ JSValue st = jsGet(ctx, op, "style");
2476
+ updateStyle(it->second, ctx, st);
2477
+ JS_FreeValue(ctx, st);
2478
+ }
2479
+ } else if (name == "update-props" ||
2480
+ name == "update-platform-view-props") {
2481
+ auto it = nodes_.find(id);
2482
+ if (it != nodes_.end()) {
2483
+ JSValue pr = jsGet(ctx, op, "changedProps");
2484
+ JSPropertyEnum *tab = nullptr;
2485
+ uint32_t plen = 0;
2486
+ if (JS_GetOwnPropertyNames(ctx, &tab, &plen, pr,
2487
+ JS_GPN_STRING_MASK |
2488
+ JS_GPN_ENUM_ONLY) == 0) {
2489
+ for (uint32_t k = 0; k < plen; k++) {
2490
+ JSAtom atom = tab[k].atom;
2491
+ JSValue keyv = JS_AtomToString(ctx, atom);
2492
+ std::string key = jsStr(ctx, keyv);
2493
+ JS_FreeValue(ctx, keyv);
2494
+ JSValue val = JS_GetProperty(ctx, pr, atom);
2495
+ updateProp(it->second, key, ctx, val);
2496
+ JS_FreeValue(ctx, val);
2497
+ JS_FreeAtom(ctx, atom);
2498
+ }
2499
+ js_free(ctx, tab);
2500
+ }
2501
+ JS_FreeValue(ctx, pr);
2502
+ }
2503
+ } else if (name == "update-semantics") {
2504
+ // ADR-0108 — el vocabulario a11y llega en una op dedicada;
2505
+ // cada clave se aplica como prop normal (AutomationProperties).
2506
+ // Las claves sin equivalente UIA caen en warnOnce.
2507
+ auto it = nodes_.find(id);
2508
+ if (it != nodes_.end()) {
2509
+ JSValue pr = jsGet(ctx, op, "semantics");
2510
+ JSPropertyEnum *tab = nullptr;
2511
+ uint32_t plen = 0;
2512
+ if (JS_GetOwnPropertyNames(ctx, &tab, &plen, pr,
2513
+ JS_GPN_STRING_MASK |
2514
+ JS_GPN_ENUM_ONLY) == 0) {
2515
+ for (uint32_t k = 0; k < plen; k++) {
2516
+ JSAtom atom = tab[k].atom;
2517
+ JSValue keyv = JS_AtomToString(ctx, atom);
2518
+ std::string key = jsStr(ctx, keyv);
2519
+ JS_FreeValue(ctx, keyv);
2520
+ JSValue val = JS_GetProperty(ctx, pr, atom);
2521
+ updateProp(it->second, key, ctx, val);
2522
+ JS_FreeValue(ctx, val);
2523
+ JS_FreeAtom(ctx, atom);
2524
+ }
2525
+ js_free(ctx, tab);
2526
+ }
2527
+ JS_FreeValue(ctx, pr);
2528
+ }
2529
+ } else if (name == "insert-child") {
2530
+ int parentId = jsInt(ctx, op, "parentId");
2531
+ int childId = jsInt(ctx, op, "childId");
2532
+ int index = jsInt(ctx, op, "index");
2533
+ auto pi = nodes_.find(parentId);
2534
+ auto ci = nodes_.find(childId);
2535
+ if (ci != nodes_.end() && ci->second.el) {
2536
+ muxc::Canvas target = surfaceOf(parentId);
2537
+ detachVisual(ci->second.el);
2538
+ // Button absorbe hijos text como label (paridad GTK).
2539
+ if (pi != nodes_.end() && pi->second.button &&
2540
+ ci->second.textBlock) {
2541
+ pi->second.button.Content(ci->second.el);
2542
+ yoga::absorbIntoButton(childId, parentId);
2543
+ } else if (target) {
2544
+ auto count = target.Children().Size();
2545
+ uint32_t idx =
2546
+ index < 0 ? count
2547
+ : std::min<uint32_t>((uint32_t)index, count);
2548
+ target.Children().InsertAt(idx, ci->second.el);
2549
+ } else {
2550
+ warnOnce(unknownOps_, "insert", name);
2551
+ }
2552
+ yoga::nodeInsert(parentId, childId, index);
2553
+ }
2554
+ } else if (name == "remove-child") {
2555
+ int parentId = jsInt(ctx, op, "parentId");
2556
+ int childId = jsInt(ctx, op, "childId");
2557
+ auto ci = nodes_.find(childId);
2558
+ if (ci != nodes_.end() && ci->second.el) {
2559
+ detachVisual(ci->second.el);
2560
+ // Hijo detachado de un shell: la nav-* del mismo batch lo
2561
+ // re-inserta como overlay parallax (ADR-0013). WinRT retiene
2562
+ // la referencia — su delete-node puede llegar antes de la op.
2563
+ auto pi = nodes_.find(parentId);
2564
+ if (pi != nodes_.end() && pi->second.type == "shell") {
2565
+ clearDetached();
2566
+ detachedEl_ = ci->second.el;
2567
+ detX_ = ci->second.layX;
2568
+ detY_ = ci->second.layY;
2569
+ detW_ = ci->second.layW;
2570
+ detH_ = ci->second.layH;
2571
+ }
2572
+ yoga::nodeRemove(parentId, childId);
2573
+ }
2574
+ } else if (name == "move-child") {
2575
+ yoga::nodeMove(jsInt(ctx, op, "parentId"),
2576
+ jsInt(ctx, op, "childId"), jsInt(ctx, op, "index"));
2577
+ // Reorden visual en el Canvas: quitar y reinsertar en index.
2578
+ int parentId = jsInt(ctx, op, "parentId");
2579
+ int childId = jsInt(ctx, op, "childId");
2580
+ auto ci = nodes_.find(childId);
2581
+ if (ci != nodes_.end() && ci->second.el) {
2582
+ muxc::Canvas target = surfaceOf(parentId);
2583
+ if (target) {
2584
+ auto children = target.Children();
2585
+ detachVisual(ci->second.el);
2586
+ int index = jsInt(ctx, op, "index");
2587
+ uint32_t idx = index < 0
2588
+ ? children.Size()
2589
+ : std::min<uint32_t>((uint32_t)index,
2590
+ children.Size());
2591
+ children.InsertAt(idx, ci->second.el);
2592
+ }
2593
+ }
2594
+ } else if (name == "delete-node") {
2595
+ deleteNode(id);
2596
+ } else if (name == "attach-event") {
2597
+ attachEvent(id, jsGetStr(ctx, op, "event"),
2598
+ jsGetStr(ctx, op, "handler"),
2599
+ jsGetStr(ctx, op, "class") == "continuous",
2600
+ jsGetStr(ctx, op, "payload"));
2601
+ } else if (name == "detach-event") {
2602
+ detachEvent(id, jsGetStr(ctx, op, "event"));
2603
+ } else if (name == "reset-node") {
2604
+ auto it = nodes_.find(id);
2605
+ if (it != nodes_.end() && it->second.scroll) {
2606
+ it->second.suppressSignal = true;
2607
+ it->second.scroll.ChangeView(nullptr, 0.0, nullptr);
2608
+ it->second.suppressSignal = false;
2609
+ }
2610
+ } else if (name == "nav-push" || name == "nav-pop" ||
2611
+ name == "nav-replace") {
2612
+ navTransition(name, ctx, op);
2613
+ } else {
2614
+ // list-*/create-platform-view/layout/batch-update —
2615
+ // caps ausentes → warn-once honesto, nunca silencio.
2616
+ warnOnce(unknownOps_, "op", name);
2617
+ }
2618
+ } catch (winrt::hresult_error const &e) {
2619
+ JSValue dump = JS_JSONStringify(ctx, op, JS_UNDEFINED, JS_UNDEFINED);
2620
+ const char *ds = JS_ToCString(ctx, dump);
2621
+ dlog("[elur] op %s id=%d hr=0x%08x %ls op=%s\n", name.c_str(), id,
2622
+ (unsigned)e.code().value, e.message().c_str(),
2623
+ ds ? ds : "?");
2624
+ if (ds)
2625
+ JS_FreeCString(ctx, ds);
2626
+ JS_FreeValue(ctx, dump);
2627
+ throw;
2628
+ } catch (std::exception const &e) {
2629
+ dlog("[elur] op %s id=%d std: %s\n", name.c_str(), id, e.what());
2630
+ throw;
2631
+ }
2632
+ JS_FreeValue(ctx, op);
2633
+ }
2634
+ JS_FreeValue(ctx, ops);
2635
+
2636
+ try {
2637
+ relayout();
2638
+ } catch (winrt::hresult_error const &e) {
2639
+ dlog("[elur] relayout hr=0x%08x %ls\n", (unsigned)e.code().value,
2640
+ e.message().c_str());
2641
+ throw;
2642
+ }
2643
+ int frame = jsInt(ctx, v, "frame");
2644
+ char fbuf[32];
2645
+ snprintf(fbuf, sizeof(fbuf), "%d", frame);
2646
+ cb_.callHandlerStr("__elur_commit_ack", fbuf);
2647
+ }
2648
+
2649
+ // ── Transiciones nav-* (paridad linux/web ADR-0013/0165) ──────────
2650
+ // Modelo: hijo detachado de un `shell` se retiene como overlay; la
2651
+ // nav-* del mismo batch lo re-inserta (push: debajo de la entrante;
2652
+ // pop: encima) y un Storyboard con SplineDoubleKeyFrame anima
2653
+ // Canvas.Left/Top + Opacity + escala — KeySpline es la MISMA
2654
+ // cubic-bezier que resuelve bezierY en linux (control points directos,
2655
+ // sin re-solver). El descriptor `def` declara capas incoming/outgoing
2656
+ // con keyframes {from,to} por prop (x e y en % del shell si vienen
2657
+ // como cadena "%"; ausentes → no anima esa prop, capa presente con x
2658
+ // ausente → quieta en su sitio).
2659
+
2660
+ static void jsToJson(JSContext *ctx, JSValueConst v, modules::Json &out) {
2661
+ out = modules::Json();
2662
+ if (JS_IsNull(v) || JS_IsUndefined(v))
2663
+ return;
2664
+ JSValue js = JS_JSONStringify(ctx, v, JS_UNDEFINED, JS_UNDEFINED);
2665
+ if (JS_IsException(js))
2666
+ return;
2667
+ const char *s = JS_ToCString(ctx, js);
2668
+ if (s) {
2669
+ modules::Json parsed;
2670
+ if (modules::jsonParse(s, parsed))
2671
+ out = std::move(parsed);
2672
+ JS_FreeCString(ctx, s);
2673
+ }
2674
+ JS_FreeValue(ctx, js);
2675
+ }
2676
+
2677
+ static double navValW(const modules::Json *v, double span) {
2678
+ if (!v)
2679
+ return NAN;
2680
+ if (v->kind == modules::Json::Num)
2681
+ return v->num;
2682
+ if (v->kind == modules::Json::Str) {
2683
+ const std::string &s = v->str;
2684
+ if (!s.empty() && s.back() == '%')
2685
+ return strtod(s.substr(0, s.size() - 1).c_str(), nullptr) / 100.0 *
2686
+ span;
2687
+ return strtod(s.c_str(), nullptr);
2688
+ }
2689
+ return NAN;
2690
+ }
2691
+
2692
+ struct NavSideW {
2693
+ double x0 = NAN, x1 = NAN, y0 = NAN, y1 = NAN;
2694
+ double op0 = NAN, op1 = NAN, sc0 = NAN, sc1 = NAN;
2695
+ };
2696
+
2697
+ static NavSideW navSideParseW(const modules::Json *side, double W,
2698
+ double H) {
2699
+ NavSideW s;
2700
+ if (!side || side->kind != modules::Json::Obj)
2701
+ return s;
2702
+ const modules::Json *f = side->get("from"), *t = side->get("to");
2703
+ if (f && f->kind == modules::Json::Obj) {
2704
+ s.x0 = navValW(f->get("x"), W);
2705
+ s.y0 = navValW(f->get("y"), H);
2706
+ s.sc0 = navValW(f->get("scale"), 1);
2707
+ s.op0 = navValW(f->get("opacity"), 1);
2708
+ }
2709
+ if (t && t->kind == modules::Json::Obj) {
2710
+ s.x1 = navValW(t->get("x"), W);
2711
+ s.y1 = navValW(t->get("y"), H);
2712
+ s.sc1 = navValW(t->get("scale"), 1);
2713
+ s.op1 = navValW(t->get("opacity"), 1);
2714
+ }
2715
+ return s;
2716
+ }
2717
+
2718
+ // easing del descriptor → control points de KeySpline (los nombres
2719
+ // mapean a las mismas curvas que animEase en linux).
2720
+ static void navSpline(const std::string &e, double cp[4]) {
2721
+ if (e == "linear") { cp[0]=0; cp[1]=0; cp[2]=1; cp[3]=1; return; }
2722
+ if (e == "ease-in") { cp[0]=.42; cp[1]=0; cp[2]=1; cp[3]=1; return; }
2723
+ if (e == "ease-in-out") { cp[0]=.42; cp[1]=0; cp[2]=.58; cp[3]=1; return; }
2724
+ // ADR-0165 "spring" = cubic-bezier(.34,1.56,.64,1).
2725
+ if (e == "spring") { cp[0]=.34; cp[1]=1.56; cp[2]=.64; cp[3]=1; return; }
2726
+ if (e == "ease") { cp[0]=.25; cp[1]=.1; cp[2]=.25; cp[3]=1; return; }
2727
+ if (e.rfind("cubic-bezier(", 0) == 0) {
2728
+ double p[4];
2729
+ int i = 0;
2730
+ const char *s = e.c_str() + 13;
2731
+ char *end = nullptr;
2732
+ while (i < 4 && (p[i] = strtod(s, &end), end != s)) {
2733
+ s = end;
2734
+ if (*s == ',' || *s == ' ')
2735
+ s++;
2736
+ i++;
2737
+ }
2738
+ if (i == 4) {
2739
+ cp[0] = p[0]; cp[1] = p[1]; cp[2] = p[2]; cp[3] = p[3];
2740
+ return;
2741
+ }
2742
+ }
2743
+ // ease-out y desconocidos → cubic-bezier(0,0,.58,1).
2744
+ cp[0] = 0; cp[1] = 0; cp[2] = .58; cp[3] = 1;
2745
+ }
2746
+
2747
+ namespace muxa_anim = winrt::Microsoft::UI::Xaml::Media::Animation;
2748
+
2749
+ void WinApplicator::clearDetached() {
2750
+ if (!detachedEl_)
2751
+ return;
2752
+ detachVisual(detachedEl_);
2753
+ detachedEl_ = nullptr;
2754
+ }
2755
+
2756
+ void WinApplicator::navTransition(const std::string &op, JSContext *ctx,
2757
+ JSValueConst jop) {
2758
+ std::string kind = "system";
2759
+ int dur = 250;
2760
+ bool specHasDur = false;
2761
+ modules::Json def;
2762
+ JSValue t = jsGet(ctx, jop, "transition");
2763
+ if (!JS_IsUndefined(t) && !JS_IsNull(t)) {
2764
+ std::string k = jsGetStr(ctx, t, "kind");
2765
+ if (!k.empty())
2766
+ kind = k;
2767
+ JSValue dv = jsGet(ctx, t, "duration");
2768
+ if (JS_IsNumber(dv)) {
2769
+ JS_ToInt32(ctx, &dur, dv);
2770
+ specHasDur = true;
2771
+ }
2772
+ JS_FreeValue(ctx, dv);
2773
+ if (kind == "custom") {
2774
+ JSValue dj = jsGet(ctx, t, "def");
2775
+ jsToJson(ctx, dj, def);
2776
+ JS_FreeValue(ctx, dj);
2777
+ }
2778
+ }
2779
+ JS_FreeValue(ctx, t);
2780
+ if (kind == "none") {
2781
+ clearDetached();
2782
+ return;
2783
+ }
2784
+ bool hasDef = kind == "custom" && def.kind == modules::Json::Obj;
2785
+ if (kind == "custom" && !hasDef)
2786
+ warnOnce(unknownOps_, "transition", "custom->system");
2787
+
2788
+ int shellId = -1;
2789
+ for (auto &kv : nodes_)
2790
+ if (kv.second.type == "shell") {
2791
+ shellId = kv.first;
2792
+ break;
2793
+ }
2794
+ muxc::Canvas surface = shellId >= 0 ? surfaceOf(shellId) : nullptr;
2795
+ if (!surface) {
2796
+ clearDetached();
2797
+ return;
2798
+ }
2799
+ auto kids = surface.Children();
2800
+ if (kids.Size() == 0) {
2801
+ clearDetached();
2802
+ return;
2803
+ }
2804
+ mux::UIElement incoming = kids.GetAt(kids.Size() - 1);
2805
+ if (!incoming ||
2806
+ winrt::get_abi(incoming) == winrt::get_abi(detachedEl_)) {
2807
+ clearDetached();
2808
+ return;
2809
+ }
2810
+ int inId = -1;
2811
+ for (auto &kv : nodes_)
2812
+ if (kv.second.el &&
2813
+ winrt::get_abi(kv.second.el) == winrt::get_abi(incoming)) {
2814
+ inId = kv.first;
2815
+ break;
2816
+ }
2817
+ double finalX = inId >= 0 ? nodes_[inId].layX : 0;
2818
+ double W = nodes_[shellId].layW > 0 ? nodes_[shellId].layW
2819
+ : (vpW_ > 0 ? vpW_ : 390);
2820
+
2821
+ double inFromX = finalX, inToX = finalX;
2822
+ mux::UIElement outgoing{nullptr};
2823
+ double outFromX = 0, outToX = 0;
2824
+ bool fade = false;
2825
+
2826
+ if (op == "nav-replace") {
2827
+ fade = true;
2828
+ dur = 180;
2829
+ } else if (op == "nav-push") {
2830
+ inFromX = finalX + W;
2831
+ if (detachedEl_) {
2832
+ outgoing = detachedEl_;
2833
+ detachedEl_ = nullptr;
2834
+ // Debajo de la entrante: overlay 0→-30%W parallax.
2835
+ muxc::Canvas::SetLeft(outgoing, detX_);
2836
+ muxc::Canvas::SetTop(outgoing, detY_);
2837
+ if (auto fe = outgoing.try_as<mux::FrameworkElement>()) {
2838
+ // Restore: el remove puede preceder al primer relayout —
2839
+ // layW/layH quedan a -1 y Width(-1) lanza E_INVALIDARG.
2840
+ if (detW_ > 0)
2841
+ fe.Width(detW_);
2842
+ if (detH_ > 0)
2843
+ fe.Height(detH_);
2844
+ }
2845
+ // Re-insertar un elemento ya en la colección lanza 0x800f1000;
2846
+ // FE.Parent puede ser null aunque siga en Children (árbol lógico
2847
+ // ≠ visual), así que se quita por IndexOf directo.
2848
+ {
2849
+ uint32_t oi = 0;
2850
+ if (kids.IndexOf(outgoing, oi))
2851
+ kids.RemoveAt(oi);
2852
+ }
2853
+ kids.InsertAt(kids.Size() - 1, outgoing);
2854
+ outFromX = detX_;
2855
+ outToX = detX_ - 0.30 * W;
2856
+ }
2857
+ } else { // nav-pop: entrante -30%→0; saliente encima 0→+W.
2858
+ inFromX = finalX - 0.30 * W;
2859
+ if (detachedEl_) {
2860
+ outgoing = detachedEl_;
2861
+ detachedEl_ = nullptr;
2862
+ muxc::Canvas::SetLeft(outgoing, detX_);
2863
+ muxc::Canvas::SetTop(outgoing, detY_);
2864
+ if (auto fe = outgoing.try_as<mux::FrameworkElement>()) {
2865
+ if (detW_ > 0)
2866
+ fe.Width(detW_);
2867
+ if (detH_ > 0)
2868
+ fe.Height(detH_);
2869
+ }
2870
+ {
2871
+ uint32_t oi = 0;
2872
+ if (kids.IndexOf(outgoing, oi))
2873
+ kids.RemoveAt(oi);
2874
+ }
2875
+ kids.Append(outgoing);
2876
+ outFromX = detX_;
2877
+ outToX = detX_ + W;
2878
+ }
2879
+ }
2880
+
2881
+ NavSideW in, out;
2882
+ double inY0 = NAN, inY1 = NAN, outY0 = NAN, outY1 = NAN;
2883
+ if (hasDef) {
2884
+ double H = nodes_[shellId].layH > 0 ? nodes_[shellId].layH
2885
+ : (vpH_ > 0 ? vpH_ : 844);
2886
+ const modules::Json *dd = def.get("duration");
2887
+ if (!specHasDur && dd && dd->kind == modules::Json::Num)
2888
+ dur = (int)dd->num;
2889
+ const modules::Json *inDef = def.get("incoming");
2890
+ if (inDef && inDef->kind == modules::Json::Obj)
2891
+ inFromX = inToX = finalX;
2892
+ in = navSideParseW(inDef, W, H);
2893
+ if (!std::isnan(in.x0))
2894
+ inFromX = in.x0;
2895
+ if (!std::isnan(in.x1))
2896
+ inToX = in.x1;
2897
+ inY0 = in.y0;
2898
+ inY1 = std::isnan(in.y1) ? in.y0 : in.y1;
2899
+ if (outgoing) {
2900
+ const modules::Json *outDef = def.get("outgoing");
2901
+ if (outDef && outDef->kind == modules::Json::Obj)
2902
+ outFromX = outToX = detX_;
2903
+ out = navSideParseW(outDef, W, H);
2904
+ if (!std::isnan(out.x0))
2905
+ outFromX = out.x0;
2906
+ if (!std::isnan(out.x1))
2907
+ outToX = out.x1;
2908
+ outY0 = out.y0;
2909
+ outY1 = std::isnan(out.y1) ? out.y0 : out.y1;
2910
+ }
2911
+ if (fade) {
2912
+ fade = false;
2913
+ incoming.Opacity(std::isnan(in.op0) ? 1 : in.op0);
2914
+ }
2915
+ }
2916
+
2917
+ double cp[4] = {.32, .72, 0, 1}; // system cubic-bezier(.32,.72,0,1)
2918
+ const modules::Json *ez = def.get("easing");
2919
+ if (ez && ez->kind == modules::Json::Str)
2920
+ navSpline(ez->str, cp);
2921
+ if (dur <= 0)
2922
+ dur = 250;
2923
+
2924
+ auto mkKey = [&](double to) {
2925
+ auto ks = muxa_anim::KeySpline();
2926
+ ks.ControlPoint1(winrt::Windows::Foundation::Point(
2927
+ (float)cp[0], (float)cp[1]));
2928
+ ks.ControlPoint2(winrt::Windows::Foundation::Point(
2929
+ (float)cp[2], (float)cp[3]));
2930
+ auto kf = muxa_anim::SplineDoubleKeyFrame();
2931
+ kf.KeySpline(ks);
2932
+ kf.Value(to);
2933
+ muxa_anim::KeyTime kt;
2934
+ kt.TimeSpan = winrt::Windows::Foundation::TimeSpan(
2935
+ std::chrono::milliseconds(dur));
2936
+ kf.KeyTime(kt);
2937
+ return kf;
2938
+ };
2939
+ // Canvas.Left/Top son "dependent animations" en WinUI: sin el flag
2940
+ // el storyboard las descarta en silencio. Opacity/transforms son
2941
+ // independientes (no afectan layout) — el flag no les hace daño.
2942
+ auto addCh = [&](muxa_anim::Storyboard &sb, mux::DependencyObject target,
2943
+ const wchar_t *path, double to) {
2944
+ auto a = muxa_anim::DoubleAnimationUsingKeyFrames();
2945
+ a.EnableDependentAnimation(true);
2946
+ a.KeyFrames().Append(mkKey(to));
2947
+ muxa_anim::Storyboard::SetTarget(a, target);
2948
+ muxa_anim::Storyboard::SetTargetProperty(a, path);
2949
+ sb.Children().Append(a);
2950
+ };
2951
+ // Escala: CompositeTransform perezoso (RenderTransformOrigin centro).
2952
+ auto scaleCh = [&](muxa_anim::Storyboard &sb, mux::UIElement el,
2953
+ double w, double h, double s0, double s1) {
2954
+ if (std::isnan(s0) && std::isnan(s1))
2955
+ return;
2956
+ auto fe = el.try_as<mux::FrameworkElement>();
2957
+ if (!fe)
2958
+ return;
2959
+ fe.RenderTransformOrigin(
2960
+ winrt::Windows::Foundation::Point(0.5f, 0.5f));
2961
+ auto tf = mux::Media::CompositeTransform();
2962
+ double s = std::isnan(s0) ? 1.0 : s0;
2963
+ tf.ScaleX(s);
2964
+ tf.ScaleY(s);
2965
+ fe.RenderTransform(tf);
2966
+ double sv = std::isnan(s1) ? s : s1;
2967
+ addCh(sb, el,
2968
+ L"(UIElement.RenderTransform).(CompositeTransform.ScaleX)", sv);
2969
+ addCh(sb, el,
2970
+ L"(UIElement.RenderTransform).(CompositeTransform.ScaleY)", sv);
2971
+ };
2972
+
2973
+ // Estado inicial: posición de arranque en el Canvas (los base values
2974
+ // los posee la animación — un relayout no pelea con el storyboard).
2975
+ muxa_anim::Storyboard sb;
2976
+ if (fade) {
2977
+ incoming.Opacity(0);
2978
+ addCh(sb, incoming, L"(UIElement.Opacity)", 1);
2979
+ } else {
2980
+ muxc::Canvas::SetLeft(incoming, inFromX);
2981
+ if (!std::isnan(inY0))
2982
+ muxc::Canvas::SetTop(incoming, inY0);
2983
+ addCh(sb, incoming, L"(Canvas.Left)", inToX);
2984
+ if (!std::isnan(inY0) || !std::isnan(inY1))
2985
+ addCh(sb, incoming, L"(Canvas.Top)",
2986
+ std::isnan(inY1) ? inY0 : inY1);
2987
+ if (!std::isnan(in.op0) || !std::isnan(in.op1)) {
2988
+ if (!std::isnan(in.op0))
2989
+ incoming.Opacity(in.op0);
2990
+ addCh(sb, incoming, L"(UIElement.Opacity)",
2991
+ std::isnan(in.op1) ? in.op0 : in.op1);
2992
+ }
2993
+ scaleCh(sb, incoming, W,
2994
+ nodes_[shellId].layH > 0 ? nodes_[shellId].layH : vpH_,
2995
+ in.sc0, in.sc1);
2996
+ }
2997
+ if (outgoing) {
2998
+ addCh(sb, outgoing, L"(Canvas.Left)", outToX);
2999
+ if (!std::isnan(outY0) || !std::isnan(outY1)) {
3000
+ if (!std::isnan(outY0))
3001
+ muxc::Canvas::SetTop(outgoing, outY0);
3002
+ addCh(sb, outgoing, L"(Canvas.Top)",
3003
+ std::isnan(outY1) ? outY0 : outY1);
3004
+ }
3005
+ if (!std::isnan(out.op0) || !std::isnan(out.op1)) {
3006
+ if (!std::isnan(out.op0))
3007
+ outgoing.Opacity(out.op0);
3008
+ addCh(sb, outgoing, L"(UIElement.Opacity)",
3009
+ std::isnan(out.op1) ? out.op0 : out.op1);
3010
+ }
3011
+ scaleCh(sb, outgoing, W,
3012
+ nodes_[shellId].layH > 0 ? nodes_[shellId].layH : vpH_,
3013
+ out.sc0, out.sc1);
3014
+ }
3015
+
3016
+ mux::UIElement outCap = outgoing;
3017
+ sb.Completed([this, outCap, surface](
3018
+ winrt::Windows::Foundation::IInspectable const &,
3019
+ winrt::Windows::Foundation::IInspectable const &) {
3020
+ if (outCap) {
3021
+ // La saliente sale de la superficie — el píxel muere aquí
3022
+ // (su delete-node ya pudo haber llegado).
3023
+ auto ch = surface.Children();
3024
+ uint32_t idx = 0;
3025
+ if (ch.IndexOf(outCap, idx))
3026
+ ch.RemoveAt(idx);
3027
+ }
3028
+ });
3029
+ sb.Begin();
3030
+ }
3031
+
3032
+ // ── Ciclo de vida ──────────────────────────────────────────────────
3033
+
3034
+ void WinApplicator::init(const muxc::Canvas &root, const HostOptions &opts,
3035
+ HostCallbacks cb) {
3036
+ root_ = root;
3037
+ root.AddHandler(mux::UIElement::KeyDownEvent(),
3038
+ winrt::box_value(muxi::KeyEventHandler(
3039
+ [this](auto const &,
3040
+ muxi::KeyRoutedEventArgs const &e) {
3041
+ // XAML islands: el foco de entrada queda en la
3042
+ // raíz aunque el foco lógico esté en el nodo —
3043
+ // la tecla burbujea desde root_. Si el foco
3044
+ // lógico está en un nodo con `key`, emitimos
3045
+ // por él (misma semántica que GTK/web).
3046
+ if (auto xr = root_.XamlRoot()) {
3047
+ auto fe = muxi::FocusManager::
3048
+ GetFocusedElement(xr)
3049
+ .try_as<mux::UIElement>();
3050
+ // Si el origen es fe o un descendiente, el
3051
+ // bubble ya pasó por su KeyDown → no duplicar.
3052
+ auto os = e.OriginalSource()
3053
+ .try_as<mux::UIElement>();
3054
+ bool covered = false;
3055
+ for (auto anc = os; anc;) {
3056
+ if (anc == fe) {
3057
+ covered = true;
3058
+ break;
3059
+ }
3060
+ anc = muxm::VisualTreeHelper::GetParent(anc)
3061
+ .try_as<mux::UIElement>();
3062
+ }
3063
+ if (fe && !covered) {
3064
+ for (auto &kv : nodes_) {
3065
+ if (kv.second.el == fe &&
3066
+ kv.second.events.count("key")) {
3067
+ emitKeyFor(kv.first, e.Key());
3068
+ break;
3069
+ }
3070
+ }
3071
+ }
3072
+ }
3073
+ })),
3074
+ true);
3075
+ cb_ = std::move(cb);
3076
+ vpW_ = opts.width;
3077
+ vpH_ = opts.height;
3078
+ yoga::init();
3079
+ yoga::setViewport((float)vpW_, (float)vpH_, rtl_);
3080
+ yoga::setMeasureHook([this](int id, float w, int wMode, float h,
3081
+ int hMode, float &ow, float &oh) {
3082
+ measureLeaf(id, w, wMode, h, hMode, ow, oh);
3083
+ });
3084
+ }
3085
+
3086
+ void WinApplicator::setViewport(int w, int h) {
3087
+ vpW_ = w;
3088
+ vpH_ = h;
3089
+ yoga::setViewport((float)w, (float)h, rtl_);
3090
+ relayout();
3091
+ if (!densityReported_) {
3092
+ densityReported_ = true;
3093
+ cb_.callHandlerStr("onDensity", "1");
3094
+ }
3095
+ if (h > 0) {
3096
+ char buf[32];
3097
+ snprintf(buf, sizeof(buf), "%d", h);
3098
+ cb_.callHandlerStr("onViewportResize", buf);
3099
+ }
3100
+ }
3101
+
3102
+ void WinApplicator::setRtl(bool rtl) {
3103
+ rtl_ = rtl;
3104
+ yoga::setViewport((float)vpW_, (float)vpH_, rtl);
3105
+ }
3106
+
3107
+ void WinApplicator::shutdown() {
3108
+ std::vector<int> ids;
3109
+ ids.reserve(nodes_.size());
3110
+ for (auto &kv : nodes_)
3111
+ ids.push_back(kv.first);
3112
+ for (int id : ids)
3113
+ deleteNode(id);
3114
+ nodes_.clear();
3115
+ yoga::shutdown();
3116
+ }
3117
+
3118
+ } // namespace elur