@elurjs/universal 0.1.10 → 0.1.12

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 (58) hide show
  1. package/cli/commands.mjs +1 -1
  2. package/cli/create-app.mjs +11 -6
  3. package/cli/dev.mjs +4 -3
  4. package/cli/elur.mjs +60 -4
  5. package/docs/INSTALACION-Y-DEV.md +7 -4
  6. package/package.json +5 -1
  7. package/targets/linux/CMakeLists.txt +196 -0
  8. package/targets/linux/README.md +422 -0
  9. package/targets/linux/ci/tsan.supp +15 -0
  10. package/targets/linux/generated/elur_module_registrar.cpp +18 -0
  11. package/targets/linux/generated/module_sources.cmake +7 -0
  12. package/targets/linux/src/elur_applicator.cpp +5073 -0
  13. package/targets/linux/src/elur_applicator.h +387 -0
  14. package/targets/linux/src/elur_clip.cpp +76 -0
  15. package/targets/linux/src/elur_clip.h +23 -0
  16. package/targets/linux/src/elur_crypto_module.cpp +121 -0
  17. package/targets/linux/src/elur_events.h +57 -0
  18. package/targets/linux/src/elur_fonts.cpp +106 -0
  19. package/targets/linux/src/elur_fonts.h +31 -0
  20. package/targets/linux/src/elur_host.cpp +1041 -0
  21. package/targets/linux/src/elur_host.h +66 -0
  22. package/targets/linux/src/elur_http_module.cpp +437 -0
  23. package/targets/linux/src/elur_js.h +40 -0
  24. package/targets/linux/src/elur_modules.cpp +453 -0
  25. package/targets/linux/src/elur_modules.h +159 -0
  26. package/targets/linux/src/elur_renderer.h +46 -0
  27. package/targets/linux/src/elur_shot.cpp +64 -0
  28. package/targets/linux/src/elur_shot.h +17 -0
  29. package/targets/linux/src/elur_skia_a11y.cpp +987 -0
  30. package/targets/linux/src/elur_skia_a11y.h +146 -0
  31. package/targets/linux/src/elur_skia_app.cpp +1770 -0
  32. package/targets/linux/src/elur_skia_app.h +18 -0
  33. package/targets/linux/src/elur_state_module.cpp +99 -0
  34. package/targets/linux/src/elur_tck_module.cpp +186 -0
  35. package/targets/linux/src/elur_ui_module.cpp +84 -0
  36. package/targets/linux/src/elur_yoga.cpp +452 -0
  37. package/targets/linux/src/elur_yoga.h +95 -0
  38. package/targets/linux/src/main.cpp +294 -0
  39. package/targets/windows/Package.appxmanifest +28 -0
  40. package/targets/windows/README.md +44 -0
  41. package/targets/windows/elur-windows.vcxproj +133 -0
  42. package/targets/windows/packages.config +10 -0
  43. package/targets/windows/src/elur_crypto_module_win.cpp +106 -0
  44. package/targets/windows/src/elur_events.h +58 -0
  45. package/targets/windows/src/elur_host_win.cpp +645 -0
  46. package/targets/windows/src/elur_host_win.h +75 -0
  47. package/targets/windows/src/elur_http_module_win.cpp +331 -0
  48. package/targets/windows/src/elur_js.h +40 -0
  49. package/targets/windows/src/elur_modules.cpp +460 -0
  50. package/targets/windows/src/elur_modules.h +159 -0
  51. package/targets/windows/src/elur_state_module.cpp +99 -0
  52. package/targets/windows/src/elur_ui_module_win.cpp +75 -0
  53. package/targets/windows/src/elur_uia_host.h +129 -0
  54. package/targets/windows/src/elur_win_applicator.cpp +3118 -0
  55. package/targets/windows/src/elur_win_applicator.h +186 -0
  56. package/targets/windows/src/elur_yoga.cpp +452 -0
  57. package/targets/windows/src/elur_yoga.h +95 -0
  58. package/targets/windows/src/main.cpp +321 -0
