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,744 @@
1
+ // Windows' half of core/PlatformServices.h: the clipboard, opening a URL, an
2
+ // alert, and getting work onto the UI thread.
3
+ //
4
+ // The last of those is the one the mounting manager depends on, and it is the
5
+ // only one with a real design decision in it. See postToUiThread below.
6
+
7
+ #include "PlatformServices.h"
8
+ #include "SystemLocale.h"
9
+ #include "ShareFallback.h"
10
+
11
+ #include "Win32Strings.h"
12
+ #include "Win32UiThread.h"
13
+
14
+ #include <windows.h>
15
+
16
+ #include <shellapi.h>
17
+ #include <shlobj.h>
18
+ #include <shobjidl.h>
19
+
20
+ #include <mutex>
21
+ #include <string>
22
+ #include <thread>
23
+ #include <utility>
24
+ #include <vector>
25
+
26
+ namespace basalt {
27
+
28
+ using win32::narrow;
29
+ using win32::widen;
30
+ namespace {
31
+
32
+ // --- the UI thread -----------------------------------------------------------
33
+ //
34
+ // A message-only window, created on whichever thread calls `installUiThread`
35
+ // first -- which the host does before it starts React Native, and which the
36
+ // tests do not do at all.
37
+ //
38
+ // A message-only window (HWND_MESSAGE) rather than posting to the host's real
39
+ // window: it exists before any surface does, it cannot be destroyed by a user
40
+ // closing something, and it keeps this seam from needing to know what the host
41
+ // draws into. It is also the mechanism a Win32 program is expected to use --
42
+ // PostMessage is the only thread-safe way into a message loop.
43
+ //
44
+ // GTK does this with g_idle_add_full and macOS with dispatch_async_f. All three
45
+ // are the same promise: the work runs on the UI thread, and work posted earlier
46
+ // runs first. That ordering is not a nicety -- a command that arrived before
47
+ // the transaction creating the view it names would find nothing and be dropped.
48
+
49
+ constexpr UINT kRunWork = WM_APP + 1;
50
+
51
+ struct UiThread {
52
+ std::mutex mutex;
53
+ std::vector<std::function<void()>> pending;
54
+ HWND window = nullptr;
55
+ std::thread::id threadId{};
56
+ };
57
+
58
+ UiThread &uiThread() {
59
+ static UiThread instance;
60
+ return instance;
61
+ }
62
+
63
+ void drainPendingWork() {
64
+ std::vector<std::function<void()>> work;
65
+ {
66
+ std::lock_guard<std::mutex> lock(uiThread().mutex);
67
+ work.swap(uiThread().pending);
68
+ }
69
+ for (auto &item : work) {
70
+ item();
71
+ }
72
+ }
73
+
74
+ LRESULT CALLBACK uiThreadProc(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam) {
75
+ if (message == kRunWork) {
76
+ drainPendingWork();
77
+ return 0;
78
+ }
79
+ return DefWindowProc(hwnd, message, wparam, lparam);
80
+ }
81
+
82
+ } // namespace
83
+
84
+ // See Win32UiThread.h.
85
+
86
+ void installUiThread() {
87
+ if (uiThread().window != nullptr) {
88
+ return;
89
+ }
90
+ static const ATOM registered = [] {
91
+ WNDCLASSEXW windowClass{};
92
+ windowClass.cbSize = sizeof(windowClass);
93
+ windowClass.lpfnWndProc = uiThreadProc;
94
+ windowClass.hInstance = GetModuleHandleW(nullptr);
95
+ windowClass.lpszClassName = L"BasaltUiThreadDispatch";
96
+ return RegisterClassExW(&windowClass);
97
+ }();
98
+ (void)registered;
99
+
100
+ uiThread().threadId = std::this_thread::get_id();
101
+ uiThread().window = CreateWindowExW(0,
102
+ L"BasaltUiThreadDispatch",
103
+ L"",
104
+ 0,
105
+ 0,
106
+ 0,
107
+ 0,
108
+ 0,
109
+ HWND_MESSAGE,
110
+ nullptr,
111
+ GetModuleHandleW(nullptr),
112
+ nullptr);
113
+ }
114
+
115
+ bool hasUiThread() {
116
+ return uiThread().window != nullptr;
117
+ }
118
+
119
+ bool isUiThread() {
120
+ // With no UI thread installed there is only one thread that matters, so
121
+ // saying yes is both true and what keeps the tests from marshalling into a
122
+ // message loop nobody is pumping.
123
+ if (uiThread().window == nullptr) {
124
+ return true;
125
+ }
126
+ return std::this_thread::get_id() == uiThread().threadId;
127
+ }
128
+
129
+ void postToUiThread(std::function<void()> work) {
130
+ if (!work) {
131
+ return;
132
+ }
133
+
134
+ // No host, so no message loop to post to: run it here. This is the harness
135
+ // and the test path, and it is safe precisely because there is no second
136
+ // thread in it. A real host installs the window first, after which even work
137
+ // posted *from* the UI thread is queued rather than run inline -- which is
138
+ // what preserves ordering against work already in the queue, and is the same
139
+ // rule the other two platforms follow.
140
+ if (uiThread().window == nullptr) {
141
+ work();
142
+ return;
143
+ }
144
+
145
+ {
146
+ std::lock_guard<std::mutex> lock(uiThread().mutex);
147
+ uiThread().pending.push_back(std::move(work));
148
+ }
149
+ PostMessageW(uiThread().window, kRunWork, 0, 0);
150
+ }
151
+
152
+ void postDelayed(double milliseconds, std::function<void()> work) {
153
+ if (!work) {
154
+ return;
155
+ }
156
+ if (uiThread().window == nullptr) {
157
+ work();
158
+ return;
159
+ }
160
+ // A timer queue rather than SetTimer: SetTimer's resolution is the message
161
+ // loop's and it coalesces, which is wrong for something a JavaScript timer is
162
+ // waiting on. The callback arrives on a pool thread, so it is bounced onto
163
+ // the UI thread rather than running there.
164
+ struct Delayed {
165
+ std::function<void()> work;
166
+ HANDLE timer = nullptr;
167
+ };
168
+ auto *delayed = new Delayed{std::move(work), nullptr};
169
+ const auto fire = [](PVOID parameter, BOOLEAN) {
170
+ auto *item = static_cast<Delayed *>(parameter);
171
+ postToUiThread([item] {
172
+ item->work();
173
+ if (item->timer != nullptr) {
174
+ DeleteTimerQueueTimer(nullptr, item->timer, nullptr);
175
+ }
176
+ delete item;
177
+ });
178
+ };
179
+ if (!CreateTimerQueueTimer(&delayed->timer,
180
+ nullptr,
181
+ fire,
182
+ delayed,
183
+ static_cast<DWORD>(milliseconds < 0 ? 0 : milliseconds),
184
+ 0,
185
+ WT_EXECUTEONLYONCE)) {
186
+ // Could not schedule it; running late is better than never.
187
+ postToUiThread(std::move(delayed->work));
188
+ delete delayed;
189
+ }
190
+ }
191
+
192
+ // --- clipboard ---------------------------------------------------------------
193
+
194
+ namespace {
195
+
196
+ // The clipboard is one lock shared by every window on the desktop, and
197
+ // OpenClipboard does not wait for it: if a window anywhere has it open, the
198
+ // call fails at once with access denied. Clipboard listeners are windows, and
199
+ // each is told of every change and opens the clipboard to read it, so a read or
200
+ // a write that lands while one is reading is refused -- and before this, the
201
+ // refusal was silent: a write simply did not happen.
202
+ //
203
+ // Found as e2e/modules.js failing "clipboard takes unicode", its second write in
204
+ // a row, in 2 of 15 runs on the development machine, which compare_hosts.sh
205
+ // reported as Windows disagreeing with Linux. What was holding the clipboard
206
+ // was never caught: with this retry in place and logging on every refusal, 190
207
+ // further runs saw none at all. So the retry is not proven to be what fixed
208
+ // that; tests/test_win32_clipboard.cpp is what shows it is needed, by holding
209
+ // the clipboard from a window and failing without it.
210
+ //
211
+ // A few short tries is what everyone does, Chromium included. Sleep(5) sleeps
212
+ // a scheduler tick, about 15ms, so this is up to ~150ms on the UI thread --
213
+ // only when somebody else has the clipboard, and a listener holds it for a
214
+ // read rather than for long.
215
+ bool openClipboard() {
216
+ constexpr int kAttempts = 10;
217
+ constexpr DWORD kPauseMs = 5;
218
+ for (int attempt = 0; attempt < kAttempts; ++attempt) {
219
+ if (OpenClipboard(nullptr)) {
220
+ return true;
221
+ }
222
+ Sleep(kPauseMs);
223
+ }
224
+ return false;
225
+ }
226
+
227
+ } // namespace
228
+
229
+ std::string clipboardText() {
230
+ if (!openClipboard()) {
231
+ return {};
232
+ }
233
+ std::string result;
234
+ // CF_UNICODETEXT rather than CF_TEXT: the ANSI variant loses anything outside
235
+ // the active code page, and a clipboard is exactly where that shows up.
236
+ if (const HANDLE handle = GetClipboardData(CF_UNICODETEXT)) {
237
+ if (const auto *text = static_cast<const wchar_t *>(GlobalLock(handle))) {
238
+ result = narrow(text);
239
+ GlobalUnlock(handle);
240
+ }
241
+ }
242
+ CloseClipboard();
243
+ return result;
244
+ }
245
+
246
+ void setClipboardText(const std::string &text) {
247
+ if (!openClipboard()) {
248
+ return;
249
+ }
250
+ EmptyClipboard();
251
+
252
+ const std::wstring wide = widen(text);
253
+ const size_t bytes = (wide.size() + 1) * sizeof(wchar_t);
254
+ // GMEM_MOVEABLE, and ownership passes to the clipboard on success -- freeing
255
+ // it afterwards is a use-after-free that usually survives long enough to be
256
+ // mysterious.
257
+ if (const HGLOBAL handle = GlobalAlloc(GMEM_MOVEABLE, bytes)) {
258
+ if (auto *destination = static_cast<wchar_t *>(GlobalLock(handle))) {
259
+ memcpy(destination, wide.c_str(), bytes);
260
+ GlobalUnlock(handle);
261
+ if (SetClipboardData(CF_UNICODETEXT, handle) == nullptr) {
262
+ GlobalFree(handle);
263
+ }
264
+ } else {
265
+ GlobalFree(handle);
266
+ }
267
+ }
268
+ CloseClipboard();
269
+ }
270
+
271
+ // --- opening a URL -----------------------------------------------------------
272
+
273
+ bool canOpenUrl(const std::string &url) {
274
+ // Answered by asking the registry whether the scheme is registered, which is
275
+ // what "can open" means on Windows: a scheme is a key under HKCR with a
276
+ // URL Protocol value. Not by trying to open it, which would open it.
277
+ const size_t colon = url.find(':');
278
+ if (colon == std::string::npos || colon == 0) {
279
+ return false;
280
+ }
281
+ const std::wstring scheme = widen(url.substr(0, colon));
282
+
283
+ HKEY key = nullptr;
284
+ if (RegOpenKeyExW(HKEY_CLASSES_ROOT, scheme.c_str(), 0, KEY_QUERY_VALUE, &key) != ERROR_SUCCESS) {
285
+ return false;
286
+ }
287
+ const bool isProtocol =
288
+ RegQueryValueExW(key, L"URL Protocol", nullptr, nullptr, nullptr, nullptr) == ERROR_SUCCESS;
289
+ RegCloseKey(key);
290
+ return isProtocol;
291
+ }
292
+
293
+ bool openUrl(const std::string &url) {
294
+ const std::wstring wide = widen(url);
295
+ // ShellExecute returns a fake HINSTANCE; anything above 32 is success. That
296
+ // is the documented contract, odd as it looks.
297
+ const auto result = reinterpret_cast<INT_PTR>(
298
+ ShellExecuteW(nullptr, L"open", wide.c_str(), nullptr, nullptr, SW_SHOWNORMAL));
299
+ return result > 32;
300
+ }
301
+
302
+ // --- sharing -----------------------------------------------------------------
303
+
304
+ // Windows does have a share UI -- the DataTransferManager's, the one the Share
305
+ // charm opens -- and reaching it means WinRT interop:
306
+ // `IDataTransferManagerInterop::ShowShareUIForWindow` against an HWND, plus the
307
+ // activation and the data-requested handler. That is worth doing and is not
308
+ // done here, because it cannot be tested from the machine this was written on
309
+ // and a share sheet that fails is worse than one that is plainly minimal. See
310
+ // docs/BACKLOG.md.
311
+ //
312
+ // Until then, the picker core/ShareFallback.h builds out of a clipboard and a
313
+ // mail client, which is what every desktop has. Nothing here beyond the call:
314
+ // it goes through showAlert, setClipboardText and openUrl, all of which are
315
+ // implemented above.
316
+ void shareContent(const ShareRequest &request, ShareCallback onDone) {
317
+ shareThroughFallbackPicker(request, std::move(onDone));
318
+ }
319
+
320
+ // --- file dialogs -------------------------------------------------------------
321
+
322
+ namespace {
323
+
324
+ // The filters, in the shape IFileDialog takes: one COMDLG_FILTERSPEC per entry,
325
+ // with the extensions joined into a single semicolon-separated pattern. The
326
+ // strings have to outlive the call, which is why they are built into a vector
327
+ // that the caller keeps rather than into temporaries.
328
+ struct FilterStorage {
329
+ std::vector<std::wstring> names;
330
+ std::vector<std::wstring> patterns;
331
+ std::vector<COMDLG_FILTERSPEC> specs;
332
+ };
333
+
334
+ FilterStorage buildFilters(const std::vector<FileFilter> &filters) {
335
+ FilterStorage storage;
336
+ storage.names.reserve(filters.size());
337
+ storage.patterns.reserve(filters.size());
338
+ for (const FileFilter &filter : filters) {
339
+ std::wstring pattern;
340
+ for (const std::string &extension : filter.extensions) {
341
+ if (!pattern.empty()) {
342
+ pattern += L";";
343
+ }
344
+ pattern += L"*.";
345
+ pattern += widen(extension);
346
+ }
347
+ storage.names.push_back(widen(filter.name.empty() ? "Files" : filter.name));
348
+ storage.patterns.push_back(std::move(pattern));
349
+ }
350
+ // Built second, because a vector that grows moves its strings and the specs
351
+ // hold pointers into them.
352
+ storage.specs.reserve(storage.names.size());
353
+ for (size_t i = 0; i < storage.names.size(); i++) {
354
+ storage.specs.push_back(
355
+ COMDLG_FILTERSPEC{storage.names[i].c_str(), storage.patterns[i].c_str()});
356
+ }
357
+ return storage;
358
+ }
359
+
360
+ std::string pathOf(IShellItem *item) {
361
+ PWSTR path = nullptr;
362
+ if (FAILED(item->GetDisplayName(SIGDN_FILESYSPATH, &path)) || path == nullptr) {
363
+ return {};
364
+ }
365
+ const std::string result = narrow(path);
366
+ CoTaskMemFree(path);
367
+ return result;
368
+ }
369
+
370
+ } // namespace
371
+
372
+ void showFileDialog(const FileDialogRequest &request, FileDialogCallback onDone) {
373
+ // Onto the UI thread. IFileDialog::Show runs its own modal loop and must be
374
+ // called on a thread with an apartment, which is the one the host's window
375
+ // lives on -- and running it on the JavaScript thread would deadlock the
376
+ // runtime.
377
+ postToUiThread([request, onDone = std::move(onDone)] {
378
+ const bool saving = request.kind == FileDialogRequest::Kind::SaveFile;
379
+
380
+ IFileDialog *dialog = nullptr;
381
+ const HRESULT created = CoCreateInstance(saving ? CLSID_FileSaveDialog : CLSID_FileOpenDialog,
382
+ nullptr,
383
+ CLSCTX_INPROC_SERVER,
384
+ IID_IFileDialog,
385
+ (void **)&dialog);
386
+ if (FAILED(created) || dialog == nullptr) {
387
+ onDone(true, {});
388
+ return;
389
+ }
390
+
391
+ DWORD options = 0;
392
+ dialog->GetOptions(&options);
393
+ options |= FOS_FORCEFILESYSTEM;
394
+ if (request.kind == FileDialogRequest::Kind::OpenFolder) {
395
+ options |= FOS_PICKFOLDERS;
396
+ }
397
+ if (request.kind == FileDialogRequest::Kind::OpenFile && request.multiple) {
398
+ options |= FOS_ALLOWMULTISELECT;
399
+ }
400
+ dialog->SetOptions(options);
401
+
402
+ if (!request.title.empty()) {
403
+ dialog->SetTitle(widen(request.title).c_str());
404
+ }
405
+ if (!request.confirmLabel.empty()) {
406
+ dialog->SetOkButtonLabel(widen(request.confirmLabel).c_str());
407
+ }
408
+ // A folder picker with file-type filters is a dialog that filters nothing
409
+ // and shows a combo box saying so.
410
+ FilterStorage filters;
411
+ if (request.kind != FileDialogRequest::Kind::OpenFolder && !request.filters.empty()) {
412
+ filters = buildFilters(request.filters);
413
+ if (!filters.specs.empty()) {
414
+ dialog->SetFileTypes(static_cast<UINT>(filters.specs.size()), filters.specs.data());
415
+ }
416
+ }
417
+ if (!request.defaultPath.empty()) {
418
+ const std::wstring wide = widen(request.defaultPath);
419
+ const size_t slash = wide.find_last_of(L"\\/");
420
+ const std::wstring directory = slash == std::wstring::npos ? L"" : wide.substr(0, slash);
421
+ const std::wstring name = slash == std::wstring::npos ? wide : wide.substr(slash + 1);
422
+
423
+ if (saving && !name.empty()) {
424
+ dialog->SetFileName(name.c_str());
425
+ }
426
+ const std::wstring folder = saving ? directory : wide;
427
+ if (!folder.empty()) {
428
+ IShellItem *item = nullptr;
429
+ if (SUCCEEDED(SHCreateItemFromParsingName(folder.c_str(), nullptr, IID_IShellItem,
430
+ (void **)&item)) &&
431
+ item != nullptr) {
432
+ dialog->SetFolder(item);
433
+ item->Release();
434
+ }
435
+ }
436
+ }
437
+
438
+ const HRESULT shown = dialog->Show(GetActiveWindow());
439
+ if (FAILED(shown)) {
440
+ // HRESULT_FROM_WIN32(ERROR_CANCELLED) is Cancel, and every other failure
441
+ // is reported the same way on purpose: an app can do nothing different
442
+ // with "the dialog would not open" than with "the person said no".
443
+ dialog->Release();
444
+ onDone(true, {});
445
+ return;
446
+ }
447
+
448
+ std::vector<std::string> paths;
449
+ IFileOpenDialog *openDialog = nullptr;
450
+ if (!saving && SUCCEEDED(dialog->QueryInterface(IID_IFileOpenDialog, (void **)&openDialog)) &&
451
+ openDialog != nullptr) {
452
+ IShellItemArray *items = nullptr;
453
+ if (SUCCEEDED(openDialog->GetResults(&items)) && items != nullptr) {
454
+ DWORD count = 0;
455
+ items->GetCount(&count);
456
+ for (DWORD i = 0; i < count; i++) {
457
+ IShellItem *item = nullptr;
458
+ if (SUCCEEDED(items->GetItemAt(i, &item)) && item != nullptr) {
459
+ std::string path = pathOf(item);
460
+ if (!path.empty()) {
461
+ paths.push_back(std::move(path));
462
+ }
463
+ item->Release();
464
+ }
465
+ }
466
+ items->Release();
467
+ }
468
+ openDialog->Release();
469
+ } else {
470
+ IShellItem *item = nullptr;
471
+ if (SUCCEEDED(dialog->GetResult(&item)) && item != nullptr) {
472
+ std::string path = pathOf(item);
473
+ if (!path.empty()) {
474
+ paths.push_back(std::move(path));
475
+ }
476
+ item->Release();
477
+ }
478
+ }
479
+
480
+ dialog->Release();
481
+ onDone(paths.empty(), paths);
482
+ });
483
+ }
484
+
485
+ // --- menus --------------------------------------------------------------------
486
+
487
+ namespace {
488
+
489
+ // "Ctrl+R" as a menu label suffix. Windows draws an accelerator by convention
490
+ // rather than by property: the text after a tab in an item's string is
491
+ // right-aligned, and that is all an HMENU knows about shortcuts. Nothing here
492
+ // binds the key -- the host does.
493
+ std::wstring withShortcut(const std::string &label, const std::string &shortcut) {
494
+ std::wstring text = widen(label);
495
+ if (!shortcut.empty()) {
496
+ text += L"\t";
497
+ text += widen(shortcut);
498
+ }
499
+ return text;
500
+ }
501
+
502
+ // Appends `entries` to `menu`, numbering every entry the way `walkMenuEntries`
503
+ // does: pre-order, counting separators and submenu parents, so a flat menu is
504
+ // numbered by position and nothing a caller already relied on moved.
505
+ //
506
+ // The command id is the index plus one, as it was: TrackPopupMenu returns zero
507
+ // for "nothing was chosen", so zero cannot also mean the first item.
508
+ //
509
+ // A submenu is its own popup, handed over with MF_POPUP. Nothing frees it here:
510
+ // DestroyMenu on the root destroys the submenus with it.
511
+ void appendMenuEntries(HMENU menu, const std::vector<MenuEntry> &entries, int *next) {
512
+ for (const MenuEntry &entry : entries) {
513
+ const int index = (*next)++;
514
+ // Counted above, drawn or not: a role this desktop cannot perform keeps its
515
+ // index so the ones after it keep theirs. See menuEntryShown.
516
+ if (!menuEntryShown(entry)) {
517
+ continue;
518
+ }
519
+ if (entry.isSeparator()) {
520
+ AppendMenuW(menu, MF_SEPARATOR, 0, nullptr);
521
+ continue;
522
+ }
523
+
524
+ const std::wstring text = withShortcut(entry.label, entry.shortcut);
525
+ if (entry.isParent()) {
526
+ HMENU submenu = CreatePopupMenu();
527
+ if (submenu == nullptr) {
528
+ continue;
529
+ }
530
+ appendMenuEntries(submenu, entry.submenu, next);
531
+ AppendMenuW(menu,
532
+ MF_POPUP | (entry.enabled ? MF_ENABLED : MF_GRAYED),
533
+ reinterpret_cast<UINT_PTR>(submenu),
534
+ text.c_str());
535
+ continue;
536
+ }
537
+
538
+ AppendMenuW(menu,
539
+ MF_STRING | (entry.enabled ? MF_ENABLED : MF_GRAYED) |
540
+ (entry.mark != MenuEntry::Mark::None && entry.checked ? MF_CHECKED
541
+ : 0U),
542
+ static_cast<UINT_PTR>(index + 1),
543
+ text.c_str());
544
+
545
+ // A bullet rather than a tick, for a radio entry. MFT_RADIOCHECK is not an
546
+ // AppendMenu flag, so it goes on afterwards by position -- and position is
547
+ // not the pre-order index, because an entry menuEntryShown drops consumes no
548
+ // position. GetMenuItemCount after the append is the one that just landed.
549
+ //
550
+ // Per item rather than CheckMenuRadioItem over the run: that call insists on
551
+ // checking one member, so it cannot draw a group with nothing chosen yet,
552
+ // which is a state a caller is entitled to pass.
553
+ if (entry.mark == MenuEntry::Mark::Radio) {
554
+ MENUITEMINFOW info = {};
555
+ info.cbSize = sizeof(info);
556
+ info.fMask = MIIM_FTYPE | MIIM_STATE;
557
+ info.fType = MFT_STRING | MFT_RADIOCHECK;
558
+ info.fState = entry.checked ? MFS_CHECKED : MFS_UNCHECKED;
559
+ if (!entry.enabled) {
560
+ info.fState |= MFS_GRAYED;
561
+ }
562
+ // MIIM_STRING is deliberately absent from the mask, so the label survives.
563
+ SetMenuItemInfoW(menu, GetMenuItemCount(menu) - 1, TRUE, &info);
564
+ }
565
+ }
566
+ }
567
+
568
+ } // namespace
569
+
570
+ void showMenu(const MenuRequest &request, MenuCallback onChosen) {
571
+ // Onto the UI thread. TrackPopupMenuEx runs its own message loop and must be
572
+ // called on the thread that owns the window -- and running it on the
573
+ // JavaScript thread would deadlock the runtime, which is the same reason
574
+ // showAlert and the GTK and AppKit menus marshal.
575
+ postToUiThread([request, onChosen = std::move(onChosen)] {
576
+ HWND window = GetActiveWindow();
577
+ if (window == nullptr) {
578
+ window = GetForegroundWindow();
579
+ }
580
+ if (window == nullptr) {
581
+ onChosen(-1);
582
+ return;
583
+ }
584
+
585
+ HMENU menu = CreatePopupMenu();
586
+ if (menu == nullptr) {
587
+ onChosen(-1);
588
+ return;
589
+ }
590
+
591
+ int next = 0;
592
+ appendMenuEntries(menu, request.entries, &next);
593
+
594
+ POINT at;
595
+ if (request.x >= 0.0 && request.y >= 0.0) {
596
+ // The request is in the window's client coordinates, which is where every
597
+ // other coordinate in this host lives; TrackPopupMenuEx wants screen.
598
+ at.x = static_cast<LONG>(request.x);
599
+ at.y = static_cast<LONG>(request.y);
600
+ ClientToScreen(window, &at);
601
+ } else if (!GetCursorPos(&at)) {
602
+ at.x = 0;
603
+ at.y = 0;
604
+ }
605
+
606
+ // SetForegroundWindow before and the null PostMessage after are both from
607
+ // the documented TrackPopupMenu recipe: without them a menu opened from a
608
+ // window that is not foreground stays up after a click elsewhere, because
609
+ // it never receives the message that would dismiss it.
610
+ SetForegroundWindow(window);
611
+ const int chosen = TrackPopupMenuEx(menu,
612
+ TPM_LEFTALIGN | TPM_TOPALIGN | TPM_RETURNCMD | TPM_NONOTIFY,
613
+ at.x,
614
+ at.y,
615
+ window,
616
+ nullptr);
617
+ PostMessageW(window, WM_NULL, 0, 0);
618
+ DestroyMenu(menu);
619
+
620
+ const int index = chosen > 0 ? chosen - 1 : -1;
621
+ // The platform's half of a role, before the caller's. `copy` has to have
622
+ // copied by the time JavaScript's `onSelect` runs, because an app whose
623
+ // handler reads the clipboard is reading what this just put there. After
624
+ // DestroyMenu, so `close` is not pulling the window out from under a menu
625
+ // that is still up.
626
+ if (index >= 0) {
627
+ const MenuEntry *entry = menuEntryAt(request.entries, index);
628
+ if (entry != nullptr && !entry->role.empty()) {
629
+ performMenuRole(entry->role);
630
+ }
631
+ }
632
+ onChosen(index);
633
+ });
634
+ }
635
+
636
+ // --- alerts ------------------------------------------------------------------
637
+
638
+ void showAlert(const AlertRequest &request, AlertCallback onButton) {
639
+ // MessageBox, which means up to three buttons and no text field. React
640
+ // Native's Alert allows more of both.
641
+ //
642
+ // TaskDialogIndirect would give arbitrary buttons and is the right answer;
643
+ // it needs a comctl32 v6 manifest, which is a host concern rather than a
644
+ // seam concern, so it waits for the host. A prompt needs a custom dialog on
645
+ // every platform -- GTK has the same gap, per docs/BACKLOG.md -- and is not
646
+ // faked here.
647
+ //
648
+ // Onto the UI thread, and back at once. PlatformServices.h says this must
649
+ // not block, and it did: MessageBoxW ran right here, on the
650
+ // JavaScript thread, so while an alert was up the runtime rendered nothing,
651
+ // and a window closed meanwhile never quit -- shutdown joins the JavaScript
652
+ // thread, which was sitting in a dialog nobody would answer. showMenu's
653
+ // comment below even says it marshals "for the same reason showAlert" does.
654
+ // It did not; now it does. The end-to-end suite never saw it because its
655
+ // alerts are answered by BASALT_TEST_DIALOG before this is reached; the
656
+ // cross-host comparison, which does not script dialogs, hung on e2e/share.js.
657
+ const std::wstring title = widen(request.title);
658
+ const std::wstring message = widen(request.message);
659
+
660
+ UINT type = MB_OK;
661
+ if (request.buttons.size() == 2) {
662
+ type = MB_OKCANCEL;
663
+ } else if (request.buttons.size() >= 3) {
664
+ type = MB_YESNOCANCEL;
665
+ }
666
+
667
+ const size_t buttonCount = request.buttons.size();
668
+ postToUiThread([title, message, type, buttonCount, onButton = std::move(onButton)] {
669
+ // Owned by the app's window rather than by nothing: modal to it, placed
670
+ // over it, and destroyed with it -- so a window that closes while an alert
671
+ // is up takes the alert along instead of leaving it on screen for a
672
+ // process that is trying to exit.
673
+ HWND owner = GetActiveWindow();
674
+ if (owner == nullptr) {
675
+ owner = GetForegroundWindow();
676
+ }
677
+ // Task-modal only when there is no window to own it: then it is the one
678
+ // way to keep the rest of this thread's windows from taking input.
679
+ const UINT modality = owner == nullptr ? MB_TASKMODAL : 0;
680
+ const int pressed = MessageBoxW(owner, message.c_str(), title.c_str(), type | modality);
681
+ // Zero is the dialog going away without an answer, which is what its
682
+ // owner being destroyed does. There is no button to report, and the app
683
+ // asking has already been told its window is closing.
684
+ if (!onButton || pressed == 0) {
685
+ return;
686
+ }
687
+
688
+ // Reported as an index into the buttons the app gave, which is what React
689
+ // Native's callback means, rather than as Windows' IDOK/IDCANCEL.
690
+ int index = 0;
691
+ switch (pressed) {
692
+ case IDOK:
693
+ case IDYES:
694
+ index = 0;
695
+ break;
696
+ case IDNO:
697
+ index = 1;
698
+ break;
699
+ case IDCANCEL:
700
+ index = buttonCount == 0 ? 0 : static_cast<int>(buttonCount) - 1;
701
+ break;
702
+ default:
703
+ index = 0;
704
+ break;
705
+ }
706
+ onButton(index, std::string{});
707
+ });
708
+ }
709
+
710
+ } // namespace basalt
711
+
712
+ // --- The desktop's language --------------------------------------------------
713
+
714
+ namespace basalt {
715
+
716
+ // `LOCALE_IREADINGLAYOUT` is Windows' own answer and is what every Win32
717
+ // application mirrors from: 1 means right to left with left-to-right numbers,
718
+ // which is Arabic and Hebrew. The other three values -- vertical layouts --
719
+ // are not mirroring and read as left to right here, which is what they are.
720
+ SystemLocale systemLocale() {
721
+ SystemLocale locale;
722
+
723
+ wchar_t name[LOCALE_NAME_MAX_LENGTH] = {};
724
+ if (GetUserDefaultLocaleName(name, LOCALE_NAME_MAX_LENGTH) > 0) {
725
+ const int bytes =
726
+ WideCharToMultiByte(CP_UTF8, 0, name, -1, nullptr, 0, nullptr, nullptr);
727
+ if (bytes > 1) {
728
+ std::string utf8(static_cast<std::size_t>(bytes - 1), '\0');
729
+ WideCharToMultiByte(CP_UTF8, 0, name, -1, utf8.data(), bytes, nullptr, nullptr);
730
+ locale.identifier = utf8;
731
+ }
732
+
733
+ DWORD layout = 0;
734
+ if (GetLocaleInfoEx(name,
735
+ LOCALE_IREADINGLAYOUT | LOCALE_RETURN_NUMBER,
736
+ reinterpret_cast<LPWSTR>(&layout),
737
+ sizeof(layout) / sizeof(wchar_t)) > 0) {
738
+ locale.rightToLeft = layout == 1;
739
+ }
740
+ }
741
+ return locale;
742
+ }
743
+
744
+ } // namespace basalt