/
plugin-view-registry.ts
882 lines (798 loc) · 37.8 KB
/
plugin-view-registry.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
// *****************************************************************************
// Copyright (C) 2018 Red Hat, Inc. and others.
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License v. 2.0 which is available at
// http://www.eclipse.org/legal/epl-2.0.
//
// This Source Code may also be made available under the following Secondary
// Licenses when the conditions for such availability set forth in the Eclipse
// Public License v. 2.0 are satisfied: GNU General Public License, version 2
// with the GNU Classpath Exception which is available at
// https://www.gnu.org/software/classpath/license.html.
//
// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
// *****************************************************************************
import { injectable, inject, postConstruct, optional } from '@theia/core/shared/inversify';
import {
ApplicationShell, ViewContainer as ViewContainerWidget, WidgetManager, QuickViewService,
ViewContainerIdentifier, ViewContainerTitleOptions, Widget, FrontendApplicationContribution,
StatefulWidget, CommonMenus, BaseWidget, TreeViewWelcomeWidget, codicon, ViewContainerPart
} from '@theia/core/lib/browser';
import { ViewContainer, View, ViewWelcome, PluginViewType } from '../../../common';
import { PluginSharedStyle } from '../plugin-shared-style';
import { DebugWidget } from '@theia/debug/lib/browser/view/debug-widget';
import { PluginViewWidget, PluginViewWidgetIdentifier } from './plugin-view-widget';
import { SCM_VIEW_CONTAINER_ID, ScmContribution } from '@theia/scm/lib/browser/scm-contribution';
import { EXPLORER_VIEW_CONTAINER_ID, FileNavigatorWidget, FILE_NAVIGATOR_ID } from '@theia/navigator/lib/browser';
import { FileNavigatorContribution } from '@theia/navigator/lib/browser/navigator-contribution';
import { DebugFrontendApplicationContribution } from '@theia/debug/lib/browser/debug-frontend-application-contribution';
import { Disposable, DisposableCollection } from '@theia/core/lib/common/disposable';
import { CommandRegistry } from '@theia/core/lib/common/command';
import { MenuModelRegistry } from '@theia/core/lib/common/menu';
import { Emitter, Event } from '@theia/core/lib/common/event';
import { ContextKeyService } from '@theia/core/lib/browser/context-key-service';
import { ViewContextKeyService } from './view-context-key-service';
import { PROBLEMS_WIDGET_ID } from '@theia/markers/lib/browser/problem/problem-widget';
import { OutputWidget } from '@theia/output/lib/browser/output-widget';
import { DebugConsoleContribution } from '@theia/debug/lib/browser/console/debug-console-contribution';
import { TERMINAL_WIDGET_FACTORY_ID } from '@theia/terminal/lib/browser/terminal-widget-impl';
import { TreeViewWidget } from './tree-view-widget';
import { SEARCH_VIEW_CONTAINER_ID } from '@theia/search-in-workspace/lib/browser/search-in-workspace-factory';
import { ThemeIcon } from '@theia/monaco-editor-core/esm/vs/platform/theme/common/themeService';
import { WebviewView, WebviewViewResolver } from '../webview-views/webview-views';
import { WebviewWidget, WebviewWidgetIdentifier } from '../webview/webview';
import { CancellationToken } from '@theia/core/lib/common/cancellation';
import { v4 } from 'uuid';
import { nls } from '@theia/core';
export const PLUGIN_VIEW_FACTORY_ID = 'plugin-view';
export const PLUGIN_VIEW_CONTAINER_FACTORY_ID = 'plugin-view-container';
export const PLUGIN_VIEW_DATA_FACTORY_ID = 'plugin-view-data';
export type ViewDataProvider = (params: { state?: object, viewInfo: View }) => Promise<TreeViewWidget>;
@injectable()
export class PluginViewRegistry implements FrontendApplicationContribution {
@inject(ApplicationShell)
protected readonly shell: ApplicationShell;
@inject(PluginSharedStyle)
protected readonly style: PluginSharedStyle;
@inject(WidgetManager)
protected readonly widgetManager: WidgetManager;
@inject(ScmContribution)
protected readonly scm: ScmContribution;
@inject(FileNavigatorContribution)
protected readonly explorer: FileNavigatorContribution;
@inject(DebugFrontendApplicationContribution)
protected readonly debug: DebugFrontendApplicationContribution;
@inject(CommandRegistry)
protected readonly commands: CommandRegistry;
@inject(MenuModelRegistry)
protected readonly menus: MenuModelRegistry;
@inject(QuickViewService) @optional()
protected readonly quickView: QuickViewService;
@inject(ContextKeyService)
protected readonly contextKeyService: ContextKeyService;
@inject(ViewContextKeyService)
protected readonly viewContextKeys: ViewContextKeyService;
protected readonly onDidExpandViewEmitter = new Emitter<string>();
readonly onDidExpandView = this.onDidExpandViewEmitter.event;
private readonly views = new Map<string, [string, View]>();
private readonly viewsWelcome = new Map<string, ViewWelcome[]>();
private readonly viewContainers = new Map<string, [string, ViewContainerTitleOptions]>();
private readonly containerViews = new Map<string, string[]>();
private readonly viewClauseContexts = new Map<string, Set<string> | undefined>();
private readonly viewDataProviders = new Map<string, ViewDataProvider>();
private readonly viewDataState = new Map<string, object>();
private readonly webviewViewResolvers = new Map<string, WebviewViewResolver>();
@postConstruct()
protected init(): void {
// VS Code Viewlets
this.trackVisibleWidget(EXPLORER_VIEW_CONTAINER_ID, { viewletId: 'workbench.view.explorer' });
this.trackVisibleWidget(SCM_VIEW_CONTAINER_ID, { viewletId: 'workbench.view.scm' });
this.trackVisibleWidget(SEARCH_VIEW_CONTAINER_ID, { viewletId: 'workbench.view.search' });
this.trackVisibleWidget(DebugWidget.ID, { viewletId: 'workbench.view.debug' });
// TODO workbench.view.extensions - Theia does not have a proper extension view yet
// VS Code Panels
this.trackVisibleWidget(PROBLEMS_WIDGET_ID, { panelId: 'workbench.panel.markers' });
this.trackVisibleWidget(OutputWidget.ID, { panelId: 'workbench.panel.output' });
this.trackVisibleWidget(DebugConsoleContribution.options.id, { panelId: 'workbench.panel.repl' });
this.trackVisibleWidget(TERMINAL_WIDGET_FACTORY_ID, { panelId: 'workbench.panel.terminal' });
// TODO workbench.panel.comments - Theia does not have a proper comments view yet
this.updateFocusedView();
this.shell.onDidChangeActiveWidget(() => this.updateFocusedView());
this.widgetManager.onWillCreateWidget(({ factoryId, widget, waitUntil }) => {
if (factoryId === EXPLORER_VIEW_CONTAINER_ID && widget instanceof ViewContainerWidget) {
waitUntil(this.prepareViewContainer('explorer', widget));
}
if (factoryId === SCM_VIEW_CONTAINER_ID && widget instanceof ViewContainerWidget) {
waitUntil(this.prepareViewContainer('scm', widget));
}
if (factoryId === SEARCH_VIEW_CONTAINER_ID && widget instanceof ViewContainerWidget) {
waitUntil(this.prepareViewContainer('search', widget));
}
if (factoryId === DebugWidget.ID && widget instanceof DebugWidget) {
const viewContainer = widget['sessionWidget']['viewContainer'];
waitUntil(this.prepareViewContainer('debug', viewContainer));
}
if (factoryId === PLUGIN_VIEW_CONTAINER_FACTORY_ID && widget instanceof ViewContainerWidget) {
waitUntil(this.prepareViewContainer(this.toViewContainerId(widget.options), widget));
}
if (factoryId === PLUGIN_VIEW_FACTORY_ID && widget instanceof PluginViewWidget) {
waitUntil(this.prepareView(widget));
}
});
this.widgetManager.onDidCreateWidget(event => {
if (event.widget instanceof FileNavigatorWidget) {
const disposable = new DisposableCollection();
disposable.push(this.registerViewWelcome({
view: 'explorer',
content: nls.localizeByDefault('You have not yet opened a folder.\n[Open Folder](command:{0})', 'workbench.action.files.openFolder'),
order: 0
}));
disposable.push(event.widget.onDidDispose(() => disposable.dispose()));
}
});
this.doRegisterViewContainer('test', 'left', {
label: 'Test',
iconClass: codicon('beaker'),
closeable: true
});
this.contextKeyService.onDidChange(e => {
for (const [, view] of this.views.values()) {
const clauseContext = this.viewClauseContexts.get(view.id);
if (clauseContext && e.affects(clauseContext)) {
this.updateViewVisibility(view.id);
}
}
for (const [viewId, viewWelcomes] of this.viewsWelcome) {
for (const [index] of viewWelcomes.entries()) {
const viewWelcomeId = this.toViewWelcomeId(index, viewId);
const clauseContext = this.viewClauseContexts.get(viewWelcomeId);
if (clauseContext && e.affects(clauseContext)) {
this.updateViewWelcomeVisibility(viewId);
}
}
}
});
}
protected async updateViewWelcomeVisibility(viewId: string): Promise<void> {
const widget = await this.getTreeViewWelcomeWidget(viewId);
if (widget) {
widget.handleWelcomeContextChange();
}
}
protected async updateViewVisibility(viewId: string): Promise<void> {
const widget = await this.getView(viewId);
if (!widget) {
if (this.isViewVisible(viewId)) {
await this.openView(viewId);
}
return;
}
const viewInfo = this.views.get(viewId);
if (!viewInfo) {
return;
}
const [viewContainerId] = viewInfo;
const viewContainer = await this.getPluginViewContainer(viewContainerId);
if (!viewContainer) {
return;
}
const part = viewContainer.getPartFor(widget);
if (!part) {
return;
}
widget.updateViewVisibility(() =>
part.setHidden(!this.isViewVisible(viewId))
);
}
protected isViewVisible(viewId: string): boolean {
const viewInfo = this.views.get(viewId);
if (!viewInfo) {
return false;
}
const [, view] = viewInfo;
return view.when === undefined || view.when === 'true' || this.contextKeyService.match(view.when);
}
registerViewContainer(location: string, viewContainer: ViewContainer): Disposable {
if (this.viewContainers.has(viewContainer.id)) {
console.warn('view container such id already registered: ', JSON.stringify(viewContainer));
return Disposable.NULL;
}
const toDispose = new DisposableCollection();
const containerClass = 'theia-plugin-view-container';
let themeIconClass = '';
const iconClass = 'plugin-view-container-icon-' + viewContainer.id;
if (viewContainer.themeIcon) {
const icon = ThemeIcon.fromString(viewContainer.themeIcon);
if (icon) {
themeIconClass = ThemeIcon.asClassName(icon) ?? '';
}
}
if (!themeIconClass) {
const iconUrl = PluginSharedStyle.toExternalIconUrl(viewContainer.iconUrl);
toDispose.push(this.style.insertRule('.' + containerClass + '.' + iconClass, () => `
mask: url('${iconUrl}') no-repeat 50% 50%;
-webkit-mask: url('${iconUrl}') no-repeat 50% 50%;
`));
}
toDispose.push(this.doRegisterViewContainer(viewContainer.id, location, {
label: viewContainer.title,
// The container class automatically sets a mask; if we're using a theme icon, we don't want one.
iconClass: (themeIconClass || containerClass) + ' ' + iconClass,
closeable: true
}));
return toDispose;
}
protected async toggleViewContainer(id: string): Promise<void> {
let widget = await this.getPluginViewContainer(id);
if (widget && widget.isAttached) {
widget.dispose();
} else {
widget = await this.openViewContainer(id);
if (widget) {
this.shell.activateWidget(widget.id);
}
}
}
protected doRegisterViewContainer(id: string, location: string, options: ViewContainerTitleOptions): Disposable {
const toDispose = new DisposableCollection();
this.viewContainers.set(id, [location, options]);
toDispose.push(Disposable.create(() => this.viewContainers.delete(id)));
const toggleCommandId = `plugin.view-container.${id}.toggle`;
toDispose.push(this.commands.registerCommand({
id: toggleCommandId,
label: 'Toggle ' + options.label + ' View'
}, {
execute: () => this.toggleViewContainer(id)
}));
toDispose.push(this.menus.registerMenuAction(CommonMenus.VIEW_VIEWS, {
commandId: toggleCommandId,
label: options.label
}));
toDispose.push(this.quickView?.registerItem({
label: options.label,
open: async () => {
const widget = await this.openViewContainer(id);
if (widget) {
this.shell.activateWidget(widget.id);
}
}
}));
toDispose.push(Disposable.create(async () => {
const widget = await this.getPluginViewContainer(id);
if (widget) {
widget.dispose();
}
}));
return toDispose;
}
getContainerViews(viewContainerId: string): string[] {
return this.containerViews.get(viewContainerId) || [];
}
registerView(viewContainerId: string, view: View): Disposable {
if (this.views.has(view.id)) {
console.warn('view with such id already registered: ', JSON.stringify(view));
return Disposable.NULL;
}
const toDispose = new DisposableCollection();
view.when = view.when?.trim();
this.views.set(view.id, [viewContainerId, view]);
toDispose.push(Disposable.create(() => this.views.delete(view.id)));
const containerViews = this.getContainerViews(viewContainerId);
containerViews.push(view.id);
this.containerViews.set(viewContainerId, containerViews);
toDispose.push(Disposable.create(() => {
const index = containerViews.indexOf(view.id);
if (index !== -1) {
containerViews.splice(index, 1);
}
}));
if (view.when && view.when !== 'false' && view.when !== 'true') {
const keys = this.contextKeyService.parseKeys(view.when);
if (keys) {
this.viewClauseContexts.set(view.id, keys);
toDispose.push(Disposable.create(() => this.viewClauseContexts.delete(view.id)));
}
}
toDispose.push(this.quickView?.registerItem({
label: view.name,
when: view.when,
open: () => this.openView(view.id, { activate: true })
}));
toDispose.push(this.commands.registerCommand({ id: `${view.id}.focus` }, {
execute: async () => { await this.openView(view.id, { activate: true }); }
}));
return toDispose;
}
async registerWebviewView(viewId: string, resolver: WebviewViewResolver): Promise<Disposable> {
if (this.webviewViewResolvers.has(viewId)) {
throw new Error(`View resolver already registered for ${viewId}`);
}
this.webviewViewResolvers.set(viewId, resolver);
const webviewView = await this.createNewWebviewView();
const token = CancellationToken.None;
this.getView(viewId).then(async view => {
if (view) {
if (view.isVisible) {
await this.prepareView(view, webviewView.webview.identifier.id);
} else {
const toDisposeOnDidExpandView = new DisposableCollection(this.onDidExpandView(async id => {
if (id === viewId) {
dispose();
await this.prepareView(view, webviewView.webview.identifier.id);
}
}));
const dispose = () => toDisposeOnDidExpandView.dispose();
view.disposed.connect(dispose);
toDisposeOnDidExpandView.push(Disposable.create(() => view.disposed.disconnect(dispose)));
}
}
});
resolver.resolve(webviewView, token);
return Disposable.create(() => {
this.webviewViewResolvers.delete(viewId);
});
}
async createNewWebviewView(): Promise<WebviewView> {
const webview = await this.widgetManager.getOrCreateWidget<WebviewWidget>(
WebviewWidget.FACTORY_ID, <WebviewWidgetIdentifier>{ id: v4() });
webview.setContentOptions({ allowScripts: true });
let _description: string | undefined;
return {
webview,
get onDidChangeVisibility(): Event<boolean> { return webview.onDidChangeVisibility; },
get onDidDispose(): Event<void> { return webview.onDidDispose; },
get title(): string | undefined { return webview.title.label; },
set title(value: string | undefined) { webview.title.label = value || ''; },
get description(): string | undefined { return _description; },
set description(value: string | undefined) { _description = value; },
dispose: webview.dispose,
show: webview.show
};
}
registerViewWelcome(viewWelcome: ViewWelcome): Disposable {
const toDispose = new DisposableCollection();
const viewsWelcome = this.viewsWelcome.get(viewWelcome.view) || [];
if (viewsWelcome.some(e => e.content === viewWelcome.content)) {
return toDispose;
}
viewsWelcome.push(viewWelcome);
this.viewsWelcome.set(viewWelcome.view, viewsWelcome);
this.handleViewWelcomeChange(viewWelcome.view);
toDispose.push(Disposable.create(() => {
const index = viewsWelcome.indexOf(viewWelcome);
if (index !== -1) {
viewsWelcome.splice(index, 1);
}
this.handleViewWelcomeChange(viewWelcome.view);
}));
if (viewWelcome.when) {
const index = viewsWelcome.indexOf(viewWelcome);
const viewWelcomeId = this.toViewWelcomeId(index, viewWelcome.view);
this.viewClauseContexts.set(viewWelcomeId, this.contextKeyService.parseKeys(viewWelcome.when));
toDispose.push(Disposable.create(() => this.viewClauseContexts.delete(viewWelcomeId)));
}
return toDispose;
}
async handleViewWelcomeChange(viewId: string): Promise<void> {
const widget = await this.getTreeViewWelcomeWidget(viewId);
if (widget) {
widget.handleViewWelcomeContentChange(this.getViewWelcomes(viewId));
}
}
protected async getTreeViewWelcomeWidget(viewId: string): Promise<TreeViewWelcomeWidget | undefined> {
switch (viewId) {
case 'explorer':
return this.widgetManager.getWidget<TreeViewWelcomeWidget>(FILE_NAVIGATOR_ID);
default:
return this.widgetManager.getWidget<TreeViewWelcomeWidget>(PLUGIN_VIEW_DATA_FACTORY_ID, { id: viewId });
}
}
getViewWelcomes(viewId: string): ViewWelcome[] {
return this.viewsWelcome.get(viewId) || [];
}
async getView(viewId: string): Promise<PluginViewWidget | undefined> {
if (!this.views.has(viewId)) {
return undefined;
}
return this.widgetManager.getWidget<PluginViewWidget>(PLUGIN_VIEW_FACTORY_ID, this.toPluginViewWidgetIdentifier(viewId));
}
async openView(viewId: string, options?: { activate?: boolean, reveal?: boolean }): Promise<PluginViewWidget | undefined> {
const view = await this.doOpenView(viewId);
if (view && options) {
if (options.activate === true) {
await this.shell.activateWidget(view.id);
} else if (options.reveal === true) {
await this.shell.revealWidget(view.id);
}
}
return view;
}
protected async doOpenView(viewId: string): Promise<PluginViewWidget | undefined> {
const widget = await this.getView(viewId);
if (widget) {
return widget;
}
const data = this.views.get(viewId);
if (!data) {
return undefined;
}
const [containerId] = data;
await this.openViewContainer(containerId);
return this.getView(viewId);
}
protected async prepareView(widget: PluginViewWidget, webviewId?: string): Promise<void> {
const data = this.views.get(widget.options.viewId);
if (!data) {
return;
}
const [, view] = data;
if (!widget.title.label) {
widget.title.label = view.name;
}
const currentDataWidget = widget.widgets[0];
const viewDataWidget = await this.createViewDataWidget(view.id, webviewId);
if (widget.isDisposed) {
viewDataWidget?.dispose();
return;
}
if (currentDataWidget !== viewDataWidget) {
if (currentDataWidget) {
currentDataWidget.dispose();
}
if (viewDataWidget) {
widget.addWidget(viewDataWidget);
}
}
}
protected getOrCreateViewContainerWidget(containerId: string): Promise<ViewContainerWidget> {
const identifier = this.toViewContainerIdentifier(containerId);
return this.widgetManager.getOrCreateWidget<ViewContainerWidget>(PLUGIN_VIEW_CONTAINER_FACTORY_ID, identifier);
}
async openViewContainer(containerId: string): Promise<ViewContainerWidget | undefined> {
if (containerId === 'explorer') {
const widget = await this.explorer.openView();
if (widget.parent instanceof ViewContainerWidget) {
return widget.parent;
}
return undefined;
}
if (containerId === 'scm') {
const widget = await this.scm.openView();
if (widget.parent instanceof ViewContainerWidget) {
return widget.parent;
}
return undefined;
}
if (containerId === 'debug') {
const widget = await this.debug.openView();
return widget['sessionWidget']['viewContainer'];
}
const data = this.viewContainers.get(containerId);
if (!data) {
return undefined;
}
const [location] = data;
const containerWidget = await this.getOrCreateViewContainerWidget(containerId);
if (!containerWidget.isAttached) {
await this.shell.addWidget(containerWidget, {
area: ApplicationShell.isSideArea(location) ? location : 'left',
rank: Number.MAX_SAFE_INTEGER
});
}
return containerWidget;
}
protected async prepareViewContainer(viewContainerId: string, containerWidget: ViewContainerWidget): Promise<void> {
const data = this.viewContainers.get(viewContainerId);
if (data) {
const [, options] = data;
containerWidget.setTitleOptions(options);
}
for (const viewId of this.getContainerViews(viewContainerId)) {
const identifier = this.toPluginViewWidgetIdentifier(viewId);
// Keep existing widget in its current container and reregister its part to the plugin view widget events.
const existingWidget = this.widgetManager.tryGetWidget<PluginViewWidget>(PLUGIN_VIEW_FACTORY_ID, identifier);
if (existingWidget && existingWidget.currentViewContainerId) {
const currentContainer = await this.getPluginViewContainer(existingWidget.currentViewContainerId);
if (currentContainer && this.registerWidgetPartEvents(existingWidget, currentContainer)) {
continue;
}
}
const widget = await this.widgetManager.getOrCreateWidget<PluginViewWidget>(PLUGIN_VIEW_FACTORY_ID, identifier);
if (containerWidget.getTrackableWidgets().indexOf(widget) === -1) {
containerWidget.addWidget(widget, {
initiallyCollapsed: !!containerWidget.getParts().length,
initiallyHidden: !this.isViewVisible(viewId)
});
}
this.registerWidgetPartEvents(widget, containerWidget);
}
}
protected registerWidgetPartEvents(widget: PluginViewWidget, containerWidget: ViewContainerWidget): ViewContainerPart | undefined {
const part = containerWidget.getPartFor(widget);
if (part) {
widget.currentViewContainerId = this.getViewContainerId(containerWidget);
part.onDidMove(event => { widget.currentViewContainerId = this.getViewContainerId(event); });
// if a view is explicitly hidden then suppress updating visibility based on `when` closure
part.onDidChangeVisibility(() => widget.suppressUpdateViewVisibility = part.isHidden);
const tryFireOnDidExpandView = () => {
if (widget.widgets.length === 0) {
if (!part.collapsed && part.isVisible) {
const viewId = this.toViewId(widget.options);
this.onDidExpandViewEmitter.fire(viewId);
}
} else {
toFire.dispose();
}
};
const toFire = new DisposableCollection(
part.onCollapsed(tryFireOnDidExpandView),
part.onDidChangeVisibility(tryFireOnDidExpandView)
);
tryFireOnDidExpandView();
return part;
}
};
protected getViewContainerId(container: ViewContainerWidget): string | undefined {
const description = this.widgetManager.getDescription(container);
switch (description?.factoryId) {
case EXPLORER_VIEW_CONTAINER_ID: return 'explorer';
case SCM_VIEW_CONTAINER_ID: return 'scm';
case SEARCH_VIEW_CONTAINER_ID: return 'search';
case undefined: return container.parent?.parent instanceof DebugWidget ? 'debug' : container.id;
case PLUGIN_VIEW_CONTAINER_FACTORY_ID: return this.toViewContainerId(description.options);
default: return container.id;
}
}
protected async getPluginViewContainer(viewContainerId: string): Promise<ViewContainerWidget | undefined> {
if (viewContainerId === 'explorer') {
return this.widgetManager.getWidget<ViewContainerWidget>(EXPLORER_VIEW_CONTAINER_ID);
}
if (viewContainerId === 'scm') {
return this.widgetManager.getWidget<ViewContainerWidget>(SCM_VIEW_CONTAINER_ID);
}
if (viewContainerId === 'search') {
return this.widgetManager.getWidget<ViewContainerWidget>(SEARCH_VIEW_CONTAINER_ID);
}
if (viewContainerId === 'debug') {
const debug = await this.widgetManager.getWidget(DebugWidget.ID);
if (debug instanceof DebugWidget) {
return debug['sessionWidget']['viewContainer'];
}
}
const identifier = this.toViewContainerIdentifier(viewContainerId);
return this.widgetManager.getWidget<ViewContainerWidget>(PLUGIN_VIEW_CONTAINER_FACTORY_ID, identifier);
}
protected async initViewContainer(containerId: string): Promise<void> {
let viewContainer = await this.getPluginViewContainer(containerId);
if (!viewContainer) {
viewContainer = await this.openViewContainer(containerId);
if (viewContainer && !viewContainer.getParts().filter(part => !part.isHidden).length) {
// close view containers without any visible view parts
viewContainer.dispose();
}
} else {
await this.prepareViewContainer(this.toViewContainerId(viewContainer.options), viewContainer);
}
}
async initWidgets(): Promise<void> {
const promises: Promise<void>[] = [];
for (const id of this.viewContainers.keys()) {
promises.push((async () => {
await this.initViewContainer(id);
})().catch(console.error));
}
promises.push((async () => {
const explorer = await this.widgetManager.getWidget(EXPLORER_VIEW_CONTAINER_ID);
if (explorer instanceof ViewContainerWidget) {
await this.prepareViewContainer('explorer', explorer);
}
})().catch(console.error));
promises.push((async () => {
const scm = await this.widgetManager.getWidget(SCM_VIEW_CONTAINER_ID);
if (scm instanceof ViewContainerWidget) {
await this.prepareViewContainer('scm', scm);
}
})().catch(console.error));
promises.push((async () => {
const search = await this.widgetManager.getWidget(SEARCH_VIEW_CONTAINER_ID);
if (search instanceof ViewContainerWidget) {
await this.prepareViewContainer('search', search);
}
})().catch(console.error));
promises.push((async () => {
const debug = await this.widgetManager.getWidget(DebugWidget.ID);
if (debug instanceof DebugWidget) {
const viewContainer = debug['sessionWidget']['viewContainer'];
await this.prepareViewContainer('debug', viewContainer);
}
})().catch(console.error));
await Promise.all(promises);
}
async removeStaleWidgets(): Promise<void> {
const views = this.widgetManager.getWidgets(PLUGIN_VIEW_FACTORY_ID);
for (const view of views) {
if (view instanceof PluginViewWidget) {
const id = this.toViewId(view.options);
if (!this.views.has(id)) {
view.dispose();
}
}
}
const viewContainers = this.widgetManager.getWidgets(PLUGIN_VIEW_CONTAINER_FACTORY_ID);
for (const viewContainer of viewContainers) {
if (viewContainer instanceof ViewContainerWidget) {
const id = this.toViewContainerId(viewContainer.options);
if (!this.viewContainers.has(id)) {
viewContainer.dispose();
}
}
}
}
protected toViewContainerIdentifier(viewContainerId: string): ViewContainerIdentifier {
return { id: PLUGIN_VIEW_CONTAINER_FACTORY_ID + ':' + viewContainerId, progressLocationId: viewContainerId };
}
protected toViewContainerId(identifier: ViewContainerIdentifier): string {
return identifier.id.substr(PLUGIN_VIEW_CONTAINER_FACTORY_ID.length + 1);
}
protected toPluginViewWidgetIdentifier(viewId: string): PluginViewWidgetIdentifier {
return { id: PLUGIN_VIEW_FACTORY_ID + ':' + viewId, viewId };
}
protected toViewId(identifier: PluginViewWidgetIdentifier): string {
return identifier.viewId;
}
protected toViewWelcomeId(index: number, viewId: string): string {
return `view-welcome.${viewId}.${index}`;
}
/**
* retrieve restored layout state from previous user session but close widgets
* widgets should be opened only when view data providers are registered
*/
onDidInitializeLayout(): void {
const widgets = this.widgetManager.getWidgets(PLUGIN_VIEW_DATA_FACTORY_ID);
for (const widget of widgets) {
if (StatefulWidget.is(widget)) {
const state = widget.storeState();
if (state) {
this.viewDataState.set(widget.id, state);
}
}
widget.dispose();
}
}
registerViewDataProvider(viewId: string, provider: ViewDataProvider): Disposable {
if (this.viewDataProviders.has(viewId)) {
console.error(`data provider for '${viewId}' view is already registered`);
return Disposable.NULL;
}
this.viewDataProviders.set(viewId, provider);
const toDispose = new DisposableCollection(Disposable.create(() => {
this.viewDataProviders.delete(viewId);
this.viewDataState.delete(viewId);
}));
this.getView(viewId).then(async view => {
if (toDispose.disposed) {
return;
}
if (view) {
if (view.isVisible) {
await this.prepareView(view);
} else {
const toDisposeOnDidExpandView = new DisposableCollection(this.onDidExpandView(async id => {
if (id === viewId) {
unsubscribe();
await this.prepareView(view);
}
}));
const unsubscribe = () => toDisposeOnDidExpandView.dispose();
view.disposed.connect(unsubscribe);
toDisposeOnDidExpandView.push(Disposable.create(() => view.disposed.disconnect(unsubscribe)));
toDispose.push(toDisposeOnDidExpandView);
}
}
});
return toDispose;
}
protected async createViewDataWidget(viewId: string, webviewId?: string): Promise<Widget | undefined> {
const view = this.views.get(viewId);
if (view?.[1]?.type === PluginViewType.Webview) {
const webviewWidget = this.widgetManager.getWidget(WebviewWidget.FACTORY_ID, <WebviewWidgetIdentifier>{ id: webviewId });
return webviewWidget;
}
const provider = this.viewDataProviders.get(viewId);
if (!view || !provider) {
return undefined;
}
const [, viewInfo] = view;
const state = this.viewDataState.get(viewId);
const widget = await provider({ state, viewInfo });
widget.handleViewWelcomeContentChange(this.getViewWelcomes(viewId));
if (StatefulWidget.is(widget)) {
this.storeViewDataStateOnDispose(viewId, widget);
} else {
this.viewDataState.delete(viewId);
}
return widget;
}
protected storeViewDataStateOnDispose(viewId: string, widget: Widget & StatefulWidget): void {
const dispose = widget.dispose.bind(widget);
widget.dispose = () => {
const state = widget.storeState();
if (state) {
this.viewDataState.set(viewId, state);
}
dispose();
};
}
protected trackVisibleWidget(factoryId: string, view: PluginViewRegistry.VisibleView): void {
this.doTrackVisibleWidget(this.widgetManager.tryGetWidget(factoryId), view);
this.widgetManager.onDidCreateWidget(event => {
if (factoryId === event.factoryId) {
const { widget } = event;
this.doTrackVisibleWidget(widget, view);
}
});
}
protected doTrackVisibleWidget(widget: Widget | undefined, view: PluginViewRegistry.VisibleView): void {
if (widget instanceof BaseWidget) {
widget.onDidChangeVisibility(() => this.updateVisibleWidget(widget, view));
const toDispose = new DisposableCollection(
Disposable.create(() => this.updateVisibleWidget(widget, view)),
this.shell.onDidChangeActiveWidget(() => {
if (this.shell.activeWidget === widget) {
this.updateVisibleWidget(widget, view);
}
})
);
if (view.sideArea !== undefined) {
toDispose.pushAll([
this.shell.onDidAddWidget(w => {
if (w === widget) {
this.updateVisibleWidget(widget, view);
}
})
]);
}
widget.disposed.connect(() => toDispose.dispose());
}
}
protected readonly visiblePanels = new Set<string>();
protected readonly visibleViewlets = new Set<string>();
protected updateVisibleWidget(widget: BaseWidget, view: PluginViewRegistry.VisibleView): void {
const visibleViews = 'viewletId' in view ? this.visibleViewlets : this.visiblePanels;
const viewId = 'viewletId' in view ? view.viewletId : view.panelId;
const visibleView = 'viewletId' in view ? this.viewContextKeys.activeViewlet : this.viewContextKeys.activePanel;
visibleViews.delete(viewId);
if (this.isVisibleWidget(widget, view)) {
visibleView.set(viewId);
visibleViews.add(viewId);
} else {
const lastVisibleView = [...visibleViews.values()][visibleViews.size - 1];
visibleView.set(lastVisibleView);
}
}
protected isVisibleWidget(widget: BaseWidget, view: PluginViewRegistry.VisibleView): boolean {
if (widget.isDisposed || !widget.isVisible) {
return false;
}
if (view.sideArea === undefined) {
return true;
}
const area = this.shell.getAreaFor(widget);
return view.sideArea === (area === 'left' || area === 'right');
}
protected updateFocusedView(): void {
const widget = this.shell.activeWidget;
if (widget instanceof PluginViewWidget) {
this.viewContextKeys.focusedView.set(widget.options.viewId);
} else {
this.viewContextKeys.focusedView.reset();
}
}
}
export namespace PluginViewRegistry {
export type VisibleView = ({ viewletId: string } | { panelId: string }) & {
/** `undefined` means any area */
sideArea?: boolean
};
}