-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
application-shell.ts
1986 lines (1844 loc) · 74.3 KB
/
application-shell.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
/********************************************************************************
* Copyright (C) 2018 TypeFox 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, optional, postConstruct } from 'inversify';
import { ArrayExt, find, toArray, each } from '@phosphor/algorithm';
import { Signal } from '@phosphor/signaling';
import {
BoxLayout, BoxPanel, DockLayout, DockPanel, FocusTracker, Layout, Panel, SplitLayout,
SplitPanel, TabBar, Widget, Title
} from '@phosphor/widgets';
import { Message } from '@phosphor/messaging';
import { IDragEvent } from '@phosphor/dragdrop';
import { RecursivePartial, Event as CommonEvent, DisposableCollection, Disposable } from '../../common';
import { animationFrame } from '../browser';
import { Saveable, SaveableWidget, SaveOptions } from '../saveable';
import { StatusBarImpl, StatusBarEntry, StatusBarAlignment } from '../status-bar/status-bar';
import { TheiaDockPanel, BOTTOM_AREA_ID, MAIN_AREA_ID } from './theia-dock-panel';
import { SidePanelHandler, SidePanel, SidePanelHandlerFactory } from './side-panel-handler';
import { TabBarRendererFactory, TabBarRenderer, SHELL_TABBAR_CONTEXT_MENU, ScrollableTabBar, ToolbarAwareTabBar } from './tab-bars';
import { SplitPositionHandler, SplitPositionOptions } from './split-panels';
import { FrontendApplicationStateService } from '../frontend-application-state';
import { TabBarToolbarRegistry, TabBarToolbarFactory, TabBarToolbar } from './tab-bar-toolbar';
import { ContextKeyService } from '../context-key-service';
import { Emitter } from '../../common/event';
import { waitForRevealed, waitForClosed } from '../widgets';
import { CorePreferences } from '../core-preferences';
import { environment } from '../../common';
/** The class name added to ApplicationShell instances. */
const APPLICATION_SHELL_CLASS = 'theia-ApplicationShell';
/** The class name added to the main and bottom area panels. */
const MAIN_BOTTOM_AREA_CLASS = 'theia-app-centers';
/** Status bar entry identifier for the bottom panel toggle button. */
const BOTTOM_PANEL_TOGGLE_ID = 'bottom-panel-toggle';
/** The class name added to the main area panel. */
const MAIN_AREA_CLASS = 'theia-app-main';
/** The class name added to the bottom area panel. */
const BOTTOM_AREA_CLASS = 'theia-app-bottom';
export type ApplicationShellLayoutVersion =
/** layout versioning is introduced, unversioned layout are not compatible */
2.0 |
/** view containers are introduced, backward compatible to 2.0 */
3.0 |
/** git history view is replaced by a more generic scm history view, backward compatible to 3.0 */
4.0;
/**
* When a version is increased, make sure to introduce a migration (ApplicationShellLayoutMigration) to this version.
*/
export const applicationShellLayoutVersion: ApplicationShellLayoutVersion = 4.0;
export const ApplicationShellOptions = Symbol('ApplicationShellOptions');
export const DockPanelRendererFactory = Symbol('DockPanelRendererFactory');
export interface DockPanelRendererFactory {
(): DockPanelRenderer
}
/**
* A renderer for dock panels that supports context menus on tabs.
*/
@injectable()
export class DockPanelRenderer implements DockLayout.IRenderer {
readonly tabBarClasses: string[] = [];
constructor(
@inject(TabBarRendererFactory) protected readonly tabBarRendererFactory: () => TabBarRenderer,
@inject(TabBarToolbarRegistry) protected readonly tabBarToolbarRegistry: TabBarToolbarRegistry,
@inject(TabBarToolbarFactory) protected readonly tabBarToolbarFactory: () => TabBarToolbar
) { }
createTabBar(): TabBar<Widget> {
const renderer = this.tabBarRendererFactory();
const tabBar = new ToolbarAwareTabBar(this.tabBarToolbarRegistry, this.tabBarToolbarFactory, {
renderer,
// Scroll bar options
handlers: ['drag-thumb', 'keyboard', 'wheel', 'touch'],
useBothWheelAxes: true,
scrollXMarginOffset: 4,
suppressScrollY: true
});
this.tabBarClasses.forEach(c => tabBar.addClass(c));
renderer.tabBar = tabBar;
tabBar.disposed.connect(() => renderer.dispose());
renderer.contextMenuPath = SHELL_TABBAR_CONTEXT_MENU;
tabBar.currentChanged.connect(this.onCurrentTabChanged, this);
return tabBar;
}
createHandle(): HTMLDivElement {
return DockPanel.defaultRenderer.createHandle();
}
protected onCurrentTabChanged(sender: ToolbarAwareTabBar, { currentIndex }: TabBar.ICurrentChangedArgs<Widget>): void {
if (currentIndex >= 0) {
sender.revealTab(currentIndex);
}
}
}
/**
* Data stored while dragging widgets in the shell.
*/
interface WidgetDragState {
startTime: number;
leftExpanded: boolean;
rightExpanded: boolean;
bottomExpanded: boolean;
lastDragOver?: IDragEvent;
leaveTimeout?: number;
}
/**
* The application shell manages the top-level widgets of the application. Use this class to
* add, remove, or activate a widget.
*/
@injectable()
export class ApplicationShell extends Widget {
/**
* The dock panel in the main shell area. This is where editors usually go to.
*/
readonly mainPanel: TheiaDockPanel;
/**
* The dock panel in the bottom shell area. In contrast to the main panel, the bottom panel
* can be collapsed and expanded.
*/
readonly bottomPanel: TheiaDockPanel;
/**
* Handler for the left side panel. The primary application views go here, such as the
* file explorer and the git view.
*/
readonly leftPanelHandler: SidePanelHandler;
/**
* Handler for the right side panel. The secondary application views go here, such as the
* outline view.
*/
readonly rightPanelHandler: SidePanelHandler;
/**
* General options for the application shell.
*/
protected options: ApplicationShell.Options;
/**
* The fixed-size panel shown on top. This one usually holds the main menu.
*/
readonly topPanel: Panel;
/**
* The current state of the bottom panel.
*/
protected readonly bottomPanelState: SidePanel.State = {
empty: true,
expansion: SidePanel.ExpansionState.collapsed,
pendingUpdate: Promise.resolve()
};
private readonly tracker = new FocusTracker<Widget>();
private dragState?: WidgetDragState;
@inject(ContextKeyService)
protected readonly contextKeyService: ContextKeyService;
protected readonly onDidAddWidgetEmitter = new Emitter<Widget>();
readonly onDidAddWidget = this.onDidAddWidgetEmitter.event;
protected fireDidAddWidget(widget: Widget): void {
this.onDidAddWidgetEmitter.fire(widget);
}
protected readonly onDidRemoveWidgetEmitter = new Emitter<Widget>();
readonly onDidRemoveWidget = this.onDidRemoveWidgetEmitter.event;
protected fireDidRemoveWidget(widget: Widget): void {
this.onDidRemoveWidgetEmitter.fire(widget);
}
protected readonly onDidChangeActiveWidgetEmitter = new Emitter<FocusTracker.IChangedArgs<Widget>>();
readonly onDidChangeActiveWidget = this.onDidChangeActiveWidgetEmitter.event;
protected readonly onDidChangeCurrentWidgetEmitter = new Emitter<FocusTracker.IChangedArgs<Widget>>();
readonly onDidChangeCurrentWidget = this.onDidChangeCurrentWidgetEmitter.event;
/**
* Construct a new application shell.
*/
constructor(
@inject(DockPanelRendererFactory) protected dockPanelRendererFactory: () => DockPanelRenderer,
@inject(StatusBarImpl) protected readonly statusBar: StatusBarImpl,
@inject(SidePanelHandlerFactory) sidePanelHandlerFactory: () => SidePanelHandler,
@inject(SplitPositionHandler) protected splitPositionHandler: SplitPositionHandler,
@inject(FrontendApplicationStateService) protected readonly applicationStateService: FrontendApplicationStateService,
@inject(ApplicationShellOptions) @optional() options: RecursivePartial<ApplicationShell.Options> = {},
@inject(CorePreferences) protected readonly corePreferences: CorePreferences
) {
super(options as Widget.IOptions);
this.addClass(APPLICATION_SHELL_CLASS);
this.id = 'theia-app-shell';
// Merge the user-defined application options with the default options
this.options = {
bottomPanel: {
...ApplicationShell.DEFAULT_OPTIONS.bottomPanel,
...options.bottomPanel || {}
},
leftPanel: {
...ApplicationShell.DEFAULT_OPTIONS.leftPanel,
...options.leftPanel || {}
},
rightPanel: {
...ApplicationShell.DEFAULT_OPTIONS.rightPanel,
...options.rightPanel || {}
}
};
this.mainPanel = this.createMainPanel();
this.topPanel = this.createTopPanel();
this.bottomPanel = this.createBottomPanel();
this.leftPanelHandler = sidePanelHandlerFactory();
this.leftPanelHandler.create('left', this.options.leftPanel);
this.leftPanelHandler.dockPanel.widgetAdded.connect((_, widget) => this.fireDidAddWidget(widget));
this.leftPanelHandler.dockPanel.widgetRemoved.connect((_, widget) => this.fireDidRemoveWidget(widget));
this.rightPanelHandler = sidePanelHandlerFactory();
this.rightPanelHandler.create('right', this.options.rightPanel);
this.rightPanelHandler.dockPanel.widgetAdded.connect((_, widget) => this.fireDidAddWidget(widget));
this.rightPanelHandler.dockPanel.widgetRemoved.connect((_, widget) => this.fireDidRemoveWidget(widget));
this.layout = this.createLayout();
this.tracker.currentChanged.connect(this.onCurrentChanged, this);
this.tracker.activeChanged.connect(this.onActiveChanged, this);
}
@postConstruct()
protected init(): void {
this.initSidebarVisibleKeyContext();
this.initFocusKeyContexts();
if (!environment.electron.is()) {
this.corePreferences.ready.then(() => {
this.setTopPanelVisibily(this.corePreferences['window.menuBarVisibility']);
});
this.corePreferences.onPreferenceChanged(preference => {
if (preference.preferenceName === 'window.menuBarVisibility') {
this.setTopPanelVisibily(preference.newValue);
}
});
}
}
protected initSidebarVisibleKeyContext(): void {
const leftSideBarPanel = this.leftPanelHandler.dockPanel;
const sidebarVisibleKey = this.contextKeyService.createKey('sidebarVisible', leftSideBarPanel.isVisible);
const onAfterShow = leftSideBarPanel['onAfterShow'].bind(leftSideBarPanel);
leftSideBarPanel['onAfterShow'] = (msg: Message) => {
onAfterShow(msg);
sidebarVisibleKey.set(true);
};
const onAfterHide = leftSideBarPanel['onAfterHide'].bind(leftSideBarPanel);
leftSideBarPanel['onAfterHide'] = (msg: Message) => {
onAfterHide(msg);
sidebarVisibleKey.set(false);
};
}
protected initFocusKeyContexts(): void {
const sideBarFocus = this.contextKeyService.createKey('sideBarFocus', false);
const panelFocus = this.contextKeyService.createKey('panelFocus', false);
const updateFocusContextKeys = () => {
const area = this.activeWidget && this.getAreaFor(this.activeWidget);
sideBarFocus.set(area === 'left');
panelFocus.set(area === 'main');
};
updateFocusContextKeys();
this.activeChanged.connect(updateFocusContextKeys);
}
protected setTopPanelVisibily(preference: string): void {
const hiddenPreferences = ['compact', 'hidden'];
this.topPanel.setHidden(hiddenPreferences.includes(preference));
}
protected onBeforeAttach(msg: Message): void {
document.addEventListener('p-dragenter', this, true);
document.addEventListener('p-dragover', this, true);
document.addEventListener('p-dragleave', this, true);
document.addEventListener('p-drop', this, true);
}
protected onAfterDetach(msg: Message): void {
document.removeEventListener('p-dragenter', this, true);
document.removeEventListener('p-dragover', this, true);
document.removeEventListener('p-dragleave', this, true);
document.removeEventListener('p-drop', this, true);
}
handleEvent(event: Event): void {
switch (event.type) {
case 'p-dragenter':
this.onDragEnter(event as IDragEvent);
break;
case 'p-dragover':
this.onDragOver(event as IDragEvent);
break;
case 'p-drop':
this.onDrop(event as IDragEvent);
break;
case 'p-dragleave':
this.onDragLeave(event as IDragEvent);
break;
}
}
protected onDragEnter({ mimeData }: IDragEvent): void {
if (!this.dragState) {
if (mimeData && mimeData.hasData('application/vnd.phosphor.widget-factory')) {
// The drag contains a widget, so we'll track it and expand side panels as needed
this.dragState = {
startTime: performance.now(),
leftExpanded: false,
rightExpanded: false,
bottomExpanded: false
};
}
}
}
protected onDragOver(event: IDragEvent): void {
const state = this.dragState;
if (state) {
state.lastDragOver = event;
if (state.leaveTimeout) {
window.clearTimeout(state.leaveTimeout);
state.leaveTimeout = undefined;
}
const { clientX, clientY } = event;
const { offsetLeft, offsetTop, clientWidth, clientHeight } = this.node;
// Don't expand any side panels right after the drag has started
const allowExpansion = performance.now() - state.startTime >= 500;
const expLeft = allowExpansion && clientX >= offsetLeft
&& clientX <= offsetLeft + this.options.leftPanel.expandThreshold;
const expRight = allowExpansion && clientX <= offsetLeft + clientWidth
&& clientX >= offsetLeft + clientWidth - this.options.rightPanel.expandThreshold;
const expBottom = allowExpansion && !expLeft && !expRight && clientY <= offsetTop + clientHeight
&& clientY >= offsetTop + clientHeight - this.options.bottomPanel.expandThreshold;
// eslint-disable-next-line no-null/no-null
if (expLeft && !state.leftExpanded && this.leftPanelHandler.tabBar.currentTitle === null) {
// The mouse cursor is moved close to the left border
this.leftPanelHandler.expand();
this.leftPanelHandler.state.pendingUpdate.then(() => this.dispatchMouseMove());
state.leftExpanded = true;
} else if (!expLeft && state.leftExpanded) {
// The mouse cursor is moved away from the left border
this.leftPanelHandler.collapse();
state.leftExpanded = false;
}
// eslint-disable-next-line no-null/no-null
if (expRight && !state.rightExpanded && this.rightPanelHandler.tabBar.currentTitle === null) {
// The mouse cursor is moved close to the right border
this.rightPanelHandler.expand();
this.rightPanelHandler.state.pendingUpdate.then(() => this.dispatchMouseMove());
state.rightExpanded = true;
} else if (!expRight && state.rightExpanded) {
// The mouse cursor is moved away from the right border
this.rightPanelHandler.collapse();
state.rightExpanded = false;
}
if (expBottom && !state.bottomExpanded && this.bottomPanel.isHidden) {
// The mouse cursor is moved close to the bottom border
this.expandBottomPanel();
this.bottomPanelState.pendingUpdate.then(() => this.dispatchMouseMove());
state.bottomExpanded = true;
} else if (!expBottom && state.bottomExpanded) {
// The mouse cursor is moved away from the bottom border
this.collapseBottomPanel();
state.bottomExpanded = false;
}
}
}
/**
* This method is called after a side panel has been expanded while dragging a widget. It fires
* a `mousemove` event so that the drag overlay markers are updated correctly in all dock panels.
*/
private dispatchMouseMove(): void {
if (this.dragState && this.dragState.lastDragOver) {
const { clientX, clientY } = this.dragState.lastDragOver;
const event = document.createEvent('MouseEvent');
event.initMouseEvent('mousemove', true, true, window, 0, 0, 0,
// eslint-disable-next-line no-null/no-null
clientX, clientY, false, false, false, false, 0, null);
document.dispatchEvent(event);
}
}
protected onDrop(event: IDragEvent): void {
const state = this.dragState;
if (state) {
if (state.leaveTimeout) {
window.clearTimeout(state.leaveTimeout);
}
this.dragState = undefined;
window.requestAnimationFrame(() => {
// Clean up the side panel state in the next frame
if (this.leftPanelHandler.dockPanel.isEmpty) {
this.leftPanelHandler.collapse();
}
if (this.rightPanelHandler.dockPanel.isEmpty) {
this.rightPanelHandler.collapse();
}
if (this.bottomPanel.isEmpty) {
this.collapseBottomPanel();
}
});
}
}
protected onDragLeave(event: IDragEvent): void {
const state = this.dragState;
if (state) {
state.lastDragOver = undefined;
if (state.leaveTimeout) {
window.clearTimeout(state.leaveTimeout);
}
state.leaveTimeout = window.setTimeout(() => {
this.dragState = undefined;
if (state.leftExpanded || this.leftPanelHandler.dockPanel.isEmpty) {
this.leftPanelHandler.collapse();
}
if (state.rightExpanded || this.rightPanelHandler.dockPanel.isEmpty) {
this.rightPanelHandler.collapse();
}
if (state.bottomExpanded || this.bottomPanel.isEmpty) {
this.collapseBottomPanel();
}
}, 100);
}
}
/**
* Create the dock panel in the main shell area.
*/
protected createMainPanel(): TheiaDockPanel {
const renderer = this.dockPanelRendererFactory();
renderer.tabBarClasses.push(MAIN_BOTTOM_AREA_CLASS);
renderer.tabBarClasses.push(MAIN_AREA_CLASS);
const dockPanel = new TheiaDockPanel({
mode: 'multiple-document',
renderer,
spacing: 0
}, this.corePreferences);
dockPanel.id = MAIN_AREA_ID;
dockPanel.widgetAdded.connect((_, widget) => this.fireDidAddWidget(widget));
dockPanel.widgetRemoved.connect((_, widget) => this.fireDidRemoveWidget(widget));
return dockPanel;
}
/**
* Create the dock panel in the bottom shell area.
*/
protected createBottomPanel(): TheiaDockPanel {
const renderer = this.dockPanelRendererFactory();
renderer.tabBarClasses.push(MAIN_BOTTOM_AREA_CLASS);
renderer.tabBarClasses.push(BOTTOM_AREA_CLASS);
const dockPanel = new TheiaDockPanel({
mode: 'multiple-document',
renderer,
spacing: 0
}, this.corePreferences);
dockPanel.id = BOTTOM_AREA_ID;
dockPanel.widgetAdded.connect((sender, widget) => {
this.refreshBottomPanelToggleButton();
});
dockPanel.widgetRemoved.connect((sender, widget) => {
if (sender.isEmpty) {
this.collapseBottomPanel();
}
this.refreshBottomPanelToggleButton();
}, this);
dockPanel.node.addEventListener('p-dragenter', event => {
// Make sure that the main panel hides its overlay when the bottom panel is expanded
this.mainPanel.overlay.hide(0);
});
dockPanel.hide();
dockPanel.widgetAdded.connect((_, widget) => this.fireDidAddWidget(widget));
dockPanel.widgetRemoved.connect((_, widget) => this.fireDidRemoveWidget(widget));
return dockPanel;
}
/**
* Create the top panel, which is used to hold the main menu.
*/
protected createTopPanel(): Panel {
const topPanel = new Panel();
topPanel.id = 'theia-top-panel';
topPanel.hide();
return topPanel;
}
/**
* Create a box layout to assemble the application shell layout.
*/
protected createBoxLayout(widgets: Widget[], stretch?: number[], options?: BoxPanel.IOptions): BoxLayout {
const boxLayout = new BoxLayout(options);
for (let i = 0; i < widgets.length; i++) {
if (stretch !== undefined && i < stretch.length) {
BoxPanel.setStretch(widgets[i], stretch[i]);
}
boxLayout.addWidget(widgets[i]);
}
return boxLayout;
}
/**
* Create a split layout to assemble the application shell layout.
*/
protected createSplitLayout(widgets: Widget[], stretch?: number[], options?: Partial<SplitLayout.IOptions>): SplitLayout {
let optParam: SplitLayout.IOptions = { renderer: SplitPanel.defaultRenderer, };
if (options) {
optParam = { ...optParam, ...options };
}
const splitLayout = new SplitLayout(optParam);
for (let i = 0; i < widgets.length; i++) {
if (stretch !== undefined && i < stretch.length) {
SplitPanel.setStretch(widgets[i], stretch[i]);
}
splitLayout.addWidget(widgets[i]);
}
return splitLayout;
}
/**
* Assemble the application shell layout. Override this method in order to change the arrangement
* of the main area and the side panels.
*/
protected createLayout(): Layout {
const bottomSplitLayout = this.createSplitLayout(
[this.mainPanel, this.bottomPanel],
[1, 0],
{ orientation: 'vertical', spacing: 0 }
);
const panelForBottomArea = new SplitPanel({ layout: bottomSplitLayout });
panelForBottomArea.id = 'theia-bottom-split-panel';
const leftRightSplitLayout = this.createSplitLayout(
[this.leftPanelHandler.container, panelForBottomArea, this.rightPanelHandler.container],
[0, 1, 0],
{ orientation: 'horizontal', spacing: 0 }
);
const panelForSideAreas = new SplitPanel({ layout: leftRightSplitLayout });
panelForSideAreas.id = 'theia-left-right-split-panel';
return this.createBoxLayout(
[this.topPanel, panelForSideAreas, this.statusBar],
[0, 1, 0],
{ direction: 'top-to-bottom', spacing: 0 }
);
}
/**
* Create an object that describes the current shell layout. This object may contain references
* to widgets; these need to be transformed before the layout can be serialized.
*/
getLayoutData(): ApplicationShell.LayoutData {
return {
version: applicationShellLayoutVersion,
mainPanel: this.mainPanel.saveLayout(),
bottomPanel: {
config: this.bottomPanel.saveLayout(),
size: this.bottomPanel.isVisible ? this.getBottomPanelSize() : this.bottomPanelState.lastPanelSize,
expanded: this.isExpanded('bottom')
},
leftPanel: this.leftPanelHandler.getLayoutData(),
rightPanel: this.rightPanelHandler.getLayoutData(),
activeWidgetId: this.activeWidget ? this.activeWidget.id : undefined
};
}
/**
* Compute the current height of the bottom panel. This implementation assumes that the container
* of the bottom panel is a `SplitPanel`.
*/
protected getBottomPanelSize(): number | undefined {
const parent = this.bottomPanel.parent;
if (parent instanceof SplitPanel && parent.isVisible) {
const index = parent.widgets.indexOf(this.bottomPanel) - 1;
if (index >= 0) {
const handle = parent.handles[index];
if (!handle.classList.contains('p-mod-hidden')) {
const parentHeight = parent.node.clientHeight;
return parentHeight - handle.offsetTop;
}
}
}
}
/**
* Determine the default size to apply when the bottom panel is expanded for the first time.
*/
protected getDefaultBottomPanelSize(): number | undefined {
const parent = this.bottomPanel.parent;
if (parent && parent.isVisible) {
return parent.node.clientHeight * this.options.bottomPanel.initialSizeRatio;
}
}
/**
* Apply a shell layout that has been previously created with `getLayoutData`.
*/
async setLayoutData(layoutData: ApplicationShell.LayoutData): Promise<void> {
const { mainPanel, bottomPanel, leftPanel, rightPanel, activeWidgetId } = layoutData;
if (leftPanel) {
this.leftPanelHandler.setLayoutData(leftPanel);
this.registerWithFocusTracker(leftPanel);
}
if (rightPanel) {
this.rightPanelHandler.setLayoutData(rightPanel);
this.registerWithFocusTracker(rightPanel);
}
// Proceed with the bottom panel once the side panels are set up
await Promise.all([this.leftPanelHandler.state.pendingUpdate, this.rightPanelHandler.state.pendingUpdate]);
if (bottomPanel) {
if (bottomPanel.config) {
this.bottomPanel.restoreLayout(bottomPanel.config);
this.registerWithFocusTracker(bottomPanel.config.main);
}
if (bottomPanel.size) {
this.bottomPanelState.lastPanelSize = bottomPanel.size;
}
if (bottomPanel.expanded) {
this.expandBottomPanel();
} else {
this.collapseBottomPanel();
}
this.refreshBottomPanelToggleButton();
}
// Proceed with the main panel once all others are set up
await this.bottomPanelState.pendingUpdate;
if (mainPanel) {
this.mainPanel.restoreLayout(mainPanel);
this.registerWithFocusTracker(mainPanel.main);
}
if (activeWidgetId) {
this.activateWidget(activeWidgetId);
}
}
/**
* Modify the height of the bottom panel. This implementation assumes that the container of the
* bottom panel is a `SplitPanel`.
*/
protected setBottomPanelSize(size: number): Promise<void> {
const enableAnimation = this.applicationStateService.state === 'ready';
const options: SplitPositionOptions = {
side: 'bottom',
duration: enableAnimation ? this.options.bottomPanel.expandDuration : 0,
referenceWidget: this.bottomPanel
};
const promise = this.splitPositionHandler.setSidePanelSize(this.bottomPanel, size, options);
const result = new Promise<void>(resolve => {
// Resolve the resulting promise in any case, regardless of whether resizing was successful
promise.then(() => resolve(), () => resolve());
});
this.bottomPanelState.pendingUpdate = this.bottomPanelState.pendingUpdate.then(() => result);
return result;
}
/**
* A promise that is resolved when all currently pending updates are done.
*/
get pendingUpdates(): Promise<void> {
return Promise.all([
this.bottomPanelState.pendingUpdate,
this.leftPanelHandler.state.pendingUpdate,
this.rightPanelHandler.state.pendingUpdate
// eslint-disable-next-line @typescript-eslint/no-explicit-any
]) as Promise<any>;
}
/**
* Track all widgets that are referenced by the given layout data.
*/
protected registerWithFocusTracker(data: DockLayout.ITabAreaConfig | DockLayout.ISplitAreaConfig | SidePanel.LayoutData | null): void {
if (data) {
if (data.type === 'tab-area') {
for (const widget of data.widgets) {
if (widget) {
this.track(widget);
}
}
} else if (data.type === 'split-area') {
for (const child of data.children) {
this.registerWithFocusTracker(child);
}
} else if (data.type === 'sidepanel' && data.items) {
for (const item of data.items) {
if (item.widget) {
this.track(item.widget);
}
}
}
}
}
/**
* Add a widget to the application shell. The given widget must have a unique `id` property,
* which will be used as the DOM id.
*
* Widgets are removed from the shell by calling their `close` or `dispose` methods.
*
* Widgets added to the top area are not tracked regarding the _current_ and _active_ states.
*/
async addWidget(widget: Widget, options: Readonly<ApplicationShell.WidgetOptions> = {}): Promise<void> {
if (!widget.id) {
console.error('Widgets added to the application shell must have a unique id property.');
return;
}
let ref: Widget | undefined = options.ref;
let area: ApplicationShell.Area = options.area || 'main';
if (!ref && (area === 'main' || area === 'bottom')) {
const tabBar = this.getTabBarFor(area);
ref = tabBar && tabBar.currentTitle && tabBar.currentTitle.owner || undefined;
}
// make sure that ref belongs to area
area = ref && this.getAreaFor(ref) || area;
const addOptions: DockPanel.IAddOptions = {};
if (ApplicationShell.isOpenToSideMode(options.mode)) {
const areaPanel = area === 'main' ? this.mainPanel : area === 'bottom' ? this.bottomPanel : undefined;
const sideRef = areaPanel && ref && (options.mode === 'open-to-left' ?
areaPanel.previousTabBarWidget(ref) :
areaPanel.nextTabBarWidget(ref));
if (sideRef) {
addOptions.ref = sideRef;
} else {
addOptions.ref = ref;
addOptions.mode = options.mode === 'open-to-left' ? 'split-left' : 'split-right';
}
} else {
addOptions.ref = ref;
addOptions.mode = options.mode;
}
const sidePanelOptions: SidePanel.WidgetOptions = { rank: options.rank };
switch (area) {
case 'main':
this.mainPanel.addWidget(widget, addOptions);
break;
case 'top':
this.topPanel.addWidget(widget);
break;
case 'bottom':
this.bottomPanel.addWidget(widget, addOptions);
break;
case 'left':
this.leftPanelHandler.addWidget(widget, sidePanelOptions);
break;
case 'right':
this.rightPanelHandler.addWidget(widget, sidePanelOptions);
break;
default:
throw new Error('Unexpected area: ' + options.area);
}
if (area !== 'top') {
this.track(widget);
}
}
/**
* The widgets contained in the given shell area.
*/
getWidgets(area: ApplicationShell.Area): Widget[] {
switch (area) {
case 'main':
return toArray(this.mainPanel.widgets());
case 'top':
return toArray(this.topPanel.widgets);
case 'bottom':
return toArray(this.bottomPanel.widgets());
case 'left':
return toArray(this.leftPanelHandler.dockPanel.widgets());
case 'right':
return toArray(this.rightPanelHandler.dockPanel.widgets());
default:
throw new Error('Illegal argument: ' + area);
}
}
/**
* Find the widget that contains the given HTML element. The returned widget may be one
* that is managed by the application shell, or one that is embedded in another widget and
* not directly managed by the shell, or a tab bar.
*/
findWidgetForElement(element: HTMLElement): Widget | undefined {
let widgetNode: HTMLElement | null = element;
while (widgetNode && !widgetNode.classList.contains('p-Widget')) {
widgetNode = widgetNode.parentElement;
}
if (widgetNode) {
return this.findWidgetForNode(widgetNode, this);
}
return undefined;
}
private findWidgetForNode(widgetNode: HTMLElement, widget: Widget): Widget | undefined {
if (widget.node === widgetNode) {
return widget;
}
let result: Widget | undefined;
each(widget.children(), child => {
result = this.findWidgetForNode(widgetNode, child);
return !result;
});
return result;
}
/**
* Finds the title widget from the tab-bar.
* @param tabBar used for providing an array of titles.
* @returns the selected title widget, else returns the currentTitle or undefined.
*/
findTitle(tabBar: TabBar<Widget>, event?: Event): Title<Widget> | undefined {
if (event?.target instanceof HTMLElement) {
let tabNode: HTMLElement | null = event.target;
while (tabNode && !tabNode.classList.contains('p-TabBar-tab')) {
tabNode = tabNode.parentElement;
}
if (tabNode && tabNode.title) {
let title = tabBar.titles.find(t => t.caption === tabNode!.title);
if (title) {
return title;
}
title = tabBar.titles.find(t => t.label === tabNode!.title);
if (title) {
return title;
}
}
}
return tabBar.currentTitle || undefined;
}
/**
* Finds the tab-bar widget.
* @returns the selected tab-bar, else returns the currentTabBar.
*/
findTabBar(event?: Event): TabBar<Widget> | undefined {
if (event?.target instanceof HTMLElement) {
const tabBar = this.findWidgetForElement(event.target);
if (tabBar instanceof TabBar) {
return tabBar;
}
}
return this.currentTabBar;
}
/**
* @returns the widget whose title has been targeted by a DOM event on a tabbar, or undefined if none can be found.
*/
findTargetedWidget(event?: Event): Widget | undefined {
if (event) {
const tab = this.findTabBar(event);
const title = tab && this.findTitle(tab, event);
return title && title.owner;
}
}
/**
* The current widget in the application shell. The current widget is the last widget that
* was active and not yet closed. See the remarks to `activeWidget` on what _active_ means.
*/
get currentWidget(): Widget | undefined {
return this.tracker.currentWidget || undefined;
}
/**
* The active widget in the application shell. The active widget is the one that has focus
* (either the widget itself or any of its contents).
*
* _Note:_ Focus is taken by a widget through the `onActivateRequest` method. It is up to the
* widget implementation which DOM element will get the focus. The default implementation
* does not take any focus; in that case the widget is never returned by this property.
*/
get activeWidget(): Widget | undefined {
return this.tracker.activeWidget || undefined;
}
/**
* Returns the last active widget in the given shell area.
*/
getCurrentWidget(area: ApplicationShell.Area): Widget | undefined {
let title: Title<Widget> | null | undefined;
switch (area) {
case 'main':
title = this.mainPanel.currentTitle;
break;
case 'bottom':
title = this.bottomPanel.currentTitle;
break;
case 'left':
title = this.leftPanelHandler.tabBar.currentTitle;
break;
case 'right':
title = this.rightPanelHandler.tabBar.currentTitle;
break;
default:
throw new Error('Illegal argument: ' + area);
}
return title ? title.owner : undefined;
}
/**
* A signal emitted whenever the `currentWidget` property is changed.
*
* @deprecated since 0.11.0, use `onDidChangeCurrentWidget` instead
*/
readonly currentChanged = new Signal<this, FocusTracker.IChangedArgs<Widget>>(this);
/**
* Handle a change to the current widget.
*/
private onCurrentChanged(sender: FocusTracker<Widget>, args: FocusTracker.IChangedArgs<Widget>): void {
this.currentChanged.emit(args);
this.onDidChangeCurrentWidgetEmitter.fire(args);
}
/**
* A signal emitted whenever the `activeWidget` property is changed.
*
* @deprecated since 0.11.0, use `onDidChangeActiveWidget` instead
*/
readonly activeChanged = new Signal<this, FocusTracker.IChangedArgs<Widget>>(this);
protected readonly toDisposeOnActiveChanged = new DisposableCollection();
/**
* Handle a change to the active widget.
*/
private onActiveChanged(sender: FocusTracker<Widget>, args: FocusTracker.IChangedArgs<Widget>): void {
this.toDisposeOnActiveChanged.dispose();
const { newValue, oldValue } = args;
if (oldValue) {
let w: Widget | null = oldValue;
while (w) {
// Remove the mark of the previously active widget
w.title.className = w.title.className.replace(' theia-mod-active', '');
w = w.parent;
}
// Reset the z-index to the default
// eslint-disable-next-line no-null/no-null
this.setZIndex(oldValue.node, null);
}
if (newValue) {
let w: Widget | null = newValue;
while (w) {
// Mark the tab of the active widget
w.title.className += ' theia-mod-active';
w = w.parent;
}
// Reveal the title of the active widget in its tab bar
const tabBar = this.getTabBarFor(newValue);
if (tabBar instanceof ScrollableTabBar) {
const index = tabBar.titles.indexOf(newValue.title);
if (index >= 0) {
tabBar.revealTab(index);
}
}
const panel = this.getAreaPanelFor(newValue);
if (panel instanceof TheiaDockPanel) {
panel.markAsCurrent(newValue.title);
}
// Set the z-index so elements with `position: fixed` contained in the active widget are displayed correctly
this.setZIndex(newValue.node, '1');
// activate another widget if an active widget will be closed
const onCloseRequest = newValue['onCloseRequest'];
newValue['onCloseRequest'] = msg => {
const currentTabBar = this.currentTabBar;
if (currentTabBar) {
const recentlyUsedInTabBar = currentTabBar['_previousTitle'] as TabBar<Widget>['currentTitle'];
if (recentlyUsedInTabBar && recentlyUsedInTabBar.owner !== newValue) {
currentTabBar.currentIndex = ArrayExt.firstIndexOf(currentTabBar.titles, recentlyUsedInTabBar);
if (currentTabBar.currentTitle) {
this.activateWidget(currentTabBar.currentTitle.owner.id);