forked from microsoft/react-native-windows
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathReactInstanceWin.cpp
More file actions
1212 lines (1038 loc) · 48.7 KB
/
ReactInstanceWin.cpp
File metadata and controls
1212 lines (1038 loc) · 48.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#include "ReactInstanceWin.h"
#include "MoveOnCopy.h"
#include "MsoUtils.h"
#include <AppModelHelpers.h>
#include <Threading/MessageDispatchQueue.h>
#include <Threading/MessageQueueThreadFactory.h>
#include <appModel.h>
#include <comUtil/qiCast.h>
#ifndef CORE_ABI
#include <LayoutService.h>
#include <XamlUIService.h>
#endif
#include "ReactErrorProvider.h"
#include "Microsoft.ReactNative/IReactNotificationService.h"
#include "NativeModules.h"
#include "NativeModulesProvider.h"
#include "Unicode.h"
#ifdef USE_FABRIC
#include <Fabric/FabricUIManagerModule.h>
#endif
#include <JSCallInvokerScheduler.h>
#include <QuirkSettings.h>
#include <SchedulerSettings.h>
#include <Shared/DevServerHelper.h>
#include <Views/ViewManager.h>
#include <dispatchQueue/dispatchQueue.h>
#include "DynamicWriter.h"
#ifndef CORE_ABI
#include "ConfigureBundlerDlg.h"
#endif
#include "DevMenu.h"
#include "IReactContext.h"
#include "IReactDispatcher.h"
#ifndef CORE_ABI
#include "Modules/AccessibilityInfoModule.h"
#include "Modules/AlertModule.h"
#endif
#if !defined(CORE_ABI) || defined(USE_FABRIC)
#include "Modules/Animated/NativeAnimatedModule.h"
#endif
#ifndef CORE_ABI
#include "Modules/AppStateModule.h"
#include "Modules/AppThemeModuleUwp.h"
#include "Modules/ClipboardModule.h"
#endif
#include "Modules/DevSettingsModule.h"
#ifndef CORE_ABI
#include "Modules/DeviceInfoModule.h"
#include "Modules/I18nManagerModule.h"
#endif
#if !defined(CORE_ABI) || defined(USE_FABRIC)
#include <Modules/ImageViewManagerModule.h>
#endif
#ifndef CORE_ABI
#include "Modules/LinkingManagerModule.h"
#include "Modules/LogBoxModule.h"
#include "Modules/NativeUIManager.h"
#include "Modules/PaperUIManagerModule.h"
#include "Modules/TimingModule.h"
#endif
#include "Modules/ReactRootViewTagGenerator.h"
#ifndef CORE_ABI
#include <Utils/UwpPreparedScriptStore.h>
#include <Utils/UwpScriptStore.h>
#endif
#include "BaseScriptStoreImpl.h"
#include "HermesRuntimeHolder.h"
#include <winrt/Windows.Storage.h>
#if defined(USE_V8)
#include "JSI/V8RuntimeHolder.h"
#endif // USE_V8
#include "RedBox.h"
#include <tuple>
#include "ChakraRuntimeHolder.h"
#include <CppRuntimeOptions.h>
#include <CreateModules.h>
#include <Utils/Helpers.h>
#include <react/renderer/runtimescheduler/RuntimeScheduler.h>
#include "CrashManager.h"
#include "JsiApi.h"
#include "ReactCoreInjection.h"
namespace Microsoft::ReactNative {
void AddStandardViewManagers(
std::vector<std::unique_ptr<Microsoft::ReactNative::IViewManager>> &viewManagers,
const Mso::React::IReactContext &context) noexcept;
std::shared_ptr<facebook::react::IUIManager> CreateUIManager2(
Mso::React::IReactContext *context,
std::vector<Microsoft::ReactNative::IViewManager> &&viewManagers) noexcept;
} // namespace Microsoft::ReactNative
using namespace winrt::Microsoft::ReactNative;
namespace Mso::React {
//=============================================================================================
// LoadedCallbackGuard ensures that the OnReactInstanceLoaded is always called.
// It calls OnReactInstanceLoaded in destructor with a cancellation error.
// If loading was previously succeeded this call with an error code is ignored.
//=============================================================================================
struct LoadedCallbackGuard {
LoadedCallbackGuard(ReactInstanceWin &reactInstance) noexcept : m_reactInstance{&reactInstance} {}
LoadedCallbackGuard(const LoadedCallbackGuard &other) = delete;
LoadedCallbackGuard &operator=(const LoadedCallbackGuard &other) = delete;
LoadedCallbackGuard(LoadedCallbackGuard &&other) = default;
LoadedCallbackGuard &operator=(LoadedCallbackGuard &&other) = default;
~LoadedCallbackGuard() noexcept {
if (m_reactInstance) {
m_reactInstance->OnReactInstanceLoaded(Mso::CancellationErrorProvider().MakeErrorCode(true));
}
}
private:
Mso::CntPtr<ReactInstanceWin> m_reactInstance;
};
struct BridgeUIBatchInstanceCallback final : public facebook::react::InstanceCallback {
BridgeUIBatchInstanceCallback(Mso::WeakPtr<ReactInstanceWin> wkInstance) : m_wkInstance(wkInstance) {}
virtual ~BridgeUIBatchInstanceCallback() = default;
void onBatchComplete() override {
if (auto instance = m_wkInstance.GetStrongPtr()) {
auto state = instance->State();
if (state != ReactInstanceState::HasError && state != ReactInstanceState::Unloaded) {
if (instance->UseWebDebugger()) {
// While using a CxxModule for UIManager (which we do when running under webdebugger)
// We need to post the batch complete to the NativeQueue to ensure that the UIManager
// has posted everything from this batch into its queue before we complete the batch.
instance->m_jsDispatchQueue.Load().Post([wkInstance = m_wkInstance]() {
if (auto instance = wkInstance.GetStrongPtr()) {
instance->m_batchingUIThread->runOnQueue([wkInstance]() {
if (auto instance = wkInstance.GetStrongPtr()) {
auto propBag = ReactPropertyBag(instance->m_reactContext->Properties());
if (auto callback = propBag.Get(winrt::Microsoft::ReactNative::implementation::ReactCoreInjection::
UIBatchCompleteCallbackProperty())) {
(*callback)(instance->m_reactContext->Properties());
}
#ifndef CORE_ABI
if (auto uiManager = Microsoft::ReactNative::GetNativeUIManager(*instance->m_reactContext).lock()) {
uiManager->onBatchComplete();
}
#endif
}
});
// For UWP we use a batching message queue to optimize the usage
// of the CoreDispatcher. Win32 already has an optimized queue.
facebook::react::BatchingMessageQueueThread *batchingUIThread =
static_cast<facebook::react::BatchingMessageQueueThread *>(instance->m_batchingUIThread.get());
if (batchingUIThread != nullptr) {
batchingUIThread->onBatchComplete();
}
}
});
} else {
instance->m_batchingUIThread->runOnQueue([wkInstance = m_wkInstance]() {
if (auto instance = wkInstance.GetStrongPtr()) {
auto propBag = ReactPropertyBag(instance->m_reactContext->Properties());
if (auto callback = propBag.Get(winrt::Microsoft::ReactNative::implementation::ReactCoreInjection::
UIBatchCompleteCallbackProperty())) {
(*callback)(instance->m_reactContext->Properties());
}
#ifndef CORE_ABI
if (auto uiManager = Microsoft::ReactNative::GetNativeUIManager(*instance->m_reactContext).lock()) {
uiManager->onBatchComplete();
}
#endif
}
});
// For UWP we use a batching message queue to optimize the usage
// of the CoreDispatcher. Win32 already has an optimized queue.
facebook::react::BatchingMessageQueueThread *batchingUIThread =
static_cast<facebook::react::BatchingMessageQueueThread *>(instance->m_batchingUIThread.get());
if (batchingUIThread != nullptr) {
batchingUIThread->onBatchComplete();
}
}
}
}
}
void incrementPendingJSCalls() override {}
void decrementPendingJSCalls() override {}
Mso::WeakPtr<ReactInstanceWin> m_wkInstance;
Mso::CntPtr<Mso::React::ReactContext> m_context;
std::weak_ptr<facebook::react::MessageQueueThread> m_uiThread;
};
//=============================================================================================
// ReactInstanceWin implementation
//=============================================================================================
/*static*/ std::mutex ReactInstanceWin::s_registryMutex;
/*static*/ std::vector<ReactInstanceWin *> ReactInstanceWin::s_instanceRegistry;
ReactInstanceWin::ReactInstanceWin(
IReactHost &reactHost,
ReactOptions const &options,
Mso::Promise<void> &&whenCreated,
Mso::Promise<void> &&whenLoaded,
Mso::VoidFunctor &&updateUI) noexcept
: Super{reactHost.NativeQueue()},
m_weakReactHost{&reactHost},
m_options{options},
m_whenCreated{std::move(whenCreated)},
m_isFastReloadEnabled(options.UseFastRefresh()),
m_isLiveReloadEnabled(options.UseLiveReload()),
m_updateUI{std::move(updateUI)},
m_useWebDebugger(options.UseWebDebugger()),
m_useDirectDebugger(options.UseDirectDebugger()),
m_debuggerBreakOnNextLine(options.DebuggerBreakOnNextLine()),
m_reactContext{Mso::Make<ReactContext>(
this,
options.Properties,
winrt::make<implementation::ReactNotificationService>(options.Notifications))} {
// As soon as the bundle is loaded or failed to load, we set the m_whenLoaded promise value in JS queue.
// It then synchronously raises the OnInstanceLoaded event in the JS queue.
// Then, we notify the ReactHost about the load event in the internal queue.
m_whenLoaded.AsFuture()
.Then<Mso::Executors::Inline>(
[onLoaded = m_options.OnInstanceLoaded, reactContext = m_reactContext](Mso::Maybe<void> &&value) noexcept {
auto errCode = value.IsError() ? value.TakeError() : Mso::ErrorCode();
if (onLoaded) {
onLoaded.Get()->Invoke(reactContext, errCode);
}
return Mso::Maybe<void>(errCode);
})
.Then(Queue(), [whenLoaded = std::move(whenLoaded)](Mso::Maybe<void> &&value) noexcept {
whenLoaded.SetValue(std::move(value));
});
// When the JS queue is shutdown, we set the m_whenDestroyed promise value as the last work item in the JS queue.
// No JS queue work can be done after that for the instance.
// The promise continuation synchronously calls the OnInstanceDestroyed event.
// Then, the Destroy() method returns the m_whenDestroyedResult future to ReactHost to handle instance destruction.
m_whenDestroyedResult =
m_whenDestroyed.AsFuture().Then<Mso::Executors::Inline>([whenLoaded = m_whenLoaded,
onDestroyed = m_options.OnInstanceDestroyed,
reactContext = m_reactContext]() noexcept {
whenLoaded.TryCancel(); // It only has an effect if whenLoaded was not set before
Microsoft::ReactNative::HermesRuntimeHolder::storeTo(ReactPropertyBag(reactContext->Properties()), nullptr);
if (onDestroyed) {
onDestroyed.Get()->Invoke(reactContext);
}
});
// We notify the ReactHost immediately that the instance is created, but the
// OnInstanceCreated event is raised only after the internal react-native instance is ready and
// it starts handling JS queue work items.
m_whenCreated.SetValue();
if (m_options.EnableDefaultCrashHandler()) {
CrashManager::RegisterCustomHandler();
}
{
std::scoped_lock lock{s_registryMutex};
s_instanceRegistry.push_back(this);
}
}
ReactInstanceWin::~ReactInstanceWin() noexcept {
std::scoped_lock lock{s_registryMutex};
auto it = std::find(s_instanceRegistry.begin(), s_instanceRegistry.end(), this);
if (it != s_instanceRegistry.end()) {
s_instanceRegistry.erase(it);
}
if (m_options.EnableDefaultCrashHandler()) {
CrashManager::UnregisterCustomHandler();
}
}
void ReactInstanceWin::InstanceCrashHandler(int fileDescriptor) noexcept {
if (!m_options.EnableDefaultCrashHandler()) {
return;
}
if (m_jsiRuntimeHolder) {
m_jsiRuntimeHolder->crashHandler(fileDescriptor);
}
// record additional information that could be useful for debugging crash dumps here
// (perhaps properties and settings or clues about the react tree)
}
/*static*/ void ReactInstanceWin::CrashHandler(int fileDescriptor) noexcept {
std::scoped_lock lock{s_registryMutex};
for (auto &entry : s_instanceRegistry) {
entry->InstanceCrashHandler(fileDescriptor);
}
}
void ReactInstanceWin::LoadModules(
const std::shared_ptr<winrt::Microsoft::ReactNative::NativeModulesProvider> &nativeModulesProvider,
const std::shared_ptr<winrt::Microsoft::ReactNative::TurboModulesProvider> &turboModulesProvider) noexcept {
auto registerTurboModule = [this, &nativeModulesProvider, &turboModulesProvider](
const wchar_t *name, const ReactModuleProvider &provider) noexcept {
if (m_options.UseWebDebugger()) {
nativeModulesProvider->AddModuleProvider(name, provider);
} else {
turboModulesProvider->AddModuleProvider(name, provider, false);
}
};
#ifdef USE_FABRIC
if (!m_options.UseWebDebugger()) {
registerTurboModule(
L"FabricUIManagerBinding",
winrt::Microsoft::ReactNative::MakeModuleProvider<::Microsoft::ReactNative::FabricUIManager>());
}
#endif
#ifndef CORE_ABI
registerTurboModule(
L"UIManager",
// TODO: Use MakeTurboModuleProvider after it satisfies ReactNativeSpecs::UIManagerSpec
winrt::Microsoft::ReactNative::MakeModuleProvider<::Microsoft::ReactNative::UIManager>());
registerTurboModule(
L"AccessibilityInfo",
winrt::Microsoft::ReactNative::MakeTurboModuleProvider<::Microsoft::ReactNative::AccessibilityInfo>());
registerTurboModule(
L"Alert", winrt::Microsoft::ReactNative::MakeTurboModuleProvider<::Microsoft::ReactNative::Alert>());
registerTurboModule(
L"Appearance", winrt::Microsoft::ReactNative::MakeTurboModuleProvider<::Microsoft::ReactNative::Appearance>());
registerTurboModule(
L"AppState", winrt::Microsoft::ReactNative::MakeTurboModuleProvider<::Microsoft::ReactNative::AppState>());
registerTurboModule(
L"AppTheme", winrt::Microsoft::ReactNative::MakeTurboModuleProvider<::Microsoft::ReactNative::AppTheme>());
registerTurboModule(
L"LogBox", winrt::Microsoft::ReactNative::MakeTurboModuleProvider<::Microsoft::ReactNative::LogBox>());
registerTurboModule(
L"Clipboard", winrt::Microsoft::ReactNative::MakeTurboModuleProvider<::Microsoft::ReactNative::Clipboard>());
registerTurboModule(
L"DeviceInfo", winrt::Microsoft::ReactNative::MakeTurboModuleProvider<::Microsoft::ReactNative::DeviceInfo>());
registerTurboModule(
L"ImageLoader", winrt::Microsoft::ReactNative::MakeTurboModuleProvider<::Microsoft::ReactNative::ImageLoader>());
registerTurboModule(
L"NativeAnimatedModule",
winrt::Microsoft::ReactNative::MakeModuleProvider<::Microsoft::ReactNative::NativeAnimatedModule>());
#elif defined(CORE_ABI) && defined(USE_FABRIC)
if (Microsoft::ReactNative::IsFabricEnabled(m_reactContext->Properties())) {
registerTurboModule(
L"ImageLoader",
winrt::Microsoft::ReactNative::MakeTurboModuleProvider<::Microsoft::ReactNative::ImageLoader>());
registerTurboModule(
L"NativeAnimatedModule",
winrt::Microsoft::ReactNative::MakeModuleProvider<::Microsoft::ReactNative::NativeAnimatedModule>());
}
#endif
registerTurboModule(
L"DevSettings", winrt::Microsoft::ReactNative::MakeTurboModuleProvider<::Microsoft::ReactNative::DevSettings>());
#ifndef CORE_ABI
registerTurboModule(
L"I18nManager", winrt::Microsoft::ReactNative::MakeTurboModuleProvider<::Microsoft::ReactNative::I18nManager>());
registerTurboModule(
L"LinkingManager",
winrt::Microsoft::ReactNative::MakeTurboModuleProvider<::Microsoft::ReactNative::LinkingManager>());
registerTurboModule(
L"Timing", winrt::Microsoft::ReactNative::MakeTurboModuleProvider<::Microsoft::ReactNative::Timing>());
#endif
registerTurboModule(
::Microsoft::React::GetWebSocketTurboModuleName(), ::Microsoft::React::GetWebSocketModuleProvider());
if (!Microsoft::React::GetRuntimeOptionBool("Blob.DisableModule")) {
registerTurboModule(::Microsoft::React::GetHttpTurboModuleName(), ::Microsoft::React::GetHttpModuleProvider());
registerTurboModule(::Microsoft::React::GetBlobTurboModuleName(), ::Microsoft::React::GetBlobModuleProvider());
registerTurboModule(
::Microsoft::React::GetFileReaderTurboModuleName(), ::Microsoft::React::GetFileReaderModuleProvider());
}
}
//! Initialize() is called from the native queue.
void ReactInstanceWin::Initialize() noexcept {
InitJSMessageThread();
InitNativeMessageThread();
InitUIMessageThread();
#ifndef CORE_ABI
// InitUIManager uses m_legacyReactInstance
InitUIManager();
#endif
Microsoft::ReactNative::DevMenuManager::InitDevMenu(m_reactContext, [weakReactHost = m_weakReactHost]() noexcept {
#ifndef CORE_ABI
Microsoft::ReactNative::ShowConfigureBundlerDialog(weakReactHost);
#endif // CORE_ABI
});
m_uiQueue->Post([this, weakThis = Mso::WeakPtr{this}]() noexcept {
// Objects that must be created on the UI thread
if (auto strongThis = weakThis.GetStrongPtr()) {
#ifndef CORE_ABI
Microsoft::ReactNative::AppThemeHolder::InitAppThemeHolder(strongThis->GetReactContext());
Microsoft::ReactNative::I18nManager::InitI18nInfo(
winrt::Microsoft::ReactNative::ReactPropertyBag(strongThis->Options().Properties));
Microsoft::ReactNative::Appearance::InitOnUIThread(strongThis->GetReactContext());
Microsoft::ReactNative::DeviceInfoHolder::InitDeviceInfoHolder(strongThis->GetReactContext());
#endif // CORE_ABI
strongThis->Queue().Post([this, weakThis]() noexcept {
if (auto strongThis = weakThis.GetStrongPtr()) {
// auto cxxModulesProviders = GetCxxModuleProviders();
auto devSettings = std::make_shared<facebook::react::DevSettings>();
devSettings->useJITCompilation = m_options.EnableJITCompilation;
devSettings->sourceBundleHost = SourceBundleHost();
devSettings->sourceBundlePort = SourceBundlePort();
devSettings->inlineSourceMap = RequestInlineSourceMap();
devSettings->debugBundlePath = DebugBundlePath();
devSettings->liveReloadCallback = GetLiveReloadCallback();
devSettings->errorCallback = GetErrorCallback();
devSettings->loggingCallback = GetLoggingCallback();
m_redboxHandler = devSettings->redboxHandler = std::move(GetRedBoxHandler());
devSettings->useDirectDebugger = m_useDirectDebugger;
devSettings->debuggerBreakOnNextLine = m_debuggerBreakOnNextLine;
devSettings->debuggerPort = m_options.DeveloperSettings.DebuggerPort;
devSettings->debuggerRuntimeName = m_options.DeveloperSettings.DebuggerRuntimeName;
devSettings->useWebDebugger = m_useWebDebugger;
devSettings->useFastRefresh = m_isFastReloadEnabled;
devSettings->bundleRootPath = BundleRootPath();
devSettings->platformName =
winrt::Microsoft::ReactNative::implementation::ReactCoreInjection::GetPlatformName(
strongThis->m_reactContext->Properties());
devSettings->waitingForDebuggerCallback = GetWaitingForDebuggerCallback();
devSettings->debuggerAttachCallback = GetDebuggerAttachCallback();
devSettings->enableDefaultCrashHandler = m_options.EnableDefaultCrashHandler();
devSettings->bundleAppId = BundleAppId();
devSettings->devBundle = RequestDevBundle();
devSettings->showDevMenuCallback = [weakThis]() noexcept {
if (auto strongThis = weakThis.GetStrongPtr()) {
strongThis->m_uiQueue->Post(
[context = strongThis->m_reactContext]() { Microsoft::ReactNative::DevMenuManager::Show(context); });
}
};
std::vector<facebook::react::NativeModuleDescription> cxxModules;
auto nmp = std::make_shared<winrt::Microsoft::ReactNative::NativeModulesProvider>();
LoadModules(nmp, m_options.TurboModuleProvider);
auto modules = nmp->GetModules(m_reactContext, m_jsMessageThread.Load());
cxxModules.insert(
cxxModules.end(), std::make_move_iterator(modules.begin()), std::make_move_iterator(modules.end()));
if (m_options.ModuleProvider != nullptr) {
std::vector<facebook::react::NativeModuleDescription> customCxxModules =
m_options.ModuleProvider->GetModules(m_reactContext, m_jsMessageThread.Load());
cxxModules.insert(std::end(cxxModules), std::begin(customCxxModules), std::end(customCxxModules));
}
std::unique_ptr<facebook::jsi::ScriptStore> scriptStore = nullptr;
std::unique_ptr<facebook::jsi::PreparedScriptStore> preparedScriptStore = nullptr;
switch (m_options.JsiEngine()) {
case JSIEngine::Hermes: {
// TODO: Should we use UwpPreparedScriptStore?
if (Microsoft::ReactNative::HasPackageIdentity()) {
preparedScriptStore =
std::make_unique<facebook::react::BasePreparedScriptStoreImpl>(getApplicationTempFolder());
} else {
wchar_t tempPath[MAX_PATH];
if (GetTempPathW(static_cast<DWORD>(std::size(tempPath)), tempPath)) {
preparedScriptStore =
std::make_unique<facebook::react::BasePreparedScriptStoreImpl>(winrt::to_string(tempPath));
}
}
auto hermesRuntimeHolder = std::make_shared<Microsoft::ReactNative::HermesRuntimeHolder>(
devSettings, m_jsMessageThread.Load(), std::move(preparedScriptStore));
Microsoft::ReactNative::HermesRuntimeHolder::storeTo(
ReactPropertyBag(m_reactContext->Properties()), hermesRuntimeHolder);
devSettings->jsiRuntimeHolder = hermesRuntimeHolder;
break;
}
case JSIEngine::V8:
#if defined(USE_V8)
{
if (Microsoft::ReactNative::HasPackageIdentity()) {
preparedScriptStore =
std::make_unique<facebook::react::BasePreparedScriptStoreImpl>(getApplicationTempFolder());
} else {
wchar_t tempPath[MAX_PATH];
if (GetTempPathW(static_cast<DWORD>(std::size(tempPath)), tempPath)) {
preparedScriptStore =
std::make_unique<facebook::react::BasePreparedScriptStoreImpl>(winrt::to_string(tempPath));
}
}
bool enableMultiThreadSupport{false};
#ifdef USE_FABRIC
enableMultiThreadSupport = Microsoft::ReactNative::IsFabricEnabled(m_reactContext->Properties());
#endif // USE_FABRIC
devSettings->jsiRuntimeHolder = std::make_shared<Microsoft::ReactNative::V8RuntimeHolder>(
devSettings, m_jsMessageThread.Load(), std::move(preparedScriptStore), enableMultiThreadSupport);
break;
}
#endif // USE_V8
case JSIEngine::Chakra:
#ifndef CORE_ABI
if (m_options.EnableByteCodeCaching || !m_options.ByteCodeFileUri.empty()) {
scriptStore = std::make_unique<Microsoft::ReactNative::UwpScriptStore>();
preparedScriptStore = std::make_unique<Microsoft::ReactNative::UwpPreparedScriptStore>(
winrt::to_hstring(m_options.ByteCodeFileUri));
}
#endif
devSettings->jsiRuntimeHolder = std::make_shared<Microsoft::JSI::ChakraRuntimeHolder>(
devSettings, m_jsMessageThread.Load(), std::move(scriptStore), std::move(preparedScriptStore));
break;
}
m_jsiRuntimeHolder = devSettings->jsiRuntimeHolder;
try {
// We need to keep the instance wrapper alive as its destruction shuts down the native queue.
m_options.TurboModuleProvider->SetReactContext(
winrt::make<implementation::ReactContext>(Mso::Copy(m_reactContext)));
auto omitNetCxxPropName = ReactPropertyBagHelper::GetName(nullptr, L"OmitNetworkingCxxModules");
auto omitNetCxxPropValue = m_options.Properties.Get(omitNetCxxPropName);
devSettings->omitNetworkingCxxModules = winrt::unbox_value_or(omitNetCxxPropValue, false);
auto useWebSocketTurboModulePropName = ReactPropertyBagHelper::GetName(nullptr, L"UseWebSocketTurboModule");
auto useWebSocketTurboModulePropValue = m_options.Properties.Get(useWebSocketTurboModulePropName);
devSettings->useWebSocketTurboModule = winrt::unbox_value_or(useWebSocketTurboModulePropValue, false);
auto bundleRootPath = devSettings->bundleRootPath;
auto jsiRuntimeHolder = devSettings->jsiRuntimeHolder;
auto instance = strongThis->m_instance.Load();
const auto runtimeExecutor = instance->getRuntimeExecutor();
const auto runtimeScheduler = std::make_shared<facebook::react::RuntimeScheduler>(runtimeExecutor);
auto instanceWrapper = facebook::react::CreateReactInstance(
std::move(instance),
std::move(bundleRootPath), // bundleRootPath
std::move(cxxModules),
m_options.TurboModuleProvider,
runtimeScheduler,
m_options.TurboModuleProvider->LongLivedObjectCollection(),
std::make_unique<BridgeUIBatchInstanceCallback>(weakThis),
m_jsMessageThread.Load(),
m_nativeMessageThread.Load(),
std::move(devSettings));
m_instanceWrapper.Exchange(std::move(instanceWrapper));
// The InstanceCreated event can be used to augment the JS environment for all JS code. So it needs to be
// triggered before any platform JS code is run. Using m_jsMessageThread instead of jsDispatchQueue avoids
// waiting for the JSCaller which can delay the event until after certain JS code has already run
m_jsMessageThread.Load()->runOnQueue([onCreated = m_options.OnInstanceCreated,
reactContext = m_reactContext,
jsiRuntimeHolder = std::move(jsiRuntimeHolder),
instanceWrapper = m_instanceWrapper.Load(),
instance = m_instance.Load(),
turboModuleProvider = m_options.TurboModuleProvider,
runtimeScheduler = std::move(runtimeScheduler),
useWebDebugger = m_options.UseWebDebugger()]() noexcept {
if (!useWebDebugger) {
#ifdef USE_FABRIC
Microsoft::ReactNative::SchedulerSettings::SetRuntimeExecutor(
winrt::Microsoft::ReactNative::ReactPropertyBag(reactContext->Properties()),
instanceWrapper->GetInstance()->getRuntimeExecutor());
#endif
if (winrt::Microsoft::ReactNative::implementation::QuirkSettings::GetUseRuntimeScheduler(
winrt::Microsoft::ReactNative::ReactPropertyBag(reactContext->Properties()))) {
Microsoft::ReactNative::SchedulerSettings::SetRuntimeScheduler(
ReactPropertyBag(reactContext->Properties()), runtimeScheduler);
}
}
#ifdef USE_FABRIC
// Eagerly init the FabricUI binding
if (!useWebDebugger) {
turboModuleProvider->getModule("FabricUIManagerBinding", instance->getJSCallInvoker());
}
#endif
if (onCreated) {
onCreated.Get()->Invoke(reactContext);
}
});
LoadJSBundles();
if (UseDeveloperSupport() && State() != ReactInstanceState::HasError) {
folly::dynamic params = folly::dynamic::array(
winrt::Microsoft::ReactNative::implementation::ReactCoreInjection::GetPlatformName(
m_reactContext->Properties()),
DebugBundlePath(),
SourceBundleHost(),
SourceBundlePort(),
m_isFastReloadEnabled,
"ws");
m_instance.Load()->callJSFunction("HMRClient", "setup", std::move(params));
}
} catch (std::exception &e) {
OnErrorWithMessage(e.what());
OnErrorWithMessage("UwpReactInstance: Failed to create React Instance.");
} catch (winrt::hresult_error const &e) {
OnErrorWithMessage(Microsoft::Common::Unicode::Utf16ToUtf8(e.message().c_str(), e.message().size()));
OnErrorWithMessage("UwpReactInstance: Failed to create React Instance.");
} catch (...) {
OnErrorWithMessage("UwpReactInstance: Failed to create React Instance.");
}
}
});
};
});
}
void ReactInstanceWin::LoadJSBundles() noexcept {
//
// We use m_jsMessageThread to load JS bundles synchronously. In that case we only load
// them if the m_jsMessageThread is not shut down (quitSynchronous() is not called).
// After the load we call OnReactInstanceLoaded callback on native queue.
//
// Note that the instance could be destroyed while we are loading JS Bundles.
// Though, the JS engine is not destroyed until this work item is not finished.
// Thus, we check the m_isDestroyed flag to see if we should do an early exit.
// Also, since we have to guarantee that the OnReactInstanceLoaded callback is called before
// the OnReactInstanceDestroyed callback, the OnReactInstanceLoaded is called right before the
// OnReactInstanceDestroyed callback in the Destroy() method. In that case any OnReactInstanceLoaded
// calls after we finish this JS message queue work item is ignored.
//
// The LoadedCallbackGuard is used for the case when runOnQueue does not execute the lambda
// before destroying it. It may happen if the m_jsMessageThread is already shutdown.
// In that case, the LoadedCallbackGuard notifies about cancellation by calling OnReactInstanceLoaded.
// The OnReactInstanceLoaded internally only accepts the first call and ignores others.
//
if (m_useWebDebugger || m_isFastReloadEnabled) {
// Getting bundle from the packager, so do everything async.
auto instanceWrapper = m_instanceWrapper.LoadWithLock();
instanceWrapper->loadBundle(Mso::Copy(JavaScriptBundleFile()));
m_jsMessageThread.Load()->runOnQueue(
[weakThis = Mso::WeakPtr{this},
loadCallbackGuard = Mso::MakeMoveOnCopyWrapper(LoadedCallbackGuard{*this})]() noexcept {
if (auto strongThis = weakThis.GetStrongPtr()) {
if (strongThis->State() != ReactInstanceState::HasError) {
strongThis->OnReactInstanceLoaded(Mso::ErrorCode{});
}
}
});
} else {
m_jsMessageThread.Load()->runOnQueue(
[weakThis = Mso::WeakPtr{this},
loadCallbackGuard = Mso::MakeMoveOnCopyWrapper(LoadedCallbackGuard{*this})]() noexcept {
if (auto strongThis = weakThis.GetStrongPtr()) {
auto instance = strongThis->m_instance.LoadWithLock();
auto instanceWrapper = strongThis->m_instanceWrapper.LoadWithLock();
if (!instance || !instanceWrapper) {
return;
}
try {
instanceWrapper->loadBundleSync(Mso::Copy(strongThis->JavaScriptBundleFile()));
if (strongThis->State() != ReactInstanceState::HasError) {
strongThis->OnReactInstanceLoaded(Mso::ErrorCode{});
}
} catch (...) {
strongThis->OnReactInstanceLoaded(Mso::ExceptionErrorProvider().MakeErrorCode(std::current_exception()));
}
}
});
}
}
void ReactInstanceWin::OnReactInstanceLoaded(const Mso::ErrorCode &errorCode) noexcept {
bool isLoadedExpected = false;
if (m_isLoaded.compare_exchange_strong(isLoadedExpected, true)) {
if (!errorCode) {
m_state = ReactInstanceState::Loaded;
m_whenLoaded.SetValue();
DrainJSCallQueue();
} else {
m_state = ReactInstanceState::HasError;
m_whenLoaded.SetError(errorCode);
OnError(errorCode);
}
}
}
Mso::Future<void> ReactInstanceWin::Destroy() noexcept {
// This method must be called from the native queue.
VerifyIsInQueueElseCrash();
if (m_isDestroyed) {
return m_whenDestroyedResult;
}
m_isDestroyed = true;
m_state = ReactInstanceState::Unloaded;
AbandonJSCallQueue();
// Make sure that the instance is not destroyed yet
if (auto instance = m_instance.Exchange(nullptr)) {
{
// Release the JSI runtime
std::scoped_lock lock{m_mutex};
m_jsiRuntimeHolder = nullptr;
m_jsiRuntime = nullptr;
}
// Release the message queues before the ui manager and instance.
m_nativeMessageThread.Exchange(nullptr);
m_jsMessageThread.Exchange(nullptr);
m_instanceWrapper.Exchange(nullptr);
m_jsDispatchQueue.Exchange(nullptr);
}
return m_whenDestroyedResult;
}
const ReactOptions &ReactInstanceWin::Options() const noexcept {
return m_options;
}
ReactInstanceState ReactInstanceWin::State() const noexcept {
return m_state;
}
void ReactInstanceWin::InitJSMessageThread() noexcept {
m_instance.Exchange(std::make_shared<facebook::react::Instance>());
winrt::Microsoft::ReactNative::IReactNotificationService service = m_reactContext->Notifications();
Mso::DispatchQueueSettings queueSettings{};
queueSettings.TaskStarting = [service](Mso::DispatchQueue const &) noexcept {
service.SendNotification(
winrt::Microsoft::ReactNative::ReactDispatcherHelper::JSDispatcherTaskStartingEventName(), nullptr, nullptr);
};
queueSettings.IdleWaitStarting = [service](Mso::DispatchQueue const &) noexcept {
service.SendNotification(
winrt::Microsoft::ReactNative::ReactDispatcherHelper::JSDispatcherIdleWaitStartingEventName(),
nullptr,
nullptr);
};
queueSettings.IdleWaitCompleted = [service](Mso::DispatchQueue const &) noexcept {
service.SendNotification(
winrt::Microsoft::ReactNative::ReactDispatcherHelper::JSDispatcherIdleWaitCompletedEventName(),
nullptr,
nullptr);
};
auto scheduler = Mso::MakeJSCallInvokerScheduler(
queueSettings,
m_instance.Load()->getJSCallInvoker(),
Mso::MakeWeakMemberFunctor(this, &ReactInstanceWin::OnError),
Mso::Copy(m_whenDestroyed));
auto jsDispatchQueue = Mso::DispatchQueue::MakeCustomQueue(Mso::CntPtr(scheduler));
auto jsDispatcher =
winrt::make<winrt::Microsoft::ReactNative::implementation::ReactDispatcher>(Mso::Copy(jsDispatchQueue));
m_options.Properties.Set(ReactDispatcherHelper::JSDispatcherProperty(), jsDispatcher);
m_jsMessageThread.Exchange(qi_cast<Mso::IJSCallInvokerQueueScheduler>(scheduler.Get())->GetMessageQueue());
m_jsDispatchQueue.Exchange(std::move(jsDispatchQueue));
}
void ReactInstanceWin::InitNativeMessageThread() noexcept {
// Native queue was already given us in constructor.
m_nativeMessageThread.Exchange(
std::make_shared<MessageDispatchQueue>(Queue(), Mso::MakeWeakMemberFunctor(this, &ReactInstanceWin::OnError)));
}
void ReactInstanceWin::InitUIMessageThread() noexcept {
// Native queue was already given us in constructor.
m_uiQueue = winrt::Microsoft::ReactNative::implementation::ReactDispatcher::GetUIDispatchQueue2(m_options.Properties);
VerifyElseCrashSz(m_uiQueue, "No UI Dispatcher provided");
m_uiMessageThread.Exchange(std::make_shared<MessageDispatchQueue2>(
*m_uiQueue, Mso::MakeWeakMemberFunctor(this, &ReactInstanceWin::OnError)));
auto batchingUIThread = Microsoft::ReactNative::MakeBatchingQueueThread(m_uiMessageThread.Load());
m_batchingUIThread = batchingUIThread;
ReactPropertyBag(m_reactContext->Properties())
.Set(
winrt::Microsoft::ReactNative::implementation::ReactCoreInjection::PostToUIBatchingQueueProperty(),
[wkBatchingUIThread = std::weak_ptr<facebook::react::BatchingMessageQueueThread>(batchingUIThread)](
winrt::Microsoft::ReactNative::ReactDispatcherCallback const &callback) {
if (auto batchingUIThread = wkBatchingUIThread.lock()) {
batchingUIThread->runOnQueue(callback);
}
});
m_jsDispatchQueue.Load().Post(
[batchingUIThread, instance = std::weak_ptr<facebook::react::Instance>(m_instance.Load())]() noexcept {
batchingUIThread->decoratedNativeCallInvokerReady(instance);
});
}
#ifndef CORE_ABI
void ReactInstanceWin::InitUIManager() noexcept {
std::vector<std::unique_ptr<Microsoft::ReactNative::IViewManager>> viewManagers;
// Custom view managers
if (m_options.ViewManagerProvider) {
viewManagers = m_options.ViewManagerProvider->GetViewManagers(m_reactContext);
}
Microsoft::ReactNative::AddStandardViewManagers(viewManagers, *m_reactContext);
auto uiManagerSettings = std::make_unique<Microsoft::ReactNative::UIManagerSettings>(
m_batchingUIThread, m_uiMessageThread.Load(), std::move(viewManagers));
Microsoft::ReactNative::UIManager::SetSettings(m_reactContext->Properties(), std::move(uiManagerSettings));
m_reactContext->Properties().Set(
implementation::XamlUIService::XamlUIServiceProperty().Handle(),
winrt::make<implementation::XamlUIService>(m_reactContext));
m_reactContext->Properties().Set(
implementation::LayoutService::LayoutServiceProperty().Handle(),
winrt::make<implementation::LayoutService>(m_reactContext));
}
#endif
facebook::react::NativeLoggingHook ReactInstanceWin::GetLoggingCallback() noexcept {
if (m_options.OnLogging) {
return [logCallback = m_options.OnLogging](facebook::react::RCTLogLevel logLevel, const char *message) {
logCallback(static_cast<LogLevel>(logLevel), message);
};
} else {
// When no logging callback was specified, use a default one in DEBUG builds
#if DEBUG
return [telemetryTag{JavaScriptBundleFile()}](facebook::react::RCTLogLevel logLevel, const char *message) {
std::ostringstream ss;
ss << "ReactNative ['" << telemetryTag << "'] (";
switch (logLevel) {
case facebook::react::RCTLogLevel::Trace:
ss << "trace";
break;
case facebook::react::RCTLogLevel::Info:
ss << "info";
break;
case facebook::react::RCTLogLevel::Warning:
ss << "warning";
break;
case facebook::react::RCTLogLevel::Error:
ss << "error";
break;
case facebook::react::RCTLogLevel::Fatal:
ss << "fatal";
break;
}
ss << "): '" << message << "'\n";
OutputDebugStringA(ss.str().c_str());
};
#else
return facebook::react::NativeLoggingHook{};
#endif
}
}
std::shared_ptr<IRedBoxHandler> ReactInstanceWin::GetRedBoxHandler() noexcept {
if (m_options.RedBoxHandler) {
return m_options.RedBoxHandler;
#ifndef CORE_ABI
} else if (UseDeveloperSupport()) {
auto localWkReactHost = m_weakReactHost;
return CreateDefaultRedBoxHandler(
winrt::Microsoft::ReactNative::ReactPropertyBag(m_reactContext->Properties()),
std::move(localWkReactHost),
*m_uiQueue);
#endif
} else {
return {};
}
}
std::function<void()> ReactInstanceWin::GetLiveReloadCallback() noexcept {
// Live reload is enabled if we provide a callback function.
if (m_isLiveReloadEnabled || m_isFastReloadEnabled) {
return Mso::MakeWeakMemberStdFunction(this, &ReactInstanceWin::OnLiveReload);
}
return std::function<void()>{};
}
std::string ReactInstanceWin::GetBytecodeFileName() noexcept {
// use bytecode caching if enabled and not debugging
// (ChakraCore debugging does not work when bytecode caching is enabled)
// TODO: implement
// bool useByteCode = Mso::React::BytecodeOptimizationEnabled() && !m_options.DeveloperSettings.UseDirectDebugger;
// return useByteCode ? Mso::React::GetBytecodeFilePath(m_options.Identity) : "";
return "";
}
std::function<void(std::string)> ReactInstanceWin::GetErrorCallback() noexcept {
return Mso::MakeWeakMemberStdFunction(this, &ReactInstanceWin::OnErrorWithMessage);
}
void ReactInstanceWin::OnErrorWithMessage(const std::string &errorMessage) noexcept {
OnError(Mso::React::ReactErrorProvider().MakeErrorCode(Mso::React::ReactError{errorMessage.c_str()}));
}
void ReactInstanceWin::OnError(const Mso::ErrorCode &errorCode) noexcept {
m_state = ReactInstanceState::HasError;
AbandonJSCallQueue();
if (m_redboxHandler && m_redboxHandler->isDevSupportEnabled()) {
ErrorInfo errorInfo;
errorInfo.Message = errorCode.ToString();
errorInfo.Id = 0;
m_redboxHandler->showNewError(std::move(errorInfo), ErrorType::Native);
}
InvokeInQueue([this, errorCode]() noexcept { m_options.OnError(errorCode); });
m_updateUI();
}
void ReactInstanceWin::OnLiveReload() noexcept {
if (auto reactHost = m_weakReactHost.GetStrongPtr()) {
reactHost->ReloadInstance();
}
}
std::function<void()> ReactInstanceWin::GetWaitingForDebuggerCallback() noexcept {
if (m_useWebDebugger) {
return Mso::MakeWeakMemberStdFunction(this, &ReactInstanceWin::OnWaitingForDebugger);
}
return {};
}
void ReactInstanceWin::OnWaitingForDebugger() noexcept {
auto state = m_state.load();
while (state == ReactInstanceState::Loading) {
if (m_state.compare_exchange_weak(state, ReactInstanceState::WaitingForDebugger)) {
break;
}
}
m_updateUI();
}
std::function<void()> ReactInstanceWin::GetDebuggerAttachCallback() noexcept {
if (m_useWebDebugger) {
return Mso::MakeWeakMemberStdFunction(this, &ReactInstanceWin::OnDebuggerAttach);
}
return {};
}
void ReactInstanceWin::OnDebuggerAttach() noexcept {
m_updateUI();
}
void ReactInstanceWin::DrainJSCallQueue() noexcept {
// Handle all items in the queue one by one.
for (;;) {
JSCallEntry entry; // To avoid callJSFunction under the lock
{
std::scoped_lock lock{m_mutex};
if (m_state == ReactInstanceState::Loaded && !m_jsCallQueue.empty()) {
entry = std::move(m_jsCallQueue.front());
m_jsCallQueue.pop_front();
} else {
break;
}
}
if (auto instance = m_instance.LoadWithLock()) {
instance->callJSFunction(std::move(entry.ModuleName), std::move(entry.MethodName), std::move(entry.Args));