/
index.ts
414 lines (362 loc) · 10.7 KB
/
index.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
// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
import { ISettingRegistry } from '@jupyterlab/coreutils';
import {
ILayoutRestorer,
JupyterFrontEnd,
JupyterFrontEndPlugin
} from '@jupyterlab/application';
import {
ICommandPalette,
InstanceTracker,
IThemeManager,
MainAreaWidget
} from '@jupyterlab/apputils';
import { ILauncher } from '@jupyterlab/launcher';
import { IFileMenu, IMainMenu } from '@jupyterlab/mainmenu';
import { ITerminalTracker, ITerminal } from '@jupyterlab/terminal';
// Name-only import so as to not trigger inclusion in main bundle
import * as WidgetModuleType from '@jupyterlab/terminal/lib/widget';
import { Menu } from '@phosphor/widgets';
/**
* The command IDs used by the terminal plugin.
*/
namespace CommandIDs {
export const createNew = 'terminal:create-new';
export const open = 'terminal:open';
export const refresh = 'terminal:refresh';
export const increaseFont = 'terminal:increase-font';
export const decreaseFont = 'terminal:decrease-font';
export const setTheme = 'terminal:set-theme';
}
/**
* The class name for the terminal icon in the default theme.
*/
const TERMINAL_ICON_CLASS = 'jp-TerminalIcon';
/**
* The default terminal extension.
*/
const plugin: JupyterFrontEndPlugin<ITerminalTracker> = {
activate,
id: '@jupyterlab/terminal-extension:plugin',
provides: ITerminalTracker,
requires: [ISettingRegistry],
optional: [
ICommandPalette,
ILauncher,
ILayoutRestorer,
IMainMenu,
IThemeManager
],
autoStart: true
};
/**
* Export the plugin as default.
*/
export default plugin;
/**
* Activate the terminal plugin.
*/
function activate(
app: JupyterFrontEnd,
settingRegistry: ISettingRegistry,
palette: ICommandPalette | null,
launcher: ILauncher | null,
restorer: ILayoutRestorer | null,
mainMenu: IMainMenu | null,
themeManager: IThemeManager
): ITerminalTracker {
const { serviceManager, commands } = app;
const category = 'Terminal';
const namespace = 'terminal';
const tracker = new InstanceTracker<MainAreaWidget<ITerminal.ITerminal>>({
namespace
});
// Bail if there are no terminals available.
if (!serviceManager.terminals.isAvailable()) {
console.log(
'Disabling terminals plugin because they are not available on the server'
);
return tracker;
}
// Handle state restoration.
if (restorer) {
restorer.restore(tracker, {
command: CommandIDs.createNew,
args: widget => ({ name: widget.content.session.name }),
name: widget => widget.content.session.name
});
}
// The cached terminal options from the setting editor.
let options: Partial<ITerminal.IOptions>;
/**
* Update the cached option values.
*/
function updateOptions(settings: ISettingRegistry.ISettings): void {
options = settings.composite;
}
/**
* Update terminal
*/
function updateTerminal(widget: MainAreaWidget<ITerminal.ITerminal>): void {
const terminal = widget.content;
if (!terminal) {
return;
}
Object.keys(options).forEach((key: keyof ITerminal.IOptions) => {
terminal.setOption(key, options[key]);
});
}
/**
* Update the settings of the current tracker instances.
*/
function updateTracker(): void {
tracker.forEach(widget => updateTerminal(widget));
}
// Fetch the initial state of the settings.
settingRegistry
.load(plugin.id)
.then(settings => {
updateOptions(settings);
updateTracker();
settings.changed.connect(() => {
updateOptions(settings);
updateTracker();
});
})
.catch(Private.showErrorMessage);
// Subscribe to changes in theme.
themeManager.themeChanged.connect((sender, args) => {
tracker.forEach(widget => {
const terminal = widget.content;
if (terminal.getOption('theme') === 'inherit') {
terminal.setOption('theme', 'inherit');
}
});
});
addCommands(app, tracker, settingRegistry, options);
if (mainMenu) {
// Add "Terminal Theme" menu below "JupyterLab Themes" menu.
const themeMenu = new Menu({ commands });
themeMenu.title.label = 'Terminal Theme';
themeMenu.addItem({
command: CommandIDs.setTheme,
args: { theme: 'inherit', isPalette: false }
});
themeMenu.addItem({
command: CommandIDs.setTheme,
args: { theme: 'light', isPalette: false }
});
themeMenu.addItem({
command: CommandIDs.setTheme,
args: { theme: 'dark', isPalette: false }
});
// Add some commands to the "View" menu.
mainMenu.settingsMenu.addGroup(
[
{ command: CommandIDs.increaseFont },
{ command: CommandIDs.decreaseFont },
{ type: 'submenu', submenu: themeMenu }
],
40
);
// Add terminal creation to the file menu.
mainMenu.fileMenu.newMenu.addGroup([{ command: CommandIDs.createNew }], 20);
// Add terminal close-and-shutdown to the file menu.
mainMenu.fileMenu.closeAndCleaners.add({
tracker,
action: 'Shutdown',
name: 'Terminal',
closeAndCleanup: (current: MainAreaWidget<ITerminal.ITerminal>) => {
// The widget is automatically disposed upon session shutdown.
return current.content.session.shutdown();
}
} as IFileMenu.ICloseAndCleaner<MainAreaWidget<ITerminal.ITerminal>>);
}
if (palette) {
// Add command palette items.
[
CommandIDs.createNew,
CommandIDs.refresh,
CommandIDs.increaseFont,
CommandIDs.decreaseFont
].forEach(command => {
palette.addItem({ command, category, args: { isPalette: true } });
});
palette.addItem({
command: CommandIDs.setTheme,
category,
args: { theme: 'inherit', isPalette: true }
});
palette.addItem({
command: CommandIDs.setTheme,
category,
args: { theme: 'light', isPalette: true }
});
palette.addItem({
command: CommandIDs.setTheme,
category,
args: { theme: 'dark', isPalette: true }
});
}
// Add a launcher item if the launcher is available.
if (launcher) {
launcher.add({
command: CommandIDs.createNew,
category: 'Other',
rank: 0
});
}
app.contextMenu.addItem({
command: CommandIDs.refresh,
selector: '.jp-Terminal',
rank: 1
});
return tracker;
}
/**
* Add the commands for the terminal.
*/
export function addCommands(
app: JupyterFrontEnd,
tracker: InstanceTracker<MainAreaWidget<ITerminal.ITerminal>>,
settingRegistry: ISettingRegistry,
options: Partial<ITerminal.IOptions>
) {
const { commands, serviceManager } = app;
// Add terminal commands.
commands.addCommand(CommandIDs.createNew, {
label: args => (args['isPalette'] ? 'New Terminal' : 'Terminal'),
caption: 'Start a new terminal session',
iconClass: args => (args['isPalette'] ? '' : TERMINAL_ICON_CLASS),
execute: async args => {
// wait for the widget to lazy load
let Terminal: typeof WidgetModuleType.Terminal;
try {
Terminal = (await Private.ensureWidget()).Terminal;
} catch (err) {
Private.showErrorMessage(err);
}
const name = args['name'] as string;
const session = await (name
? serviceManager.terminals
.connectTo(name)
.catch(() => serviceManager.terminals.startNew())
: serviceManager.terminals.startNew());
const term = new Terminal(session, options);
term.title.icon = TERMINAL_ICON_CLASS;
term.title.label = '...';
let main = new MainAreaWidget({ content: term });
app.shell.add(main);
void tracker.add(main);
app.shell.activateById(main.id);
}
});
commands.addCommand(CommandIDs.open, {
execute: args => {
const name = args['name'] as string;
// Check for a running terminal with the given name.
const widget = tracker.find(value => {
let content = value.content;
return content.session.name === name || false;
});
if (widget) {
app.shell.activateById(widget.id);
} else {
// Otherwise, create a new terminal with a given name.
return commands.execute(CommandIDs.createNew, { name });
}
}
});
commands.addCommand(CommandIDs.refresh, {
label: 'Refresh Terminal',
caption: 'Refresh the current terminal session',
execute: async () => {
let current = tracker.currentWidget;
if (!current) {
return;
}
app.shell.activateById(current.id);
try {
await current.content.refresh();
if (current) {
current.content.activate();
}
} catch (err) {
Private.showErrorMessage(err);
}
},
isEnabled: () => tracker.currentWidget !== null
});
commands.addCommand(CommandIDs.increaseFont, {
label: 'Increase Terminal Font Size',
execute: async () => {
let { fontSize } = ITerminal.defaultOptions;
if (fontSize < 72) {
try {
await settingRegistry.set(plugin.id, 'fontSize', fontSize + 1);
} catch (err) {
Private.showErrorMessage(err);
}
}
}
});
commands.addCommand(CommandIDs.decreaseFont, {
label: 'Decrease Terminal Font Size',
execute: async () => {
let { fontSize } = ITerminal.defaultOptions;
if (fontSize > 9) {
try {
await settingRegistry.set(plugin.id, 'fontSize', fontSize - 1);
} catch (err) {
Private.showErrorMessage(err);
}
}
}
});
commands.addCommand(CommandIDs.setTheme, {
label: args => {
const theme = args['theme'] as string;
const displayName = theme[0].toUpperCase() + theme.substring(1);
return args['isPalette']
? `Use ${displayName} Terminal Theme`
: displayName;
},
caption: 'Set the terminal theme',
isToggled: args => args['theme'] === ITerminal.defaultOptions.theme,
execute: async args => {
const theme = args['theme'] as ITerminal.Theme;
try {
await settingRegistry.set(plugin.id, 'theme', theme);
commands.notifyCommandChanged(CommandIDs.setTheme);
} catch (err) {
Private.showErrorMessage(err);
}
}
});
}
/**
* A namespace for private data.
*/
namespace Private {
/**
* A Promise for the initial load of the terminal widget.
*/
export let widgetReady: Promise<typeof WidgetModuleType>;
/**
* Lazy-load the widget (and xterm library and addons)
*/
export function ensureWidget(): Promise<typeof WidgetModuleType> {
if (widgetReady) {
return widgetReady;
}
widgetReady = import('@jupyterlab/terminal/lib/widget');
return widgetReady;
}
/**
* Utility function for consistent error reporting
*/
export function showErrorMessage(error: Error): void {
console.error(`Failed to configure ${plugin.id}: ${error.message}`);
}
}