basalt-win32 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/LICENSE +21 -0
  2. package/cli/runWindows.js +35 -0
  3. package/cli/shared.js +75 -0
  4. package/native/CMakeLists.txt +429 -0
  5. package/native/tests/test_win32_accessibility.cpp +585 -0
  6. package/native/tests/test_win32_animated_image.cpp +351 -0
  7. package/native/tests/test_win32_clipboard.cpp +121 -0
  8. package/native/tests/test_win32_focus.cpp +195 -0
  9. package/native/tests/test_win32_hittest.cpp +750 -0
  10. package/native/tests/test_win32_image.cpp +370 -0
  11. package/native/tests/test_win32_imageloader.cpp +208 -0
  12. package/native/tests/test_win32_input.cpp +511 -0
  13. package/native/tests/test_win32_key_events.cpp +84 -0
  14. package/native/tests/test_win32_mounting.cpp +757 -0
  15. package/native/tests/test_win32_paint.cpp +1799 -0
  16. package/native/tests/test_win32_scrollview.cpp +647 -0
  17. package/native/tests/test_win32_selection.cpp +215 -0
  18. package/native/tests/test_win32_text.cpp +1456 -0
  19. package/native/tests/test_win32_textinput.cpp +1594 -0
  20. package/native/tests/test_win32_titlebar.cpp +111 -0
  21. package/native/tests/test_win32_titlebar_actions.cpp +62 -0
  22. package/native/tests/test_win32_view.cpp +222 -0
  23. package/native/win32/ColorSchemeWin32.cpp +56 -0
  24. package/native/win32/ComponentRegistryWin32.cpp +156 -0
  25. package/native/win32/DirectWriteLayout.cpp +485 -0
  26. package/native/win32/DirectWriteLayout.h +77 -0
  27. package/native/win32/DirectWriteLayoutManager.cpp +154 -0
  28. package/native/win32/FontRegistryDirectWrite.cpp +117 -0
  29. package/native/win32/PlatformServicesWin32.cpp +744 -0
  30. package/native/win32/RnWin32Accessible.cpp +343 -0
  31. package/native/win32/RnWin32Accessible.h +130 -0
  32. package/native/win32/RnWin32Image.cpp +588 -0
  33. package/native/win32/RnWin32Image.h +139 -0
  34. package/native/win32/RnWin32TextLayout.cpp +1379 -0
  35. package/native/win32/RnWin32TextLayout.h +390 -0
  36. package/native/win32/RnWin32View.cpp +2956 -0
  37. package/native/win32/RnWin32View.h +926 -0
  38. package/native/win32/Win32AnimationChoreographer.cpp +76 -0
  39. package/native/win32/Win32AnimationChoreographer.h +61 -0
  40. package/native/win32/Win32Clip.h +209 -0
  41. package/native/win32/Win32Cursors.cpp +309 -0
  42. package/native/win32/Win32Cursors.h +121 -0
  43. package/native/win32/Win32DropTarget.cpp +567 -0
  44. package/native/win32/Win32DropTarget.h +42 -0
  45. package/native/win32/Win32Focus.cpp +262 -0
  46. package/native/win32/Win32Focus.h +109 -0
  47. package/native/win32/Win32ImageLoader.cpp +199 -0
  48. package/native/win32/Win32ImageLoader.h +133 -0
  49. package/native/win32/Win32InputScopes.h +92 -0
  50. package/native/win32/Win32KeyEvents.cpp +126 -0
  51. package/native/win32/Win32KeyEvents.h +20 -0
  52. package/native/win32/Win32MenuBar.cpp +382 -0
  53. package/native/win32/Win32MenuBar.h +16 -0
  54. package/native/win32/Win32MountingManager.cpp +1282 -0
  55. package/native/win32/Win32MountingManager.h +243 -0
  56. package/native/win32/Win32Offscreen.h +53 -0
  57. package/native/win32/Win32Packaging.cpp +161 -0
  58. package/native/win32/Win32Packaging.h +56 -0
  59. package/native/win32/Win32RunLoopObserver.cpp +48 -0
  60. package/native/win32/Win32RunLoopObserver.h +42 -0
  61. package/native/win32/Win32ScrollView.cpp +718 -0
  62. package/native/win32/Win32ScrollView.h +256 -0
  63. package/native/win32/Win32SkiaContext.cpp +221 -0
  64. package/native/win32/Win32SkiaContext.h +53 -0
  65. package/native/win32/Win32SkiaModule.cpp +80 -0
  66. package/native/win32/Win32SkiaModule.h +50 -0
  67. package/native/win32/Win32SkiaPeer.cpp +358 -0
  68. package/native/win32/Win32SkiaPeer.h +66 -0
  69. package/native/win32/Win32SkiaUnicode.cpp +42 -0
  70. package/native/win32/Win32Snapshot.cpp +201 -0
  71. package/native/win32/Win32Snapshot.h +66 -0
  72. package/native/win32/Win32Strings.h +54 -0
  73. package/native/win32/Win32TextInput.cpp +1296 -0
  74. package/native/win32/Win32TextInput.h +341 -0
  75. package/native/win32/Win32TitleBar.cpp +562 -0
  76. package/native/win32/Win32TitleBar.h +146 -0
  77. package/native/win32/Win32TitleBarLayout.cpp +46 -0
  78. package/native/win32/Win32TitleBarLayout.h +58 -0
  79. package/native/win32/Win32TouchDispatcher.cpp +577 -0
  80. package/native/win32/Win32TouchDispatcher.h +201 -0
  81. package/native/win32/Win32UiThread.h +27 -0
  82. package/native/win32/Win32WindowControl.cpp +329 -0
  83. package/native/win32/Win32WindowModule.cpp +209 -0
  84. package/native/win32/Win32WindowModule.h +72 -0
  85. package/native/win32/demo_layout_win32.cpp +232 -0
  86. package/native/win32/main_win32.cpp +2722 -0
  87. package/native/win32/mount_harness_win32.cpp +316 -0
  88. package/package.json +25 -4
  89. package/react-native.config.js +22 -0
  90. package/README.md +0 -3
