-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathindex.js
More file actions
5544 lines (5183 loc) · 183 KB
/
index.js
File metadata and controls
5544 lines (5183 loc) · 183 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
// @flow
import * as React from 'react';
import { type State } from './MainFrameState';
import './MainFrame.css';
import Snackbar from '@material-ui/core/Snackbar';
import HomeIcon from '../UI/CustomSvgIcons/Home';
import DebuggerIcon from '../UI/CustomSvgIcons/Debug';
import ProjectResourcesIcon from '../UI/CustomSvgIcons/ProjectResources';
import SceneIcon from '../UI/CustomSvgIcons/Scene';
import EventsIcon from '../UI/CustomSvgIcons/Events';
import ExternalEventsIcon from '../UI/CustomSvgIcons/ExternalEvents';
import ExternalLayoutIcon from '../UI/CustomSvgIcons/ExternalLayout';
import ExtensionIcon from '../UI/CustomSvgIcons/Extension';
import SearchIcon from '../UI/CustomSvgIcons/Search';
import ProjectTitlebar from './ProjectTitlebar';
import PreferencesDialog from './Preferences/PreferencesDialog';
import AboutDialog from './AboutDialog';
import ProjectManager from '../ProjectManager';
import LoaderModal from '../UI/LoaderModal';
import CloseConfirmDialog from '../UI/CloseConfirmDialog';
import ProfileDialog from '../Profile/ProfileDialog';
import PurchaseClaimDialog from '../Profile/PurchaseClaimDialog';
import Window from '../Utils/Window';
import { showErrorBox } from '../UI/Messages/MessageBox';
import EditorTabsPane, {
type EditorTabsPaneCommonProps,
} from './EditorTabsPane';
import {
getEditorTabsInitialState,
openEditorTab,
closeProjectTabs,
closeLayoutTabs,
closeExternalLayoutTabs,
closeExternalEventsTabs,
closeEventsFunctionsExtensionTabs,
closeCustomObjectTab,
closeEventsBasedObjectVariantTab,
saveUiSettings,
type EditorTabsState,
type EditorKind,
getEventsFunctionsExtensionEditor,
notifyPreviewOrExportWillStart,
getCurrentTabForPane,
getCustomObjectEditor,
getOpenedAskAiEditor,
getEditorTabOpenedWithKey,
changeCurrentTab,
getAllEditorTabs,
hasEditorsInPane,
closeEditorTab,
} from './EditorTabs/EditorTabsHandler';
import { renderDebuggerEditorContainer } from './EditorContainers/DebuggerEditorContainer';
import { renderEventsEditorContainer } from './EditorContainers/EventsEditorContainer';
import { renderExternalEventsEditorContainer } from './EditorContainers/ExternalEventsEditorContainer';
import { renderSceneEditorContainer } from './EditorContainers/SceneEditorContainer';
import { renderExternalLayoutEditorContainer } from './EditorContainers/ExternalLayoutEditorContainer';
import { renderEventsFunctionsExtensionEditorContainer } from './EditorContainers/EventsFunctionsExtensionEditorContainer';
import { renderCustomObjectEditorContainer } from './EditorContainers/CustomObjectEditorContainer';
import { renderHomePageContainer } from './EditorContainers/HomePage';
import { type OpenAskAiOptions } from '../AiGeneration/Utils';
import { exceptionallyGuardAgainstDeadObject } from '../Utils/IsNullPtr';
import { renderAskAiEditorContainer } from '../AiGeneration/AskAiEditorContainer';
import { renderResourcesEditorContainer } from './EditorContainers/ResourcesEditorContainer';
import { renderGlobalEventsSearchEditorContainer } from './EditorContainers/GlobalEventsSearchEditorContainer';
import {
type RenderEditorContainerPropsWithRef,
type SceneEventsOutsideEditorChanges,
type InstancesOutsideEditorChanges,
type ObjectsOutsideEditorChanges,
type ObjectGroupsOutsideEditorChanges,
} from './EditorContainers/BaseEditor';
import { type Exporter } from '../ExportAndShare/ShareDialog';
import ResourcesLoader from '../ResourcesLoader/index';
import {
type PreviewLauncherInterface,
type PreviewLauncherProps,
type PreviewLauncherComponent,
type LaunchPreviewOptions,
} from '../ExportAndShare/PreviewLauncher.flow';
import {
type ResourceSource,
type ChooseResourceFunction,
type ChooseResourceOptions,
type ResourceManagementProps,
} from '../ResourcesList/ResourceSource';
import { type ResourceExternalEditor } from '../ResourcesList/ResourceExternalEditor';
import { type JsExtensionsLoader } from '../JsExtensionsLoader';
import EventsFunctionsExtensionsContext from '../EventsFunctionsExtensionsLoader/EventsFunctionsExtensionsContext';
import {
getElectronUpdateNotificationTitle,
getElectronUpdateNotificationBody,
type ElectronUpdateStatus,
} from './UpdaterTools';
import ChangelogDialogContainer from './Changelog/ChangelogDialogContainer';
import { type MessageDescriptor } from '../Utils/i18n/MessageDescriptor.flow';
import { getNotNullTranslationFunction } from '../Utils/i18n/getTranslationFunction';
import { type I18n } from '@lingui/core';
import { t } from '@lingui/macro';
import LanguageDialog from './Preferences/LanguageDialog';
import PreferencesContext, {
type InAppTutorialUserProgress,
} from './Preferences/PreferencesContext';
import { getFunctionNameFromType } from '../EventsFunctionsExtensionsLoader';
import {
type ShareDialogWithoutExportsProps,
type ShareTab,
} from '../ExportAndShare/ShareDialog';
import { getStartupTimesSummary } from '../Utils/StartupTimes';
import {
type StorageProvider,
type StorageProviderOperations,
type FileMetadata,
type SaveAsLocation,
type SaveAsOptions,
type FileMetadataAndStorageProviderName,
type ResourcesActionsMenuBuilder,
type SaveProjectOptions,
} from '../ProjectsStorage';
import OpenFromStorageProviderDialog from '../ProjectsStorage/OpenFromStorageProviderDialog';
import SaveToStorageProviderDialog from '../ProjectsStorage/SaveToStorageProviderDialog';
import { useOpenConfirmDialog } from '../ProjectsStorage/OpenConfirmDialog';
import verifyProjectContent from '../ProjectsStorage/ProjectContentChecker';
import UnsavedChangesContext from './UnsavedChangesContext';
import {
type BuildMainMenuProps,
type MainMenuCallbacks,
type MainMenuExtraCallbacks,
} from './MainMenu';
import useForceUpdate from '../Utils/UseForceUpdate';
import useStateWithCallback from '../Utils/UseSetStateWithCallback';
import { useKeyboardShortcuts, useShortcutMap } from '../KeyboardShortcuts';
import useMainFrameCommands from './MainFrameCommands';
import {
CommandPaletteWithAlgoliaSearch,
type CommandPaletteInterface,
} from '../CommandPalette/CommandPalette';
import { isExtensionNameTaken } from '../ProjectManager/EventFunctionExtensionNameVerifier';
import {
type PreviewState,
usePreviewDebuggerServerWatcher,
} from './PreviewState';
import { type HotReloadPreviewButtonProps } from '../HotReload/HotReloadPreviewButton';
import HotReloadLogsDialog from '../HotReload/HotReloadLogsDialog';
import { useDiscordRichPresence } from '../Utils/UpdateDiscordRichPresence';
import { delay } from '../Utils/Delay';
import useNewProjectDialog from './UseNewProjectDialog';
import { findAndLogProjectPreviewErrors } from '../Utils/ProjectErrorsChecker';
import { renameResourcesInProject } from '../ResourcesList/ResourceUtils';
import { NewResourceDialog } from '../ResourcesList/NewResourceDialog';
import {
addCreateBadgePreHookIfNotClaimed,
TRIVIAL_FIRST_DEBUG,
TRIVIAL_FIRST_PREVIEW,
} from '../Utils/GDevelopServices/Badge';
import AuthenticatedUserContext from '../Profile/AuthenticatedUserContext';
import StartInAppTutorialDialog from './EditorContainers/HomePage/InAppTutorials/StartInAppTutorialDialog';
import LeaderboardProvider from '../Leaderboard/LeaderboardProvider';
import {
sendInAppTutorialStarted,
sendEventsExtractedAsFunction,
sendPreviewStarted,
} from '../Utils/Analytics/EventSender';
import { useLeaderboardReplacer } from '../Leaderboard/UseLeaderboardReplacer';
import useAlertDialog from '../UI/Alert/useAlertDialog';
import {
useResourceMover,
type ResourceMover,
} from '../ProjectsStorage/ResourceMover';
import {
useResourceFetcher,
type ResourceFetcher,
} from '../ProjectsStorage/ResourceFetcher';
import QuitInAppTutorialDialog from '../InAppTutorial/QuitInAppTutorialDialog';
import InAppTutorialContext from '../InAppTutorial/InAppTutorialContext';
import useOpenInitialDialog from '../Utils/UseOpenInitialDialog';
import { type InAppTutorialOrchestratorInterface } from '../InAppTutorial/InAppTutorialOrchestrator';
import useInAppTutorialOrchestrator from '../InAppTutorial/useInAppTutorialOrchestrator';
import {
useStableUpToDateCallback,
useStableUpToDateRef,
} from '../Utils/UseStableUpToDateCallback';
import { emptyStorageProvider } from '../ProjectsStorage/ProjectStorageProviders';
import CustomDragLayer from '../UI/DragAndDrop/CustomDragLayer';
import CloudProjectRecoveryDialog from '../ProjectsStorage/CloudStorageProvider/CloudProjectRecoveryDialog';
import CloudProjectSaveChoiceDialog from '../ProjectsStorage/CloudStorageProvider/CloudProjectSaveChoiceDialog';
import CloudStorageProvider from '../ProjectsStorage/CloudStorageProvider';
import useCreateProject from '../Utils/UseCreateProject';
import newNameGenerator from '../Utils/NewNameGenerator';
import { addDefaultLightToAllLayers } from '../ProjectCreation/CreateProject';
import { type NewProjectSetup } from '../ProjectCreation/NewProjectSetupDialog';
import useEditorTabsStateSaving from './EditorTabs/UseEditorTabsStateSaving';
import PixiResourcesLoader from '../ObjectsRendering/PixiResourcesLoader';
import useResourcesWatcher from './ResourcesWatcher';
import { extractGDevelopApiErrorStatusAndCode } from '../Utils/GDevelopServices/Errors';
import { type CourseChapter } from '../Utils/GDevelopServices/Asset';
import useVersionHistory from '../VersionHistory/UseVersionHistory';
import { ProjectManagerDrawer } from '../ProjectManager/ProjectManagerDrawer';
import DiagnosticReportDialog from '../ExportAndShare/DiagnosticReportDialog';
import MemoryTrackedRegistryDialog from './MemoryTrackedRegistryDialog';
import { scanProjectForValidationErrors } from '../Utils/EventsValidationScanner';
import useSaveReminder from './UseSaveReminder';
import { useMultiplayerLobbyConfigurator } from './UseMultiplayerLobbyConfigurator';
import { useAuthenticatedPlayer } from './UseAuthenticatedPlayer';
import ListIcon from '../UI/ListIcon';
import { QuickCustomizationDialog } from '../QuickCustomization/QuickCustomizationDialog';
import { type ObjectWithContext } from '../ObjectsList/EnumerateObjects';
import useGamesList from '../GameDashboard/UseGamesList';
import useCapturesManager from './UseCapturesManager';
import {
readProjectSettings,
getProjectDirectory,
} from '../Utils/ProjectSettingsReader';
import { applyProjectPreferences } from '../Utils/ApplyProjectPreferences';
import {
EmbeddedGameFrame,
setEditorHotReloadNeeded,
isEditorHotReloadNeeded,
} from '../EmbeddedGame/EmbeddedGameFrame';
import useHomePageSwitch from './useHomePageSwitch';
import { useNavigationToEvent } from './UseNavigationToEvent';
import useNavigateFromGlobalSearch from './UseNavigateFromGlobalSearch';
import RobotIcon from '../ProjectCreation/RobotIcon';
import PublicProfileContext from '../Profile/PublicProfileContext';
import { useGamesPlatformFrame } from './EditorContainers/HomePage/PlaySection/UseGamesPlatformFrame';
import { useExtensionLoadErrorDialog } from '../Utils/UseExtensionLoadErrorDialog';
import { PanesContainer } from './PanesContainer';
import {
registerOnResourceExternallyChangedCallback,
unregisterOnResourceExternallyChangedCallback,
} from '../MainFrame/ResourcesWatcher';
import {
type EditorCameraState,
type PreviewInGameEditorTarget,
type HotReloadSteps,
} from '../EmbeddedGame/EmbeddedGameFrame';
import StandaloneDialog from './StandAloneDialog';
import { useInGameEditorSettings } from '../EmbeddedGame/InGameEditorSettings';
import { ProjectScopedContainersAccessor } from '../InstructionOrExpression/EventsScope';
import { useAutomatedRegularInGameEditorRestart } from '../EmbeddedGame/UseAutomatedRegularInGameEditorRestart';
import type { EditorTab } from './EditorTabs/EditorTabsHandler';
const GD_STARTUP_TIMES = global.GD_STARTUP_TIMES || [];
const gd: libGDevelop = global.gd;
const editorKindToRenderer: {
[key: EditorKind]: (props: RenderEditorContainerPropsWithRef) => React.Node,
} = {
debugger: renderDebuggerEditorContainer,
'layout events': renderEventsEditorContainer,
'external events': renderExternalEventsEditorContainer,
layout: renderSceneEditorContainer,
'external layout': renderExternalLayoutEditorContainer,
'events functions extension': renderEventsFunctionsExtensionEditorContainer,
'custom object': renderCustomObjectEditorContainer,
'start page': renderHomePageContainer,
resources: renderResourcesEditorContainer,
'global-search': renderGlobalEventsSearchEditorContainer,
'ask-ai': renderAskAiEditorContainer,
};
const defaultSnackbarAutoHideDuration = 3000;
const findStorageProviderFor = (
i18n: I18n,
storageProviders: Array<StorageProvider>,
fileMetadataAndStorageProviderName: FileMetadataAndStorageProviderName
): ?StorageProvider => {
const { storageProviderName } = fileMetadataAndStorageProviderName;
const storageProvider = storageProviders.filter(
storageProvider => storageProvider.internalName === storageProviderName
)[0];
if (!storageProvider) {
showErrorBox({
message: i18n._(
t`Unable to open the project because this provider is unknown: ${storageProviderName}. Try to open the project again from another location.`
),
rawError: new Error(
`Can't find storage provider called "${storageProviderName}"`
),
errorId: 'unknown-storage-provider',
});
return;
}
return storageProvider;
};
/**
* Compares a React reference to the current project (truth source)
* and a project stored in a variable (coming probably from a React state).
* It is useful to detect if the project stored in a variable is still
* valid (still currently opened). If it's not, it means the variable is "stale".
*/
const isCurrentProjectFresh = (
currentProjectRef: {| current: ?gdProject |},
currentProject: gdProject
) =>
currentProjectRef.current &&
currentProject.ptr === currentProjectRef.current.ptr;
/**
* When a project is created or opened, the fileMetadata is not aware of some project
* properties like the projectUuid or the name, until the project is deserialized.
* This function returns a new fileMetadata with the latest project properties,
* allowing the editor to have the latest information.
*/
const updateFileMetadataWithOpenedProject = (
fileMetadata: FileMetadata,
project: gdProject
) => ({
...fileMetadata,
gameId: project.getProjectUuid(),
name: project.getName(),
});
const initialPreviewState: PreviewState = {
previewLayoutName: null,
previewExternalLayoutName: null,
isPreviewOverriden: false,
overridenPreviewLayoutName: null,
overridenPreviewExternalLayoutName: null,
};
const usePreviewLoadingState = () => {
const forceUpdate = useForceUpdate();
const previewLoadingRef = React.useRef<
null | 'preview' | 'hot-reload-for-in-game-edition'
>(null);
return {
previewLoadingRef,
setPreviewLoading: React.useCallback(
(previewLoading: null | 'preview' | 'hot-reload-for-in-game-edition') => {
previewLoadingRef.current = previewLoading;
forceUpdate();
},
[forceUpdate]
),
};
};
export type Props = {|
renderMainMenu?: (
BuildMainMenuProps,
MainMenuCallbacks,
MainMenuExtraCallbacks
) => React.Node,
renderPreviewLauncher?: (
props: PreviewLauncherProps,
ref: (previewLauncher: ?PreviewLauncherInterface) => void
// $FlowFixMe[prop-missing]
) => React.Element<PreviewLauncherComponent>,
onEditObject?: gdObject => void,
storageProviders: Array<StorageProvider>,
resourceMover: ResourceMover,
resourceFetcher: ResourceFetcher,
getStorageProviderOperations: (
storageProvider?: ?StorageProvider
) => StorageProviderOperations,
getStorageProviderResourceOperations: () => ?ResourcesActionsMenuBuilder,
getStorageProvider: () => StorageProvider,
resourceSources: Array<ResourceSource>,
resourceExternalEditors: Array<ResourceExternalEditor>,
requestUpdate?: () => void,
renderShareDialog: ShareDialogWithoutExportsProps => React.Node,
renderGDJSDevelopmentWatcher?: ?({|
onGDJSUpdated: () => Promise<void> | void,
|}) => React.Node,
extensionsLoader?: JsExtensionsLoader,
initialFileMetadataToOpen: ?FileMetadata,
initialExampleSlugToOpen: ?string,
quickPublishOnlineWebExporter: Exporter,
i18n: I18n,
|};
const MainFrame = (props: Props): React.MixedElement => {
const [state, setState]: [
State,
((State => State) | State) => Promise<State>,
] = useStateWithCallback(
({
currentProject: null,
currentFileMetadata: null,
editorTabs: getEditorTabsInitialState(),
snackMessage: '',
snackMessageOpen: false,
snackDuration: defaultSnackbarAutoHideDuration,
updateStatus: { message: '', status: 'unknown' },
openFromStorageProviderDialogOpen: false,
saveToStorageProviderDialogOpen: false,
gdjsDevelopmentWatcherEnabled: false,
toolbarButtons: [],
}: State)
);
const authenticatedUser = React.useContext(AuthenticatedUserContext);
const [
cloudProjectFileMetadataToRecover,
setCloudProjectFileMetadataToRecover,
] = React.useState<?FileMetadata>(null);
const [
cloudProjectRecoveryOpenedVersionId,
setCloudProjectRecoveryOpenedVersionId,
] = React.useState<?string>(null);
const [
cloudProjectSaveChoiceOpen,
setCloudProjectSaveChoiceOpen,
] = React.useState<boolean>(false);
const [
chooseResourceOptions,
setChooseResourceOptions,
] = React.useState<?ChooseResourceOptions>(null);
const [onResourceChosen, setOnResourceChosen] = React.useState<?({|
selectedResources: Array<gdResource>,
selectedSourceName: string,
|}) => void>(null);
const _previewLauncher = React.useRef((null: ?PreviewLauncherInterface));
const forceUpdate = useForceUpdate();
const [isLoadingProject, setIsLoadingProject] = React.useState<boolean>(
false
);
const [isSavingProject, setIsSavingProject] = React.useState<boolean>(false);
const [projectManagerOpen, openProjectManager] = React.useState<boolean>(
false
);
const [languageDialogOpen, openLanguageDialog] = React.useState<boolean>(
false
);
const [aboutDialogOpen, openAboutDialog] = React.useState<boolean>(false);
const [profileDialogOpen, openProfileDialog] = React.useState<boolean>(false);
const [
preferencesDialogOpen,
openPreferencesDialog,
] = React.useState<boolean>(false);
const [
newProjectSetupDialogOpen,
setNewProjectSetupDialogOpen,
] = React.useState<boolean>(false);
const [isProjectOpening, setIsProjectOpening] = React.useState<boolean>(
false
);
const [
isProjectClosedSoAvoidReloadingExtensions,
setIsProjectClosedSoAvoidReloadingExtensions,
] = React.useState<boolean>(false);
const [shareDialogOpen, setShareDialogOpen] = React.useState<boolean>(false);
const [
shareDialogInitialTab,
setShareDialogInitialTab,
] = React.useState<?ShareTab>(null);
const [
standaloneDialogOpen,
setStandaloneDialogOpen,
] = React.useState<boolean>(false);
const {
showConfirmation,
showAlert,
showDeleteConfirmation,
} = useAlertDialog();
const preferences = React.useContext(PreferencesContext);
const { setHasProjectOpened } = preferences;
const { previewLoadingRef, setPreviewLoading } = usePreviewLoadingState();
const shortcutMap = useShortcutMap();
const [
diagnosticReportDialogOpen,
setDiagnosticReportDialogOpen,
] = React.useState<boolean>(false);
const [
memoryTrackerRegistryDialogOpen,
setMemoryTrackedRegistryDialogOpen,
] = React.useState<boolean>(false);
/**
* Checks for diagnostic errors in the project if blocking is enabled.
* Returns true if there are errors and the action should be blocked.
*/
const checkDiagnosticErrorsAndIfShouldBlock = React.useCallback(
async (
project: ?gdProject,
actionType: 'preview' | 'export'
): Promise<boolean> => {
if (
!project ||
!preferences.getBlockPreviewAndExportOnDiagnosticErrors()
) {
return false;
}
try {
const validationErrors = scanProjectForValidationErrors(project);
if (validationErrors.length > 0) {
const openReport = await showConfirmation({
title: t`Diagnostic errors found`,
message:
actionType === 'preview'
? t`Your project has ${
validationErrors.length
} diagnostic error(s). Please fix them before launching a preview.`
: t`Your project has ${
validationErrors.length
} diagnostic error(s). Please fix them before exporting.`,
dismissButtonLabel: t`Close`,
confirmButtonLabel: t`Open report`,
});
if (openReport) {
setDiagnosticReportDialogOpen(true);
}
return true;
}
} catch (error) {
console.error('Error scanning project for validation errors:', error);
}
return false;
},
[preferences, showConfirmation, setDiagnosticReportDialogOpen]
);
const [previewState, setPreviewState] = React.useState(initialPreviewState);
const commandPaletteRef = React.useRef((null: ?CommandPaletteInterface));
const inAppTutorialOrchestratorRef = React.useRef<?InAppTutorialOrchestratorInterface>(
null
);
const [
loaderModalOpeningMessage,
setLoaderModalOpeningMessage,
] = React.useState<?MessageDescriptor>(null);
const eventsFunctionsExtensionsContext = React.useContext(
EventsFunctionsExtensionsContext
);
const previewDebuggerServer =
_previewLauncher.current &&
_previewLauncher.current.getPreviewDebuggerServer();
const {
hasNonEditionPreviewsRunning,
gameHotReloadLogs,
editorHotReloadLogs,
editorUncaughtError,
clearGameHotReloadLogs,
clearEditorHotReloadLogs,
clearEditorUncaughtError,
hardReloadAllPreviews,
} = usePreviewDebuggerServerWatcher(previewDebuggerServer);
const {
ensureInteractionHappened,
renderOpenConfirmDialog,
} = useOpenConfirmDialog();
const {
openLeaderboardReplacerDialogIfNeeded,
renderLeaderboardReplacerDialog,
} = useLeaderboardReplacer();
const {
configureMultiplayerLobbiesIfNeeded,
} = useMultiplayerLobbyConfigurator();
const eventsFunctionsExtensionsState = React.useContext(
EventsFunctionsExtensionsContext
);
const unsavedChanges = React.useContext(UnsavedChangesContext);
const {
hasUnsavedChanges,
sealUnsavedChanges,
triggerUnsavedChanges,
} = unsavedChanges;
const {
currentlyRunningInAppTutorial,
getInAppTutorialShortHeader,
endTutorial: doEndTutorial,
startTutorial,
startStepIndex,
startProjectData,
} = React.useContext(InAppTutorialContext);
const [
selectedInAppTutorialInfo,
setSelectedInAppTutorialInfo,
] = React.useState<null | {|
tutorialId: string,
userProgress: ?InAppTutorialUserProgress,
|}>(null);
const {
InAppTutorialOrchestrator,
orchestratorProps,
} = useInAppTutorialOrchestrator({ editorTabs: state.editorTabs });
const [
quitInAppTutorialDialogOpen,
setQuitInAppTutorialDialogOpen,
] = React.useState<boolean>(false);
const { setPendingEventNavigation } = useNavigationToEvent({
editorTabs: state.editorTabs,
});
const [
fileMetadataOpeningProgress,
setFileMetadataOpeningProgress,
] = React.useState<?number>(null);
const [
fileMetadataOpeningMessage,
setFileMetadataOpeningMessage,
] = React.useState<?MessageDescriptor>(null);
const [
quickCustomizationDialogOpenedFromGameId,
setQuickCustomizationDialogOpenedFromGameId,
] = React.useState<?string>(null);
const [gameEditorMode, setGameEditorMode] = React.useState<
'embedded-game' | 'instances-editor'
>('instances-editor');
// This is just for testing, to check if we're getting the right state
// and gives us an idea about the number of re-renders.
// React.useEffect(() => {
// console.log(state);
// });
const { currentFileMetadata, updateStatus } = state;
const currentProject = exceptionallyGuardAgainstDeadObject(
state.currentProject
);
const {
renderShareDialog,
resourceSources,
renderPreviewLauncher,
resourceExternalEditors,
resourceMover,
resourceFetcher,
getStorageProviderOperations,
getStorageProviderResourceOperations,
getStorageProvider,
initialFileMetadataToOpen,
initialExampleSlugToOpen,
i18n,
renderGDJSDevelopmentWatcher,
renderMainMenu,
quickPublishOnlineWebExporter,
} = props;
const {
ensureResourcesAreMoved,
renderResourceMoverDialog,
} = useResourceMover({ resourceMover });
const {
ensureResourcesAreFetched,
renderResourceFetcherDialog,
} = useResourceFetcher({ resourceFetcher });
useResourcesWatcher({
getStorageProvider,
fileMetadata: currentFileMetadata,
isProjectSplitInMultipleFiles: currentProject
? currentProject.isFolderProject()
: false,
});
const gamesList = useGamesList();
const {
createCaptureOptionsForPreview,
onCaptureFinished,
onGameScreenshotsClaimed,
getGameUnverifiedScreenshotUrls,
getHotReloadPreviewLaunchCaptureOptions,
} = useCapturesManager({ project: currentProject, gamesList });
const { getAuthenticatedPlayerForPreview } = useAuthenticatedPlayer({
project: currentProject,
gamesList,
});
const {
setExtensionLoadingResults,
hasExtensionLoadErrors,
renderExtensionLoadErrorDialog,
} = useExtensionLoadErrorDialog();
/**
* This reference is useful to get the current opened project,
* even in the callback of a hook/promise - without risking to read "stale" data.
* This can be different from the `currentProject` (coming from the state)
* that an effect or a callback manipulates when a promise resolves for instance.
* See `isCurrentProjectFresh`.
*/
const currentProjectRef = useStableUpToDateRef(currentProject);
const getEditorOpeningOptions = React.useCallback(
({
kind,
name,
dontFocusTab,
project,
paneIdentifier,
continueProcessingFunctionCallsOnMount,
}: {
kind: EditorKind,
name: string,
dontFocusTab?: boolean,
project?: ?gdProject,
paneIdentifier?: 'left' | 'center' | 'right',
continueProcessingFunctionCallsOnMount?: boolean,
}) => {
const label =
kind === 'resources'
? i18n._(t`Resources`)
: kind === 'global-search'
? i18n._(t`Global search`)
: kind === 'ask-ai'
? i18n._(t`Ask AI`)
: kind === 'start page'
? undefined
: kind === 'debugger'
? i18n._(t`Debugger`)
: kind === 'layout events'
? name + ` ${i18n._(t`(Events)`)}`
: kind === 'custom object'
? name.split('::')[2] ||
name.split('::')[1] + ` ${i18n._(t`(Object)`)}`
: name;
const tabOptions =
kind === 'layout'
? { data: { scene: name, type: 'layout' } }
: kind === 'layout events'
? { data: { scene: name, type: 'layout-events' } }
: undefined;
const key = [
'layout',
'layout events',
'external events',
'external layout',
'events functions extension',
'custom object',
].includes(kind)
? `${kind} ${name}`
: kind;
let customIconUrl = '';
if (kind === 'events functions extension' || kind === 'custom object') {
const extensionName = name.split('::')[0];
if (
project &&
project.hasEventsFunctionsExtensionNamed(extensionName)
) {
const eventsFunctionsExtension = project.getEventsFunctionsExtension(
extensionName
);
customIconUrl = eventsFunctionsExtension.getIconUrl();
}
}
const icon =
kind === 'start page' ? (
<HomeIcon titleAccess="Home" />
) : kind === 'debugger' ? (
<DebuggerIcon />
) : kind === 'resources' ? (
<ProjectResourcesIcon />
) : kind === 'global-search' ? (
<SearchIcon />
) : kind === 'layout' ? (
<SceneIcon />
) : kind === 'layout events' ? (
<EventsIcon />
) : kind === 'external events' ? (
<ExternalEventsIcon />
) : kind === 'external layout' ? (
<ExternalLayoutIcon />
) : kind === 'events functions extension' ||
kind === 'custom object' ? (
<ExtensionIcon />
) : kind === 'ask-ai' ? (
<RobotIcon size={16} />
) : null;
const closable = kind !== 'start page';
const extraEditorProps =
kind === 'start page'
? { storageProviders: props.storageProviders }
: kind === 'ask-ai'
? {
continueProcessingFunctionCallsOnMount,
}
: undefined;
return {
icon,
renderCustomIcon: customIconUrl
? (brightness: number) => (
<ListIcon
iconSize={20}
src={customIconUrl}
brightness={brightness}
/>
)
: null,
closable,
label,
projectItemName: name,
tabOptions,
kind,
renderEditorContainer: editorKindToRenderer[kind],
extraEditorProps,
key,
dontFocusTab,
paneIdentifier: paneIdentifier || 'center',
};
},
[i18n, props.storageProviders]
);
const setEditorTabs = React.useCallback(
// $FlowFixMe[missing-local-annot]
newEditorTabs => {
setState(state => ({
...state,
editorTabs: newEditorTabs,
}));
},
[setState]
);
const {
hasAPreviousSaveForEditorTabsState,
openEditorTabsFromPersistedState,
} = useEditorTabsStateSaving({
currentProjectId: currentProject ? currentProject.getProjectUuid() : null,
editorTabs: state.editorTabs,
setEditorTabs: setEditorTabs,
// $FlowFixMe[incompatible-type]
getEditorOpeningOptions,
});
const _closeSnackMessage = React.useCallback(
() => {
setState(state => ({
...state,
snackMessageOpen: false,
snackDuration: defaultSnackbarAutoHideDuration, // Reset to default when closing the snackbar.
}));
},
[setState]
);
const _showSnackMessage = React.useCallback(
(snackMessage: string, autoHideDuration?: number | null) => {
setState(state => ({
...state,
snackMessage,
snackMessageOpen: true,
snackDuration:
autoHideDuration !== undefined
? autoHideDuration // Allow setting null, for infinite duration.
: defaultSnackbarAutoHideDuration,
}));
},
[setState]
);
const _replaceSnackMessage = React.useCallback(
(snackMessage: string, autoHideDuration?: number | null) => {
_closeSnackMessage();
setTimeout(() => _showSnackMessage(snackMessage, autoHideDuration), 200);
},
[_closeSnackMessage, _showSnackMessage]
);
const openShareDialog = React.useCallback(
async (initialTab?: ShareTab) => {
if (
await checkDiagnosticErrorsAndIfShouldBlock(currentProject, 'export')
) {
return;
}
notifyPreviewOrExportWillStart(state.editorTabs);
setShareDialogInitialTab(initialTab || null);
setShareDialogOpen(true);
},
[state.editorTabs, currentProject, checkDiagnosticErrorsAndIfShouldBlock]
);
const closeShareDialog = React.useCallback(
() => {
setShareDialogOpen(false);
setShareDialogInitialTab(null);
},
[setShareDialogOpen, setShareDialogInitialTab]
);
const openInitialFileMetadata = async () => {
if (!initialFileMetadataToOpen) return;
// We use the current storage provider, as it's supposed to be able to open
// the initial file metadata. Indeed, it's the responsibility of the `ProjectStorageProviders`
// to set the initial storage provider if an initial file metadata is set.
const state = await openFromFileMetadata(initialFileMetadataToOpen);
if (state)
openSceneOrProjectManager({
currentProject: state.currentProject,
editorTabs: state.editorTabs,
});
};
const _languageDidChange = () => {
// A change in the language will automatically be applied
// on all React components, as it's handled by GDI18nProvider.
// We still have this method that will be called when the language
// dialog is closed after a language change. We then reload GDevelop
// extensions so that they declare all objects/actions/condition/etc...
// using the new language.
console.info('Language changed, reloading extensions...');
gd.MeasurementUnit.applyTranslation();
gd.JsPlatform.get().reloadBuiltinExtensions();
eventsFunctionsExtensionsState.reloadProjectEventsFunctionsExtensions(
currentProject
);
_loadExtensions().catch(() => {});
};
const _loadExtensions = (): Promise<void> => {
const { extensionsLoader, i18n } = props;
if (!extensionsLoader) {
console.info(
'No extensions loader specified, skipping extensions loading.'
);
return Promise.reject(new Error('No extension loader specified.'));
}
return extensionsLoader
.loadAllExtensions(getNotNullTranslationFunction(i18n))
.then(
({
expectedNumberOfJSExtensionModulesLoaded,
results: loadingResults,
}) => {
const successLoadingResults = loadingResults.filter(
loadingResult => !loadingResult.result.error
);
console.info(
`Loaded ${
successLoadingResults.length
}/${expectedNumberOfJSExtensionModulesLoaded} JS extensions.`
);
setExtensionLoadingResults({
expectedNumberOfJSExtensionModulesLoaded,
results: loadingResults,
});
}
);
};
useDiscordRichPresence(currentProject);
const openAskAi = React.useCallback(
(options: ?OpenAskAiOptions) => {
const {
aiRequestId,
paneIdentifier,
continueProcessingFunctionCallsOnMount,
} = options || {};
const newPaneIdentifier =
paneIdentifier || (currentProject ? 'right' : 'center');
setState(state => {
let openedEditor = getOpenedAskAiEditor(state.editorTabs);
let newEditorTabs = state.editorTabs;
if (openedEditor) {
if (openedEditor.paneIdentifier !== newPaneIdentifier) {
// The editor is opened, but not at the right position, close it.
// It will re-open in the right pane.
// Tell the editor not to suspend the AI request on close, since
// we're just repositioning it, not intentionally closing it.
if (openedEditor.askAiEditor) {
openedEditor.askAiEditor.prepareToReposition();
}
newEditorTabs = closeEditorTab(
newEditorTabs,
openedEditor.editorTab
);
newEditorTabs = openEditorTab(
newEditorTabs,
// $FlowFixMe[incompatible-type]
getEditorOpeningOptions({
kind: 'ask-ai',
name: '',
paneIdentifier: newPaneIdentifier,
continueProcessingFunctionCallsOnMount,
})
);
}
}
newEditorTabs = openEditorTab(
newEditorTabs,
// $FlowFixMe[incompatible-type]
getEditorOpeningOptions({
kind: 'ask-ai',
name: '',
paneIdentifier: newPaneIdentifier,
continueProcessingFunctionCallsOnMount,
})
);