@@ -0,0 +1,1770 @@
1
+ // elur_skia_app.cpp — aplicador del carril Skia opt-in (Linux, fases
2
+ // 0-1 de docs/propuestas/skia-renderer-arbol.md): DisplayOp → SkiaTree
3
+ // compartido (native/skia-tree) + espejo Yoga + GtkDrawingArea.
4
+ //
5
+ // Alcance (declarado): pinta el árbol completo a un surface raster
6
+ // por draw_func; press/longPress/pan por hit-test; scroll gestual
7
+ // host-side (drag + fling exponencial + rueda) con clamp al extent;
8
+ // switch/slider pintados e interactivos; image local vía loaders
9
+ // GTK4. Sin GPU (raster CPU), sin IME ni árbol AT-SPI virtual, sin
10
+ // pipeline remoto de imágenes — fases 2-3 del documento. Ops fuera
11
+ // de alcance → warn-once explícito, nunca silencio.
12
+
13
+ #include "elur_skia_app.h"
14
+ #include "elur_skia_a11y.h"
15
+
16
+ #if ELUR_HAS_SKIA
17
+
18
+ #include "elur_applicator.h" // elurDomKeyName compartido (evento key)
19
+ #include "elur_fonts.h"
20
+ #include "elur_host.h"
21
+ #include "elur_js.h"
22
+ #include "elur_modules.h" // jsonEscape compartido (payloads)
23
+ #include "elur_yoga.h"
24
+ #include "native/skia-tree/elur_skia_tree.h"
25
+
26
+ #include <algorithm>
27
+ #include <cairo.h>
28
+ #include <cmath>
29
+ #include <cstdlib>
30
+ #include <epoxy/gl.h>
31
+ #include <libsoup/soup.h>
32
+ #include <list>
33
+ #include <unordered_map>
34
+ #include <unordered_set>
35
+
36
+ #include "include/core/SkBitmap.h"
37
+ #include "include/core/SkCanvas.h"
38
+ #include "include/core/SkColorSpace.h"
39
+ #include "include/core/SkImage.h"
40
+ #if ELUR_SKIA_GL
41
+ #include "include/gpu/ganesh/GrBackendSurface.h"
42
+ #include "include/gpu/ganesh/GrDirectContext.h"
43
+ #include "include/gpu/ganesh/SkSurfaceGanesh.h"
44
+ #include "include/gpu/ganesh/gl/GrGLBackendSurface.h"
45
+ #include "include/gpu/ganesh/gl/GrGLDirectContext.h"
46
+ #include "include/gpu/ganesh/gl/GrGLInterface.h"
47
+ #include "include/gpu/ganesh/gl/epoxy/GrGLMakeEpoxyEGLInterface.h"
48
+ #endif
49
+ #include "include/ports/SkFontMgr_fontconfig.h"
50
+ #include "include/ports/SkFontScanner_FreeType.h"
51
+
52
+ namespace elur {
53
+
54
+ namespace {
55
+
56
+ class SkiaApplicator : public HostRenderer {
57
+ public:
58
+ void init(GtkWidget *surface, const HostOptions &opts,
59
+ HostCallbacks cb) override;
60
+ void shutdown() override;
61
+ void applyFrame(JSContext *ctx, JSValueConst v) override;
62
+ void setViewport(int w, int h) override;
63
+ void setRtl(bool rtl) override;
64
+ void setTrace(bool on) override { trace_ = on; }
65
+
66
+ // Públicos: el draw_func y las gesture son callbacks C de GTK.
67
+ GtkWidget *area_ = nullptr;
68
+ HostCallbacks cb_;
69
+ skia::SkiaTree tree_;
70
+ SkiaA11y a11y_; // árbol AT-SPI virtual (fase 2)
71
+ bool trace_ = false;
72
+ std::string bundleDir_;
73
+
74
+ void relayout();
75
+ void warnOnce(std::unordered_map<std::string, int> &m, const char *kind,
76
+ const std::string &what);
77
+ void emitBound(int nodeId, const char *ev, const std::string &data);
78
+ void emitScrollState(int id);
79
+ bool focusable(int id);
80
+ void focusChain(std::vector<int> &out);
81
+ void setFocus(int id);
82
+ void focusStep(int dir);
83
+ void focusAt(float x, float y);
84
+ void setValueEmit(int id, const std::string &v);
85
+ void imCursor();
86
+ void loadImage(int id, const std::string &src);
87
+ void imgDeliver(const std::string &src, sk_sp<SkImage> img, int bytes);
88
+ void imgDropWaiter(int nodeId);
89
+ void stopFling();
90
+ void createPlatformView(int id, const std::string &module,
91
+ const std::string &view, JSContext *ctx,
92
+ JSValueConst props);
93
+ void syncPv();
94
+
95
+ // Estado del gesto en curso — un drag sirve a pan / scroll / slider
96
+ // (decisión en drag-begin por hit-test; parity fase BUBBLE de GTK).
97
+ struct {
98
+ int mode = 0; // 0 idle · 1 scroll · 2 pan · 3 slider
99
+ int target = 0;
100
+ double ox0 = 0, oy0 = 0; // punto del begin (coords del área)
101
+ float lx = 0, ly = 0; // últimos offsets acumulados
102
+ float vx = 0, vy = 0; // velocidad px/s (EMA)
103
+ gint64 lastT = 0;
104
+ bool panStarted = false;
105
+ bool consumed = false; // control/longpress ya respondió al gesto
106
+ } drag_;
107
+ // Fling en curso (tick callback del frame clock).
108
+ int flingNode_ = 0;
109
+ float flingVx_ = 0, flingVy_ = 0;
110
+ gint64 flingT_ = 0;
111
+
112
+ // Foco virtual + IME (fase 2 — el árbol no tiene widgets: la
113
+ // cadena Tab, los eventos focus/blur y el GtkIMContext son del host).
114
+ int focused_ = 0;
115
+ GtkIMContext *im_ = nullptr;
116
+ bool imComposing_ = false;
117
+ // Atajos globales (ADR-0179) — combo canónico por attach-event
118
+ // "shortcut"; la dedup de autorepeat es por keycode.
119
+ std::vector<std::pair<int, std::string>> hotkeys_;
120
+ std::unordered_set<guint> keysDown_;
121
+
122
+ // Platform views (ADR-0181): el widget real de la factory vive como
123
+ // hijo del GtkOverlay que envuelve el canvas (pvLayer_), posicionado
124
+ // al rect absoluto del nodo por margins en cada relayout/scroll. Su
125
+ // AT-SPI y eventos son los del widget; el nodo del árbol no
126
+ // materializa accesible propio.
127
+ GtkWidget *pvLayer_ = nullptr;
128
+ std::unordered_map<int, GtkWidget *> pvWidgets_;
129
+
130
+ // fontScale (§1.4, espejo sp): mismo origen que el carril views —
131
+ // ELUR_FONT_SCALE o text-scaling-factor de GNOME, con watch.
132
+ GSettings *fontScaleSettings_ = nullptr;
133
+ void initFontScale();
134
+ void applyFontScale(double s);
135
+
136
+ // Backend GPU opt-in (fase 4): Ganesh sobre GtkGLArea. raster por
137
+ // default — si MakeGL falla, fallbackToRaster cambia el widget.
138
+ bool glBackend_ = false;
139
+ #if ELUR_SKIA_GL
140
+ struct {
141
+ sk_sp<const GrGLInterface> iface;
142
+ sk_sp<GrDirectContext> ctx;
143
+ // Surface cacheada por (w,h,fbo) — crear rt+surface por frame es el
144
+ // coste dominante bajo rasterizadores por software (llvmpipe).
145
+ sk_sp<SkSurface> surface;
146
+ int w = 0, h = 0;
147
+ unsigned fbo = 0;
148
+ bool failed = false;
149
+ } gl_;
150
+ #endif
151
+ void wireSurface();
152
+ void fallbackToRaster();
153
+ // Repintado: en GLArea con auto_render=FALSE el "render" solo se
154
+ // emite si se pidió explícitamente — queue_draw solo marca dirty.
155
+ void repaint() {
156
+ #if ELUR_SKIA_GL
157
+ if (glBackend_ && GTK_IS_GL_AREA(area_)) {
158
+ gtk_gl_area_queue_render(GTK_GL_AREA(area_));
159
+ return;
160
+ }
161
+ #endif
162
+ gtk_widget_queue_draw(area_);
163
+ }
164
+
165
+ // Pipeline de imagen (ADR-0071 — mismas cotas que el carril views:
166
+ // dedup por src, cache LRU por bytes, presión live).
167
+ SoupSession *soup_ = nullptr;
168
+ GCancellable *imgCanc_ = nullptr;
169
+ std::unordered_map<std::string, std::vector<int>> imgInFlight_;
170
+ struct ImgEnt {
171
+ sk_sp<SkImage> img;
172
+ int bytes = 0;
173
+ std::list<std::string>::iterator lru;
174
+ };
175
+ std::unordered_map<std::string, ImgEnt> imgCache_;
176
+ std::list<std::string> imgLru_;
177
+ long imgCacheBytes_ = 0, imgLiveBytes_ = 0;
178
+ std::unordered_map<int, std::string> imgSrc_; // src vigente por nodo
179
+ std::unordered_map<int, int> imgBytes_; // live accounting por nodo
180
+
181
+ private:
182
+ int vpW_ = 0, vpH_ = 0;
183
+ bool rtl_ = false;
184
+ bool densityReported_ = false;
185
+ std::unordered_map<std::string, int> unknownOps_;
186
+ std::unordered_map<std::string, int> unknownTypes_;
187
+ std::unordered_map<std::string, int> unknownProps_;
188
+ std::unordered_map<std::string, int> unknownStyles_;
189
+ };
190
+
191
+ SkiaApplicator g_skia;
192
+
193
+ static std::string xyJson(double x, double y) {
194
+ char b1[24], b2[24];
195
+ return std::string("{\"x\":") + g_ascii_dtostr(b1, sizeof(b1), x) +
196
+ ",\"y\":" + g_ascii_dtostr(b2, sizeof(b2), y) + "}";
197
+ }
198
+
199
+ void SkiaApplicator::emitBound(int nodeId, const char *ev,
200
+ const std::string &data) {
201
+ auto it = tree_.nodes.find(nodeId);
202
+ if (it == tree_.nodes.end())
203
+ return;
204
+ auto eb = it->second.events.find(ev);
205
+ if (eb == it->second.events.end())
206
+ return;
207
+ emitHostEvent(
208
+ cb_,
209
+ EventBind{eb->second.handler, eb->second.continuous, eb->second.payload},
210
+ ev, "user", data);
211
+ }
212
+
213
+ void SkiaApplicator::emitScrollState(int id) {
214
+ auto it = tree_.nodes.find(id);
215
+ if (it == tree_.nodes.end())
216
+ return;
217
+ char b1[24], b2[24], buf[160];
218
+ snprintf(buf, sizeof(buf), "{\"y\":%s,\"vh\":%s,\"node\":%d}",
219
+ g_ascii_dtostr(b1, sizeof(b1), (double)it->second.scrollY),
220
+ g_ascii_dtostr(b2, sizeof(b2), (double)it->second.rh), id);
221
+ emitBound(id, "scroll", buf);
222
+ syncPv(); // el scroll mueve los rects absolutos de las PV también
223
+ }
224
+
225
+ // ── Platform views (ADR-0181) ───────────────────────────────────
226
+ // Mismo contrato que el carril views: la factory "module:view" del
227
+ // registry crea el widget real; bajo el carril árbol entra como hijo
228
+ // del GtkOverlay (pvLayer_) y syncPv lo alinea al rect absoluto del
229
+ // nodo en cada relayout/scroll. El accessible del AT es el del
230
+ // widget — el nodo virtual no materializa accesible (a11y_.add se
231
+ // salta para platform-view, evita duplicados).
232
+ void SkiaApplicator::createPlatformView(int id, const std::string &module,
233
+ const std::string &view, JSContext *ctx,
234
+ JSValueConst props) {
235
+ modules::PvFactory f = Applicator::resolvePlatformView(module, view);
236
+ if (!f || !pvLayer_) {
237
+ warnOnce(unknownOps_, "platform-view", module + ":" + view);
238
+ return;
239
+ }
240
+ modules::PvEmit emit = [](int nid, const char *ev, const char *d) {
241
+ g_skia.emitBound(nid, ev, d ? d : "{}");
242
+ };
243
+ GtkWidget *w = f(id, emit);
244
+ if (!w) {
245
+ warnOnce(unknownOps_, "platform-view-null", module + ":" + view);
246
+ return;
247
+ }
248
+ g_object_ref_sink(w);
249
+ pvWidgets_[id] = w;
250
+ // Hijo overlay directo: posición por alignment+margins (el hueco
251
+ // del overlay no absorbe eventos — el gesto cae al canvas).
252
+ gtk_widget_set_halign(w, GTK_ALIGN_START);
253
+ gtk_widget_set_valign(w, GTK_ALIGN_START);
254
+ gtk_overlay_add_overlay(GTK_OVERLAY(pvLayer_), w);
255
+ // Oculto hasta insert-child — paridad con el carril views, donde
256
+ // el widget no se ve hasta que entra a la jerarquía.
257
+ gtk_widget_set_visible(w, FALSE);
258
+ // El nodo entra al árbol para layout/props/eventos; al AT virtual
259
+ // no — su accessible lo aporta el widget real (evita duplicados).
260
+ tree_.createNode(id, "platform-view");
261
+ yoga::nodeCreate(id, "platform-view");
262
+ if (!JS_IsUndefined(props) && !JS_IsNull(props)) {
263
+ JSPropertyEnum *tab = nullptr;
264
+ uint32_t cnt = 0;
265
+ if (JS_GetOwnPropertyNames(ctx, &tab, &cnt, props,
266
+ JS_GPN_STRING_MASK | JS_GPN_ENUM_ONLY) == 0) {
267
+ for (uint32_t k = 0; k < cnt; k++) {
268
+ JSValue key = JS_AtomToValue(ctx, tab[k].atom);
269
+ JSValue val = JS_GetProperty(ctx, props, tab[k].atom);
270
+ std::string ks = jsStr(ctx, key);
271
+ if (ks == "enabled")
272
+ gtk_widget_set_sensitive(w, JS_ToBool(ctx, val));
273
+ else if (ks == "disabled")
274
+ gtk_widget_set_sensitive(w, !JS_ToBool(ctx, val));
275
+ JS_FreeValue(ctx, val);
276
+ JS_FreeValue(ctx, key);
277
+ }
278
+ JS_FreePropertyEnum(ctx, tab, cnt);
279
+ }
280
+ }
281
+ syncPv();
282
+ }
283
+
284
+ void SkiaApplicator::syncPv() {
285
+ // Posición = rect absoluto del nodo (scroll y reparent entran por
286
+ // absPos) materializado en margins del hijo overlay; el tamaño lo
287
+ // fija el size-request — mismo efecto observable que el move/
288
+ // resize del GtkFixed en el carril views.
289
+ for (auto &[id, w] : pvWidgets_) {
290
+ float ax = 0, ay = 0;
291
+ auto it = tree_.nodes.find(id);
292
+ if (it == tree_.nodes.end() || !tree_.absPos(id, ax, ay))
293
+ continue;
294
+ const skia::SkiaNode &n = it->second;
295
+ gtk_widget_set_margin_start(w, (int)ax);
296
+ gtk_widget_set_margin_top(w, (int)ay);
297
+ gtk_widget_set_size_request(w, (int)(n.rw + 0.5f), (int)(n.rh + 0.5f));
298
+ }
299
+ }
300
+
301
+ // ── Foco virtual + IME (fase 2) ─────────────────────────────────
302
+ // Cadena de foco propia (los nodos no son widgets): foco por clic
303
+ // (ancestro focusable más profundo del hit) y Tab/Shift-Tab en orden
304
+ // de documento; anillo en el painter (tree_.focusedId) y eventos
305
+ // focus/blur por emitBound. Focusable = prop `focusable` explícita,
306
+ // tipos interactivos (paridad con los defaults del a11y) o evento
307
+ // `key` ligado (paridad views: attach key → focusable).
308
+ //
309
+ // IME: un GtkIMMulticontext propio del host — el árbol no tiene
310
+ // GtkEditable interno, así que el commit sí escribe: inserta en
311
+ // props["value"] del text-input enfocado (caret al final — el cursor
312
+ // real es gap declarado de ADR-0109), remide por Yoga, repinta y
313
+ // emite `input` {text,composing}. Los preedit se re-emiten como
314
+ // `composition` (misma fase/vocabulario del carril views).
315
+
316
+ bool SkiaApplicator::focusable(int id) {
317
+ auto it = tree_.nodes.find(id);
318
+ if (it == tree_.nodes.end() || it->second.displayNone ||
319
+ !it->second.hasRect || it->second.absorbedBy)
320
+ return false;
321
+ const skia::SkiaNode &n = it->second;
322
+ auto p = n.props.find("focusable");
323
+ if (p != n.props.end())
324
+ return p->second == "true";
325
+ const std::string &t = n.type;
326
+ if (t == "text-input" || t == "button" || t == "switch" || t == "slider")
327
+ return true;
328
+ return n.events.count("key") > 0;
329
+ }
330
+
331
+ static void focusChainInto(const skia::SkiaTree &tree,
332
+ const std::vector<int> &ids, SkiaApplicator &app,
333
+ std::vector<int> &out) {
334
+ for (int id : ids) {
335
+ auto it = tree.nodes.find(id);
336
+ if (it == tree.nodes.end())
337
+ continue;
338
+ if (app.focusable(id))
339
+ out.push_back(id);
340
+ focusChainInto(tree, it->second.children, app, out);
341
+ }
342
+ }
343
+
344
+ void SkiaApplicator::focusChain(std::vector<int> &out) {
345
+ focusChainInto(tree_, tree_.roots, *this, out);
346
+ }
347
+
348
+ void SkiaApplicator::setFocus(int id) {
349
+ if (id == focused_ || (id && !focusable(id)))
350
+ return;
351
+ int old = focused_;
352
+ focused_ = id;
353
+ tree_.focusedId = id;
354
+ if (old) {
355
+ a11y_.setFocused(old, false);
356
+ emitBound(old, "blur", "{}");
357
+ auto oi = tree_.nodes.find(old);
358
+ if (im_ && oi != tree_.nodes.end() && oi->second.type == "text-input") {
359
+ gtk_im_context_focus_out(im_);
360
+ gtk_im_context_reset(im_);
361
+ imComposing_ = false;
362
+ }
363
+ }
364
+ if (id) {
365
+ a11y_.setFocused(id, true);
366
+ emitBound(id, "focus", "{}");
367
+ auto ni = tree_.nodes.find(id);
368
+ if (im_ && ni != tree_.nodes.end() && ni->second.type == "text-input") {
369
+ gtk_im_context_focus_in(im_);
370
+ imCursor();
371
+ }
372
+ }
373
+ repaint();
374
+ }
375
+
376
+ void SkiaApplicator::focusStep(int dir) {
377
+ std::vector<int> chain;
378
+ focusChain(chain);
379
+ if (chain.empty()) {
380
+ setFocus(0);
381
+ return;
382
+ }
383
+ if (!focused_) {
384
+ setFocus(dir > 0 ? chain.front() : chain.back());
385
+ return;
386
+ }
387
+ int idx = -1;
388
+ for (size_t i = 0; i < chain.size(); i++)
389
+ if (chain[i] == focused_) {
390
+ idx = (int)i;
391
+ break;
392
+ }
393
+ // El nodo enfocado salió de la cadena (borrado/hidden) → reinicia
394
+ // desde el borde en la dirección del paso.
395
+ int next = idx < 0 ? (dir > 0 ? 0 : (int)chain.size() - 1)
396
+ : (idx + dir + (int)chain.size()) % (int)chain.size();
397
+ setFocus(chain[next]);
398
+ }
399
+
400
+ // Clic → el foco cae al ancestro focusable más profundo del path
401
+ // (paridad GTK: el widget bajo el puntero reclama el foco, no el
402
+ // contenedor). Clic en zona sin focusable → desenfoca.
403
+ void SkiaApplicator::focusAt(float x, float y) {
404
+ gtk_widget_grab_focus(area_);
405
+ int cur = tree_.nodeAt(x, y);
406
+ while (cur && !focusable(cur)) {
407
+ auto it = tree_.nodes.find(cur);
408
+ cur = it == tree_.nodes.end() ? 0 : it->second.parent;
409
+ }
410
+ setFocus(cur);
411
+ }
412
+
413
+ // value programático ↔ IME: muta props["value"], remide la hoja,
414
+ // repinta y emite input con el vocabulario views
415
+ // ({"text","composing"}). También refresca el accesible (textContent
416
+ // lee value para text-input).
417
+ void SkiaApplicator::setValueEmit(int id, const std::string &v) {
418
+ auto it = tree_.nodes.find(id);
419
+ if (it == tree_.nodes.end())
420
+ return;
421
+ tree_.setProp(id, "value", v);
422
+ yoga::nodeSetText(id);
423
+ relayout();
424
+ a11y_.textChanged(id);
425
+ std::string d = "{\"text\":\"" + modules::jsonEscape(v) +
426
+ std::string("\",\"composing\":") +
427
+ (imComposing_ ? "true}" : "false}");
428
+ emitBound(id, "input", d);
429
+ repaint();
430
+ }
431
+
432
+ // Popup de candidatas IBus: esquina inferior del input en coords del
433
+ // área — la misma aproximación declarada del carril views.
434
+ void SkiaApplicator::imCursor() {
435
+ if (!im_ || !focused_)
436
+ return;
437
+ float ax = 0, ay = 0;
438
+ GdkRectangle r{0, 0, 1, 1};
439
+ if (tree_.absPos(focused_, ax, ay)) {
440
+ auto it = tree_.nodes.find(focused_);
441
+ r.x = (int)ax;
442
+ r.y = (int)(ay + (it != tree_.nodes.end() ? it->second.rh : 0));
443
+ }
444
+ gtk_im_context_set_cursor_location(im_, &r);
445
+ }
446
+
447
+ void skiaDrawFunc(GtkDrawingArea *, cairo_t *cr, int w, int h, gpointer) {
448
+ if (w <= 0 || h <= 0)
449
+ return;
450
+ // Raster CPU (fase 0): el buffer lo posee cairo (ARGB32 premul ≡
451
+ // N32-premul en LE) y Skia pinta sobre el mismo puntero — cero copia
452
+ // y la vida del dato no depende del stack del draw (el cr que llega
453
+ // puede ser de recording/snapshot: relee el source después).
454
+ cairo_surface_t *img = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, w, h);
455
+ unsigned char *data = cairo_image_surface_get_data(img);
456
+ int stride = cairo_image_surface_get_stride(img);
457
+ SkImageInfo info = SkImageInfo::MakeN32Premul(w, h);
458
+ SkBitmap bmp;
459
+ if (bmp.installPixels(info, data, (size_t)stride)) {
460
+ bmp.eraseColor(SK_ColorWHITE); // base de ventana como el GtkWindow
461
+ SkCanvas canvas(bmp);
462
+ g_skia.tree_.paint(canvas);
463
+ }
464
+ cairo_surface_mark_dirty(img);
465
+ cairo_set_source_surface(cr, img, 0, 0);
466
+ cairo_paint(cr);
467
+ cairo_surface_destroy(img);
468
+ }
469
+
470
+ #if ELUR_SKIA_GL
471
+ // Backend GPU (fase 4): dentro del signal "render" el contexto GL del
472
+ // GtkGLArea ya es current — Ganesh envuelve el FBO que GTK tiene bound
473
+ // (puede ser un FBO intermedio, no el 0) y el árbol pinta igual que el
474
+ // raster. Si el contexto/interfaz no existe, una vez warn + swap del
475
+ // widget al área raster (fallback real, no silencio).
476
+ gboolean skiaGlRender(GtkGLArea *area, GdkGLContext *, gpointer) {
477
+ if (g_skia.gl_.failed)
478
+ return TRUE;
479
+ if (!g_skia.gl_.ctx) {
480
+ g_skia.gl_.iface = GrGLInterfaces::MakeEpoxyEGL();
481
+ if (g_skia.gl_.iface)
482
+ g_skia.gl_.ctx = GrDirectContexts::MakeGL(g_skia.gl_.iface);
483
+ if (!g_skia.gl_.ctx) {
484
+ g_skia.gl_.failed = true;
485
+ g_warning("[skia] backend gl: sin GrDirectContext — cayendo a raster");
486
+ g_idle_add(
487
+ +[](gpointer) -> gboolean {
488
+ g_skia.fallbackToRaster();
489
+ return G_SOURCE_REMOVE;
490
+ },
491
+ nullptr);
492
+ return TRUE;
493
+ }
494
+ g_message("[skia] backend gl activo (Ganesh via epoxy)");
495
+ }
496
+ int scale = gtk_widget_get_scale_factor(GTK_WIDGET(area));
497
+ int w = gtk_widget_get_width(GTK_WIDGET(area)) * scale;
498
+ int h = gtk_widget_get_height(GTK_WIDGET(area)) * scale;
499
+ if (w <= 0 || h <= 0)
500
+ return TRUE;
501
+ GLint fbo = 0;
502
+ glGetIntegerv(GL_FRAMEBUFFER_BINDING, &fbo);
503
+ if (!g_skia.gl_.surface || g_skia.gl_.w != w || g_skia.gl_.h != h ||
504
+ g_skia.gl_.fbo != (unsigned)fbo) {
505
+ GrGLFramebufferInfo fboInfo;
506
+ fboInfo.fFBOID = (GrGLuint)fbo;
507
+ fboInfo.fFormat = GL_RGBA8;
508
+ auto rt = GrBackendRenderTargets::MakeGL(w, h, 0, 0, fboInfo);
509
+ g_skia.gl_.surface = SkSurfaces::WrapBackendRenderTarget(
510
+ g_skia.gl_.ctx.get(), rt, kBottomLeft_GrSurfaceOrigin,
511
+ kRGBA_8888_SkColorType, nullptr, nullptr);
512
+ g_skia.gl_.w = w;
513
+ g_skia.gl_.h = h;
514
+ g_skia.gl_.fbo = (unsigned)fbo;
515
+ if (!g_skia.gl_.surface) {
516
+ g_warning("[skia] backend gl: WrapBackendRenderTarget falló");
517
+ return TRUE;
518
+ }
519
+ }
520
+ g_skia.gl_.surface->getCanvas()->clear(SK_ColorWHITE);
521
+ g_skia.tree_.paint(*g_skia.gl_.surface->getCanvas());
522
+ g_skia.gl_.ctx->flushAndSubmit();
523
+ return TRUE;
524
+ }
525
+
526
+ // El contexto muere con el widget — los objetos Ganesh deben soltarse
527
+ // mientras un contexto GL sigue existiendo (unrealize del GLArea).
528
+ void skiaGlUnrealize(GtkWidget *, gpointer) {
529
+ g_skia.gl_.surface.reset();
530
+ g_skia.gl_.w = g_skia.gl_.h = 0;
531
+ g_skia.gl_.fbo = 0;
532
+ g_skia.gl_.ctx.reset();
533
+ g_skia.gl_.iface.reset();
534
+ }
535
+
536
+ // Si el GLArea no pudo crear su contexto, "render" no se emite jamás —
537
+ // el fallback debe dispararse aquí, no en render. El error se asienta
538
+ // perezoso (realize o primer snapshot): se relee a los 300 ms, tiempo
539
+ // suficiente para el primer frame y sin tocar el path de éxito (si el
540
+ // ctx Ganesh ya existe no hay nada que mirar).
541
+ void skiaGlRealize(GtkWidget *area, gpointer) {
542
+ g_object_ref(area);
543
+ g_timeout_add(
544
+ 300,
545
+ +[](gpointer p) -> gboolean {
546
+ GtkWidget *w = GTK_WIDGET(p);
547
+ if (!g_skia.gl_.ctx) {
548
+ const GError *err = gtk_gl_area_get_error(GTK_GL_AREA(w));
549
+ if (err) {
550
+ g_warning(
551
+ "[skia] backend gl: contexto GL no disponible (%s) — raster",
552
+ err->message);
553
+ g_skia.gl_.failed = true;
554
+ g_skia.fallbackToRaster();
555
+ }
556
+ }
557
+ g_object_unref(w);
558
+ return G_SOURCE_REMOVE;
559
+ },
560
+ area);
561
+ }
562
+ #endif // ELUR_SKIA_GL
563
+
564
+ void skiaPressReleased(GtkGestureClick *, int, double x, double y, gpointer) {
565
+ if (g_skia.drag_.consumed) {
566
+ g_skia.drag_.consumed = false;
567
+ return; // longPress/control ya respondió — el click no es press
568
+ }
569
+ g_skia.focusAt((float)x, (float)y); // el foco sigue al puntero
570
+ int hit = g_skia.tree_.nodeAt((float)x, (float)y);
571
+ if (hit) {
572
+ auto it = g_skia.tree_.nodes.find(hit);
573
+ if (it != g_skia.tree_.nodes.end()) {
574
+ if (it->second.type == "switch") {
575
+ bool on = g_skia.tree_.switchToggle(hit);
576
+ g_skia.emitBound(hit, "change",
577
+ std::string("{\"checked\":") +
578
+ (on ? "true}" : "false}"));
579
+ g_skia.repaint();
580
+ return;
581
+ }
582
+ if (it->second.type == "slider") {
583
+ float lx = 0, ly = 0;
584
+ g_skia.tree_.pointInNode(hit, (float)x, (float)y, lx, ly);
585
+ float v = g_skia.tree_.sliderSetAt(hit, lx);
586
+ char b1[24], b2[24], buf[160];
587
+ snprintf(buf, sizeof(buf),
588
+ "{\"progress\":%s,\"text\":\"%s\",\"composing\":false}",
589
+ g_ascii_dtostr(b1, sizeof(b1), (double)v),
590
+ g_ascii_dtostr(b2, sizeof(b2), (double)v));
591
+ g_skia.emitBound(hit, "input", buf);
592
+ g_skia.repaint();
593
+ return;
594
+ }
595
+ }
596
+ }
597
+ int id = g_skia.tree_.hitTest((float)x, (float)y, "press");
598
+ if (!id)
599
+ return;
600
+ g_skia.emitBound(id, "press", "{}");
601
+ }
602
+
603
+ // ── Teclado + IME (fase 2) ──────────────────────────────────────
604
+ // Orden por tecla sobre el text-input enfocado: IM filter primero
605
+ // (IBus puede consumirla para la candidata), luego Tab a la cadena,
606
+ // `key` ligado, Enter→submit y edición directa (caret al final —
607
+ // gap ADR-0109: sin navegación de cursor en esta fase).
608
+
609
+ static void skiaImCommit(GtkIMContext *, const char *str, gpointer) {
610
+ if (!str || !*str || !g_skia.focused_)
611
+ return;
612
+ auto it = g_skia.tree_.nodes.find(g_skia.focused_);
613
+ if (it == g_skia.tree_.nodes.end() || it->second.type != "text-input")
614
+ return;
615
+ std::string v;
616
+ if (auto p = it->second.props.find("value"); p != it->second.props.end())
617
+ v = p->second;
618
+ g_skia.setValueEmit(g_skia.focused_, v + str);
619
+ }
620
+
621
+ static void skiaEmitComp(const char *phase, const std::string &text) {
622
+ if (!g_skia.focused_)
623
+ return;
624
+ std::string d = "{\"phase\":\"";
625
+ d += phase;
626
+ d += "\",\"text\":\"" + modules::jsonEscape(text) + "\"}";
627
+ g_skia.emitBound(g_skia.focused_, "composition", d);
628
+ }
629
+
630
+ static void skiaImPreeditStart(GtkIMContext *, gpointer) {
631
+ g_skia.imComposing_ = true;
632
+ skiaEmitComp("start", "");
633
+ }
634
+
635
+ static void skiaImPreeditChanged(GtkIMContext *im, gpointer) {
636
+ char *pre = nullptr;
637
+ gtk_im_context_get_preedit_string(im, &pre, nullptr, nullptr);
638
+ skiaEmitComp("update", pre ? pre : "");
639
+ g_free(pre);
640
+ }
641
+
642
+ static void skiaImPreeditEnd(GtkIMContext *, gpointer) {
643
+ g_skia.imComposing_ = false;
644
+ skiaEmitComp("end", "");
645
+ }
646
+
647
+ static gboolean skiaKeyPressed(GtkEventControllerKey *kc, guint keyval,
648
+ guint keycode, GdkModifierType state, gpointer) {
649
+ int fid = g_skia.focused_;
650
+ auto fi = g_skia.tree_.nodes.find(fid);
651
+ bool isText =
652
+ fid && fi != g_skia.tree_.nodes.end() && fi->second.type == "text-input";
653
+
654
+ // 0. Atajo global (ADR-0179) — capture-parity del carril views: ve
655
+ // la tecla antes que IM/key del nodo; editando solo disparan
656
+ // combos ctrl/alt/meta/F*/escape (el resto es texto del usuario).
657
+ if (!g_skia.hotkeys_.empty() && g_skia.keysDown_.insert(keycode).second) {
658
+ std::string key = elurDomKeyName(keyval);
659
+ if (!key.empty()) {
660
+ std::string combo = elurComboOf(key, state);
661
+ if (!isText || elurFiresWhileEditing(combo)) {
662
+ for (auto h = g_skia.hotkeys_.rbegin(); h != g_skia.hotkeys_.rend();
663
+ ++h) {
664
+ if (h->second == combo && g_skia.tree_.nodes.count(h->first)) {
665
+ g_skia.emitBound(h->first, "shortcut", "{}");
666
+ return TRUE;
667
+ }
668
+ }
669
+ }
670
+ }
671
+ }
672
+
673
+ // 1. IM primero — la candidata puede consumir la tecla (Enter
674
+ // confirma preedit, nunca llega a submit).
675
+ if (isText && g_skia.im_) {
676
+ GdkEvent *ev =
677
+ gtk_event_controller_get_current_event(GTK_EVENT_CONTROLLER(kc));
678
+ if (ev && gtk_im_context_filter_keypress(g_skia.im_, ev))
679
+ return TRUE;
680
+ }
681
+ // 2. Cadena de foco — Tab/Shift-Tab (ISO_Left_Tab = shift-tab real).
682
+ if (keyval == GDK_KEY_Tab || keyval == GDK_KEY_KP_Tab ||
683
+ keyval == GDK_KEY_ISO_Left_Tab) {
684
+ g_skia.focusStep((state & GDK_SHIFT_MASK) ? -1 : 1);
685
+ return TRUE;
686
+ }
687
+ if (!fid)
688
+ return FALSE;
689
+ // 3. `key` ligado al nodo — mismo payload que el carril views.
690
+ if (fi->second.events.count("key")) {
691
+ std::string name = elur::elurDomKeyName(keyval);
692
+ if (!name.empty()) {
693
+ std::string d = "{\"key\":\"" + modules::jsonEscape(name) + "\"";
694
+ if (state & GDK_CONTROL_MASK)
695
+ d += ",\"ctrl\":true";
696
+ if (state & GDK_ALT_MASK)
697
+ d += ",\"alt\":true";
698
+ if (state & GDK_SHIFT_MASK)
699
+ d += ",\"shift\":true";
700
+ if (state & (GDK_SUPER_MASK | GDK_META_MASK))
701
+ d += ",\"meta\":true";
702
+ d += "}";
703
+ g_skia.emitBound(fid, "key", d);
704
+ return TRUE;
705
+ }
706
+ }
707
+ if (!isText)
708
+ return FALSE;
709
+ // 4. Enter → submit (paridad GtkEntry::activate del carril views).
710
+ if (keyval == GDK_KEY_Return || keyval == GDK_KEY_KP_Enter ||
711
+ keyval == GDK_KEY_ISO_Enter) {
712
+ std::string v;
713
+ if (auto p = fi->second.props.find("value"); p != fi->second.props.end())
714
+ v = p->second;
715
+ g_skia.emitBound(fid, "submit",
716
+ "{\"text\":\"" + modules::jsonEscape(v) + "\"}");
717
+ return TRUE;
718
+ }
719
+ // 5. Edición al final del buffer (caret fijo — gap ADR-0109).
720
+ if (keyval == GDK_KEY_BackSpace) {
721
+ std::string v;
722
+ if (auto p = fi->second.props.find("value"); p != fi->second.props.end())
723
+ v = p->second;
724
+ if (v.empty())
725
+ return TRUE;
726
+ // Borra el último carácter UTF-8 completo.
727
+ const gchar *end = v.c_str() + v.size();
728
+ const gchar *prev = g_utf8_find_prev_char(v.c_str(), end);
729
+ g_skia.setValueEmit(fid, std::string(v.c_str(), prev - v.c_str()));
730
+ return TRUE;
731
+ }
732
+ if (keyval == GDK_KEY_Delete || keyval == GDK_KEY_KP_Delete ||
733
+ keyval == GDK_KEY_Left || keyval == GDK_KEY_KP_Left ||
734
+ keyval == GDK_KEY_Right || keyval == GDK_KEY_KP_Right ||
735
+ keyval == GDK_KEY_Home || keyval == GDK_KEY_KP_Home ||
736
+ keyval == GDK_KEY_End || keyval == GDK_KEY_KP_End)
737
+ return TRUE; // el input consume las teclas de caret (fijas al final)
738
+ return FALSE;
739
+ }
740
+
741
+ // ── Gestos fase 1: scroll físico / pan / longPress ────────────────
742
+ // Un GtkGestureDrag único sobre el área decide en drag-begin qué
743
+ // reclama el gesto: pan bindado > slider > scrollable ancestro —
744
+ // paridad con la captura por widget del carril views (la gesture del
745
+ // nodo con handler gana; el scroll nativo cede en slop).
746
+
747
+ static double panSlop() {
748
+ int t = 8;
749
+ g_object_get(gtk_settings_get_default(), "gtk-dnd-drag-threshold", &t,
750
+ nullptr);
751
+ return t;
752
+ }
753
+
754
+ void skiaDragBegin(GtkGestureDrag *, double x, double y, gpointer) {
755
+ auto &d = g_skia.drag_;
756
+ d = {};
757
+ d.ox0 = x;
758
+ d.oy0 = y;
759
+ d.lastT = g_get_monotonic_time();
760
+ int pan = g_skia.tree_.hitTest((float)x, (float)y, "pan");
761
+ if (pan) {
762
+ d.mode = 2;
763
+ d.target = pan;
764
+ } else {
765
+ int hit = g_skia.tree_.nodeAt((float)x, (float)y);
766
+ if (hit) {
767
+ auto it = g_skia.tree_.nodes.find(hit);
768
+ if (it != g_skia.tree_.nodes.end() && it->second.type == "slider") {
769
+ d.mode = 3;
770
+ d.target = hit;
771
+ d.consumed = true;
772
+ float lx = 0, ly = 0;
773
+ g_skia.tree_.pointInNode(hit, (float)x, (float)y, lx, ly);
774
+ float v = g_skia.tree_.sliderSetAt(hit, lx);
775
+ char b1[24], b2[24], buf[160];
776
+ snprintf(buf, sizeof(buf),
777
+ "{\"progress\":%s,\"text\":\"%s\",\"composing\":false}",
778
+ g_ascii_dtostr(b1, sizeof(b1), (double)v),
779
+ g_ascii_dtostr(b2, sizeof(b2), (double)v));
780
+ g_skia.emitBound(hit, "input", buf);
781
+ g_skia.repaint();
782
+ }
783
+ }
784
+ if (!d.mode) {
785
+ int sc = g_skia.tree_.scrollableAt((float)x, (float)y);
786
+ if (sc) {
787
+ d.mode = 1;
788
+ d.target = sc;
789
+ g_skia.stopFling(); // agarrar el contenido corta el fling
790
+ }
791
+ }
792
+ }
793
+ if (getenv("ELUR_DEBUG"))
794
+ g_warning("[drag:skia] begin x=%.0f y=%.0f mode=%d target=%d", x, y, d.mode,
795
+ d.target);
796
+ }
797
+
798
+ void skiaDragUpdate(GtkGestureDrag *, double ox, double oy, gpointer) {
799
+ auto &d = g_skia.drag_;
800
+ if (!d.mode)
801
+ return;
802
+ double px = d.ox0 + ox, py = d.oy0 + oy;
803
+ if (d.mode == 2) {
804
+ // Slop + fases start/move — paridad onPanUpdate del carril views.
805
+ if (!d.panStarted) {
806
+ if (std::hypot(ox, oy) <= panSlop())
807
+ return;
808
+ d.panStarted = true;
809
+ d.consumed = true;
810
+ char b[4][24];
811
+ std::string s = std::string("{\"phase\":\"start\",\"x\":") +
812
+ g_ascii_dtostr(b[0], 24, px) +
813
+ ",\"y\":" + g_ascii_dtostr(b[1], 24, py) +
814
+ ",\"dx\":" + g_ascii_dtostr(b[2], 24, ox) +
815
+ ",\"dy\":" + g_ascii_dtostr(b[3], 24, oy) + "}";
816
+ g_skia.emitBound(d.target, "pan", s);
817
+ }
818
+ char b[4][24];
819
+ std::string m = std::string("{\"phase\":\"move\",\"x\":") +
820
+ g_ascii_dtostr(b[0], 24, px) +
821
+ ",\"y\":" + g_ascii_dtostr(b[1], 24, py) +
822
+ ",\"dx\":" + g_ascii_dtostr(b[2], 24, ox) +
823
+ ",\"dy\":" + g_ascii_dtostr(b[3], 24, oy) + "}";
824
+ g_skia.emitBound(d.target, "pan", m);
825
+ return;
826
+ }
827
+ if (d.mode == 3) {
828
+ float lx = 0, ly = 0;
829
+ g_skia.tree_.pointInNode(d.target, (float)px, (float)py, lx, ly);
830
+ float v = g_skia.tree_.sliderSetAt(d.target, lx);
831
+ char b1[24], b2[24], buf[160];
832
+ snprintf(buf, sizeof(buf),
833
+ "{\"progress\":%s,\"text\":\"%s\",\"composing\":false}",
834
+ g_ascii_dtostr(b1, sizeof(b1), (double)v),
835
+ g_ascii_dtostr(b2, sizeof(b2), (double)v));
836
+ g_skia.emitBound(d.target, "input", buf);
837
+ g_skia.repaint();
838
+ return;
839
+ }
840
+ // Scroll por arrastre (touch-style): el offset del gesto se resta —
841
+ // arrastrar hacia arriba baja el contenido (scrollY crece).
842
+ float incX = (float)ox - d.lx, incY = (float)oy - d.ly;
843
+ d.lx = (float)ox;
844
+ d.ly = (float)oy;
845
+ gint64 now = g_get_monotonic_time();
846
+ double dt = (now - d.lastT) / 1e6;
847
+ d.lastT = now;
848
+ if (dt > 0) {
849
+ // EMA de velocidad para el fling (px/s).
850
+ float ivx = -incX / (float)dt, ivy = -incY / (float)dt;
851
+ d.vx = d.vx * 0.5f + ivx * 0.5f;
852
+ d.vy = d.vy * 0.5f + ivy * 0.5f;
853
+ }
854
+ bool moved = g_skia.tree_.scrollBy(d.target, -incX, -incY);
855
+ if (getenv("ELUR_DEBUG"))
856
+ g_warning("[drag:skia] upd inc=%.0f,%.0f moved=%d maxY=%.0f", incX, incY,
857
+ moved, g_skia.tree_.maxScrollY(d.target));
858
+ if (moved) {
859
+ d.consumed = true;
860
+ g_skia.emitScrollState(d.target);
861
+ g_skia.repaint();
862
+ }
863
+ }
864
+
865
+ gboolean skiaFlingTick(GtkWidget *, GdkFrameClock *clock, gpointer) {
866
+ gint64 now = gdk_frame_clock_get_frame_time(clock);
867
+ double dt = (now - g_skia.flingT_) / 1e6;
868
+ g_skia.flingT_ = now;
869
+ if (dt <= 0 || dt > 0.1)
870
+ dt = 0.016;
871
+ // Fricción exponencial (~OverScroller/DecelerateInterpolator).
872
+ float k = (float)std::exp(-4.0 * dt);
873
+ g_skia.flingVx_ *= k;
874
+ g_skia.flingVy_ *= k;
875
+ if (std::fabs(g_skia.flingVx_) < 12 && std::fabs(g_skia.flingVy_) < 12) {
876
+ g_skia.flingNode_ = 0;
877
+ return G_SOURCE_REMOVE;
878
+ }
879
+ if (!g_skia.tree_.scrollBy(g_skia.flingNode_, g_skia.flingVx_ * (float)dt,
880
+ g_skia.flingVy_ * (float)dt)) {
881
+ g_skia.flingNode_ = 0; // topó el límite — termina
882
+ return G_SOURCE_REMOVE;
883
+ }
884
+ g_skia.emitScrollState(g_skia.flingNode_);
885
+ g_skia.repaint();
886
+ return G_SOURCE_CONTINUE;
887
+ }
888
+
889
+ void skiaDragEnd(GtkGestureDrag *, double ox, double oy, gpointer) {
890
+ auto &d = g_skia.drag_;
891
+ if (d.mode == 2 && d.panStarted) {
892
+ char b[4][24];
893
+ std::string s = std::string("{\"phase\":\"end\",\"x\":") +
894
+ g_ascii_dtostr(b[0], 24, d.ox0 + ox) +
895
+ ",\"y\":" + g_ascii_dtostr(b[1], 24, d.oy0 + oy) +
896
+ ",\"dx\":" + g_ascii_dtostr(b[2], 24, ox) +
897
+ ",\"dy\":" + g_ascii_dtostr(b[3], 24, oy) + "}";
898
+ g_skia.emitBound(d.target, "pan", s);
899
+ } else if (d.mode == 1) {
900
+ // Fling si queda velocidad al soltar (umbral ~ OverScroller).
901
+ float v = std::hypot(d.vx, d.vy);
902
+ if (v > 120.f && d.target) {
903
+ g_skia.flingNode_ = d.target;
904
+ g_skia.flingVx_ = d.vx;
905
+ g_skia.flingVy_ = d.vy;
906
+ g_skia.flingT_ = g_get_monotonic_time();
907
+ gtk_widget_add_tick_callback(g_skia.area_, skiaFlingTick, nullptr,
908
+ nullptr);
909
+ }
910
+ }
911
+ d.mode = 0;
912
+ d.target = 0;
913
+ }
914
+
915
+ void skiaDragCancel(GtkGestureDrag *, GdkEventSequence *, gpointer) {
916
+ auto &d = g_skia.drag_;
917
+ if (d.mode == 2 && d.panStarted) {
918
+ // GTK emite cancel y luego end: cancel cierra el pan (end ignora).
919
+ char b[4][24];
920
+ std::string s = std::string("{\"phase\":\"end\",\"x\":") +
921
+ g_ascii_dtostr(b[0], 24, d.ox0 + d.lx) +
922
+ ",\"y\":" + g_ascii_dtostr(b[1], 24, d.oy0 + d.ly) +
923
+ ",\"dx\":" + g_ascii_dtostr(b[2], 24, (double)d.lx) +
924
+ ",\"dy\":" + g_ascii_dtostr(b[3], 24, (double)d.ly) + "}";
925
+ g_skia.emitBound(d.target, "pan", s);
926
+ }
927
+ d.mode = 0;
928
+ d.target = 0;
929
+ }
930
+
931
+ void skiaLongPressed(GtkGestureLongPress *g, double x, double y, gpointer) {
932
+ int id = g_skia.tree_.hitTest((float)x, (float)y, "longPress");
933
+ if (!id)
934
+ return;
935
+ g_skia.drag_.consumed = true; // el release posterior no es press
936
+ gtk_gesture_set_state(GTK_GESTURE(g), GTK_EVENT_SEQUENCE_CLAIMED);
937
+ g_skia.emitBound(id, "longPress", xyJson(x, y));
938
+ }
939
+
940
+ gboolean skiaWheelScroll(GtkEventControllerScroll *c, double dx, double dy,
941
+ gpointer) {
942
+ GdkEvent *ev =
943
+ gtk_event_controller_get_current_event(GTK_EVENT_CONTROLLER(c));
944
+ if (!ev)
945
+ return FALSE;
946
+ double px = 0, py = 0;
947
+ gdk_event_get_position(ev, &px, &py);
948
+ if (std::isnan(px) || std::isnan(py)) {
949
+ // La rueda sintética (botón X11 4-7 → scroll) viaja sin posición;
950
+ // el puntero real la tiene — el área llena la ventana, así que
951
+ // coords de superficie == coords de área. Se consulta el master
952
+ // pointer del seat: el device del evento es el esclavo XTest y
953
+ // XIQueryPointer sobre él devuelve XI_BadDevice.
954
+ GdkSeat *seat =
955
+ gdk_display_get_default_seat(gtk_widget_get_display(g_skia.area_));
956
+ GdkDevice *dev = seat ? gdk_seat_get_pointer(seat) : nullptr;
957
+ GdkSurface *s = gtk_native_get_surface(gtk_widget_get_native(g_skia.area_));
958
+ GdkModifierType mask;
959
+ if (dev && s)
960
+ gdk_surface_get_device_position(s, dev, &px, &py, &mask);
961
+ }
962
+ int id = g_skia.tree_.scrollableAt((float)px, (float)py);
963
+ if (!id)
964
+ return FALSE;
965
+ // Unidad GdkScroll = detent de rueda ≈ 3 líneas del widget (GTK usa
966
+ // ~potencia de 2 del unit; 40px/detent = ~3×13px de línea GTK).
967
+ g_skia.stopFling();
968
+ if (g_skia.tree_.scrollBy(id, (float)dx * 40.f, (float)dy * 40.f)) {
969
+ g_skia.emitScrollState(id);
970
+ g_skia.repaint();
971
+ }
972
+ return TRUE;
973
+ }
974
+
975
+ } // namespace
976
+
977
+ void SkiaApplicator::init(GtkWidget *surface, const HostOptions &opts,
978
+ HostCallbacks cb) {
979
+ area_ = surface;
980
+ cb_ = std::move(cb);
981
+ bundleDir_ = opts.bundleDir;
982
+ if (const char *d = getenv("ELUR_BUNDLE_DIR"))
983
+ bundleDir_ = d; // escape de depuración
984
+ // fontconfig del proceso ya lleva las fuentes del bundle
985
+ // (registerBundleFonts corrió en activate) — el scanner FreeType
986
+ // debe usar el MISMO FcConfig, no uno nuevo: con nullptr Skia crea
987
+ // una config default y las caras del bundle quedarían invisibles.
988
+ // FcConfigReference transfiere la ref extra — Skia la destruye al
989
+ // morir el mgr sin tumbar la config del proceso.
990
+ FcConfig *fc = FcConfigGetCurrent();
991
+ if (fc)
992
+ FcConfigReference(fc);
993
+ tree_.setFontMgr(SkFontMgr_New_FontConfig(fc, SkFontScanner_Make_FreeType()));
994
+ initFontScale();
995
+
996
+ // Intrínsecos de switch/slider medidos de widgets GTK reales
997
+ // (unrealized — measure resuelve estilo sin realization). Paridad
998
+ // exacta con lo que el carril views informa, sin constantes.
999
+ {
1000
+ GtkWidget *sw = gtk_switch_new();
1001
+ GtkWidget *sl = gtk_scale_new(GTK_ORIENTATION_HORIZONTAL, nullptr);
1002
+ int mn, nw, nh;
1003
+ gtk_widget_measure(sw, GTK_ORIENTATION_HORIZONTAL, -1, &mn, &nw, nullptr,
1004
+ nullptr);
1005
+ gtk_widget_measure(sw, GTK_ORIENTATION_VERTICAL, -1, &mn, &nh, nullptr,
1006
+ nullptr);
1007
+ int lw, lh;
1008
+ gtk_widget_measure(sl, GTK_ORIENTATION_HORIZONTAL, -1, &mn, &lw, nullptr,
1009
+ nullptr);
1010
+ gtk_widget_measure(sl, GTK_ORIENTATION_VERTICAL, -1, &mn, &lh, nullptr,
1011
+ nullptr);
1012
+ tree_.setIntrinsics((float)nw, (float)nh, (float)lw, (float)lh);
1013
+ // Widgets toplevel = floating ref: sink antes del unref.
1014
+ g_object_ref_sink(sw);
1015
+ g_object_unref(sw);
1016
+ g_object_ref_sink(sl);
1017
+ g_object_unref(sl);
1018
+ }
1019
+
1020
+ glBackend_ = opts.skiaBackend == "gl" && GTK_IS_GL_AREA(surface);
1021
+ wireSurface();
1022
+ yoga::init();
1023
+ yoga::setMeasureHook(
1024
+ [](int id, float w, int wMode, float h, int hMode, float &ow, float &oh) {
1025
+ g_skia.tree_.measure(id, w, wMode, h, hMode, ow, oh);
1026
+ });
1027
+ yoga::setBaselineHook(
1028
+ [](int id, float w, float h) { return g_skia.tree_.baseline(id, w, h); });
1029
+ }
1030
+
1031
+ // Cableado común de la superficie — se usa en init y en el fallback
1032
+ // GPU→raster (mismo wiring para GtkDrawingArea y GtkGLArea: gestos,
1033
+ // teclado, IM, a11y y la capa overlay de platform views).
1034
+ void SkiaApplicator::wireSurface() {
1035
+ #if ELUR_SKIA_GL
1036
+ if (glBackend_) {
1037
+ gtk_gl_area_set_auto_render(GTK_GL_AREA(area_), FALSE);
1038
+ g_signal_connect(area_, "render", G_CALLBACK(skiaGlRender), nullptr);
1039
+ g_signal_connect(area_, "unrealize", G_CALLBACK(skiaGlUnrealize), nullptr);
1040
+ g_signal_connect_after(area_, "realize", G_CALLBACK(skiaGlRealize),
1041
+ nullptr);
1042
+ // init corre en idle tras gtk_window_present — si el widget ya está
1043
+ // realized el signal no volverá a emitirse: el check se agenda ya.
1044
+ if (gtk_widget_get_realized(area_))
1045
+ skiaGlRealize(area_, nullptr);
1046
+ } else
1047
+ #endif
1048
+ gtk_drawing_area_set_draw_func(GTK_DRAWING_AREA(area_), skiaDrawFunc,
1049
+ nullptr, nullptr);
1050
+ GtkGesture *g = gtk_gesture_click_new();
1051
+ gtk_gesture_single_set_button(GTK_GESTURE_SINGLE(g), 0);
1052
+ g_signal_connect(g, "released", G_CALLBACK(skiaPressReleased), nullptr);
1053
+ gtk_widget_add_controller(area_, GTK_EVENT_CONTROLLER(g));
1054
+ GtkGesture *dg = gtk_gesture_drag_new();
1055
+ g_signal_connect(dg, "drag-begin", G_CALLBACK(skiaDragBegin), nullptr);
1056
+ g_signal_connect(dg, "drag-update", G_CALLBACK(skiaDragUpdate), nullptr);
1057
+ g_signal_connect(dg, "drag-end", G_CALLBACK(skiaDragEnd), nullptr);
1058
+ g_signal_connect(dg, "cancel", G_CALLBACK(skiaDragCancel), nullptr);
1059
+ gtk_widget_add_controller(area_, GTK_EVENT_CONTROLLER(dg));
1060
+ GtkGesture *lp = gtk_gesture_long_press_new();
1061
+ g_signal_connect(lp, "pressed", G_CALLBACK(skiaLongPressed), nullptr);
1062
+ gtk_widget_add_controller(area_, GTK_EVENT_CONTROLLER(lp));
1063
+ GtkEventController *wh =
1064
+ gtk_event_controller_scroll_new(GTK_EVENT_CONTROLLER_SCROLL_BOTH_AXES);
1065
+ g_signal_connect(wh, "scroll", G_CALLBACK(skiaWheelScroll), nullptr);
1066
+ gtk_widget_add_controller(area_, wh);
1067
+
1068
+ // Teclado + IM (fase 2): el área es la única superficie de teclas —
1069
+ // la cadena Tab y los eventos del nodo enfocado corren por el
1070
+ // controller; el IMContext propio escribe sobre props["value"].
1071
+ gtk_widget_set_focusable(area_, TRUE);
1072
+ GtkEventController *kc = gtk_event_controller_key_new();
1073
+ g_signal_connect(kc, "key-pressed", G_CALLBACK(skiaKeyPressed), nullptr);
1074
+ g_signal_connect(kc, "key-released",
1075
+ G_CALLBACK(+[](GtkEventControllerKey *, guint, guint keycode,
1076
+ GdkModifierType, gpointer) {
1077
+ g_skia.keysDown_.erase(keycode);
1078
+ }),
1079
+ nullptr);
1080
+ gtk_widget_add_controller(area_, kc);
1081
+ g_signal_connect_swapped(area_, "map", G_CALLBACK(gtk_widget_grab_focus),
1082
+ area_);
1083
+ if (!im_) {
1084
+ im_ = gtk_im_multicontext_new();
1085
+ g_signal_connect(im_, "commit", G_CALLBACK(skiaImCommit), nullptr);
1086
+ g_signal_connect(im_, "preedit-start", G_CALLBACK(skiaImPreeditStart),
1087
+ nullptr);
1088
+ g_signal_connect(im_, "preedit-changed", G_CALLBACK(skiaImPreeditChanged),
1089
+ nullptr);
1090
+ g_signal_connect(im_, "preedit-end", G_CALLBACK(skiaImPreeditEnd), nullptr);
1091
+ }
1092
+ gtk_im_context_set_client_widget(im_, area_);
1093
+
1094
+ a11y_.init(area_, &tree_);
1095
+ // Capa de platform views: el GtkOverlay que envuelve el área (las
1096
+ // PV son hijos overlay directos, posicionados por margins — sin
1097
+ // contenedor que absorba el picking). Sin overlay las PV se
1098
+ // declaran gap (warn, nodo ausente — mismo observable que views
1099
+ // sin factory).
1100
+ if (GtkWidget *par = gtk_widget_get_parent(area_); par && GTK_IS_OVERLAY(par))
1101
+ pvLayer_ = par;
1102
+ }
1103
+
1104
+ // Fallback GPU→raster: el GLArea quedó vivo pero sin contexto Ganesh
1105
+ // válido — lo cambio por un ElurSkiaArea dentro del mismo overlay y
1106
+ // re-cableo todo (gestos/teclado/IM/a11y). Los widgets PV del overlay
1107
+ // no se tocan.
1108
+ void SkiaApplicator::fallbackToRaster() {
1109
+ glBackend_ = false;
1110
+ GtkWidget *overlay = gtk_widget_get_parent(area_);
1111
+ GtkWidget *newArea = elur_skia_area_new();
1112
+ if (overlay && GTK_IS_OVERLAY(overlay)) {
1113
+ gtk_overlay_set_child(GTK_OVERLAY(overlay), newArea);
1114
+ }
1115
+ area_ = newArea;
1116
+ focused_ = 0;
1117
+ wireSurface();
1118
+ repaint();
1119
+ }
1120
+
1121
+ void SkiaApplicator::shutdown() {
1122
+ a11y_.shutdown();
1123
+ if (im_) {
1124
+ gtk_im_context_set_client_widget(im_, nullptr);
1125
+ g_object_unref(im_);
1126
+ im_ = nullptr;
1127
+ }
1128
+ if (fontScaleSettings_) {
1129
+ g_object_unref(fontScaleSettings_);
1130
+ fontScaleSettings_ = nullptr;
1131
+ }
1132
+ if (imgCanc_)
1133
+ g_cancellable_cancel(imgCanc_);
1134
+ // Las respuestas canceladas llegan igualmente al finish — el
1135
+ // shutdown no puede desregistrar callbacks de libsoup ya armados,
1136
+ // así que las estructuras sobreviven hasta el cierre del proceso
1137
+ // (paridad con el carril views, que tampoco drena en shutdown).
1138
+ if (soup_)
1139
+ soup_session_abort(soup_);
1140
+ yoga::shutdown();
1141
+ }
1142
+
1143
+ // fontScale (§1.4 — espejo del contrato sp de Android): el fontSize
1144
+ // declarado se multiplica por el factor vigente. Mismo origen que el
1145
+ // carril views: ELUR_FONT_SCALE (dev) → text-scaling-factor de GNOME
1146
+ // con watch → 1.0. Sin esto el carril medía distinto que views en el
1147
+ // mismo escritorio (row wrap falso).
1148
+ void SkiaApplicator::initFontScale() {
1149
+ double s = elurEnvFontScale();
1150
+ if (s <= 0) {
1151
+ GSettingsSchemaSource *src = g_settings_schema_source_get_default();
1152
+ GSettingsSchema *sc = src ? g_settings_schema_source_lookup(
1153
+ src, "org.gnome.desktop.interface", TRUE)
1154
+ : nullptr;
1155
+ if (sc) {
1156
+ fontScaleSettings_ = g_settings_new("org.gnome.desktop.interface");
1157
+ g_settings_schema_unref(sc);
1158
+ s = g_settings_get_double(fontScaleSettings_, "text-scaling-factor");
1159
+ g_signal_connect(fontScaleSettings_, "changed::text-scaling-factor",
1160
+ G_CALLBACK(+[](GSettings *gs, const char *, gpointer) {
1161
+ double v =
1162
+ g_settings_get_double(gs, "text-scaling-factor");
1163
+ if (v > 0)
1164
+ g_skia.applyFontScale(v);
1165
+ }),
1166
+ nullptr);
1167
+ }
1168
+ }
1169
+ tree_.setFontScale(s > 0 ? s : 1.0);
1170
+ }
1171
+
1172
+ // Re-aplica un factor nuevo: las hojas remiden con la fuente escalada
1173
+ // y relayout — mismo efecto que Applicator::applyFontScale en views.
1174
+ void SkiaApplicator::applyFontScale(double s) {
1175
+ if (s <= 0)
1176
+ return;
1177
+ tree_.setFontScale(s);
1178
+ yoga::markAllLeavesDirty();
1179
+ relayout();
1180
+ }
1181
+
1182
+ void SkiaApplicator::stopFling() { flingNode_ = 0; }
1183
+
1184
+ // image src local → GdkTexture (loaders GTK4: PNG/JPEG/WebP) →
1185
+ // píxeles RGBA-premul → SkImage raster. Remoto/data: queda al
1186
+ // pipeline ImageService (fase 2 — warn explícito, nunca silencio).
1187
+ // Cotas del pipeline de imagen — mismas constantes que el carril
1188
+ // views (ADR-0071): fetch deduplicado por src, cache LRU acotado por
1189
+ // bytes, entrega sin cachear cuando la presión live supera el
1190
+ // presupuesto. Decode siempre por loaders GTK4 (la lib no enlaza
1191
+ // SkCodec) → RGBA premul → bitmap inmutable.
1192
+ static constexpr int IMG_MAX_BYTES = 16 * 1024 * 1024;
1193
+ static constexpr long IMG_MAX_CACHE = 16L * 1024 * 1024;
1194
+ static constexpr long IMG_MAX_LIVE = 64L * 1024 * 1024;
1195
+ static constexpr int IMG_MAX_WAITERS = 64;
1196
+
1197
+ static sk_sp<SkImage> texToImage(GdkTexture *tex) {
1198
+ GdkTextureDownloader *dl = gdk_texture_downloader_new(tex);
1199
+ gdk_texture_downloader_set_format(dl, GDK_MEMORY_R8G8B8A8_PREMULTIPLIED);
1200
+ gsize stride = 0;
1201
+ GBytes *bytes = gdk_texture_downloader_download_bytes(dl, &stride);
1202
+ gdk_texture_downloader_free(dl);
1203
+ int w = gdk_texture_get_width(tex), h = gdk_texture_get_height(tex);
1204
+ if (!bytes)
1205
+ return nullptr;
1206
+ gsize len = 0;
1207
+ const void *px = g_bytes_get_data(bytes, &len);
1208
+ SkImageInfo info =
1209
+ SkImageInfo::Make(w, h, kRGBA_8888_SkColorType, kPremul_SkAlphaType);
1210
+ // El bitmap posee su buffer (allocPixels copia por filas — respeta
1211
+ // el stride del downloader) — asImage comparte sin depender de
1212
+ // SkImages.h ni de la vida del GBytes.
1213
+ SkBitmap bmp;
1214
+ bmp.allocPixels(info);
1215
+ if (getenv("ELUR_DEBUG"))
1216
+ g_warning("[image:skia] texToImage %dx%d stride=%zu len=%zu need=%zu", w, h,
1217
+ stride, len, (size_t)h * stride);
1218
+ if (stride && (size_t)len >= (size_t)h * stride) {
1219
+ for (int r = 0; r < h; r++)
1220
+ memcpy((char *)bmp.getPixels() + r * bmp.rowBytes(),
1221
+ (const char *)px + r * stride, (size_t)w * 4);
1222
+ } else {
1223
+ bmp.eraseColor(SK_ColorTRANSPARENT);
1224
+ }
1225
+ bmp.setImmutable();
1226
+ g_bytes_unref(bytes);
1227
+ return bmp.asImage();
1228
+ }
1229
+
1230
+ void SkiaApplicator::imgDropWaiter(int nodeId) {
1231
+ for (auto &kv : imgInFlight_)
1232
+ kv.second.erase(std::remove(kv.second.begin(), kv.second.end(), nodeId),
1233
+ kv.second.end());
1234
+ }
1235
+
1236
+ void SkiaApplicator::imgDeliver(const std::string &src, sk_sp<SkImage> img,
1237
+ int bytes) {
1238
+ std::vector<int> waiters;
1239
+ auto it = imgInFlight_.find(src);
1240
+ if (it != imgInFlight_.end()) {
1241
+ waiters = std::move(it->second);
1242
+ imgInFlight_.erase(it);
1243
+ }
1244
+ if (img && imgLiveBytes_ <= IMG_MAX_LIVE) {
1245
+ auto old = imgCache_.find(src);
1246
+ if (old != imgCache_.end()) {
1247
+ imgCacheBytes_ -= old->second.bytes;
1248
+ imgLru_.erase(old->second.lru);
1249
+ imgCache_.erase(old);
1250
+ }
1251
+ ImgEnt e;
1252
+ e.img = img; // copia — los waiters de abajo reciben el mismo sk_sp
1253
+ e.bytes = bytes;
1254
+ imgLru_.push_front(src);
1255
+ e.lru = imgLru_.begin();
1256
+ imgCache_[src] = e;
1257
+ imgCacheBytes_ += bytes;
1258
+ while (imgCacheBytes_ > IMG_MAX_CACHE && !imgLru_.empty()) {
1259
+ const std::string &k = imgLru_.back();
1260
+ auto eit = imgCache_.find(k);
1261
+ if (eit != imgCache_.end()) {
1262
+ imgCacheBytes_ -= eit->second.bytes;
1263
+ imgCache_.erase(eit);
1264
+ }
1265
+ imgLru_.pop_back();
1266
+ }
1267
+ }
1268
+ for (int id : waiters) {
1269
+ auto si = imgSrc_.find(id);
1270
+ if (si == imgSrc_.end() || si->second != src) {
1271
+ if (getenv("ELUR_DEBUG"))
1272
+ g_warning("[image:skia] waiter %d caducó (src=%s)", id,
1273
+ si == imgSrc_.end() ? "-" : si->second.c_str());
1274
+ continue; // rebind/delete supersede — el waiter caducó
1275
+ }
1276
+ auto ni = tree_.nodes.find(id);
1277
+ if (ni == tree_.nodes.end())
1278
+ continue;
1279
+ if (getenv("ELUR_DEBUG"))
1280
+ g_warning("[image:skia] aplica id=%d type=%s hasRect=%d %gx%g", id,
1281
+ ni->second.type.c_str(), (int)ni->second.hasRect, ni->second.rw,
1282
+ ni->second.rh);
1283
+ imgLiveBytes_ -= imgBytes_[id];
1284
+ imgBytes_[id] = img ? bytes : 0;
1285
+ imgLiveBytes_ += imgBytes_[id];
1286
+ tree_.setImage(id, img);
1287
+ yoga::nodeSetText(id); // el natural de la imagen remide la hoja
1288
+ relayout();
1289
+ repaint();
1290
+ }
1291
+ }
1292
+
1293
+ struct SkiaImgFetch {
1294
+ std::string src;
1295
+ SoupMessage *msg;
1296
+ };
1297
+
1298
+ static void skiaOnImgFetched(GObject *, GAsyncResult *res, gpointer d) {
1299
+ SkiaImgFetch *c = static_cast<SkiaImgFetch *>(d);
1300
+ GError *err = nullptr;
1301
+ GBytes *body = soup_session_send_and_read_finish(g_skia.soup_, res, &err);
1302
+ sk_sp<SkImage> img;
1303
+ int bytes = 0;
1304
+ if (!err && body && g_bytes_get_size(body) <= (gsize)IMG_MAX_BYTES &&
1305
+ soup_message_get_status(c->msg) == SOUP_STATUS_OK) {
1306
+ GdkTexture *tex = gdk_texture_new_from_bytes(body, nullptr);
1307
+ if (tex) {
1308
+ img = texToImage(tex);
1309
+ bytes = gdk_texture_get_width(tex) * gdk_texture_get_height(tex) * 4;
1310
+ g_object_unref(tex);
1311
+ } else if (getenv("ELUR_DEBUG"))
1312
+ g_warning("[image:skia] decode falló");
1313
+ } else if (getenv("ELUR_DEBUG"))
1314
+ g_warning("[image:skia] fetch falló: %s (status %u) %s",
1315
+ err ? err->message : "?", soup_message_get_status(c->msg),
1316
+ c->src.c_str());
1317
+ if (getenv("ELUR_DEBUG"))
1318
+ g_warning("[image:skia] deliver %s img=%d bytes=%d", c->src.c_str(),
1319
+ img != nullptr, bytes);
1320
+ g_skia.imgDeliver(c->src, img, bytes);
1321
+ if (body)
1322
+ g_bytes_unref(body);
1323
+ if (err)
1324
+ g_error_free(err);
1325
+ g_object_unref(c->msg);
1326
+ delete c;
1327
+ }
1328
+
1329
+ void SkiaApplicator::loadImage(int id, const std::string &src) {
1330
+ auto si = imgSrc_.find(id);
1331
+ const std::string prev = si == imgSrc_.end() ? "" : si->second;
1332
+ if (getenv("ELUR_DEBUG"))
1333
+ g_warning("[image:skia] loadImage id=%d prev=%s src=%s", id, prev.c_str(),
1334
+ src.c_str());
1335
+ if (prev == src)
1336
+ return;
1337
+ // Rebind: supersede — fuera de waiters previos y descuenta lo que
1338
+ // el nodo retenía del src anterior.
1339
+ imgDropWaiter(id);
1340
+ imgLiveBytes_ -= imgBytes_[id];
1341
+ imgBytes_[id] = 0;
1342
+ imgSrc_[id] = src;
1343
+ tree_.setImage(id, nullptr);
1344
+ if (src.empty())
1345
+ return;
1346
+
1347
+ if (src.rfind("data:", 0) == 0) {
1348
+ // Estimación previa (3B/4chars base64): un data: enorme se
1349
+ // rechaza sin decodificar un byte (ADR-0071).
1350
+ size_t comma = src.find(',');
1351
+ long est = comma == std::string::npos
1352
+ ? 0
1353
+ : (long)((src.size() - comma - 1) * 3 / 4);
1354
+ if (est > 0 && est <= IMG_MAX_BYTES) {
1355
+ gsize outLen = 0;
1356
+ guchar *raw = g_base64_decode(src.c_str() + comma + 1, &outLen);
1357
+ if (raw && outLen <= (gsize)IMG_MAX_BYTES) {
1358
+ GBytes *gb = g_bytes_new_take(raw, outLen);
1359
+ GdkTexture *tex = gdk_texture_new_from_bytes(gb, nullptr);
1360
+ g_bytes_unref(gb);
1361
+ if (tex) {
1362
+ sk_sp<SkImage> img = texToImage(tex);
1363
+ int bytes =
1364
+ gdk_texture_get_width(tex) * gdk_texture_get_height(tex) * 4;
1365
+ g_object_unref(tex);
1366
+ imgBytes_[id] = bytes;
1367
+ imgLiveBytes_ += bytes;
1368
+ tree_.setImage(id, img);
1369
+ yoga::nodeSetText(id);
1370
+ relayout();
1371
+ repaint();
1372
+ return;
1373
+ }
1374
+ g_warning("[image:skia] data: decode falló");
1375
+ } else {
1376
+ g_free(raw);
1377
+ }
1378
+ } else if (est > IMG_MAX_BYTES && getenv("ELUR_DEBUG"))
1379
+ g_warning("[image:skia] data: over %dB", IMG_MAX_BYTES);
1380
+ return;
1381
+ }
1382
+
1383
+ if (src.rfind("http", 0) == 0) {
1384
+ auto ci = imgCache_.find(src);
1385
+ if (ci != imgCache_.end()) {
1386
+ imgLru_.splice(imgLru_.begin(), imgLru_, ci->second.lru);
1387
+ imgBytes_[id] = ci->second.bytes;
1388
+ imgLiveBytes_ += ci->second.bytes;
1389
+ tree_.setImage(id, ci->second.img);
1390
+ yoga::nodeSetText(id);
1391
+ relayout();
1392
+ repaint();
1393
+ return;
1394
+ }
1395
+ auto &waiters = imgInFlight_[src];
1396
+ for (int wid : waiters)
1397
+ if (wid == id)
1398
+ return;
1399
+ if ((int)waiters.size() >= IMG_MAX_WAITERS)
1400
+ return; // overflow — el próximo bind reintenta
1401
+ waiters.push_back(id);
1402
+ if (waiters.size() > 1)
1403
+ return; // fetch ya en vuelo para este src
1404
+ if (!soup_)
1405
+ soup_ = soup_session_new();
1406
+ if (!imgCanc_)
1407
+ imgCanc_ = g_cancellable_new();
1408
+ SoupMessage *msg = soup_message_new("GET", src.c_str());
1409
+ if (!msg) {
1410
+ waiters.pop_back();
1411
+ imgDeliver(src, nullptr, 0);
1412
+ return;
1413
+ }
1414
+ auto *ctx = new SkiaImgFetch{src, msg};
1415
+ soup_session_send_and_read_async(soup_, msg, G_PRIORITY_DEFAULT, imgCanc_,
1416
+ skiaOnImgFetched, ctx);
1417
+ return;
1418
+ }
1419
+
1420
+ // Local: CWD-relativo — paridad exacta con gtk_picture_set_filename
1421
+ // del carril views (en Android el mismo src es asset del bundle).
1422
+ GFile *f = g_file_new_for_path(src.c_str());
1423
+ GdkTexture *tex = gdk_texture_new_from_file(f, nullptr);
1424
+ g_object_unref(f);
1425
+ if (!tex) {
1426
+ warnOnce(unknownProps_, "image", src);
1427
+ return;
1428
+ }
1429
+ sk_sp<SkImage> img = texToImage(tex);
1430
+ int bytes = gdk_texture_get_width(tex) * gdk_texture_get_height(tex) * 4;
1431
+ g_object_unref(tex);
1432
+ if (!img) {
1433
+ warnOnce(unknownProps_, "image", "download falló: " + src);
1434
+ return;
1435
+ }
1436
+ imgBytes_[id] = bytes;
1437
+ imgLiveBytes_ += bytes;
1438
+ tree_.setImage(id, img);
1439
+ yoga::nodeSetText(id); // el natural de la imagen remide la hoja
1440
+ relayout();
1441
+ repaint();
1442
+ }
1443
+
1444
+ void SkiaApplicator::warnOnce(std::unordered_map<std::string, int> &m,
1445
+ const char *kind, const std::string &what) {
1446
+ int &c = m[what];
1447
+ c++;
1448
+ if (c == 1)
1449
+ g_warning("[elur-linux:skia] %s sin soporte aún: %s", kind, what.c_str());
1450
+ }
1451
+
1452
+ void SkiaApplicator::setViewport(int w, int h) {
1453
+ vpW_ = w;
1454
+ vpH_ = h;
1455
+ yoga::setViewport((float)w, (float)h, rtl_);
1456
+ relayout();
1457
+ if (!densityReported_) {
1458
+ densityReported_ = true;
1459
+ cb_.callHandlerStr("onDensity", "1");
1460
+ }
1461
+ if (h > 0) {
1462
+ char buf[32];
1463
+ snprintf(buf, sizeof(buf), "%d", h);
1464
+ cb_.callHandlerStr("onViewportResize", buf);
1465
+ }
1466
+ }
1467
+
1468
+ void SkiaApplicator::setRtl(bool rtl) {
1469
+ rtl_ = rtl;
1470
+ tree_.setRtl(rtl);
1471
+ yoga::setViewport((float)vpW_, (float)vpH_, rtl);
1472
+ }
1473
+
1474
+ void SkiaApplicator::relayout() {
1475
+ int n = yoga::layoutIfDirty([](int id, float x, float y, float w, float h) {
1476
+ g_skia.tree_.setRect(id, x, y, w, h);
1477
+ });
1478
+ if (n > 0 && area_)
1479
+ repaint();
1480
+ if (n > 0)
1481
+ syncPv();
1482
+ if (n > 0 && focused_)
1483
+ imCursor(); // el rect del input movió — el popup lo sigue
1484
+ if (trace_ && n > 0)
1485
+ yoga::dumpRects(stderr);
1486
+ }
1487
+
1488
+ void SkiaApplicator::applyFrame(JSContext *ctx, JSValueConst v) {
1489
+ JSValue ops = jsGet(ctx, v, "ops");
1490
+ if (!JS_IsArray(ops)) {
1491
+ JS_FreeValue(ctx, ops);
1492
+ return;
1493
+ }
1494
+ int64_t len = 0;
1495
+ JS_GetLength(ctx, ops, &len);
1496
+
1497
+ for (int64_t i = 0; i < len; i++) {
1498
+ JSValue op = JS_GetPropertyInt64(ctx, ops, i);
1499
+ std::string name = jsGetStr(ctx, op, "op");
1500
+ int id = jsInt(ctx, op, "id");
1501
+ if (getenv("ELUR_DEBUG"))
1502
+ g_warning("[op:skia] %s id=%d p=%d c=%d i=%d", name.c_str(), id,
1503
+ jsInt(ctx, op, "parentId"), jsInt(ctx, op, "childId"),
1504
+ jsInt(ctx, op, "index"));
1505
+
1506
+ if (name == "create-node") {
1507
+ std::string type = jsGetStr(ctx, op, "type");
1508
+ tree_.createNode(id, type);
1509
+ a11y_.add(id);
1510
+ yoga::nodeCreate(id, type);
1511
+ // Tipos del vocabulario fuera del set pintado en fase 0-1.
1512
+ static const std::unordered_set<std::string> known = {
1513
+ "view", "column", "row", "text", "button",
1514
+ "image", "scroll", "scroll-view", "shell", "screen",
1515
+ "text-input", "switch", "slider"};
1516
+ if (!known.count(type))
1517
+ warnOnce(unknownTypes_, "tipo", type);
1518
+ } else if (name == "update-text") {
1519
+ tree_.updateText(id, jsGetStr(ctx, op, "value"));
1520
+ a11y_.textChanged(id);
1521
+ yoga::nodeSetText(id);
1522
+ } else if (name == "update-style") {
1523
+ JSValue st = jsGet(ctx, op, "style");
1524
+ JSPropertyEnum *tab = nullptr;
1525
+ uint32_t n = 0;
1526
+ if (JS_GetOwnPropertyNames(ctx, &tab, &n, st,
1527
+ JS_GPN_STRING_MASK | JS_GPN_ENUM_ONLY) == 0) {
1528
+ for (uint32_t k = 0; k < n; k++) {
1529
+ JSValue key = JS_AtomToValue(ctx, tab[k].atom);
1530
+ JSValue val = JS_GetProperty(ctx, st, tab[k].atom);
1531
+ std::string ks = jsStr(ctx, key);
1532
+ bool isNum = JS_IsNumber(val);
1533
+ double d = 0;
1534
+ std::string vs;
1535
+ if (isNum)
1536
+ JS_ToFloat64(ctx, &d, val);
1537
+ else
1538
+ vs = jsStr(ctx, val);
1539
+ yoga::nodeSetStyle(id, ks, isNum, d, vs);
1540
+ // El alias familia-declarada→familia-real lo sirve el target
1541
+ // (elur_fonts), no fontconfig — igual que el path Pango.
1542
+ if (ks == "fontFamily")
1543
+ vs = elur::fonts::resolveStack(vs);
1544
+ // Sin warn de clave desconocida — paridad con el aplicador
1545
+ // views: las no-visuales las resuelve la tabla Yoga y las
1546
+ // ajenas se ignoran igual en ambos renderers.
1547
+ tree_.setStyle(id, ks, isNum, d, vs);
1548
+ JS_FreeValue(ctx, val);
1549
+ JS_FreeValue(ctx, key);
1550
+ }
1551
+ JS_FreePropertyEnum(ctx, tab, n);
1552
+ }
1553
+ JS_FreeValue(ctx, st);
1554
+ } else if (name == "update-props" || name == "update-platform-view-props") {
1555
+ JSValue pr = jsGet(ctx, op, "changedProps");
1556
+ JSPropertyEnum *tab = nullptr;
1557
+ uint32_t n = 0;
1558
+ if (JS_GetOwnPropertyNames(ctx, &tab, &n, pr,
1559
+ JS_GPN_STRING_MASK | JS_GPN_ENUM_ONLY) == 0) {
1560
+ for (uint32_t k = 0; k < n; k++) {
1561
+ JSValue key = JS_AtomToValue(ctx, tab[k].atom);
1562
+ JSValue val = JS_GetProperty(ctx, pr, tab[k].atom);
1563
+ std::string ks = jsStr(ctx, key);
1564
+ if (auto pw = pvWidgets_.find(id);
1565
+ pw != pvWidgets_.end() && (ks == "enabled" || ks == "disabled")) {
1566
+ gtk_widget_set_sensitive(pw->second, ks == "enabled"
1567
+ ? JS_ToBool(ctx, val)
1568
+ : !JS_ToBool(ctx, val));
1569
+ }
1570
+ if (ks == "shell" || ks == "activeTab") {
1571
+ // Cromo móvil sin equivalente desktop (ADR-0177) — warn
1572
+ // explícito como el carril views, no tragar en silencio.
1573
+ auto ti = tree_.nodes.find(id);
1574
+ warnOnce(unknownProps_, "prop-pendiente",
1575
+ ks + "@" +
1576
+ (ti != tree_.nodes.end() ? ti->second.type : "?"));
1577
+ }
1578
+ if (JS_IsString(val)) {
1579
+ tree_.setProp(id, ks, jsStr(ctx, val));
1580
+ } else if (JS_IsNumber(val)) {
1581
+ double d = 0;
1582
+ JS_ToFloat64(ctx, &d, val);
1583
+ char b[40];
1584
+ snprintf(b, sizeof(b), "%.10g", d);
1585
+ tree_.setProp(id, ks, b);
1586
+ } else if (JS_IsBool(val)) {
1587
+ tree_.setProp(id, ks, JS_ToBool(ctx, val) ? "true" : "false");
1588
+ } else if (JS_IsNull(val) || JS_IsUndefined(val)) {
1589
+ tree_.setProp(id, ks, "");
1590
+ } else {
1591
+ // Objetos/arrays (spans, stateStyle, animate…) — fases
1592
+ // posteriores; warn-once como el aplicador de views.
1593
+ warnOnce(unknownProps_, "prop", ks);
1594
+ }
1595
+ if (ks == "value")
1596
+ yoga::nodeSetText(id); // value programático remide la hoja
1597
+ if (ks == "dir") {
1598
+ auto ni = tree_.nodes.find(id);
1599
+ yoga::nodeSetDir(id, ni != tree_.nodes.end() &&
1600
+ ni->second.props["dir"] == "rtl");
1601
+ }
1602
+ if (ks == "as")
1603
+ a11y_.applyAs(id, jsStr(ctx, val));
1604
+ if (ks == "src") {
1605
+ auto ni = tree_.nodes.find(id);
1606
+ if (ni != tree_.nodes.end() && ni->second.type == "image")
1607
+ loadImage(id, jsStr(ctx, val));
1608
+ }
1609
+ JS_FreeValue(ctx, val);
1610
+ JS_FreeValue(ctx, key);
1611
+ }
1612
+ JS_FreePropertyEnum(ctx, tab, n);
1613
+ }
1614
+ JS_FreeValue(ctx, pr);
1615
+ } else if (name == "insert-child") {
1616
+ int parentId = jsInt(ctx, op, "parentId");
1617
+ int childId = jsInt(ctx, op, "childId");
1618
+ int index = jsInt(ctx, op, "index");
1619
+ a11y_.childUnlinked(childId); // reparent: REMOVED del padre previo
1620
+ tree_.insertChild(parentId, childId, index);
1621
+ a11y_.childLinked(childId);
1622
+ yoga::nodeInsert(parentId, childId, index);
1623
+ if (auto pw = pvWidgets_.find(childId); pw != pvWidgets_.end())
1624
+ gtk_widget_set_visible(pw->second, TRUE);
1625
+ } else if (name == "remove-child") {
1626
+ int parentId = jsInt(ctx, op, "parentId");
1627
+ int childId = jsInt(ctx, op, "childId");
1628
+ a11y_.childUnlinked(childId); // REMOVED con el padre aún intacto
1629
+ tree_.removeChild(parentId, childId);
1630
+ yoga::nodeRemove(parentId, childId);
1631
+ if (auto pw = pvWidgets_.find(childId); pw != pvWidgets_.end())
1632
+ gtk_widget_set_visible(pw->second, FALSE);
1633
+ } else if (name == "move-child") {
1634
+ int parentId = jsInt(ctx, op, "parentId");
1635
+ int childId = jsInt(ctx, op, "childId");
1636
+ int index = jsInt(ctx, op, "index");
1637
+ tree_.moveChild(parentId, childId, index);
1638
+ a11y_.childLinked(childId);
1639
+ yoga::nodeMove(parentId, childId, index);
1640
+ } else if (name == "delete-node") {
1641
+ imgDropWaiter(id);
1642
+ imgLiveBytes_ -= imgBytes_[id];
1643
+ imgBytes_.erase(id);
1644
+ imgSrc_.erase(id);
1645
+ if (auto pw = pvWidgets_.find(id); pw != pvWidgets_.end()) {
1646
+ gtk_widget_unparent(pw->second);
1647
+ g_object_unref(pw->second);
1648
+ pvWidgets_.erase(pw);
1649
+ }
1650
+ a11y_.remove(id); // antes de deleteNode — el subárbol aún intacto
1651
+ tree_.deleteNode(id);
1652
+ if (focused_ && !tree_.nodes.count(focused_)) {
1653
+ // El foco muere con el subárbol — no hay blur (el bind se fue).
1654
+ focused_ = 0;
1655
+ tree_.focusedId = 0;
1656
+ if (im_) {
1657
+ gtk_im_context_focus_out(im_);
1658
+ gtk_im_context_reset(im_);
1659
+ imComposing_ = false;
1660
+ }
1661
+ }
1662
+ yoga::nodeDelete(id);
1663
+ } else if (name == "attach-event") {
1664
+ std::string evName = jsGetStr(ctx, op, "event");
1665
+ tree_.attachEvent(id, evName, jsGetStr(ctx, op, "handler"),
1666
+ jsGetStr(ctx, op, "class") == "continuous",
1667
+ jsGetStr(ctx, op, "payload"));
1668
+ if (evName == "shortcut") {
1669
+ // El combo canónico viaja en el payload del attach (ADR-0179).
1670
+ modules::Json p;
1671
+ const modules::Json *c =
1672
+ modules::jsonParse(jsGetStr(ctx, op, "payload"), p) ? p.get("combo")
1673
+ : nullptr;
1674
+ std::string combo = c ? c->asStr() : "";
1675
+ if (!combo.empty()) {
1676
+ hotkeys_.erase(
1677
+ std::remove_if(hotkeys_.begin(), hotkeys_.end(),
1678
+ [id](auto &h) { return h.first == id; }),
1679
+ hotkeys_.end());
1680
+ hotkeys_.push_back({id, combo});
1681
+ }
1682
+ }
1683
+ } else if (name == "detach-event") {
1684
+ std::string evName = jsGetStr(ctx, op, "event");
1685
+ tree_.detachEvent(id, evName);
1686
+ if (evName == "shortcut")
1687
+ hotkeys_.erase(std::remove_if(hotkeys_.begin(), hotkeys_.end(),
1688
+ [id](auto &h) { return h.first == id; }),
1689
+ hotkeys_.end());
1690
+ } else if (name == "reset-node") {
1691
+ tree_.resetNode(id);
1692
+ } else if (name == "nav-push" || name == "nav-pop" ||
1693
+ name == "nav-replace") {
1694
+ // Sin animación de transición bajo el carril árbol (fase
1695
+ // posterior): el contenido llega igual por create/insert/delete
1696
+ // — la op nav-* solo declara la navegación.
1697
+ } else if (name == "create-platform-view") {
1698
+ JSValue props = jsGet(ctx, op, "props");
1699
+ createPlatformView(id, jsGetStr(ctx, op, "module"),
1700
+ jsGetStr(ctx, op, "view"), ctx, props);
1701
+ JS_FreeValue(ctx, props);
1702
+ } else if (name == "set-platform-view-visible") {
1703
+ auto it = pvWidgets_.find(id);
1704
+ if (it != pvWidgets_.end()) {
1705
+ JSValue vis = jsGet(ctx, op, "visible");
1706
+ gtk_widget_set_visible(it->second, JS_ToBool(ctx, vis));
1707
+ JS_FreeValue(ctx, vis);
1708
+ }
1709
+ } else if (name == "update-semantics") {
1710
+ // Fase 2: materializa en el árbol AT-SPI virtual — mismo
1711
+ // vocabulario que el carril views (ADR-0117).
1712
+ JSValue sem = jsGet(ctx, op, "semantics");
1713
+ JSPropertyEnum *tab = nullptr;
1714
+ uint32_t cnt = 0;
1715
+ if (JS_GetOwnPropertyNames(ctx, &tab, &cnt, sem,
1716
+ JS_GPN_STRING_MASK | JS_GPN_ENUM_ONLY) == 0) {
1717
+ for (uint32_t k = 0; k < cnt; k++) {
1718
+ JSValue kv = JS_GetProperty(ctx, sem, tab[k].atom);
1719
+ JSValue kk = JS_AtomToValue(ctx, tab[k].atom);
1720
+ std::string key = jsStr(ctx, kk);
1721
+ bool isNull = JS_IsNull(kv) || JS_IsUndefined(kv);
1722
+ double num = 0;
1723
+ JS_ToFloat64(ctx, &num, kv);
1724
+ a11y_.apply(id, key, isNull, jsStr(ctx, kv), num, JS_ToBool(ctx, kv));
1725
+ JS_FreeValue(ctx, kv);
1726
+ JS_FreeValue(ctx, kk);
1727
+ }
1728
+ JS_FreePropertyEnum(ctx, tab, cnt);
1729
+ }
1730
+ JS_FreeValue(ctx, sem);
1731
+ } else {
1732
+ // list-*/layout/batch-update — fases posteriores del carril
1733
+ // Skia; warn-once explícito.
1734
+ warnOnce(unknownOps_, "op", name);
1735
+ }
1736
+ JS_FreeValue(ctx, op);
1737
+ }
1738
+ JS_FreeValue(ctx, ops);
1739
+
1740
+ relayout();
1741
+ int frame = jsInt(ctx, v, "frame");
1742
+ char fbuf[32];
1743
+ snprintf(fbuf, sizeof(fbuf), "%d", frame);
1744
+ cb_.callHandlerStr("__elur_commit_ack", fbuf);
1745
+ }
1746
+
1747
+ HostRenderer *skiaHostRenderer() { return &g_skia; }
1748
+
1749
+ bool skiaAvailable() { return true; }
1750
+
1751
+ } // namespace elur
1752
+
1753
+ #if ELUR_SKIA_GL
1754
+ // Con skia_use_epoxy_egl la lib no compila un GrGLMakeNativeInterface
1755
+ // — GrGLGpu lo referencia igualmente (MakeGL sin iface). Se define a
1756
+ // nivel global (linkage externo) delegando a epoxy: resuelve EGL/GLX
1757
+ // según el contexto vigente en el thread.
1758
+ sk_sp<const GrGLInterface> GrGLMakeNativeInterface() {
1759
+ return GrGLInterfaces::MakeEpoxyEGL();
1760
+ }
1761
+ #endif
1762
+
1763
+ #else // !ELUR_HAS_SKIA
1764
+
1765
+ namespace elur {
1766
+ HostRenderer *skiaHostRenderer() { return nullptr; }
1767
+ bool skiaAvailable() { return false; }
1768
+ } // namespace elur
1769
+
1770
+ #endif // ELUR_HAS_SKIA