@@ -0,0 +1,1282 @@
1
+ #include "Win32MountingManager.h"
2
+
3
+ #include "BackgroundLayers.h"
4
+ #include "BlendModes.h"
5
+ #include "CursorNames.h"
6
+ #include "Filters.h"
7
+ #include "Gradients.h"
8
+ #include "LegacyShadow.h"
9
+
10
+ #include "DirectWriteLayout.h"
11
+ #include "WritingDirections.h"
12
+ #include "TextAlignments.h"
13
+ #include "ImageBytes.h"
14
+ #include "ImageProgress.h"
15
+ #include "PlatformServices.h"
16
+ #include "UIManagerAccess.h"
17
+
18
+ #ifdef BASALT_HAS_SKIA
19
+ #include "Win32SkiaPeer.h"
20
+ #endif
21
+
22
+ #include <react/renderer/components/image/ImageEventEmitter.h>
23
+ #include <react/renderer/components/image/ImageProps.h>
24
+ #include <react/renderer/components/text/ParagraphProps.h>
25
+ #include <react/renderer/components/text/ParagraphState.h>
26
+ #include <react/renderer/components/view/ViewProps.h>
27
+ #include <react/renderer/core/ConcreteState.h>
28
+ #include <react/renderer/graphics/Color.h>
29
+ #include <react/renderer/uimanager/UIManager.h>
30
+
31
+ #include <glog/logging.h>
32
+
33
+ #include <algorithm>
34
+ #include <memory>
35
+ #include <string>
36
+ #include <string_view>
37
+ #include <utility>
38
+ #include <vector>
39
+
40
+ namespace basalt {
41
+
42
+ using facebook::react::ImageProps;
43
+ using facebook::react::ImageResizeMode;
44
+ using facebook::react::MountingTransaction;
45
+ using facebook::react::ParagraphState;
46
+ using facebook::react::ShadowView;
47
+ using facebook::react::SurfaceId;
48
+ using facebook::react::Tag;
49
+ using facebook::react::ViewProps;
50
+ using win32::RnImageFit;
51
+ using win32::RnWin32View;
52
+
53
+ Win32MountingManager::Win32MountingManager()
54
+ : scrollViews_([this](Tag tag) { return eventEmitterForTag(tag); }),
55
+ textInputs_([this](Tag tag) { return eventEmitterForTag(tag); }) {
56
+ // The pull past the top of a list, counted in core/PullToRefresh.h and fired
57
+ // at whichever <RefreshControl> that scroll view has. Identical on all three
58
+ // desktops, which is the point of the two of them being portable.
59
+ scrollViews_.setOverscrollTopHandler([this](Tag tag, double amount) {
60
+ if (amount <= 0.0) {
61
+ pullToRefresh().release(tag);
62
+ return;
63
+ }
64
+ if (pullToRefresh().pull(tag, amount)) {
65
+ fireRefresh(tag);
66
+ }
67
+ });
68
+ }
69
+
70
+ Win32MountingManager::~Win32MountingManager() noexcept {
71
+ // MountingWalk cannot do this from its own destructor: by the time a base
72
+ // destructor runs, the platform half that knows how to free a view is already
73
+ // gone. Its header says so, and every platform has to make this call.
74
+ releaseAllViews();
75
+ }
76
+
77
+ // ---------------------------------------------------------------------------
78
+ // IMountingManager
79
+ // ---------------------------------------------------------------------------
80
+
81
+ void Win32MountingManager::executeMount(SurfaceId surfaceId, MountingTransaction &&transaction) {
82
+ // This runs on the JS thread: Scheduler::uiManagerDidFinishTransaction queues
83
+ // the mount via RuntimeScheduler::scheduleRenderingUpdate, which drains in the
84
+ // event loop's "update the rendering" step with the jsi::Runtime live. A view
85
+ // here is not thread-affine the way a GtkWidget or an NSView is -- it is a
86
+ // plain C++ object -- but the *painting* is, and so is every HWND a later
87
+ // <TextInput> will own. So nothing here may touch a view either.
88
+ //
89
+ // Always post, never run inline even when already on the UI thread. The queue
90
+ // is FIFO, and running one transaction inline while another is already
91
+ // queued would reorder them -- so this is about ordering rather than about
92
+ // thread-safety, and it is why the condition is absent rather than merely
93
+ // unnecessary.
94
+ //
95
+ // That is this project's choice rather than everyone's, and worth being exact
96
+ // about: iOS takes the other side. RCTMountingManager::scheduleTransaction
97
+ // runs `initiateTransaction` inline when `RCTIsMainQueue()`, and only
98
+ // dispatches otherwise. It gets away with it because under Fabric the JS
99
+ // thread is not the main thread, so the fast path is reached only when
100
+ // everything is already on one thread and there is nothing to reorder against.
101
+ // GTK and AppKit both queue unconditionally here, and this matches them.
102
+ //
103
+ // None of this changed with the New Architecture. What JSI removed is the
104
+ // *bridge* -- the JSON serialisation and the asynchronous message queue
105
+ // between JavaScript and native, which is why a TurboModule call is now a
106
+ // direct C++ call and why `measure` can answer synchronously. Mounting was
107
+ // never on that path: Fabric computes layout off the UI thread, commits to
108
+ // the shadow tree, and the mutations still have to be applied where the
109
+ // platform permits. Thread affinity is USER32's rule, not the bridge's.
110
+ //
111
+ // MountingTransaction is move-only, so it travels in a shared_ptr the lambda
112
+ // can capture -- std::function requires its target to be copyable.
113
+ //
114
+ // `alive` and `epoch` are what stop a queued transaction being applied against
115
+ // an instance that has since been destroyed, which a reload does on a thread of
116
+ // its own. See MountingWalk::mountGuard.
117
+ auto pending = std::make_shared<MountingTransaction>(std::move(transaction));
118
+ postToUiThread([this, surfaceId, pending, alive = mountGuard(), epoch = mountEpoch()] {
119
+ if (alive.expired() || mountEpoch() != epoch) {
120
+ return;
121
+ }
122
+ applyTransaction(surfaceId, std::move(*pending));
123
+ });
124
+ }
125
+
126
+ void Win32MountingManager::applyTransaction(SurfaceId surfaceId,
127
+ MountingTransaction &&transaction) {
128
+ // `maintainVisibleContentPosition` is measured before the mutations and acted
129
+ // on after them, which is the only place either half can go: the prop is
130
+ // about how far a child moved *during* a transaction. iOS hangs the same pair
131
+ // off `mountingTransactionWillMount` and `...DidMount`.
132
+ scrollViews_.prepareMaintainVisiblePosition();
133
+
134
+ // The walk itself is in core/MountingWalk.h and is shared with the other two
135
+ // desktops; what is Windows about mounting is below, in the operations it
136
+ // calls back into.
137
+ applyMutations(transaction.getMutations());
138
+
139
+ // And the other half, before anything repaints: the offset moves so that the
140
+ // child the list was looking at is still under the eye.
141
+ scrollViews_.adjustForMaintainVisiblePosition();
142
+
143
+ // Tell the UIManager the transaction is on screen. Anything registered as a
144
+ // mount hook -- Reanimated's is the one that matters -- is waiting for this,
145
+ // and without it an animated style is computed every frame, committed to the
146
+ // shadow tree, and never resumed, so nothing moves. ReactCxxPlatform calls it
147
+ // nowhere.
148
+ // Refuses a surface the UIManager no longer has, which is what a reload's
149
+ // teardown leaves behind. See core/UIManagerAccess.h.
150
+ reportMountedSurface(surfaceId);
151
+
152
+ // After the mutations, because a view can be labelled by one that mounts
153
+ // after it: Fabric mounts in tree order, and the label of a field often
154
+ // follows it.
155
+ applyLabelRelations();
156
+
157
+ // And after those, because an announcement is the last word on a
158
+ // transaction: the text a live region says now is what every mutation in
159
+ // this batch has left it saying.
160
+ announceLiveRegions();
161
+
162
+ // And ask the host to repaint, because on Windows nothing does that on its
163
+ // own. See setOnDidMount. This also positions and shows the peers through
164
+ // syncBounds, which is why the autoFocus flush comes after it rather than
165
+ // before: a control is created without WS_VISIBLE.
166
+ if (onDidMount_) {
167
+ onDidMount_();
168
+ }
169
+
170
+ // Now that the tree is on screen, anything `autoFocus` asked for can be given
171
+ // focus. See Win32TextInput.h.
172
+ textInputs_.flushAutoFocus();
173
+ }
174
+
175
+ void Win32MountingManager::setOnDidMount(std::function<void()> onDidMount) {
176
+ onDidMount_ = std::move(onDidMount);
177
+ }
178
+
179
+ void Win32MountingManager::dispatchCommand(const ShadowView &shadowView,
180
+ const std::string &commandName,
181
+ const folly::dynamic &args) {
182
+ // Same trip, for the same reason, and posted onto the same queue so it stays
183
+ // behind the transaction that created the view it names. A scrollTo that
184
+ // arrived before its ScrollView was mounted would find no entry and be
185
+ // dropped.
186
+ const Tag tag = shadowView.tag;
187
+ postToUiThread([this, tag, commandName, args] { applyCommand(tag, commandName, args); });
188
+ }
189
+
190
+ void Win32MountingManager::applyCommand(Tag tag,
191
+ const std::string &commandName,
192
+ const folly::dynamic &args) {
193
+ if (scrollViews_.dispatchCommand(tag, commandName, args)) {
194
+ return;
195
+ }
196
+ if (textInputs_.dispatchCommand(tag, commandName, args)) {
197
+ return;
198
+ }
199
+ // React DevTools' overlay, answered the same way on all three: see
200
+ // core/DebuggingOverlay.h.
201
+ if (applyOverlayCommand(tag, commandName, args)) {
202
+ return;
203
+ }
204
+ // Dropped silently rather than logged. Every command the other two desktops
205
+ // implement is now implemented here, so what reaches this line is a command
206
+ // for a component this platform does not claim -- which is expected rather
207
+ // than exceptional, and would otherwise be logged on every frame of a list.
208
+ }
209
+
210
+ facebook::react::ComponentRegistryFactory Win32MountingManager::getComponentRegistryFactory() {
211
+ return facebook::react::getDefaultComponentRegistryFactory();
212
+ }
213
+
214
+ bool Win32MountingManager::hasComponent(const std::string &name) {
215
+ // Only what actually mounts. Claiming more would be worse than admitting the
216
+ // gap: the registry would build shadow nodes nothing can put on screen, and
217
+ // the app would render blank rectangles instead of failing somewhere legible.
218
+ //
219
+ // Paragraph is the mountable half of <Text>; Text and RawText exist only in
220
+ // the shadow tree, folded into the Paragraph's AttributedString.
221
+ //
222
+ // This list and ComponentRegistryWin32.cpp are two statements of one fact and
223
+ // must agree.
224
+ return name == "View" || name == "RootView" || name == "Paragraph" ||
225
+ name == "ScrollView" || name == "Image" || name == "TextInput" ||
226
+ name == "ActivityIndicatorView" || name == "Switch" || name == "ModalHostView" ||
227
+ name == "PullToRefreshView" || name == "UnimplementedNativeView" ||
228
+ name == "DebuggingOverlay";
229
+ }
230
+
231
+ void Win32MountingManager::setUIManager(
232
+ std::weak_ptr<facebook::react::UIManager> uiManager) noexcept {
233
+ setSharedUIManager(std::move(uiManager));
234
+ }
235
+
236
+ void Win32MountingManager::setSchedulerTaskExecutor(
237
+ facebook::react::SchedulerTaskExecutor &&schedulerTaskExecutor) noexcept {
238
+ // A null executor means `destroyReactInstance`: the Scheduler and the
239
+ // SurfaceManager are about to go, and anything this already queued to the UI
240
+ // thread would be applied against them. Non-null means a new instance, which
241
+ // needs nothing from here.
242
+ if (!schedulerTaskExecutor) {
243
+ invalidatePendingMounts();
244
+ }
245
+ }
246
+
247
+ // ---------------------------------------------------------------------------
248
+ // What MountingWalk asks of a platform
249
+ // ---------------------------------------------------------------------------
250
+
251
+ RnWin32View *Win32MountingManager::createView(const ShadowView &shadowView) {
252
+ return new RnWin32View(shadowView.tag);
253
+ }
254
+
255
+ RnWin32View *Win32MountingManager::createRootView(Tag tag) {
256
+ return new RnWin32View(tag);
257
+ }
258
+
259
+ void Win32MountingManager::destroyView(RnWin32View *view) {
260
+ // The one operation that is genuinely different here. On GTK the registry
261
+ // holds a g_object_ref_sink and this is an unref; under ARC it is nothing at
262
+ // all, because erasing the map entry releases the last strong reference. A
263
+ // plain C++ object has neither, so the registry's ownership is written out:
264
+ // this is where a view stops existing.
265
+ //
266
+ // Safe against a view that is still parented, because ~RnWin32View detaches
267
+ // itself -- though Fabric guarantees a Remove before every Delete, so that
268
+ // should never be the path taken.
269
+ delete view;
270
+ }
271
+
272
+ void Win32MountingManager::insertChild(RnWin32View *parent, RnWin32View *child, int index) {
273
+ parent->insertChild(child, index);
274
+ }
275
+
276
+ void Win32MountingManager::removeChild(RnWin32View *parent, RnWin32View *child) {
277
+ parent->removeChild(child);
278
+ }
279
+
280
+ void Win32MountingManager::applyLabelRelations() {
281
+ if (labels_.empty()) {
282
+ return;
283
+ }
284
+ for (const auto &change : labels_.changes()) {
285
+ RnWin32View *view = viewForTag(change.tag);
286
+ if (view == nullptr) {
287
+ continue;
288
+ }
289
+ std::vector<RnWin32View *> resolved;
290
+ resolved.reserve(change.labels.size());
291
+ for (const Tag tag : change.labels) {
292
+ if (RnWin32View *label = viewForTag(tag); label != nullptr) {
293
+ resolved.push_back(label);
294
+ }
295
+ }
296
+ view->setLabelledBy(std::move(resolved));
297
+ }
298
+
299
+ // `experimental_accessibilityOrder` comes out of the same registry and is
300
+ // deliberately not applied here. UIA has no reading-order property: a client
301
+ // walks the fragment tree, and the order is the order the tree is in. The
302
+ // other two hosts have `aria-flowto` and `accessibilityChildren` to point at;
303
+ // reordering the view tree itself to fake it would move what is painted.
304
+ // Recorded in backlog/platform-windows.md, and the scenario skips here by
305
+ // name with that reason.
306
+ }
307
+
308
+ void Win32MountingManager::announceLiveRegions() {
309
+ if (liveRegions_.empty()) {
310
+ return;
311
+ }
312
+ for (const Tag tag : liveRegions_.tags()) {
313
+ RnWin32View *view = viewForTag(tag);
314
+ if (view == nullptr) {
315
+ continue;
316
+ }
317
+ // A label stands in for the text when the app set one: an icon-only status
318
+ // has no paragraph of its own, and the label is what would be read. Both
319
+ // other hosts make the same choice in the same order.
320
+ const auto label = liveRegionLabels_.find(tag);
321
+ std::string text = label != liveRegionLabels_.end() ? label->second : std::string();
322
+ if (text.empty()) {
323
+ text = view->collectText();
324
+ }
325
+ const auto politeness = liveRegions_.noticed(tag, text);
326
+ if (!politeness.has_value()) {
327
+ continue;
328
+ }
329
+ const bool assertive = *politeness == basalt::LiveRegionPoliteness::Assertive;
330
+ view->announce(text, assertive);
331
+ // Logged as well as announced: nothing in an automated run has a screen
332
+ // reader attached, so this line is how an end-to-end test sees that it
333
+ // happened. The same line the GTK host writes, read by the same scenario.
334
+ LOG(INFO) << "announced" << (assertive ? " (assertive): " : ": ") << text;
335
+ }
336
+ }
337
+
338
+ void Win32MountingManager::forgetTag(Tag tag) {
339
+ scrollViews_.remove(tag);
340
+ textInputs_.remove(tag);
341
+ imageUris_.erase(tag);
342
+ switchValues_.erase(tag);
343
+ labels_.forget(tag);
344
+ liveRegions_.forget(tag);
345
+ liveRegionLabels_.erase(tag);
346
+ #ifdef BASALT_HAS_SKIA
347
+ // Unregisters the canvas. This is the one moment a view is known to be
348
+ // finished with, and a canvas left registered is a surface the package will
349
+ // keep rendering into for a tag nothing will ever draw again.
350
+ forgetSkiaCanvas(tag);
351
+ #endif
352
+ }
353
+
354
+ // ---------------------------------------------------------------------------
355
+ // Applying a ShadowView to a view
356
+ // ---------------------------------------------------------------------------
357
+
358
+ void Win32MountingManager::updateView(RnWin32View *view, const ShadowView &shadowView) {
359
+ applyProps(view, shadowView);
360
+ applyText(view, shadowView);
361
+ applyImage(view, shadowView);
362
+ applyAccessibility(view, shadowView);
363
+ #ifdef BASALT_HAS_SKIA
364
+ // After applyProps, which is what puts nativeID on the view -- a canvas
365
+ // registers itself by that id and cannot attach before it is there. The size
366
+ // it reads comes from the shadow view rather than from the frame
367
+ // applyLayoutMetrics is about to set, so being before that one is only
368
+ // incidental.
369
+ //
370
+ // onDidMount_ is handed over as the way to say "the screen is stale": a
371
+ // canvas renders between transactions, when nothing else will invalidate the
372
+ // window. See Win32SkiaPeer.h.
373
+ applySkiaCanvas(view, shadowView, onDidMount_);
374
+ #endif
375
+ applyLayoutMetrics(view, shadowView);
376
+ // Last: the scroll manager clamps its offset against the frame that was just
377
+ // applied, and forces the clip that applyProps may have read as `visible`.
378
+ applyScrollView(view, shadowView);
379
+ applyTextInput(view, shadowView);
380
+ // After layout: a control is drawn centred in the frame it was just given,
381
+ // and a <Modal> commits that frame's size back into its own state.
382
+ applyControls(view, shadowView);
383
+ }
384
+
385
+ void Win32MountingManager::applyProps(RnWin32View *view, const ShadowView &shadowView) {
386
+ const auto props = std::dynamic_pointer_cast<const ViewProps>(shadowView.props);
387
+ if (props == nullptr) {
388
+ return;
389
+ }
390
+
391
+ if (props->backgroundColor) {
392
+ const auto components = facebook::react::colorComponentsFromColor(props->backgroundColor);
393
+ view->setBackgroundColor(
394
+ components.red, components.green, components.blue, components.alpha, true);
395
+ } else {
396
+ // Not transparent black: a view with no background does not paint at all.
397
+ view->setBackgroundColor(0, 0, 0, 0, false);
398
+ }
399
+
400
+ view->setOpacity(props->opacity);
401
+
402
+ // overflow: 'hidden'. React Native's default is 'visible'.
403
+ view->setClipsChildren(props->getClipsContentToBounds());
404
+
405
+ // Radii depend on the frame -- percentage radii, and the clamping that stops
406
+ // opposite corners overlapping -- so they are resolved against the layout
407
+ // metrics rather than read raw.
408
+ const auto borders = props->resolveBorderMetrics(shadowView.layoutMetrics);
409
+ // All four corners, each with its own horizontal and vertical radius, in the
410
+ // order GtkMountingManager passes them and describeTree prints them. This
411
+ // used to hand over the top-left horizontal radius alone, which was right for
412
+ // a single `borderRadius` and visibly wrong for anything else.
413
+ const float radii[8] = {
414
+ static_cast<float>(borders.borderRadii.topLeft.horizontal),
415
+ static_cast<float>(borders.borderRadii.topLeft.vertical),
416
+ static_cast<float>(borders.borderRadii.topRight.horizontal),
417
+ static_cast<float>(borders.borderRadii.topRight.vertical),
418
+ static_cast<float>(borders.borderRadii.bottomRight.horizontal),
419
+ static_cast<float>(borders.borderRadii.bottomRight.vertical),
420
+ static_cast<float>(borders.borderRadii.bottomLeft.horizontal),
421
+ static_cast<float>(borders.borderRadii.bottomLeft.vertical),
422
+ };
423
+ view->setCornerRadii(radii);
424
+
425
+ // Top, right, bottom, left, as GTK takes them -- the order CSS names the
426
+ // edges in, and not the order RectangleEdges stores them. An edge without a
427
+ // colour is transparent, so it draws nothing whatever its width.
428
+ const float widths[4] = {
429
+ static_cast<float>(borders.borderWidths.top),
430
+ static_cast<float>(borders.borderWidths.right),
431
+ static_cast<float>(borders.borderWidths.bottom),
432
+ static_cast<float>(borders.borderWidths.left),
433
+ };
434
+ float colours[16] = {};
435
+ const facebook::react::SharedColor *edges[4] = {
436
+ &borders.borderColors.top,
437
+ &borders.borderColors.right,
438
+ &borders.borderColors.bottom,
439
+ &borders.borderColors.left,
440
+ };
441
+ for (int i = 0; i < 4; i++) {
442
+ if (*edges[i]) {
443
+ const auto components = facebook::react::colorComponentsFromColor(*edges[i]);
444
+ colours[i * 4 + 0] = components.red;
445
+ colours[i * 4 + 1] = components.green;
446
+ colours[i * 4 + 2] = components.blue;
447
+ colours[i * 4 + 3] = components.alpha;
448
+ }
449
+ }
450
+ view->setBorders(widths, colours);
451
+
452
+ // `borderStyle`, from the *resolved* metrics like the widths and the colours
453
+ // above. The raw `props->borderStyles` is a cascade of optionals with a slot
454
+ // per spelling, and `borderStyle: 'dashed'` sets the `all` slot: reading the
455
+ // four sides directly finds nothing, which is how every dashed border in a
456
+ // React app came to draw solid on the other two hosts while the tests that
457
+ // set the style on the view by hand passed.
458
+ //
459
+ // The first side that asks for something other than solid decides the whole
460
+ // border, because a dashed border is one stroked path and a path carries one
461
+ // dash pattern. Both other hosts made the same choice; see
462
+ // backlog/correctness.md.
463
+ {
464
+ const auto &styles = borders.borderStyles;
465
+ win32::RnWin32View::LineStyle style = win32::RnWin32View::LineStyle::Solid;
466
+ const facebook::react::BorderStyle sides[4] = {
467
+ styles.top, styles.right, styles.bottom, styles.left};
468
+ for (const auto &side : sides) {
469
+ if (side == facebook::react::BorderStyle::Dotted) {
470
+ style = win32::RnWin32View::LineStyle::Dotted;
471
+ break;
472
+ }
473
+ if (side == facebook::react::BorderStyle::Dashed) {
474
+ style = win32::RnWin32View::LineStyle::Dashed;
475
+ break;
476
+ }
477
+ }
478
+ view->setBorderStyle(style);
479
+ }
480
+
481
+ view->setZIndex(static_cast<int>(props->zIndex.value_or(0)));
482
+
483
+ // resolveTransform folds in transformOrigin, but only when one was set: the
484
+ // default anchor is the view's centre, which is what RnWin32View::paint
485
+ // already assumes.
486
+ const auto transform = props->resolveTransform(shadowView.layoutMetrics);
487
+ if (transform == facebook::react::Transform::Identity()) {
488
+ view->setTransform(nullptr);
489
+ } else {
490
+ view->setTransform(transform.matrix.data());
491
+ }
492
+
493
+ // `backfaceVisibility: 'hidden'`, which stops the back of a card being drawn
494
+ // mirrored halfway through a flip. Whether a transform has turned away is
495
+ // core/Backface.h's to decide, so all three hide the same face.
496
+ //
497
+ // Applied after the transform, because the view has to know the matrix
498
+ // before it can say which way it is facing.
499
+ view->setHidesBackFace(props->backfaceVisibility ==
500
+ facebook::react::BackfaceVisibility::Hidden);
501
+
502
+ // Only a hidden title bar reads this, to find the drag regions an app marked
503
+ // with <TitleBar.DragRegion>.
504
+ view->setNativeId(props->nativeId);
505
+
506
+ // And the same id in the registry, so that another view's
507
+ // `accessibilityLabelledBy` can look one up. See `core/LabelRegistry.h`.
508
+ labels_.setNativeId(shadowView.tag, props->nativeId);
509
+ // `accessibilityLabelledBy`: other views, named by their nativeID, whose text
510
+ // names this one. Only recorded here -- resolving needs every view in the
511
+ // transaction to have been seen, so it happens once at the end of the mount.
512
+ labels_.setLabelledBy(shadowView.tag, props->accessibilityLabelledBy.value);
513
+ // `experimental_accessibilityOrder` is deliberately not recorded here, and the
514
+ // support page says so rather than this host quietly holding a resolution
515
+ // nothing reads: UIA has no reading-order property. A client walks the
516
+ // fragment tree and the order is the order the tree is in, where GTK has
517
+ // `aria-flowto` and AppKit can replace `accessibilityChildren`. Reordering the
518
+ // view tree to fake it would move what is painted. See applyLabelRelations.
519
+
520
+ // `accessibilityLiveRegion`: a status message to read out when it changes.
521
+ // Recorded here and acted on after the transaction, the text being whatever
522
+ // the region says once every mutation in the batch has landed.
523
+ liveRegions_.setPoliteness(shadowView.tag, props->accessibilityLiveRegion);
524
+ // The label, if the app set one, which stands in for the text: an icon-only
525
+ // status has no paragraph of its own.
526
+ if (props->accessibilityLiveRegion == facebook::react::AccessibilityLiveRegion::None) {
527
+ liveRegionLabels_.erase(shadowView.tag);
528
+ } else {
529
+ liveRegionLabels_[shadowView.tag] = props->accessibilityLabel;
530
+ }
531
+
532
+ // Hit testing only. `hitTest` reads it; nothing about painting does.
533
+ switch (props->pointerEvents) {
534
+ case facebook::react::PointerEventsMode::None:
535
+ view->setPointerEvents(win32::RnWin32View::PointerEvents::None);
536
+ break;
537
+ case facebook::react::PointerEventsMode::BoxNone:
538
+ view->setPointerEvents(win32::RnWin32View::PointerEvents::BoxNone);
539
+ break;
540
+ case facebook::react::PointerEventsMode::BoxOnly:
541
+ view->setPointerEvents(win32::RnWin32View::PointerEvents::BoxOnly);
542
+ break;
543
+ case facebook::react::PointerEventsMode::Auto:
544
+ view->setPointerEvents(win32::RnWin32View::PointerEvents::Auto);
545
+ break;
546
+ }
547
+
548
+ // `backgroundImage`: linear and radial gradients. The angle or the ending
549
+ // shape, the box size and CSS's colour-stop fixup are resolved here through
550
+ // `core/Gradients.h`, shared with the other two hosts, and the view layer is
551
+ // handed points and radii and a list of stops: the resolution is the
552
+ // specified part and belongs in one place, and the drawing is the toolkit's.
553
+ //
554
+ // One list rather than two, because `background-image` is one list and the
555
+ // first in it is the one on top: two lists would lose the order between a
556
+ // radial gradient and a linear one.
557
+ //
558
+ // Against this mutation's own frame, and `applyProps` runs on every update,
559
+ // so a resized view gets a resized gradient without the view layer knowing
560
+ // anything about angles or corners.
561
+ {
562
+ const auto &metrics = shadowView.layoutMetrics;
563
+ // The two areas CSS gives a background. The painting area is the border
564
+ // box, which is what it is clipped to; the positioning area is the padding
565
+ // box, which sizes and positions it. They differ on any view with a border.
566
+ const basalt::BackgroundArea painting{0.0f,
567
+ 0.0f,
568
+ static_cast<float>(metrics.frame.size.width),
569
+ static_cast<float>(metrics.frame.size.height)};
570
+ // getPaddingFrame's origin is already relative to the view -- it is the
571
+ // border widths -- so nothing here subtracts the frame's own position.
572
+ const auto paddingFrame = metrics.getPaddingFrame();
573
+ const basalt::BackgroundArea positioning{
574
+ static_cast<float>(paddingFrame.origin.x),
575
+ static_cast<float>(paddingFrame.origin.y),
576
+ static_cast<float>(paddingFrame.size.width),
577
+ static_cast<float>(paddingFrame.size.height)};
578
+
579
+ std::vector<win32::RnWin32View::Gradient> gradients;
580
+ gradients.reserve(props->backgroundImage.size());
581
+ for (size_t index = 0; index < props->backgroundImage.size(); index++) {
582
+ const auto &image = props->backgroundImage[index];
583
+ // Each list is indexed modulo its own length, which is CSS's rule for a
584
+ // list shorter than the image list and is what iOS does.
585
+ const basalt::BackgroundLayer layer = basalt::resolveBackgroundLayer(
586
+ positioning,
587
+ painting,
588
+ basalt::backgroundSizeAt(props->backgroundSize, index),
589
+ basalt::backgroundPositionAt(props->backgroundPosition, index),
590
+ basalt::backgroundRepeatAt(props->backgroundRepeat, index));
591
+ if (layer.empty()) {
592
+ continue;
593
+ }
594
+ // The gradient is resolved against the image's size and then offset to
595
+ // where the image goes: a gradient that resolved against the view would
596
+ // ignore `backgroundSize` even with the rectangle right.
597
+ win32::RnWin32View::Gradient converted;
598
+ converted.area[0] = layer.x;
599
+ converted.area[1] = layer.y;
600
+ converted.area[2] = layer.width;
601
+ converted.area[3] = layer.height;
602
+ converted.tile[0] = layer.tileX;
603
+ converted.tile[1] = layer.tileY;
604
+ converted.tile[2] = layer.tileWidth;
605
+ converted.tile[3] = layer.tileHeight;
606
+ converted.repeats = layer.repeats();
607
+
608
+ const std::vector<facebook::react::ColorStop> *colorStops = nullptr;
609
+ float rayLength = 0.0f;
610
+ if (std::holds_alternative<facebook::react::LinearGradient>(image)) {
611
+ const auto &gradient = std::get<facebook::react::LinearGradient>(image);
612
+ const basalt::GradientLine line =
613
+ basalt::linearGradientLine(gradient, layer.width, layer.height);
614
+ converted.kind = win32::RnWin32View::Gradient::Kind::Linear;
615
+ converted.startX = line.startX + layer.x;
616
+ converted.startY = line.startY + layer.y;
617
+ converted.endX = line.endX + layer.x;
618
+ converted.endY = line.endY + layer.y;
619
+ colorStops = &gradient.colorStops;
620
+ rayLength = line.length();
621
+ } else {
622
+ const auto &gradient = std::get<facebook::react::RadialGradient>(image);
623
+ const basalt::GradientEllipse shape =
624
+ basalt::radialGradientEllipse(gradient, layer.width, layer.height);
625
+ converted.kind = win32::RnWin32View::Gradient::Kind::Radial;
626
+ converted.centreX = shape.centerX + layer.x;
627
+ converted.centreY = shape.centerY + layer.y;
628
+ converted.radiusX = shape.radiusX;
629
+ converted.radiusY = shape.radiusY;
630
+ colorStops = &gradient.colorStops;
631
+ rayLength = shape.rayLength();
632
+ }
633
+
634
+ const auto resolved = basalt::resolveGradientStops(*colorStops, rayLength);
635
+ if (resolved.empty()) {
636
+ continue;
637
+ }
638
+ converted.stops.reserve(resolved.size());
639
+ for (const auto &stop : resolved) {
640
+ win32::RnWin32View::GradientStop one;
641
+ one.offset = stop.offset;
642
+ one.colour[0] = stop.red;
643
+ one.colour[1] = stop.green;
644
+ one.colour[2] = stop.blue;
645
+ one.colour[3] = stop.alpha;
646
+ converted.stops.push_back(one);
647
+ }
648
+ gradients.push_back(std::move(converted));
649
+ }
650
+ view->setGradients(std::move(gradients));
651
+ }
652
+
653
+ // `boxShadow`, as React Native's own six fields: GSK's shadow nodes take the
654
+ // same six and CALayer's properties are built from them, so nothing converts
655
+ // here either and each view layer decides what a shadow is made of.
656
+ //
657
+ // The list also carries the older iOS shadow props, converted in
658
+ // `core/LegacyShadow.h`: one mechanism from here down, so a view with
659
+ // `shadowOpacity` and a view with `boxShadow` take the same path, and a
660
+ // legacy shadow goes behind every CSS one.
661
+ {
662
+ const std::vector<facebook::react::BoxShadow> all = basalt::allShadows(*props);
663
+ std::vector<win32::RnWin32View::BoxShadow> shadows;
664
+ shadows.reserve(all.size());
665
+ for (const auto &shadow : all) {
666
+ win32::RnWin32View::BoxShadow one;
667
+ one.dx = static_cast<float>(shadow.offsetX);
668
+ one.dy = static_cast<float>(shadow.offsetY);
669
+ one.blur = static_cast<float>(shadow.blurRadius);
670
+ one.spread = static_cast<float>(shadow.spreadDistance);
671
+ if (shadow.color) {
672
+ const auto components = facebook::react::colorComponentsFromColor(shadow.color);
673
+ one.colour[0] = components.red;
674
+ one.colour[1] = components.green;
675
+ one.colour[2] = components.blue;
676
+ one.colour[3] = components.alpha;
677
+ }
678
+ one.inset = shadow.inset;
679
+ shadows.push_back(one);
680
+ }
681
+ view->setBoxShadows(std::move(shadows));
682
+ }
683
+
684
+ // The `cursor` style property, as a CSS keyword. GDK's names are CSS's so the
685
+ // GTK host passes it straight through; here the view stores it and the window
686
+ // answers `WM_SETCURSOR` with whatever is under the pointer, Win32 having no
687
+ // per-view cursor at all. `core/CursorNames.h` is what says a value's name.
688
+ view->setCursor(basalt::cursorName(props->cursor));
689
+
690
+ // `mixBlendMode`, as a CSS keyword, shared with the other two hosts for the
691
+ // reason `core/BlendModes.h` gives: React Native's list is CSS's and so is
692
+ // every compositor's, so the keyword is the thing that crosses the seam and
693
+ // each view layer maps it. Direct2D's blend modes are CSS's plus a few of its
694
+ // own, including the one GSK has no node for.
695
+ view->setBlendMode(basalt::blendModeName(props->mixBlendMode));
696
+
697
+ // `filter`. The arithmetic is `core/Filters.h`'s and is shared with the other
698
+ // two hosts: nine CSS functions collapse to one colour matrix, one blur, one
699
+ // opacity and the drop shadows in order, because seven of them are affine
700
+ // maps of colour and composing those is multiplying their matrices.
701
+ {
702
+ const basalt::ResolvedFilters resolved = basalt::resolveFilters(props->filter);
703
+ win32::RnWin32View::Filters filters;
704
+ if (!resolved.empty()) {
705
+ filters.hasMatrix = resolved.hasMatrix;
706
+ for (int i = 0; i < 16; i++) {
707
+ filters.matrix[i] = resolved.matrix.m[i];
708
+ }
709
+ for (int i = 0; i < 4; i++) {
710
+ filters.offset[i] = resolved.matrix.offset[i];
711
+ }
712
+ filters.blurRadius = resolved.blurRadius;
713
+ filters.opacity = resolved.opacity;
714
+ filters.shadows.reserve(resolved.dropShadows.size());
715
+ for (const auto &shadow : resolved.dropShadows) {
716
+ win32::RnWin32View::FilterShadow one;
717
+ one.dx = shadow.dx;
718
+ one.dy = shadow.dy;
719
+ // The standard deviation unchanged: `CLSID_D2D1Shadow` takes one, where
720
+ // GSK's shadow node takes CSS's radius and the GTK half doubles it.
721
+ one.standardDeviation = shadow.standardDeviation;
722
+ one.colour[0] = shadow.red;
723
+ one.colour[1] = shadow.green;
724
+ one.colour[2] = shadow.blue;
725
+ one.colour[3] = shadow.alpha;
726
+ filters.shadows.push_back(one);
727
+ }
728
+ }
729
+ view->setFilters(filters);
730
+ }
731
+
732
+ // The outline: CSS's, drawn outside the box and taking no layout space, so
733
+ // nothing about it touches the frame. React Native carries one width, one
734
+ // colour, one offset and one style for the whole ring, unlike the border's
735
+ // four of each.
736
+ {
737
+ float colour[4] = {0.0f, 0.0f, 0.0f, 0.0f};
738
+ if (props->outlineColor) {
739
+ const auto components = facebook::react::colorComponentsFromColor(props->outlineColor);
740
+ colour[0] = components.red;
741
+ colour[1] = components.green;
742
+ colour[2] = components.blue;
743
+ colour[3] = components.alpha;
744
+ }
745
+ win32::RnWin32View::LineStyle style = win32::RnWin32View::LineStyle::Solid;
746
+ switch (props->outlineStyle) {
747
+ case facebook::react::OutlineStyle::Dotted:
748
+ style = win32::RnWin32View::LineStyle::Dotted;
749
+ break;
750
+ case facebook::react::OutlineStyle::Dashed:
751
+ style = win32::RnWin32View::LineStyle::Dashed;
752
+ break;
753
+ case facebook::react::OutlineStyle::Solid:
754
+ break;
755
+ }
756
+ view->setOutline(static_cast<float>(props->outlineWidth),
757
+ static_cast<float>(props->outlineOffset),
758
+ colour,
759
+ style);
760
+ }
761
+
762
+ // `hitSlop`, which grows what a press can land on without moving a pixel.
763
+ // Top, right, bottom, left, the order the other two hosts store it in and
764
+ // the order CSS names the edges.
765
+ const float insets[4] = {
766
+ static_cast<float>(props->hitSlop.top),
767
+ static_cast<float>(props->hitSlop.right),
768
+ static_cast<float>(props->hitSlop.bottom),
769
+ static_cast<float>(props->hitSlop.left),
770
+ };
771
+ view->setHitSlop(insets);
772
+ }
773
+
774
+ // A <Paragraph> carries its text in state, not props: ParagraphShadowNode
775
+ // resolves the whole <Text> subtree into one AttributedString and commits it as
776
+ // ParagraphState, which is why nothing here walks child shadow nodes.
777
+ void Win32MountingManager::applyText(RnWin32View *view, const ShadowView &shadowView) {
778
+ if (shadowView.componentName == nullptr ||
779
+ std::string_view(shadowView.componentName) != "Paragraph") {
780
+ return;
781
+ }
782
+
783
+ const auto state =
784
+ std::dynamic_pointer_cast<const facebook::react::ConcreteState<ParagraphState>>(
785
+ shadowView.state);
786
+ if (state == nullptr) {
787
+ return;
788
+ }
789
+
790
+ const auto &data = state->getData();
791
+ // Built through the same function the measurement seam uses, which is what
792
+ // makes the painted lines break where the measured ones did.
793
+ // `adjustsFontSizeToFit` again, against the frame rather than the constraint:
794
+ // the text is painted into the box Yoga assigned, which is the box it has to
795
+ // fit. Measuring and painting run the same search through the same builder,
796
+ // which is what keeps the painted size the measured one.
797
+ // The *content* box, not the frame: a <Text> may carry padding and a border,
798
+ // and Yoga measured the paragraph against the size inside them. See
799
+ // RnWin32View::setTextInset.
800
+ const auto &insets = shadowView.layoutMetrics.contentInsets;
801
+ const basalt::FontFit fit =
802
+ win32::textFitScale(data.attributedString,
803
+ data.paragraphAttributes,
804
+ static_cast<float>(shadowView.layoutMetrics.frame.size.width -
805
+ insets.left - insets.right),
806
+ static_cast<float>(shadowView.layoutMetrics.frame.size.height -
807
+ insets.top - insets.bottom));
808
+ view->setTextLayout(
809
+ win32::buildTextLayout(data.attributedString, data.paragraphAttributes, fit));
810
+ // The two dump lines a paragraph's box and string cannot show: what the app
811
+ // asked for, and where its text ended up. `textAlign` is relative in two of
812
+ // its five spellings, so the prop is not the answer; see
813
+ // core/TextAlignments.h.
814
+ // The padding and border the paragraph sits inside, which the view draws at
815
+ // and hit-tests against. Yoga has already laid the box out with them; this is
816
+ // what stops the text being drawn underneath its own padding.
817
+ view->setTextInset(static_cast<float>(insets.left),
818
+ static_cast<float>(insets.top),
819
+ static_cast<float>(insets.right),
820
+ static_cast<float>(insets.bottom));
821
+ view->setParagraphNames(
822
+ basalt::writingDirectionName(basalt::writingDirection(data.attributedString)),
823
+ basalt::paragraphTextAlignmentName(data.attributedString),
824
+ basalt::textAlignVerticalName(data.paragraphAttributes.textAlignVertical));
825
+
826
+ // `<Text selectable>`, which `userSelect` also arrives in: React Native's own
827
+ // `Text.js` maps the style onto the prop. From the props rather than the
828
+ // state, unlike the text itself.
829
+ const auto paragraphProps =
830
+ std::dynamic_pointer_cast<const facebook::react::ParagraphProps>(shadowView.props);
831
+ view->setTextSelectable(paragraphProps != nullptr && paragraphProps->isSelectable);
832
+ }
833
+
834
+ namespace {
835
+
836
+ RnImageFit toImageFit(ImageResizeMode mode) {
837
+ switch (mode) {
838
+ case ImageResizeMode::Contain:
839
+ return RnImageFit::Contain;
840
+ case ImageResizeMode::Stretch:
841
+ return RnImageFit::Stretch;
842
+ case ImageResizeMode::Center:
843
+ case ImageResizeMode::None:
844
+ return RnImageFit::Center;
845
+ case ImageResizeMode::Repeat:
846
+ return RnImageFit::Repeat;
847
+ case ImageResizeMode::Cover:
848
+ break;
849
+ }
850
+ return RnImageFit::Cover;
851
+ }
852
+
853
+ } // namespace
854
+
855
+ void Win32MountingManager::applyImage(RnWin32View *view, const ShadowView &shadowView) {
856
+ if (shadowView.componentName == nullptr ||
857
+ std::string_view(shadowView.componentName) != "Image") {
858
+ return;
859
+ }
860
+
861
+ const auto props = std::dynamic_pointer_cast<const ImageProps>(shadowView.props);
862
+ if (props == nullptr) {
863
+ return;
864
+ }
865
+
866
+ const RnImageFit fit = toImageFit(props->resizeMode);
867
+ // The whole source rather than only its uri: `onLoad` reports it back, which
868
+ // is what an app reading `event.nativeEvent.source` is given.
869
+ const facebook::react::ImageSource source =
870
+ props->sources.empty() ? facebook::react::ImageSource{} : props->sources.front();
871
+ const std::string uri = source.uri;
872
+
873
+ // `tintColor`, applied before the load rather than in its callback: the tint
874
+ // is a prop and the image is a loader's answer, and either can arrive first.
875
+ if (props->tintColor) {
876
+ const auto components = facebook::react::colorComponentsFromColor(*props->tintColor);
877
+ const float rgba[4] = {components.red, components.green, components.blue, components.alpha};
878
+ view->setImageTint(true, rgba);
879
+ } else {
880
+ view->setImageTint(false, nullptr);
881
+ }
882
+
883
+ // `blurRadius`, for the same reason and in the same place: a prop beside a
884
+ // loader's answer. The GTK host had this assignment *inside* the branch that
885
+ // read the tint, so a blurred image with no tintColor came out sharp and
886
+ // every unit test still passed; see the scenario that caught it.
887
+ view->setImageBlur(static_cast<float>(props->blurRadius));
888
+
889
+ // The frames of an animated image, asked of the loader rather than carried in
890
+ // the load callback: being animated is a property of the file, and the
891
+ // callback's job is the pixels. Applied on every mutation like the fit, and
892
+ // the view compares the first frame so a re-apply does not restart it.
893
+ const auto applyAnimation = [this](RnWin32View *target, const std::string &forUri) {
894
+ if (target == nullptr) {
895
+ return;
896
+ }
897
+ win32::RnWin32ImageFrames frames = forUri.empty()
898
+ ? win32::RnWin32ImageFrames{}
899
+ : imageLoader_->animation(forUri);
900
+ target->setImageFrames(
901
+ std::move(frames.frames), std::move(frames.delaysMs), frames.loopCount);
902
+ };
903
+
904
+ // A mutation that changed only layout must not restart the load, or an
905
+ // <Image> flickers whenever its parent resizes. The fit is applied every time
906
+ // regardless, because changing it is cheap and does not touch the pixels.
907
+ const auto previous = imageUris_.find(shadowView.tag);
908
+ if (previous != imageUris_.end() && previous->second == uri) {
909
+ view->setImage(view->image(), fit);
910
+ applyAnimation(view, uri);
911
+ return;
912
+ }
913
+ imageUris_[shadowView.tag] = uri;
914
+
915
+ if (uri.empty()) {
916
+ view->setImage(nullptr, fit);
917
+ applyAnimation(view, uri);
918
+ return;
919
+ }
920
+
921
+ // Clear whatever was showing: the source changed, and leaving the old picture
922
+ // up while the new one loads is worse than a blank box, because it looks like
923
+ // the change did not take.
924
+ view->setImage(nullptr, fit);
925
+
926
+ // `<Image>`'s load events, which this host emitted none of until 2026-10-10:
927
+ // `onLoadStart`, `onProgress`, `onLoad`, `onError` and `onLoadEnd` all
928
+ // reached JavaScript on the other two hosts and nothing here ever dispatched
929
+ // one, so an app that showed a spinner until `onLoad` showed it forever on
930
+ // Windows.
931
+ //
932
+ // Always, rather than only when `shouldNotifyLoadEvents` is set: that prop is
933
+ // Android's signal and never arrives, because a platform that is neither
934
+ // Android nor iOS takes `ImageViewNativeComponent`'s iOS branch, whose
935
+ // `validAttributes` has no such field. iOS emits unconditionally and lets the
936
+ // emitter be the thing that knows whether anybody is listening, which is both
937
+ // correct and what the lookup below already does -- it answers null when
938
+ // nothing is.
939
+ if (auto emitter = std::dynamic_pointer_cast<const facebook::react::ImageEventEmitter>(
940
+ eventEmitterForTag(shadowView.tag))) {
941
+ emitter->onLoadStart();
942
+ }
943
+
944
+ // `<Image onProgress>`, for an http source: the bytes as they arrive, from
945
+ // the fetching thread. The emitter is looked up *here*, on the UI thread, and
946
+ // captured -- `eventEmitterForTag` reads a map only this thread may touch
947
+ // (see core/MountingWalk.h), and a progress tick arrives on another.
948
+ //
949
+ // Which ticks become events is core/ImageProgress.h's: all three hosts gate
950
+ // them the same way, and the arithmetic is testable where the lambda is not.
951
+ basalt::ImageProgress reportProgress;
952
+ if (auto emitter = std::dynamic_pointer_cast<const facebook::react::ImageEventEmitter>(
953
+ eventEmitterForTag(shadowView.tag))) {
954
+ auto ticker = std::make_shared<basalt::ImageProgressTicker>();
955
+ reportProgress = [emitter, ticker](long long loaded, long long total) {
956
+ if (const auto progress = ticker->tick(loaded, total)) {
957
+ emitter->onProgress(*progress, loaded, total);
958
+ }
959
+ };
960
+ }
961
+
962
+ // The fetch is in the shared half, which knows file, data: and http URIs --
963
+ // a URI means the same thing on every desktop -- and the loader puts both it
964
+ // and the decode on a worker thread.
965
+ //
966
+ // The completion captures the *tag*, not the view. A view can be deleted
967
+ // while its bytes are in flight, and capturing the pointer would be a
968
+ // use-after-free on a slow network; looking it up again is the arrangement
969
+ // GTK settled on for the same reason. `this` is safe to capture because the
970
+ // loader is a member and cannot outlive the manager -- and the loader itself
971
+ // guards the case where the manager goes first.
972
+ const Tag tag = shadowView.tag;
973
+ imageLoader_->load(
974
+ uri,
975
+ [this, tag, uri, fit, source, applyAnimation](
976
+ std::shared_ptr<win32::RnWin32Image> image, const std::string &error) {
977
+ // The pixels first, then the events. A view may have been deleted or
978
+ // re-sourced while its bytes were in flight, and neither stops the load
979
+ // that finished from being worth reporting -- the other two hosts emit
980
+ // for the request rather than for the view, and an app listening for
981
+ // `onLoadEnd` to take a spinner down needs it either way.
982
+ RnWin32View *target = viewForTag(tag);
983
+ const auto current = imageUris_.find(tag);
984
+ const bool stillWanted =
985
+ target != nullptr && current != imageUris_.end() && current->second == uri;
986
+ if (stillWanted) {
987
+ target->setImage(image, fit);
988
+ applyAnimation(target, uri);
989
+ // The screen is stale and no transaction is coming: the bytes arrived
990
+ // on their own clock, after the mount that asked for them. On GTK and
991
+ // AppKit the view is a widget and queues its own draw; here only the
992
+ // host has the HWND, and `onDidMount_` is the way to say so -- which
993
+ // also starts the animation timer, without which an animated GIF
994
+ // would hold its frames and never advance.
995
+ if (onDidMount_) {
996
+ onDidMount_();
997
+ }
998
+ }
999
+
1000
+ auto emitter = std::dynamic_pointer_cast<const facebook::react::ImageEventEmitter>(
1001
+ eventEmitterForTag(tag));
1002
+ if (emitter == nullptr) {
1003
+ return;
1004
+ }
1005
+ if (image != nullptr) {
1006
+ // The decoded size, which the props do not carry for a remote image:
1007
+ // `onLoad`'s payload is `source.size` times `source.scale`, so a source
1008
+ // that arrived as `{uri}` and nothing else reported zero by zero on
1009
+ // every host. iOS fills it in the same place and the same way, from the
1010
+ // image it has just decoded -- `RCTImageComponentView`'s
1011
+ // `didReceiveImage:` assigns `imageSource.size` before emitting.
1012
+ //
1013
+ // Divided by the scale because the payload multiplies by it: the event
1014
+ // reports pixels, and a 2x asset is half as many points.
1015
+ facebook::react::ImageSource loaded = source;
1016
+ const double scale = loaded.scale > 0 ? loaded.scale : 1.0;
1017
+ loaded.size = {
1018
+ static_cast<facebook::react::Float>(image->width() / scale),
1019
+ static_cast<facebook::react::Float>(image->height() / scale)};
1020
+ emitter->onLoad(loaded);
1021
+ } else {
1022
+ emitter->onError(facebook::react::ImageErrorInfo{.error = error});
1023
+ }
1024
+ emitter->onLoadEnd();
1025
+ },
1026
+ std::move(reportProgress));
1027
+ }
1028
+
1029
+ namespace {
1030
+
1031
+ win32::RnAccessibleFlag toFlag(bool value) {
1032
+ return value ? win32::RnAccessibleFlag::True : win32::RnAccessibleFlag::False;
1033
+ }
1034
+
1035
+ // The role React Native effectively means for this view: what the app asked
1036
+ // for, or what the component implies.
1037
+ //
1038
+ // A <Text> is a label and an <Image> is an image whether or not the app said
1039
+ // so, which is what makes an ordinary screen navigable without every developer
1040
+ // having annotated it. Both other platforms infer the same two.
1041
+ std::string effectiveRole(const ShadowView &shadowView) {
1042
+ if (const auto props =
1043
+ std::dynamic_pointer_cast<const facebook::react::AccessibilityProps>(shadowView.props)) {
1044
+ if (!props->accessibilityRole.empty()) {
1045
+ return props->accessibilityRole;
1046
+ }
1047
+ }
1048
+ if (shadowView.componentName != nullptr) {
1049
+ const std::string_view name(shadowView.componentName);
1050
+ if (name == "Paragraph") {
1051
+ return "text";
1052
+ }
1053
+ if (name == "Image") {
1054
+ return "image";
1055
+ }
1056
+ }
1057
+ return {};
1058
+ }
1059
+
1060
+ } // namespace
1061
+
1062
+ void Win32MountingManager::applyAccessibility(RnWin32View *view, const ShadowView &shadowView) {
1063
+ const auto props =
1064
+ std::dynamic_pointer_cast<const facebook::react::AccessibilityProps>(shadowView.props);
1065
+ if (props == nullptr) {
1066
+ return;
1067
+ }
1068
+
1069
+ win32::RnAccessibleInfo info;
1070
+ info.role = effectiveRole(shadowView);
1071
+
1072
+ // A label given in props wins. Falling back to a Paragraph's own text means a
1073
+ // plain <Text> announces itself without the app having repeated the string in
1074
+ // an accessibilityLabel, which is what the other two hosts do.
1075
+ info.label = props->accessibilityLabel;
1076
+ if (info.label.empty() && view->textLayout() != nullptr) {
1077
+ info.label = view->textLayout()->text();
1078
+ }
1079
+ info.hint = props->accessibilityHint;
1080
+ // `testID`, which no host read until 2026-10-09. UIA publishes it as the
1081
+ // automation id; see RnWin32Accessible.cpp.
1082
+ info.testId = props->testId;
1083
+ // `accessibilityViewIsModal`, which UIA calls a dialog.
1084
+ info.modal = props->accessibilityViewIsModal;
1085
+
1086
+ const auto &state = props->accessibilityState;
1087
+ if (state.has_value()) {
1088
+ info.state.disabled = toFlag(state->disabled);
1089
+ info.state.selected = toFlag(state->selected);
1090
+ info.state.busy = toFlag(state->busy);
1091
+ if (state->checked != facebook::react::AccessibilityState::Unchecked ||
1092
+ !info.role.empty()) {
1093
+ // Tri-state on purpose: `checked` unset is not the same as false, and a
1094
+ // view that never mentions being checked must not report ToggleState_Off.
1095
+ // React Native's own enum has no "unset", so Unchecked on a view with no
1096
+ // role is treated as "did not say".
1097
+ info.state.checked = state->checked == facebook::react::AccessibilityState::Checked
1098
+ ? win32::RnAccessibleFlag::True
1099
+ : win32::RnAccessibleFlag::False;
1100
+ }
1101
+ if (state->expanded.has_value()) {
1102
+ info.state.expanded = toFlag(*state->expanded);
1103
+ }
1104
+ }
1105
+
1106
+ // `accessibilityValue`: a range, a position in it and a text form, each
1107
+ // independent. Carried as it arrived, optionals and all, because an absent
1108
+ // part has to stay absent all the way to the provider -- a view that said
1109
+ // nothing about its range must not be announced as sitting at the bottom of
1110
+ // one. Both other hosts keep the same distinction; see RnWin32Accessible.h.
1111
+ info.value.min = props->accessibilityValue.min;
1112
+ info.value.max = props->accessibilityValue.max;
1113
+ info.value.now = props->accessibilityValue.now;
1114
+ info.value.text = props->accessibilityValue.text;
1115
+
1116
+ // accessible={false} and accessibilityElementsHidden both mean "not for a
1117
+ // screen reader".
1118
+ info.hidden = !props->accessible ||
1119
+ props->importantForAccessibility == facebook::react::ImportantForAccessibility::NoHideDescendants;
1120
+
1121
+ view->setAccessibleInfo(info);
1122
+
1123
+ // Keyboard focus. `accessible` is the signal because React Native's
1124
+ // `focusable` prop never reaches this platform -- see Win32Focus.h -- and
1125
+ // because it is what <Pressable> sets on everything it renders. A hidden view
1126
+ // is not focusable whatever it says: Tab stopping on something nobody can see
1127
+ // is worse than Tab skipping it.
1128
+ // A control is focusable whether or not the app said `accessible`.
1129
+ //
1130
+ // React Native's `focusable` prop never reaches this platform -- ReactCommon
1131
+ // parses it only into Android's and tvOS's props -- so `accessible` is the
1132
+ // signal, and <Pressable> sets it. <Switch> does not: on a phone the native
1133
+ // control is focusable by being a control, and React Native never had to say
1134
+ // so. On a desktop a switch that Tab skips is simply broken, so being a
1135
+ // control is the signal here too.
1136
+ // Disabled is excluded, which is what every desktop does: Tab skips a control
1137
+ // that cannot be operated rather than stopping on one that does nothing.
1138
+ const basalt::ControlState control = basalt::controlStateOf(shadowView);
1139
+ const bool isControl = control.kind == basalt::ControlKind::Switch && !control.disabled;
1140
+ view->setFocusable((props->accessible || isControl) && !props->accessibilityElementsHidden);
1141
+ }
1142
+
1143
+ void Win32MountingManager::applyLayoutMetrics(RnWin32View *view, const ShadowView &shadowView) {
1144
+ const auto &frame = shadowView.layoutMetrics.frame;
1145
+ view->setFrame(frame.origin.x, frame.origin.y, frame.size.width, frame.size.height);
1146
+
1147
+ // display: 'none' keeps the node in the shadow tree but takes it out of
1148
+ // layout and painting -- and, here, out of hit testing too.
1149
+ view->setHidden(shadowView.layoutMetrics.displayType == facebook::react::DisplayType::None);
1150
+
1151
+ // TODO(layout): pointScaleFactor, once a high-DPI backing store is involved.
1152
+ }
1153
+
1154
+ void Win32MountingManager::applyScrollView(RnWin32View *view, const ShadowView &shadowView) {
1155
+ if (std::string_view(shadowView.componentName) != "ScrollView") {
1156
+ return;
1157
+ }
1158
+ scrollViews_.update(view, shadowView);
1159
+ }
1160
+
1161
+ // ---------------------------------------------------------------------------
1162
+ // The wheel
1163
+ // ---------------------------------------------------------------------------
1164
+
1165
+ bool Win32MountingManager::scrollAt(
1166
+ RnWin32View *root, double x, double y, double deltaX, double deltaY) {
1167
+ return scrollViews_.scrollAt(root, x, y, deltaX, deltaY);
1168
+ }
1169
+
1170
+ // ---------------------------------------------------------------------------
1171
+ // <TextInput>
1172
+ // ---------------------------------------------------------------------------
1173
+
1174
+
1175
+ // ---------------------------------------------------------------------------
1176
+ // Controls
1177
+ // ---------------------------------------------------------------------------
1178
+
1179
+ void Win32MountingManager::applyControlPeer(RnWin32View *view, const basalt::ControlState &state) {
1180
+ RnWin32View::ControlStyle style;
1181
+ style.on = state.on;
1182
+ style.disabled = state.disabled;
1183
+ style.large = state.large;
1184
+ style.hidesWhenStopped = state.hidesWhenStopped;
1185
+ style.hasThumb = state.hasForeground;
1186
+ style.hasTrackOn = state.hasTrackOn;
1187
+ style.hasTrackOff = state.hasTrackOff;
1188
+ std::copy(std::begin(state.foreground), std::end(state.foreground), std::begin(style.thumb));
1189
+ std::copy(std::begin(state.trackOn), std::end(state.trackOn), std::begin(style.trackOn));
1190
+ std::copy(std::begin(state.trackOff), std::end(state.trackOff), std::begin(style.trackOff));
1191
+
1192
+ if (state.kind == basalt::ControlKind::Switch) {
1193
+ switchValues_[static_cast<Tag>(view->tag())] = state.on;
1194
+ }
1195
+
1196
+ view->setControl(state.kind == basalt::ControlKind::Switch ? RnWin32View::Control::Switch
1197
+ : RnWin32View::Control::Spinner,
1198
+ style,
1199
+ basalt::describeControl(state));
1200
+ }
1201
+
1202
+ void Win32MountingManager::setHighlights(RnWin32View *view,
1203
+ const std::vector<basalt::Highlight> &highlights) {
1204
+ std::vector<RnWin32View::Highlight> converted;
1205
+ converted.reserve(highlights.size());
1206
+ for (const basalt::Highlight &highlight : highlights) {
1207
+ RnWin32View::Highlight entry;
1208
+ entry.x = highlight.x;
1209
+ entry.y = highlight.y;
1210
+ entry.width = highlight.width;
1211
+ entry.height = highlight.height;
1212
+ std::copy(std::begin(highlight.color), std::end(highlight.color), std::begin(entry.color));
1213
+ entry.filled = highlight.filled;
1214
+ converted.push_back(entry);
1215
+ }
1216
+ view->setHighlights(std::move(converted));
1217
+ // Nothing else asks for a repaint: an overlay command arrives outside a mount
1218
+ // transaction, so the window would otherwise show the highlight at whatever
1219
+ // moment something else happened to invalidate it.
1220
+ if (onDidMount_) {
1221
+ onDidMount_();
1222
+ }
1223
+ }
1224
+
1225
+ void Win32MountingManager::pressedView(Tag tag) {
1226
+ RnWin32View *view = viewForTag(tag);
1227
+ if (view == nullptr || view->control() != RnWin32View::Control::Switch) {
1228
+ return;
1229
+ }
1230
+ if (view->controlStyle().disabled) {
1231
+ return;
1232
+ }
1233
+ const auto known = switchValues_.find(tag);
1234
+ if (known == switchValues_.end()) {
1235
+ return;
1236
+ }
1237
+
1238
+ // Told, and then left alone. React Native's <Switch> is a controlled
1239
+ // component: the app's `value` prop is the only thing that moves it, and a
1240
+ // switch that flipped itself would show a state its props do not agree with
1241
+ // -- which is exactly what an app that ignores onValueChange is supposed to
1242
+ // look like. The other two hosts have to put their real widget back for the
1243
+ // same reason; here there is nothing to put back, because nothing moved.
1244
+ basalt::emitSwitchChange(eventEmitterForTag(tag), tag, !known->second);
1245
+ }
1246
+
1247
+ void Win32MountingManager::applyTextInput(RnWin32View *view, const ShadowView &shadowView) {
1248
+ if (std::string_view(shadowView.componentName) != "TextInput") {
1249
+ return;
1250
+ }
1251
+ textInputs_.update(view, shadowView);
1252
+ }
1253
+
1254
+ void Win32MountingManager::setHostWindow(HWND window) {
1255
+ textInputs_.setHostWindow(window);
1256
+ }
1257
+
1258
+ void Win32MountingManager::syncTextInputBounds(RnWin32View *root) {
1259
+ textInputs_.syncBounds(root);
1260
+ }
1261
+
1262
+ bool Win32MountingManager::handleControlCommand(WPARAM wparam, LPARAM lparam) {
1263
+ return textInputs_.handleControlCommand(wparam, lparam);
1264
+ }
1265
+
1266
+ HBITMAP Win32MountingManager::textInputCaretBitmap(Tag tag) const {
1267
+ return textInputs_.caretBitmapFor(tag);
1268
+ }
1269
+
1270
+ HBRUSH Win32MountingManager::controlColor(HDC deviceContext, HWND control) {
1271
+ return textInputs_.controlColor(deviceContext, control);
1272
+ }
1273
+
1274
+ bool Win32MountingManager::typeIntoFocusedTextInput(const std::string &text) {
1275
+ return textInputs_.typeIntoFocused(text);
1276
+ }
1277
+
1278
+ bool Win32MountingManager::focusTextInputAt(RnWin32View *root, double x, double y) {
1279
+ return textInputs_.focusAt(root, x, y);
1280
+ }
1281
+
1282
+ } // namespace basalt