index.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  1. // Copyright (c) Jupyter Development Team.
  2. // Distributed under the terms of the Modified BSD License.
  3. import {
  4. JupyterLab, JupyterLabPlugin
  5. } from '@jupyterlab/application';
  6. import {
  7. showDialog, showErrorMessage, Dialog, ICommandPalette
  8. } from '@jupyterlab/apputils';
  9. import {
  10. IChangedArgs, ISettingRegistry
  11. } from '@jupyterlab/coreutils';
  12. import {
  13. renameDialog, getOpenPath, DocumentManager, IDocumentManager
  14. } from '@jupyterlab/docmanager';
  15. import {
  16. DocumentRegistry
  17. } from '@jupyterlab/docregistry';
  18. import {
  19. IMainMenu
  20. } from '@jupyterlab/mainmenu';
  21. import {
  22. Contents, Kernel
  23. } from '@jupyterlab/services';
  24. import {
  25. IDisposable
  26. } from '@phosphor/disposable';
  27. /**
  28. * The command IDs used by the document manager plugin.
  29. */
  30. namespace CommandIDs {
  31. export
  32. const clone = 'docmanager:clone';
  33. export
  34. const close = 'docmanager:close';
  35. export
  36. const closeAllFiles = 'docmanager:close-all-files';
  37. export
  38. const deleteFile = 'docmanager:delete-file';
  39. export
  40. const newUntitled = 'docmanager:new-untitled';
  41. export
  42. const open = 'docmanager:open';
  43. export
  44. const openBrowserTab = 'docmanager:open-browser-tab';
  45. export
  46. const openDirect = 'docmanager:open-direct';
  47. export
  48. const rename = 'docmanager:rename';
  49. export
  50. const restoreCheckpoint = 'docmanager:restore-checkpoint';
  51. export
  52. const save = 'docmanager:save';
  53. export
  54. const saveAll = 'docmanager:save-all';
  55. export
  56. const saveAs = 'docmanager:save-as';
  57. export
  58. const toggleAutosave = 'docmanager:toggle-autosave';
  59. export
  60. const showInFileBrowser = 'docmanager:show-in-file-browser';
  61. }
  62. const pluginId = '@jupyterlab/docmanager-extension:plugin';
  63. /**
  64. * The default document manager provider.
  65. */
  66. const plugin: JupyterLabPlugin<IDocumentManager> = {
  67. id: pluginId,
  68. provides: IDocumentManager,
  69. requires: [ICommandPalette, IMainMenu, ISettingRegistry],
  70. activate: (app: JupyterLab, palette: ICommandPalette, menu: IMainMenu, settingRegistry: ISettingRegistry): IDocumentManager => {
  71. const manager = app.serviceManager;
  72. const contexts = new WeakSet<DocumentRegistry.Context>();
  73. const opener: DocumentManager.IWidgetOpener = {
  74. open: (widget, options) => {
  75. const shell = app.shell;
  76. if (!widget.id) {
  77. widget.id = `document-manager-${++Private.id}`;
  78. }
  79. widget.title.dataset = {
  80. 'type': 'document-title',
  81. ...widget.title.dataset
  82. };
  83. if (!widget.isAttached) {
  84. app.shell.addToMainArea(widget, options || {});
  85. }
  86. shell.activateById(widget.id);
  87. // Handle dirty state for open documents.
  88. let context = docManager.contextForWidget(widget);
  89. if (!contexts.has(context)) {
  90. handleContext(app, context);
  91. contexts.add(context);
  92. }
  93. }
  94. };
  95. const registry = app.docRegistry;
  96. const when = app.restored.then(() => void 0);
  97. const docManager = new DocumentManager({ registry, manager, opener, when });
  98. // Register the file operations commands.
  99. addCommands(app, docManager, palette, opener, settingRegistry);
  100. // Keep up to date with the settings registry.
  101. const onSettingsUpdated = (settings: ISettingRegistry.ISettings) => {
  102. const autosave = settings.get('autosave').composite as boolean | null;
  103. docManager.autosave = (autosave === true || autosave === false)
  104. ? autosave
  105. : true;
  106. app.commands.notifyCommandChanged(CommandIDs.toggleAutosave);
  107. };
  108. // Fetch the initial state of the settings.
  109. Promise.all([settingRegistry.load(pluginId), app.restored])
  110. .then(([settings]) => {
  111. settings.changed.connect(onSettingsUpdated);
  112. onSettingsUpdated(settings);
  113. }).catch((reason: Error) => {
  114. console.error(reason.message);
  115. });
  116. menu.settingsMenu.addGroup([{ command: CommandIDs.toggleAutosave }], 5);
  117. return docManager;
  118. }
  119. };
  120. /**
  121. * Export the plugin as default.
  122. */
  123. export default plugin;
  124. /**
  125. * Add the file operations commands to the application's command registry.
  126. */
  127. function addCommands(app: JupyterLab, docManager: IDocumentManager, palette: ICommandPalette, opener: DocumentManager.IWidgetOpener, settingRegistry: ISettingRegistry): void {
  128. const { commands, docRegistry } = app;
  129. const category = 'File Operations';
  130. const isEnabled = () => {
  131. const { currentWidget } = app.shell;
  132. return !!(currentWidget && docManager.contextForWidget(currentWidget));
  133. };
  134. const fileType = () => {
  135. const { currentWidget } = app.shell;
  136. if (!currentWidget) {
  137. return 'File';
  138. }
  139. const context = docManager.contextForWidget(currentWidget);
  140. if (!context) {
  141. return '';
  142. }
  143. const fts = docRegistry.getFileTypesForPath(context.path);
  144. return (fts.length && fts[0].displayName) ? fts[0].displayName : 'File';
  145. };
  146. commands.addCommand(CommandIDs.close, {
  147. label: () => {
  148. const widget = app.shell.currentWidget;
  149. let name = 'File';
  150. if (widget) {
  151. const typeName = fileType();
  152. name = typeName || widget.title.label;
  153. }
  154. return `Close ${name}`;
  155. },
  156. isEnabled: () => !!app.shell.currentWidget &&
  157. !!app.shell.currentWidget.title.closable,
  158. execute: () => {
  159. if (app.shell.currentWidget) {
  160. app.shell.currentWidget.close();
  161. }
  162. }
  163. });
  164. commands.addCommand(CommandIDs.closeAllFiles, {
  165. label: 'Close All',
  166. execute: () => { app.shell.closeAll(); }
  167. });
  168. commands.addCommand(CommandIDs.deleteFile, {
  169. label: () => `Delete ${fileType()}`,
  170. execute: args => {
  171. const path = typeof args['path'] === 'undefined' ? ''
  172. : args['path'] as string;
  173. if (!path) {
  174. const command = CommandIDs.deleteFile;
  175. throw new Error(`A non-empty path is required for ${command}.`);
  176. }
  177. return docManager.deleteFile(path);
  178. }
  179. });
  180. commands.addCommand(CommandIDs.newUntitled, {
  181. execute: args => {
  182. const errorTitle = args['error'] as string || 'Error';
  183. const path = typeof args['path'] === 'undefined' ? ''
  184. : args['path'] as string;
  185. let options: Partial<Contents.ICreateOptions> = {
  186. type: args['type'] as Contents.ContentType,
  187. path
  188. };
  189. if (args['type'] === 'file') {
  190. options.ext = args['ext'] as string || '.txt';
  191. }
  192. return docManager.services.contents.newUntitled(options)
  193. .catch(error => showErrorMessage(errorTitle, error));
  194. },
  195. label: args => args['label'] as string || `New ${args['type'] as string}`
  196. });
  197. commands.addCommand(CommandIDs.open, {
  198. execute: args => {
  199. const path = typeof args['path'] === 'undefined' ? ''
  200. : args['path'] as string;
  201. const factory = args['factory'] as string || void 0;
  202. const kernel = args['kernel'] as Kernel.IModel || void 0;
  203. const options = args['options'] as DocumentRegistry.IOpenOptions || void 0;
  204. return docManager.services.contents.get(path, { content: false })
  205. .then(() => docManager.openOrReveal(path, factory, kernel, options));
  206. },
  207. icon: args => args['icon'] as string || '',
  208. label: args => (args['label'] || args['factory']) as string,
  209. mnemonic: args => args['mnemonic'] as number || -1
  210. });
  211. commands.addCommand(CommandIDs.openBrowserTab, {
  212. execute: args => {
  213. const path = typeof args['path'] === 'undefined' ? ''
  214. : args['path'] as string;
  215. if (!path) {
  216. return;
  217. }
  218. return docManager.services.contents.getDownloadUrl(path).then(url => {
  219. window.open(url, '_blank');
  220. });
  221. },
  222. icon: args => args['icon'] as string || '',
  223. label: () => 'Open in New Browser Tab'
  224. });
  225. commands.addCommand(CommandIDs.openDirect, {
  226. label: () => 'Open from Path',
  227. caption: 'Open from path',
  228. isEnabled: () => true,
  229. execute: () => {
  230. return getOpenPath(docManager.services.contents).then(path => {
  231. if (!path) {
  232. return;
  233. }
  234. docManager.services.contents.get(path, { content: false }).then( (args) => {
  235. // exists
  236. return commands.execute(CommandIDs.open, {path: path});
  237. }, () => {
  238. // does not exist
  239. return showDialog({
  240. title: 'Cannot open',
  241. body: 'File not found',
  242. buttons: [Dialog.okButton()]
  243. });
  244. });
  245. return;
  246. });
  247. },
  248. });
  249. commands.addCommand(CommandIDs.restoreCheckpoint, {
  250. label: () => `Revert ${fileType()} to Saved`,
  251. caption: 'Revert contents to previous checkpoint',
  252. isEnabled,
  253. execute: () => {
  254. if (isEnabled()) {
  255. let context = docManager.contextForWidget(app.shell.currentWidget);
  256. if (context.model.readOnly) {
  257. return context.revert();
  258. }
  259. return context.restoreCheckpoint().then(() => context.revert());
  260. }
  261. }
  262. });
  263. commands.addCommand(CommandIDs.save, {
  264. label: () => `Save ${fileType()}`,
  265. caption: 'Save and create checkpoint',
  266. isEnabled,
  267. execute: () => {
  268. if (isEnabled()) {
  269. let context = docManager.contextForWidget(app.shell.currentWidget);
  270. if (context.model.readOnly) {
  271. return showDialog({
  272. title: 'Cannot Save',
  273. body: 'Document is read-only',
  274. buttons: [Dialog.okButton()]
  275. });
  276. }
  277. return context.save()
  278. .then(() => context.createCheckpoint())
  279. .catch(err => {
  280. // If the save was canceled by user-action, do nothing.
  281. if (err.message === 'Cancel') {
  282. return;
  283. }
  284. throw err;
  285. });
  286. }
  287. }
  288. });
  289. commands.addCommand(CommandIDs.saveAll, {
  290. label: () => 'Save All',
  291. caption: 'Save all open documents',
  292. isEnabled: () => {
  293. const iterator = app.shell.widgets('main');
  294. let widget = iterator.next();
  295. while (widget) {
  296. if (docManager.contextForWidget(widget)) {
  297. return true;
  298. }
  299. widget = iterator.next();
  300. }
  301. return false;
  302. },
  303. execute: () => {
  304. const iterator = app.shell.widgets('main');
  305. const promises: Promise<void>[] = [];
  306. const paths = new Set<string>(); // Cache so we don't double save files.
  307. let widget = iterator.next();
  308. while (widget) {
  309. const context = docManager.contextForWidget(widget);
  310. if (context && !context.model.readOnly && !paths.has(context.path)) {
  311. paths.add(context.path);
  312. promises.push(context.save());
  313. }
  314. widget = iterator.next();
  315. }
  316. return Promise.all(promises);
  317. }
  318. });
  319. commands.addCommand(CommandIDs.saveAs, {
  320. label: () => `Save ${fileType()} As…`,
  321. caption: 'Save with new path',
  322. isEnabled,
  323. execute: () => {
  324. if (isEnabled()) {
  325. let context = docManager.contextForWidget(app.shell.currentWidget);
  326. return context.saveAs();
  327. }
  328. }
  329. });
  330. commands.addCommand(CommandIDs.rename, {
  331. label: () => `Rename ${fileType()}…`,
  332. isEnabled,
  333. execute: () => {
  334. if (isEnabled()) {
  335. let context = docManager.contextForWidget(app.shell.currentWidget);
  336. return renameDialog(docManager, context!.path);
  337. }
  338. }
  339. });
  340. commands.addCommand(CommandIDs.clone, {
  341. label: () => `New View for ${fileType()}`,
  342. isEnabled,
  343. execute: (args) => {
  344. const widget = app.shell.currentWidget;
  345. const options = args['options'] as DocumentRegistry.IOpenOptions || void 0;
  346. if (!widget) {
  347. return;
  348. }
  349. // Clone the widget.
  350. let child = docManager.cloneWidget(widget);
  351. if (child) {
  352. opener.open(child, options);
  353. }
  354. },
  355. });
  356. commands.addCommand(CommandIDs.toggleAutosave, {
  357. label: 'Autosave Documents',
  358. isToggled: () => docManager.autosave,
  359. execute: () => {
  360. const value = !docManager.autosave;
  361. const key = 'autosave';
  362. return settingRegistry.set(pluginId, key, value)
  363. .catch((reason: Error) => {
  364. console.error(`Failed to set ${pluginId}:${key} - ${reason.message}`);
  365. });
  366. }
  367. });
  368. commands.addCommand(CommandIDs.showInFileBrowser, {
  369. label: () => `Show in file browser`,
  370. isEnabled,
  371. execute: () => {
  372. let context = docManager.contextForWidget(app.shell.currentWidget);
  373. if (!context) {
  374. return;
  375. }
  376. // 'activate-main' is needed if this command is selected in the "open tabs" sidebar
  377. commands.execute('filebrowser:activate-main');
  378. commands.execute('filebrowser:navigate-main', {path: context.path});
  379. }
  380. });
  381. app.contextMenu.addItem({
  382. command: CommandIDs.rename,
  383. selector: '[data-type="document-title"]',
  384. rank: 1
  385. });
  386. app.contextMenu.addItem({
  387. command: CommandIDs.clone,
  388. selector: '[data-type="document-title"]',
  389. rank: 2
  390. });
  391. app.contextMenu.addItem({
  392. command: CommandIDs.showInFileBrowser,
  393. selector: '[data-type="document-title"]',
  394. rank: 3
  395. });
  396. [
  397. CommandIDs.openDirect,
  398. CommandIDs.save,
  399. CommandIDs.restoreCheckpoint,
  400. CommandIDs.saveAs,
  401. CommandIDs.clone,
  402. CommandIDs.close,
  403. CommandIDs.closeAllFiles,
  404. CommandIDs.toggleAutosave
  405. ].forEach(command => { palette.addItem({ command, category }); });
  406. }
  407. /**
  408. * Handle dirty state for a context.
  409. */
  410. function handleContext(app: JupyterLab, context: DocumentRegistry.Context): void {
  411. let disposable: IDisposable | null = null;
  412. let onStateChanged = (sender: any, args: IChangedArgs<any>) => {
  413. if (args.name === 'dirty') {
  414. if (args.newValue === true) {
  415. if (!disposable) {
  416. disposable = app.setDirty();
  417. }
  418. } else if (disposable) {
  419. disposable.dispose();
  420. disposable = null;
  421. }
  422. }
  423. };
  424. context.ready.then(() => {
  425. context.model.stateChanged.connect(onStateChanged);
  426. if (context.model.dirty) {
  427. disposable = app.setDirty();
  428. }
  429. });
  430. context.disposed.connect(() => {
  431. if (disposable) {
  432. disposable.dispose();
  433. }
  434. });
  435. }
  436. /**
  437. * A namespace for private module data.
  438. */
  439. namespace Private {
  440. /**
  441. * A counter for unique IDs.
  442. */
  443. export
  444. let id = 0;
  445. }