-
Notifications
You must be signed in to change notification settings - Fork 41
/
launch.ts
1192 lines (1095 loc) · 41.3 KB
/
launch.ts
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
import type OpenFin from "@openfin/core";
import {
WindowType,
getCurrentSync,
type BrowserSnapshot,
type BrowserWorkspacePlatformWindowOptions,
type Page
} from "@openfin/workspace-platform";
import { isAppPreferenceUpdatable } from "./apps";
import { launchConnectedApp } from "./connections";
import * as endpointProvider from "./endpoint";
import { createLogger } from "./logger-provider";
import { MANIFEST_TYPES } from "./manifest-types";
import { bringViewToFront, bringWindowToFront, doesViewExist, doesWindowExist } from "./platform/browser";
import { getSettings } from "./settings";
import type {
NativeLaunchOptions,
PlatformApp,
PlatformAppIdentifier,
UpdatableLaunchPreference,
ViewLaunchOptions,
WindowLaunchOptions,
PreferenceConstraintUrl,
HostLaunchOptions
} from "./shapes/app-shapes";
import type { WindowPositioningOptions } from "./shapes/browser-shapes";
import * as snapProvider from "./snap";
import { formatError, getCommandLineArgs, isEmpty, isStringValue, objectClone, randomUUID } from "./utils";
import { getWindowPositionOptions, getWindowPositionUsingStrategy } from "./utils-position";
const logger = createLogger("Launch");
let windowPositioningOptions: WindowPositioningOptions | undefined;
/**
* Launch an application in the way specified by its manifest type.
* @param platformApp The application to launch.
* @param launchPreference launchPreferences if updatable for your the application.
* @param callerIdentity optionally pass information related to the caller to consider when launching.
* @returns Identifiers specific to the type of application launched.
*/
export async function launch(
platformApp: PlatformApp,
launchPreference?: UpdatableLaunchPreference,
callerIdentity?: OpenFin.Identity
): Promise<PlatformAppIdentifier[] | undefined> {
try {
logger.info("Application launch requested", platformApp);
if (isEmpty(platformApp)) {
logger.warn("An empty app definition was passed to launch");
return [];
}
const app = objectClone(platformApp);
const platformAppIdentities: PlatformAppIdentifier[] = [];
switch (app.manifestType) {
case MANIFEST_TYPES.External.id:
case MANIFEST_TYPES.InlineExternal.id: {
const platformIdentity = await launchExternal(app, undefined, launchPreference);
if (platformIdentity) {
platformAppIdentities.push(platformIdentity);
}
break;
}
case MANIFEST_TYPES.Appasset.id:
case MANIFEST_TYPES.InlineAppAsset.id: {
const platformIdentity = await launchAppAsset(app, undefined, launchPreference);
if (platformIdentity) {
platformAppIdentities.push(platformIdentity);
}
break;
}
case MANIFEST_TYPES.InlineView.id:
case MANIFEST_TYPES.View.id: {
const platformIdentity = await launchView(app, launchPreference, callerIdentity);
if (platformIdentity) {
platformAppIdentities.push(platformIdentity);
}
break;
}
case MANIFEST_TYPES.Window.id:
case MANIFEST_TYPES.InlineWindow.id: {
const platformIdentity = await launchWindow(app, launchPreference, callerIdentity);
if (platformIdentity) {
platformAppIdentities.push(platformIdentity);
}
break;
}
case MANIFEST_TYPES.Snapshot.id:
case MANIFEST_TYPES.InlineSnapshot.id: {
const identities = await launchSnapshot(app);
if (identities) {
platformAppIdentities.push(...identities);
}
break;
}
case MANIFEST_TYPES.Manifest.id: {
const manifestApp = await fin.Application.startFromManifest(app.manifest);
const manifestUUID = manifestApp?.identity?.uuid;
if (!isEmpty(manifestUUID)) {
platformAppIdentities.push({
uuid: manifestUUID,
name: manifestUUID,
appId: app.appId
});
}
break;
}
case MANIFEST_TYPES.DesktopBrowser.id: {
await fin.System.openUrlWithBrowser(app.manifest);
break;
}
case MANIFEST_TYPES.Endpoint.id: {
if (endpointProvider.hasEndpoint(app.manifest)) {
const identity = await endpointProvider.requestResponse<
{
payload: PlatformApp;
launchPreference?: UpdatableLaunchPreference;
callerIdentity?: OpenFin.Identity;
},
OpenFin.Identity
>(app.manifest, { payload: app, launchPreference, callerIdentity });
if (isEmpty(identity)) {
logger.warn(
`App with id: ${app.appId} encountered when launched using endpoint: ${app.manifest}.`
);
} else {
platformAppIdentities.push({ ...identity, appId: app.appId });
}
} else {
logger.warn(
`App with id: ${app.appId} could not be launched as it is of manifestType: ${app.manifestType} and the endpoint: ${app.manifest} is not available.`
);
}
break;
}
case MANIFEST_TYPES.Connection.id: {
logger.info(
"An app defined by a connection (connected app) has been selected. Passing selection to connection"
);
const identity = await launchConnectedApp(app);
if (!isEmpty(identity)) {
platformAppIdentities.push({ ...identity, appId: app.appId });
}
break;
}
default: {
logger.error("We do not support the manifest type so this app cannot be launched.", app);
}
}
logger.info("Finished application launch request");
return platformAppIdentities;
} catch (err) {
logger.error("Failed during application launch request", err);
}
}
/**
* Bring the applications views to the front.
* @param platformApp The application to bring to the front.
* @param platformAppIdentifiers Additional app identifiers to bring to the front.
*/
export async function bringToFront(
platformApp: PlatformApp,
platformAppIdentifiers: PlatformAppIdentifier[]
): Promise<void> {
switch (platformApp.manifestType) {
case MANIFEST_TYPES.External.id:
case MANIFEST_TYPES.InlineExternal.id:
case MANIFEST_TYPES.Manifest.id:
case MANIFEST_TYPES.DesktopBrowser.id:
case MANIFEST_TYPES.Endpoint.id:
case MANIFEST_TYPES.Connection.id: {
logger.info(`Bringing apps of type: ${platformApp.manifestType} to front is not supported.`);
break;
}
case MANIFEST_TYPES.InlineView.id:
case MANIFEST_TYPES.View.id: {
if (Array.isArray(platformAppIdentifiers) && platformAppIdentifiers.length === 1) {
await bringViewToFront({ identity: platformAppIdentifiers[0] });
} else {
logger.warn(
`A request to bring a view app to front was received but we didn't receive exactly one identity for app: ${platformApp.appId}.`
);
}
break;
}
case MANIFEST_TYPES.Window.id:
case MANIFEST_TYPES.InlineWindow.id: {
if (Array.isArray(platformAppIdentifiers) && platformAppIdentifiers.length === 1) {
await bringWindowToFront({ identity: platformAppIdentifiers[0] });
} else {
logger.warn(
`A request to bring a window app to front was received but we didn't receive exactly one identity for app: ${platformApp.appId}.`
);
}
break;
}
case MANIFEST_TYPES.UnregisteredApp.id: {
if (Array.isArray(platformAppIdentifiers) && platformAppIdentifiers.length === 1) {
// isView - this should be the majority of cases for an unregistered app
let isView = true;
try {
const view = fin.View.wrapSync(platformAppIdentifiers[0]);
const viewInfo = await view.getInfo();
logger.info("View Info", viewInfo);
} catch {
isView = false;
}
if (isView) {
await bringViewToFront({ identity: platformAppIdentifiers[0] });
} else {
await bringWindowToFront({ identity: platformAppIdentifiers[0] });
}
} else {
logger.warn(
`A request to bring a window app to front was received but we didn't receive exactly one identity for app: ${platformApp.appId}.`
);
}
break;
}
case MANIFEST_TYPES.Snapshot.id: {
if (Array.isArray(platformAppIdentifiers) && platformAppIdentifiers.length > 0) {
for (const identity of platformAppIdentifiers) {
await bringViewToFront({ identity });
}
} else {
logger.warn(
`A request to bring a snapshot app to front was received but we didn't receive at least one view for app: ${platformApp.appId}.`
);
}
break;
}
default: {
logger.error(
"We do not support the manifest type so this app cannot be brought to front.",
platformApp
);
}
}
}
/**
* Get the platform app identifiers of all the views in a window.
* @param name The identity name of the window.
* @param uuid The identity uuid of the window.
* @param appId The application to map the view identities with.
* @returns List of platform app identifiers.
*/
async function getViewIdentities(
name: string,
uuid: string,
appId: string
): Promise<PlatformAppIdentifier[]> {
const identity = { uuid, name };
const win = fin.Window.wrapSync(identity);
const views = await win.getCurrentViews();
const viewIdentities = views.map((view) => ({ ...view.identity, appId }));
await win.setAsForeground();
return viewIdentities;
}
/**
* Get a manifest as either a string or a specific object type.
* @param platformApp The application to get the manifest from.
* @returns The manifest object.
*/
function getInlineManifest<T>(platformApp: PlatformApp): T {
if (isStringValue(platformApp.manifest) && platformApp.manifest.startsWith("{")) {
return JSON.parse(platformApp.manifest) as T;
}
return platformApp.manifest as T;
}
/**
* Get a manifest from a url.
* @param platformApp The application to get the manifest from.
* @returns The manifest object.
*/
async function getManifest<T>(platformApp: PlatformApp): Promise<T | undefined> {
const platformEndpointId = getManifestEndpointId();
const appEndpointId = getManifestEndpointId(platformApp.appId);
let targetEndpointId: string | undefined;
if (endpointProvider.hasEndpoint(appEndpointId)) {
targetEndpointId = appEndpointId;
} else if (endpointProvider.hasEndpoint(platformEndpointId)) {
targetEndpointId = platformEndpointId;
}
try {
if (isEmpty(targetEndpointId)) {
const manifestResponse = await fetch(platformApp.manifest);
const manifest = (await manifestResponse.json()) as T;
return manifest;
}
const endpointManifest = await endpointProvider.requestResponse<{ url: string; appId: string }, T>(
targetEndpointId,
{ url: platformApp.manifest, appId: platformApp.appId }
);
return endpointManifest;
} catch (error) {
logger.error(
`There was an error while trying to fetch the manifest: ${platformApp.manifest} for appId: ${platformApp.appId}`,
error
);
}
}
/**
* Generates an endpoint id for fetching manifests.
* @param appId if an appId is specified then the endpointId is specific for fetching this app's manifest
* @returns the Id that should be used for an endpoint lookup
*/
function getManifestEndpointId(appId?: string): string {
const platformManifestEndpoint = "manifest-get";
if (isEmpty(appId)) {
return platformManifestEndpoint;
}
return `${platformManifestEndpoint}-${appId}`;
}
/**
* Launch a window for the platform app.
* @param windowApp The app to launch the window for.
* @param launchPreference Optional custom launch preferences
* @param callerIdentity optionally pass information related to the caller to consider when launching.
* @returns The identity of the window launched.
*/
async function launchWindow(
windowApp: PlatformApp,
launchPreference?: UpdatableLaunchPreference,
callerIdentity?: OpenFin.Identity
): Promise<PlatformAppIdentifier | undefined> {
if (isEmpty(windowApp)) {
logger.warn("No app was passed to launchWindow");
return;
}
if (
windowApp.manifestType !== MANIFEST_TYPES.Window.id &&
windowApp.manifestType !== MANIFEST_TYPES.InlineWindow.id
) {
logger.warn(
`The app passed was not of manifestType ${MANIFEST_TYPES.Window.id} or ${MANIFEST_TYPES.InlineWindow.id}.`
);
return;
}
let manifest: OpenFin.WindowOptions | undefined;
if (windowApp.manifestType === MANIFEST_TYPES.Window.id) {
manifest = await getManifest<OpenFin.WindowOptions>(windowApp);
} else {
// conversion because of manifestType. In most use cases manifest is always a path to an executable or to a manifest file. For classic windows we are demonstrating how it could be used
// for passing the manifest inline
manifest = getInlineManifest(windowApp);
}
if (isEmpty(manifest)) {
logger.error(
`There was a problem encountered while trying to fetch the manifest for app: ${windowApp.appId}. Returning without launching.`
);
return;
}
let name = manifest.name;
let wasNameSpecified = !isEmpty(name);
if (!wasNameSpecified && windowApp?.instanceMode === "single") {
logger.info(
`A unique name was not provided in the manifest of this window but the custom config indicates that this app is supposed to have a single instance so we are using the appId: ${windowApp.appId} as the unique name.`
);
name = windowApp.appId;
// assign the new name to the manifest in case the view doesn't exist yet (as it is dynamically allocated and not part of the app's manifest)
manifest.name = name;
wasNameSpecified = true;
} else if (!wasNameSpecified) {
name = `${windowApp.appId}/${randomUUID()}`;
manifest.name = name;
}
let identity = { uuid: fin.me.identity.uuid, name };
let windowExists = false;
if (wasNameSpecified) {
windowExists = await doesWindowExist(identity, true);
}
if (!windowExists) {
try {
const appLaunchPreference = objectClone(windowApp.launchPreference) ?? {};
const appLaunchPreferenceOptions =
(objectClone(windowApp.launchPreference?.options) as WindowLaunchOptions) ??
({ type: "window" } as WindowLaunchOptions);
const canUpdateBounds = isAppPreferenceUpdatable(windowApp, "bounds");
const canUpdateCentered = isAppPreferenceUpdatable(windowApp, "centered");
const canUpdateCustomData = isAppPreferenceUpdatable(windowApp, "custom-data");
const canUpdateInterop = isAppPreferenceUpdatable(windowApp, "interop");
const canUpdateUrl = isAppPreferenceUpdatable(windowApp, "url");
if (!isEmpty(canUpdateBounds) && !isEmpty(launchPreference?.bounds)) {
const callerIdentityBasedLocation = await getCallerIdentityBasedPosition(callerIdentity);
appLaunchPreference.bounds = {
...appLaunchPreference.bounds,
...callerIdentityBasedLocation,
...launchPreference?.bounds
};
}
if (!isEmpty(canUpdateCentered) && !isEmpty(launchPreference?.defaultCentered)) {
appLaunchPreference.defaultCentered = launchPreference?.defaultCentered;
}
if (appLaunchPreferenceOptions?.type === "window" && launchPreference?.options?.type === "window") {
if (!isEmpty(canUpdateCustomData) && !isEmpty(launchPreference?.options?.window?.customData)) {
if (isEmpty(appLaunchPreferenceOptions.window)) {
appLaunchPreferenceOptions.window = {};
}
appLaunchPreferenceOptions.window.customData = {
...appLaunchPreferenceOptions.window?.customData,
...launchPreference.options?.window?.customData
};
}
if (!isEmpty(canUpdateInterop) && !isEmpty(launchPreference?.options?.window?.interop)) {
if (isEmpty(appLaunchPreferenceOptions.window)) {
appLaunchPreferenceOptions.window = {};
}
appLaunchPreferenceOptions.window.interop = launchPreference?.options.window?.interop;
}
if (!isEmpty(canUpdateUrl) && !isEmpty(launchPreference?.options?.window?.url)) {
if (isEmpty(appLaunchPreferenceOptions.window)) {
appLaunchPreferenceOptions.window = {};
}
if (isValidUrl(manifest.url, launchPreference.options.window.url, canUpdateUrl.constraint)) {
appLaunchPreferenceOptions.window.url = launchPreference.options.window.url;
}
}
}
const platform = getCurrentSync();
manifest.defaultHeight = appLaunchPreference?.bounds?.height ?? manifest.defaultHeight;
manifest.height = appLaunchPreference?.bounds?.height ?? manifest.height;
manifest.defaultWidth = appLaunchPreference?.bounds?.width ?? manifest.defaultWidth;
manifest.width = appLaunchPreference?.bounds?.width ?? manifest.width;
manifest.defaultCentered = appLaunchPreference?.defaultCentered ?? manifest.defaultCentered;
manifest.x = appLaunchPreference.bounds?.left ?? manifest.x;
manifest.defaultLeft = appLaunchPreference.bounds?.left ?? manifest.defaultLeft;
manifest.y = appLaunchPreference.bounds?.top ?? manifest.y;
manifest.defaultTop = appLaunchPreference.bounds?.top ?? manifest.defaultTop;
if (
!isEmpty(appLaunchPreferenceOptions?.window) &&
isStringValue(appLaunchPreferenceOptions?.window?.url)
) {
logger.debug(
`Updating app with id: ${windowApp.appId}. The url of the window app is defined via launch preferences: ${manifest.url} is being replaced with ${appLaunchPreferenceOptions.window?.url}`
);
manifest.url = appLaunchPreferenceOptions.window.url;
}
if (!isEmpty(appLaunchPreferenceOptions?.window?.customData)) {
logger.debug(
`Updating app with id: ${windowApp.appId}. The custom data is being updated with launch preferences:`,
appLaunchPreferenceOptions.window?.customData
);
manifest.customData = appLaunchPreferenceOptions.window?.customData;
}
if (
!isEmpty(appLaunchPreferenceOptions?.window) &&
!isEmpty(appLaunchPreferenceOptions?.window?.interop)
) {
logger.debug(
`Updating app with id: ${windowApp.appId}. The interop definition is being updated with launch preferences:`,
appLaunchPreferenceOptions.window?.interop
);
manifest.interop = appLaunchPreferenceOptions.window.interop;
}
const createdWindow = await platform.createWindow(manifest);
identity = createdWindow.identity;
await bringWindowToFront({ window: createdWindow });
} catch (err) {
logger.error("Error launching window", err);
return;
}
}
return { ...identity, appId: windowApp.appId };
}
/**
* Launch a view for the platform app.
* @param viewApp The app to launch the view for.
* @param launchPreference The preferences (if supported) that you would like to apply
* @param callerIdentity optionally pass information related to the caller to consider when launching.
* @returns The identity of the view launched.
*/
async function launchView(
viewApp: PlatformApp,
launchPreference?: UpdatableLaunchPreference,
callerIdentity?: OpenFin.Identity
): Promise<PlatformAppIdentifier | undefined> {
if (isEmpty(viewApp)) {
logger.warn("No app was passed to launchView");
return;
}
if (
viewApp.manifestType !== MANIFEST_TYPES.View.id &&
viewApp.manifestType !== MANIFEST_TYPES.InlineView.id
) {
logger.warn(
`The app passed was not of manifestType ${MANIFEST_TYPES.View.id} or ${MANIFEST_TYPES.InlineView.id}.`
);
return;
}
let manifest: OpenFin.ViewOptions | undefined;
if (viewApp.manifestType === MANIFEST_TYPES.View.id) {
manifest = await getManifest<OpenFin.ViewOptions>(viewApp);
} else {
// conversion because of manifestType. In most use cases manifest is always a path to an executable or to a manifest file. For views we are demonstrating how it could be used
// for passing the manifest inline
manifest = getInlineManifest(viewApp);
}
if (isEmpty(manifest)) {
logger.error(
`There was a problem encountered while trying to fetch the manifest for app: ${viewApp.appId}. Returning without launching.`
);
return;
}
let name = manifest.name;
let wasNameSpecified = !isEmpty(name);
if (!wasNameSpecified && viewApp?.instanceMode === "single") {
logger.info(
`A unique name was not provided in the manifest of this view but the custom config indicates that this app is supposed to have a single instance so we are using the appId: ${viewApp.appId} as the unique name.`
);
name = viewApp.appId;
// assign the new name to the manifest in case the view doesn't exist yet (as it is dynamically allocated and not part of the app's manifest)
manifest.name = name;
wasNameSpecified = true;
} else if (!wasNameSpecified) {
name = `${viewApp.appId}/${randomUUID()}`;
manifest.name = name;
}
let identity = { uuid: fin.me.identity.uuid, name };
let viewExists = false;
if (wasNameSpecified) {
viewExists = await doesViewExist(identity, true);
}
if (!viewExists) {
try {
const platform = getCurrentSync();
const appLaunchPreference = objectClone(viewApp.launchPreference) ?? {};
const appLaunchPreferenceOptions =
objectClone(viewApp.launchPreference?.options) ??
({
type: "view"
} as ViewLaunchOptions);
const canUpdateBounds = isAppPreferenceUpdatable(viewApp, "bounds");
const canUpdateCentered = isAppPreferenceUpdatable(viewApp, "centered");
const canUpdateHostOptions = isAppPreferenceUpdatable(viewApp, "host-options");
const canUpdateCustomData = isAppPreferenceUpdatable(viewApp, "custom-data");
const canUpdateInterop = isAppPreferenceUpdatable(viewApp, "interop");
const canUpdateUrl = isAppPreferenceUpdatable(viewApp, "url");
if (!isEmpty(canUpdateBounds) && (!isEmpty(launchPreference?.bounds) || !isEmpty(callerIdentity))) {
const callerIdentityBasedLocation = await getCallerIdentityBasedPosition(callerIdentity);
appLaunchPreference.bounds = {
...appLaunchPreference.bounds,
...callerIdentityBasedLocation,
...launchPreference?.bounds
};
}
if (!isEmpty(canUpdateCentered) && !isEmpty(launchPreference?.defaultCentered)) {
appLaunchPreference.defaultCentered = launchPreference?.defaultCentered;
}
if (appLaunchPreferenceOptions?.type === "view" && launchPreference?.options?.type === "view") {
if (isEmpty(appLaunchPreferenceOptions.host)) {
appLaunchPreferenceOptions.host = {};
}
if (!isEmpty(canUpdateHostOptions) && !isEmpty(launchPreference?.options?.host)) {
if (
isStringValue(appLaunchPreferenceOptions.host?.url) &&
isStringValue(launchPreference.options.host?.url) &&
!isValidUrl(
appLaunchPreferenceOptions.host.url,
launchPreference.options.host.url,
canUpdateHostOptions.constraint
)
) {
// a url already exists and the suggested one does not match so reset it
launchPreference.options.host.url = undefined;
}
appLaunchPreferenceOptions.host = {
...appLaunchPreferenceOptions.host,
...launchPreference.options?.host
};
}
if (!isEmpty(canUpdateCustomData) && !isEmpty(launchPreference?.options?.view?.customData)) {
if (isEmpty(appLaunchPreferenceOptions.view)) {
appLaunchPreferenceOptions.view = {};
}
appLaunchPreferenceOptions.view.customData = {
...appLaunchPreferenceOptions.view?.customData,
...launchPreference.options?.view?.customData
};
}
if (!isEmpty(canUpdateInterop) && !isEmpty(launchPreference?.options?.view?.interop)) {
if (isEmpty(appLaunchPreferenceOptions.view)) {
appLaunchPreferenceOptions.view = {};
}
appLaunchPreferenceOptions.view.interop = launchPreference?.options.view?.interop;
}
if (!isEmpty(canUpdateUrl) && !isEmpty(launchPreference?.options?.view?.url)) {
if (isEmpty(appLaunchPreferenceOptions.view)) {
appLaunchPreferenceOptions.view = {};
}
if (isValidUrl(manifest.url, launchPreference.options.view.url, canUpdateUrl.constraint)) {
appLaunchPreferenceOptions.view.url = launchPreference.options.view.url;
}
}
}
if (appLaunchPreferenceOptions?.type === "view" && !isEmpty(appLaunchPreferenceOptions?.view)) {
if (isStringValue(appLaunchPreferenceOptions.view.url)) {
logger.debug(
`Updating app with id: ${viewApp.appId} url with launch preferences: ${manifest.url} with ${appLaunchPreferenceOptions.view.url}`
);
manifest.url = appLaunchPreferenceOptions.view.url;
}
if (!isEmpty(appLaunchPreferenceOptions.view?.customData)) {
logger.debug(
`Updating app with id: ${viewApp.appId} customData with merged launch preferences.`,
appLaunchPreferenceOptions.view.customData
);
manifest.customData = appLaunchPreferenceOptions.view.customData;
}
if (!isEmpty(appLaunchPreferenceOptions?.view?.interop)) {
logger.debug(
`Updating app with id: ${viewApp.appId} interop config with launch preferences.`,
appLaunchPreferenceOptions.view.interop
);
manifest.interop = appLaunchPreferenceOptions.view.interop;
}
}
const bounds = appLaunchPreference?.bounds;
const host: HostLaunchOptions | undefined =
!isEmpty(appLaunchPreferenceOptions) && appLaunchPreferenceOptions.type === "view"
? appLaunchPreferenceOptions?.host
: undefined;
const defaultCentered = appLaunchPreference?.defaultCentered ?? false;
if (!isEmpty(bounds) || !isEmpty(host)) {
let workspacePlatform:
| Partial<BrowserWorkspacePlatformWindowOptions>
| { windowType: WindowType.Platform }
| undefined = {};
const layout = {
content: [
{
type: "stack",
content: [
{
type: "component",
componentName: "view",
componentState: manifest
}
]
}
],
settings: {
hasHeaders: host?.hasHeaders
}
};
workspacePlatform = {
windowType: !isEmpty(host?.url) ? WindowType.Platform : undefined,
disableMultiplePages: host?.disableMultiplePages,
title: host?.title,
favicon: host?.icon
};
if (!isEmpty(host?.pageTitle) || !isEmpty(host?.pageIcon)) {
const page: Page = {
pageId: `page-${randomUUID()}`,
iconUrl: host?.pageIcon,
title: await platform.Browser.getUniquePageTitle(host?.pageTitle),
layout
};
workspacePlatform.pages = [page];
}
if (host?.disableToolbarOptions === true) {
workspacePlatform.toolbarOptions = { buttons: [] };
}
if (Object.keys(workspacePlatform).length === 0) {
workspacePlatform = undefined;
}
const preferenceWindow = await platform.createWindow({
workspacePlatform,
url: host?.url,
height: bounds?.height,
defaultHeight: bounds?.height,
defaultWidth: bounds?.width,
defaultLeft: bounds?.left,
defaultTop: bounds?.top,
width: bounds?.width,
defaultCentered,
layout
});
const createdViews = await preferenceWindow.getCurrentViews();
if (createdViews.length === 1) {
if (createdViews[0].identity.name === identity.name) {
identity = createdViews[0].identity;
} else {
logger.warn(
`The specified view id: ${identity.name} was not found in the returned view so we will be returning undefined as we cannot confirm the view was created.`
);
return;
}
} else {
logger.warn(
`We expected to create a single view with identity ${identity.name} but a preference was specified and the created window had more than the requested view ${createdViews.length}`
);
const matchedView = createdViews.find((view) => view.identity.name === identity.name);
if (isEmpty(matchedView)) {
logger.warn(
`The specified view id: ${identity.name} was not found in the list of returned views so we will be returning undefined as we cannot confirm the view was created.`
);
return;
}
identity = matchedView.identity;
}
} else {
const createdView = await platform.createView(manifest);
identity = createdView.identity;
}
} catch (err) {
logger.error("Error launching view", err);
return;
}
}
return { ...identity, appId: viewApp.appId };
}
/**
* Launch a snapshot for the platform app.
* @param snapshotApp The app to launch snapshot view for.
* @returns The identities of the snapshot parts launched.
*/
async function launchSnapshot(snapshotApp: PlatformApp): Promise<PlatformAppIdentifier[] | undefined> {
if (isEmpty(snapshotApp)) {
logger.warn("No app was passed to launchSnapshot");
return;
}
if (
snapshotApp.manifestType !== MANIFEST_TYPES.Snapshot.id &&
snapshotApp.manifestType !== MANIFEST_TYPES.InlineSnapshot.id
) {
logger.warn(
`The app passed was not of manifestType ${MANIFEST_TYPES.Snapshot.id} or ${MANIFEST_TYPES.InlineSnapshot.id}`
);
return;
}
let manifest: BrowserSnapshot | undefined;
if (snapshotApp.manifestType === MANIFEST_TYPES.Snapshot.id) {
logger.info(`Fetching snapshot for app ${snapshotApp.appId} from url: ${snapshotApp.manifest}`);
manifest = await getManifest<BrowserSnapshot>(snapshotApp);
} else {
logger.info(`Using snapshot defined in manifest setting of app ${snapshotApp.appId}`);
manifest = getInlineManifest(snapshotApp);
}
if (isEmpty(manifest)) {
logger.error(
`There was a problem encountered while trying to fetch the manifest for app: ${snapshotApp.appId}. Returning without launching.`
);
return;
}
const windows = manifest.windows;
const windowsToCreate = [];
if (Array.isArray(windows)) {
const windowsToGather: string[] = [];
const viewIds: PlatformAppIdentifier[] = [];
for (const currentWindow of windows) {
if (Array.isArray(currentWindow.workspacePlatform?.pages)) {
for (let i = 0; i < currentWindow.workspacePlatform.pages.length; i++) {
const page = currentWindow.workspacePlatform.pages[i];
if (!isEmpty(page.layout)) {
page.layout = updateInstanceIds(page.layout);
}
currentWindow.workspacePlatform.pages[i] = page;
}
} else {
currentWindow.layout = updateInstanceIds(currentWindow.layout);
}
const uuid = randomUUID();
const name = currentWindow.name ?? `${snapshotApp.appId}/${uuid}`;
currentWindow.name = name;
windowsToCreate.push(currentWindow);
windowsToGather.push(name);
}
manifest.windows = windowsToCreate;
if (windowsToCreate.length > 0) {
const platform = getCurrentSync();
try {
await platform.applySnapshot(manifest);
} catch (err) {
logger.error("Error trying to apply snapshot to platform", err, manifest);
}
}
for (const targetWindow of windowsToGather) {
const windowViewIds = await getViewIdentities(targetWindow, fin.me.identity.uuid, snapshotApp.appId);
viewIds.push(...windowViewIds);
}
return viewIds;
}
}
/**
* Launch an app asset for the platform app.
* @param appAssetApp The app to launch app asset view for.
* @param instanceId Provide an instance id for the app being launched.
* @param launchPreference Optional custom launch preferences
* @returns The identities of the snapshot parts launched.
*/
export async function launchAppAsset(
appAssetApp: PlatformApp,
instanceId?: string,
launchPreference?: UpdatableLaunchPreference
): Promise<PlatformAppIdentifier | undefined> {
const options: OpenFin.ExternalProcessRequestType = {};
logger.info(`Request to launch app asset app of type ${appAssetApp.manifestType}`);
if (appAssetApp.manifestType === MANIFEST_TYPES.Appasset.id) {
options.alias = appAssetApp.manifest;
} else if (appAssetApp.manifestType === MANIFEST_TYPES.InlineAppAsset.id) {
const appAssetInfo: OpenFin.AppAssetInfo = getInlineManifest(appAssetApp);
let availableAppAsset: OpenFin.AppAssetInfo | undefined;
try {
availableAppAsset = await fin.System.getAppAssetInfo({ alias: appAssetInfo.alias });
} catch (appAssetError) {
logger.debug(
`App asset info for alias: ${
appAssetInfo.alias
} is not available. Response from getAppAssetInfo: ${formatError(appAssetError)}`
);
}
if (isEmpty(availableAppAsset) || appAssetInfo.version !== availableAppAsset.version) {
logger.info(`App asset with alias: ${appAssetInfo.alias} does not exist in memory. Fetching it.`);
try {
await fin.System.downloadAsset(appAssetInfo, (progress) => {
const downloadedPercent = Math.floor((progress.downloadedBytes / progress.totalBytes) * 100);
logger.info(`Downloaded ${downloadedPercent}% of app asset with appId of ${appAssetApp.appId}`);
});
} catch (error) {
logger.error(`Error trying to download app asset with app id: ${appAssetApp.appId}`, error);
return;
}
}
options.alias = appAssetInfo.alias;
options.arguments = appAssetInfo.args;
} else {
logger.warn(
"An app asset app was passed to launch app asset but it didn't match the supported manifest types."
);
return;
}
if (appAssetApp.instanceMode === "single") {
// use the appId as the UUID and OpenFin will only be able to launch a single instance
options.uuid = options.uuid ?? appAssetApp.appId;
} else {
options.uuid = `${options.uuid ?? appAssetApp.appId}/${
isStringValue(instanceId) ? instanceId : randomUUID()
}`;
}
try {
logger.info(`Launching app asset with appId: ${appAssetApp.appId} with the following options:`, options);
const identity = await launchExternalProcess(appAssetApp, options, instanceId, launchPreference);
logger.info(
`External app with appId: ${appAssetApp.appId} launched with the following identity`,
identity
);
return identity;
} catch (error) {
logger.error(`Error trying to launch app asset with appId: ${appAssetApp.appId}}`, error);
}
}
/**
* Launch an external for the platform app.
* @param externalApp The app to launch external view for.
* @param instanceId Provide an instance id for the app being launched.
* @param launchPreference Optional custom launch preferences
* @returns The identities of the app parts launched.
*/
export async function launchExternal(
externalApp: PlatformApp,
instanceId?: string,
launchPreference?: UpdatableLaunchPreference
): Promise<PlatformAppIdentifier | undefined> {
let options: OpenFin.ExternalProcessRequestType = {};
logger.info(`Request to external app of type ${externalApp.manifestType}`);
if (externalApp.manifestType === MANIFEST_TYPES.External.id) {
options.path = externalApp.manifest;
} else if (externalApp.manifestType === MANIFEST_TYPES.InlineExternal.id) {
options = getInlineManifest(externalApp);
} else {
logger.warn("An external app was passed to launch but it didn't match the supported manifest types.");
return;
}
if (externalApp.instanceMode === "single") {
// use the appId as the UUID and OpenFin will only be able to launch a single instance
options.uuid = options.uuid ?? externalApp.appId;
} else {
options.uuid = `${options.uuid ?? externalApp.appId}/${
isStringValue(instanceId) ? instanceId : randomUUID()
}`;
}
try {
logger.info(
`Launching external app asset with appId: ${externalApp.appId} with the following options:`,
options
);
const identity = await launchExternalProcess(externalApp, options, instanceId, launchPreference);
logger.info(
`External app with appId: ${externalApp.appId} launched with the following identity`,
identity
);
return identity;
} catch (err) {
logger.error(`Error trying to launch external with appId: ${externalApp.appId}`, err);
}
}
/**
* Launch an external process either in regular or snap mode.
* @param app The app being launched.
* @param options The launch options.
* @param instanceId Provide an instance id for the app being launched.
* @param launchPreference Optional custom launch preferences
* @returns The identity of the process.
*/
async function launchExternalProcess(
app: PlatformApp,
options: OpenFin.ExternalProcessRequestType,
instanceId?: string,
launchPreference?: UpdatableLaunchPreference
): Promise<PlatformAppIdentifier> {
const nativeOptions =
(objectClone(app.launchPreference?.options) as NativeLaunchOptions) ??
({ type: "native" } as NativeLaunchOptions);
const canUpdateArgs = isAppPreferenceUpdatable(app, "arguments");
const hasPath = isStringValue(options.path);
let identity: PlatformAppIdentifier | undefined;
let args: string[] | undefined;
if (
!isEmpty(canUpdateArgs) &&
launchPreference?.options?.type === "native" &&
Array.isArray(launchPreference?.options?.native?.arguments)
) {
args = launchPreference.options.native?.arguments;
logger.debug(`Using passed launch preference for the args for app ${app.appId}`, args);