manager.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715
  1. // Copyright (c) Jupyter Development Team.
  2. // Distributed under the terms of the Modified BSD License.
  3. import { ISessionContext, sessionContextDialogs } from '@jupyterlab/apputils';
  4. import { PathExt } from '@jupyterlab/coreutils';
  5. import {
  6. DocumentRegistry,
  7. Context,
  8. IDocumentWidget
  9. } from '@jupyterlab/docregistry';
  10. import { IDocumentProviderFactory } from '@jupyterlab/docprovider';
  11. import { Contents, Kernel, ServiceManager } from '@jupyterlab/services';
  12. import { nullTranslator, ITranslator } from '@jupyterlab/translation';
  13. import { ArrayExt, find } from '@lumino/algorithm';
  14. import { UUID } from '@lumino/coreutils';
  15. import { IDisposable } from '@lumino/disposable';
  16. import { AttachedProperty } from '@lumino/properties';
  17. import { ISignal, Signal } from '@lumino/signaling';
  18. import { Widget } from '@lumino/widgets';
  19. import { SaveHandler } from './savehandler';
  20. import { IDocumentManager } from './tokens';
  21. import { DocumentWidgetManager } from './widgetmanager';
  22. /**
  23. * The document manager.
  24. *
  25. * #### Notes
  26. * The document manager is used to register model and widget creators,
  27. * and the file browser uses the document manager to create widgets. The
  28. * document manager maintains a context for each path and model type that is
  29. * open, and a list of widgets for each context. The document manager is in
  30. * control of the proper closing and disposal of the widgets and contexts.
  31. */
  32. export class DocumentManager implements IDocumentManager {
  33. /**
  34. * Construct a new document manager.
  35. */
  36. constructor(options: DocumentManager.IOptions) {
  37. this.translator = options.translator || nullTranslator;
  38. this.registry = options.registry;
  39. this.services = options.manager;
  40. this._collaborative = !!options.collaborative;
  41. this._dialogs = options.sessionDialogs || sessionContextDialogs;
  42. this._docProviderFactory = options.docProviderFactory;
  43. this._opener = options.opener;
  44. this._when = options.when || options.manager.ready;
  45. const widgetManager = new DocumentWidgetManager({
  46. registry: this.registry,
  47. translator: this.translator
  48. });
  49. widgetManager.activateRequested.connect(this._onActivateRequested, this);
  50. this._widgetManager = widgetManager;
  51. this._setBusy = options.setBusy;
  52. }
  53. /**
  54. * The registry used by the manager.
  55. */
  56. readonly registry: DocumentRegistry;
  57. /**
  58. * The service manager used by the manager.
  59. */
  60. readonly services: ServiceManager.IManager;
  61. /**
  62. * A signal emitted when one of the documents is activated.
  63. */
  64. get activateRequested(): ISignal<this, string> {
  65. return this._activateRequested;
  66. }
  67. /**
  68. * Whether to autosave documents.
  69. */
  70. get autosave(): boolean {
  71. return this._autosave;
  72. }
  73. set autosave(value: boolean) {
  74. this._autosave = value;
  75. // For each existing context, start/stop the autosave handler as needed.
  76. this._contexts.forEach(context => {
  77. const handler = Private.saveHandlerProperty.get(context);
  78. if (!handler) {
  79. return;
  80. }
  81. if (value === true && !handler.isActive) {
  82. handler.start();
  83. } else if (value === false && handler.isActive) {
  84. handler.stop();
  85. }
  86. });
  87. }
  88. /**
  89. * Determines the time interval for autosave in seconds.
  90. */
  91. get autosaveInterval(): number {
  92. return this._autosaveInterval;
  93. }
  94. set autosaveInterval(value: number) {
  95. this._autosaveInterval = value;
  96. // For each existing context, set the save interval as needed.
  97. this._contexts.forEach(context => {
  98. const handler = Private.saveHandlerProperty.get(context);
  99. if (!handler) {
  100. return;
  101. }
  102. handler.saveInterval = value || 120;
  103. });
  104. }
  105. /**
  106. * Get whether the document manager has been disposed.
  107. */
  108. get isDisposed(): boolean {
  109. return this._isDisposed;
  110. }
  111. /**
  112. * Dispose of the resources held by the document manager.
  113. */
  114. dispose(): void {
  115. if (this.isDisposed) {
  116. return;
  117. }
  118. this._isDisposed = true;
  119. // Clear any listeners for our signals.
  120. Signal.clearData(this);
  121. // Close all the widgets for our contexts and dispose the widget manager.
  122. this._contexts.forEach(context => {
  123. return this._widgetManager.closeWidgets(context);
  124. });
  125. this._widgetManager.dispose();
  126. // Clear the context list.
  127. this._contexts.length = 0;
  128. }
  129. /**
  130. * Clone a widget.
  131. *
  132. * @param widget - The source widget.
  133. *
  134. * @returns A new widget or `undefined`.
  135. *
  136. * #### Notes
  137. * Uses the same widget factory and context as the source, or returns
  138. * `undefined` if the source widget is not managed by this manager.
  139. */
  140. cloneWidget(widget: Widget): IDocumentWidget | undefined {
  141. return this._widgetManager.cloneWidget(widget);
  142. }
  143. /**
  144. * Close all of the open documents.
  145. *
  146. * @returns A promise resolving when the widgets are closed.
  147. */
  148. closeAll(): Promise<void> {
  149. return Promise.all(
  150. this._contexts.map(context => this._widgetManager.closeWidgets(context))
  151. ).then(() => undefined);
  152. }
  153. /**
  154. * Close the widgets associated with a given path.
  155. *
  156. * @param path - The target path.
  157. *
  158. * @returns A promise resolving when the widgets are closed.
  159. */
  160. closeFile(path: string): Promise<void> {
  161. const close = this._contextsForPath(path).map(c =>
  162. this._widgetManager.closeWidgets(c)
  163. );
  164. return Promise.all(close).then(x => undefined);
  165. }
  166. /**
  167. * Get the document context for a widget.
  168. *
  169. * @param widget - The widget of interest.
  170. *
  171. * @returns The context associated with the widget, or `undefined` if no such
  172. * context exists.
  173. */
  174. contextForWidget(widget: Widget): DocumentRegistry.Context | undefined {
  175. return this._widgetManager.contextForWidget(widget);
  176. }
  177. /**
  178. * Copy a file.
  179. *
  180. * @param fromFile - The full path of the original file.
  181. *
  182. * @param toDir - The full path to the target directory.
  183. *
  184. * @returns A promise which resolves to the contents of the file.
  185. */
  186. copy(fromFile: string, toDir: string): Promise<Contents.IModel> {
  187. return this.services.contents.copy(fromFile, toDir);
  188. }
  189. /**
  190. * Create a new file and return the widget used to view it.
  191. *
  192. * @param path - The file path to create.
  193. *
  194. * @param widgetName - The name of the widget factory to use. 'default' will use the default widget.
  195. *
  196. * @param kernel - An optional kernel name/id to override the default.
  197. *
  198. * @returns The created widget, or `undefined`.
  199. *
  200. * #### Notes
  201. * This function will return `undefined` if a valid widget factory
  202. * cannot be found.
  203. */
  204. createNew(
  205. path: string,
  206. widgetName = 'default',
  207. kernel?: Partial<Kernel.IModel>
  208. ): Widget | undefined {
  209. return this._createOrOpenDocument('create', path, widgetName, kernel);
  210. }
  211. /**
  212. * Delete a file.
  213. *
  214. * @param path - The full path to the file to be deleted.
  215. *
  216. * @returns A promise which resolves when the file is deleted.
  217. *
  218. * #### Notes
  219. * If there is a running session associated with the file and no other
  220. * sessions are using the kernel, the session will be shut down.
  221. */
  222. deleteFile(path: string): Promise<void> {
  223. return this.services.sessions
  224. .stopIfNeeded(path)
  225. .then(() => {
  226. return this.services.contents.delete(path);
  227. })
  228. .then(() => {
  229. this._contextsForPath(path).forEach(context =>
  230. this._widgetManager.deleteWidgets(context)
  231. );
  232. return Promise.resolve(void 0);
  233. });
  234. }
  235. /**
  236. * See if a widget already exists for the given path and widget name.
  237. *
  238. * @param path - The file path to use.
  239. *
  240. * @param widgetName - The name of the widget factory to use. 'default' will use the default widget.
  241. *
  242. * @returns The found widget, or `undefined`.
  243. *
  244. * #### Notes
  245. * This can be used to find an existing widget instead of opening
  246. * a new widget.
  247. */
  248. findWidget(
  249. path: string,
  250. widgetName: string | null = 'default'
  251. ): IDocumentWidget | undefined {
  252. const newPath = PathExt.normalize(path);
  253. let widgetNames = [widgetName];
  254. if (widgetName === 'default') {
  255. const factory = this.registry.defaultWidgetFactory(newPath);
  256. if (!factory) {
  257. return undefined;
  258. }
  259. widgetNames = [factory.name];
  260. } else if (widgetName === null) {
  261. widgetNames = this.registry
  262. .preferredWidgetFactories(newPath)
  263. .map(f => f.name);
  264. }
  265. for (const context of this._contextsForPath(newPath)) {
  266. for (const widgetName of widgetNames) {
  267. if (widgetName !== null) {
  268. const widget = this._widgetManager.findWidget(context, widgetName);
  269. if (widget) {
  270. return widget;
  271. }
  272. }
  273. }
  274. }
  275. return undefined;
  276. }
  277. /**
  278. * Create a new untitled file.
  279. *
  280. * @param options - The file content creation options.
  281. */
  282. newUntitled(options: Contents.ICreateOptions): Promise<Contents.IModel> {
  283. if (options.type === 'file') {
  284. options.ext = options.ext || '.txt';
  285. }
  286. return this.services.contents.newUntitled(options);
  287. }
  288. /**
  289. * Open a file and return the widget used to view it.
  290. *
  291. * @param path - The file path to open.
  292. *
  293. * @param widgetName - The name of the widget factory to use. 'default' will use the default widget.
  294. *
  295. * @param kernel - An optional kernel name/id to override the default.
  296. *
  297. * @returns The created widget, or `undefined`.
  298. *
  299. * #### Notes
  300. * This function will return `undefined` if a valid widget factory
  301. * cannot be found.
  302. */
  303. open(
  304. path: string,
  305. widgetName = 'default',
  306. kernel?: Partial<Kernel.IModel>,
  307. options?: DocumentRegistry.IOpenOptions
  308. ): IDocumentWidget | undefined {
  309. return this._createOrOpenDocument(
  310. 'open',
  311. path,
  312. widgetName,
  313. kernel,
  314. options
  315. );
  316. }
  317. /**
  318. * Open a file and return the widget used to view it.
  319. * Reveals an already existing editor.
  320. *
  321. * @param path - The file path to open.
  322. *
  323. * @param widgetName - The name of the widget factory to use. 'default' will use the default widget.
  324. *
  325. * @param kernel - An optional kernel name/id to override the default.
  326. *
  327. * @returns The created widget, or `undefined`.
  328. *
  329. * #### Notes
  330. * This function will return `undefined` if a valid widget factory
  331. * cannot be found.
  332. */
  333. openOrReveal(
  334. path: string,
  335. widgetName = 'default',
  336. kernel?: Partial<Kernel.IModel>,
  337. options?: DocumentRegistry.IOpenOptions
  338. ): IDocumentWidget | undefined {
  339. const widget = this.findWidget(path, widgetName);
  340. if (widget) {
  341. this._opener.open(widget, options || {});
  342. return widget;
  343. }
  344. return this.open(path, widgetName, kernel, options || {});
  345. }
  346. /**
  347. * Overwrite a file.
  348. *
  349. * @param oldPath - The full path to the original file.
  350. *
  351. * @param newPath - The full path to the new file.
  352. *
  353. * @returns A promise containing the new file contents model.
  354. */
  355. overwrite(oldPath: string, newPath: string): Promise<Contents.IModel> {
  356. // Cleanly overwrite the file by moving it, making sure the original does
  357. // not exist, and then renaming to the new path.
  358. const tempPath = `${newPath}.${UUID.uuid4()}`;
  359. const cb = () => this.rename(tempPath, newPath);
  360. return this.rename(oldPath, tempPath)
  361. .then(() => {
  362. return this.deleteFile(newPath);
  363. })
  364. .then(cb, cb);
  365. }
  366. /**
  367. * Rename a file or directory.
  368. *
  369. * @param oldPath - The full path to the original file.
  370. *
  371. * @param newPath - The full path to the new file.
  372. *
  373. * @returns A promise containing the new file contents model. The promise
  374. * will reject if the newPath already exists. Use [[overwrite]] to overwrite
  375. * a file.
  376. */
  377. rename(oldPath: string, newPath: string): Promise<Contents.IModel> {
  378. return this.services.contents.rename(oldPath, newPath);
  379. }
  380. /**
  381. * Find a context for a given path and factory name.
  382. */
  383. private _findContext(
  384. path: string,
  385. factoryName: string
  386. ): Private.IContext | undefined {
  387. const normalizedPath = this.services.contents.normalize(path);
  388. return find(this._contexts, context => {
  389. return (
  390. context.path === normalizedPath && context.factoryName === factoryName
  391. );
  392. });
  393. }
  394. /**
  395. * Get the contexts for a given path.
  396. *
  397. * #### Notes
  398. * There may be more than one context for a given path if the path is open
  399. * with multiple model factories (for example, a notebook can be open with a
  400. * notebook model factory and a text model factory).
  401. */
  402. private _contextsForPath(path: string): Private.IContext[] {
  403. const normalizedPath = this.services.contents.normalize(path);
  404. return this._contexts.filter(context => context.path === normalizedPath);
  405. }
  406. /**
  407. * Create a context from a path and a model factory.
  408. */
  409. private _createContext(
  410. path: string,
  411. factory: DocumentRegistry.ModelFactory,
  412. kernelPreference?: ISessionContext.IKernelPreference
  413. ): Private.IContext {
  414. // TODO: Make it impossible to open two different contexts for the same
  415. // path. Or at least prompt the closing of all widgets associated with the
  416. // old context before opening the new context. This will make things much
  417. // more consistent for the users, at the cost of some confusion about what
  418. // models are and why sometimes they cannot open the same file in different
  419. // widgets that have different models.
  420. // Allow options to be passed when adding a sibling.
  421. const adopter = (
  422. widget: IDocumentWidget,
  423. options?: DocumentRegistry.IOpenOptions
  424. ) => {
  425. this._widgetManager.adoptWidget(context, widget);
  426. this._opener.open(widget, options);
  427. };
  428. const modelDBFactory =
  429. this.services.contents.getModelDBFactory(path) || undefined;
  430. const context = new Context({
  431. opener: adopter,
  432. manager: this.services,
  433. factory,
  434. path,
  435. kernelPreference,
  436. modelDBFactory,
  437. setBusy: this._setBusy,
  438. sessionDialogs: this._dialogs,
  439. collaborative: this._collaborative,
  440. docProviderFactory: this._docProviderFactory
  441. });
  442. const handler = new SaveHandler({
  443. context,
  444. saveInterval: this.autosaveInterval
  445. });
  446. Private.saveHandlerProperty.set(context, handler);
  447. void context.ready.then(() => {
  448. if (this.autosave) {
  449. handler.start();
  450. }
  451. });
  452. context.disposed.connect(this._onContextDisposed, this);
  453. this._contexts.push(context);
  454. return context;
  455. }
  456. /**
  457. * Handle a context disposal.
  458. */
  459. private _onContextDisposed(context: Private.IContext): void {
  460. ArrayExt.removeFirstOf(this._contexts, context);
  461. }
  462. /**
  463. * Get the widget factory for a given widget name.
  464. */
  465. private _widgetFactoryFor(
  466. path: string,
  467. widgetName: string
  468. ): DocumentRegistry.WidgetFactory | undefined {
  469. const { registry } = this;
  470. if (widgetName === 'default') {
  471. const factory = registry.defaultWidgetFactory(path);
  472. if (!factory) {
  473. return undefined;
  474. }
  475. widgetName = factory.name;
  476. }
  477. return registry.getWidgetFactory(widgetName);
  478. }
  479. /**
  480. * Creates a new document, or loads one from disk, depending on the `which` argument.
  481. * If `which==='create'`, then it creates a new document. If `which==='open'`,
  482. * then it loads the document from disk.
  483. *
  484. * The two cases differ in how the document context is handled, but the creation
  485. * of the widget and launching of the kernel are identical.
  486. */
  487. private _createOrOpenDocument(
  488. which: 'open' | 'create',
  489. path: string,
  490. widgetName = 'default',
  491. kernel?: Partial<Kernel.IModel>,
  492. options?: DocumentRegistry.IOpenOptions
  493. ): IDocumentWidget | undefined {
  494. const widgetFactory = this._widgetFactoryFor(path, widgetName);
  495. if (!widgetFactory) {
  496. return undefined;
  497. }
  498. const modelName = widgetFactory.modelName || 'text';
  499. const factory = this.registry.getModelFactory(modelName);
  500. if (!factory) {
  501. return undefined;
  502. }
  503. // Handle the kernel pereference.
  504. const preference = this.registry.getKernelPreference(
  505. path,
  506. widgetFactory.name,
  507. kernel
  508. );
  509. let context: Private.IContext | null;
  510. let ready: Promise<void> = Promise.resolve(undefined);
  511. // Handle the load-from-disk case
  512. if (which === 'open') {
  513. // Use an existing context if available.
  514. context = this._findContext(path, factory.name) || null;
  515. if (!context) {
  516. context = this._createContext(path, factory, preference);
  517. // Populate the model, either from disk or a
  518. // model backend.
  519. ready = this._when.then(() => context!.initialize(false));
  520. }
  521. } else if (which === 'create') {
  522. context = this._createContext(path, factory, preference);
  523. // Immediately save the contents to disk.
  524. ready = this._when.then(() => context!.initialize(true));
  525. } else {
  526. throw new Error(`Invalid argument 'which': ${which}`);
  527. }
  528. const widget = this._widgetManager.createWidget(widgetFactory, context);
  529. this._opener.open(widget, options || {});
  530. // If the initial opening of the context fails, dispose of the widget.
  531. ready.catch(err => {
  532. widget.close();
  533. });
  534. return widget;
  535. }
  536. /**
  537. * Handle an activateRequested signal from the widget manager.
  538. */
  539. private _onActivateRequested(
  540. sender: DocumentWidgetManager,
  541. args: string
  542. ): void {
  543. this._activateRequested.emit(args);
  544. }
  545. protected translator: ITranslator;
  546. private _activateRequested = new Signal<this, string>(this);
  547. private _contexts: Private.IContext[] = [];
  548. private _opener: DocumentManager.IWidgetOpener;
  549. private _widgetManager: DocumentWidgetManager;
  550. private _isDisposed = false;
  551. private _autosave = true;
  552. private _autosaveInterval = 120;
  553. private _when: Promise<void>;
  554. private _setBusy: (() => IDisposable) | undefined;
  555. private _dialogs: ISessionContext.IDialogs;
  556. private _docProviderFactory: IDocumentProviderFactory | undefined;
  557. private _collaborative: boolean;
  558. }
  559. /**
  560. * A namespace for document manager statics.
  561. */
  562. export namespace DocumentManager {
  563. /**
  564. * The options used to initialize a document manager.
  565. */
  566. export interface IOptions {
  567. /**
  568. * A document registry instance.
  569. */
  570. registry: DocumentRegistry;
  571. /**
  572. * A service manager instance.
  573. */
  574. manager: ServiceManager.IManager;
  575. /**
  576. * A widget opener for sibling widgets.
  577. */
  578. opener: IWidgetOpener;
  579. /**
  580. * A promise for when to start using the manager.
  581. */
  582. when?: Promise<void>;
  583. /**
  584. * A function called when a kernel is busy.
  585. */
  586. setBusy?: () => IDisposable;
  587. /**
  588. * The provider for session dialogs.
  589. */
  590. sessionDialogs?: ISessionContext.IDialogs;
  591. /**
  592. * The applicaton language translator.
  593. */
  594. translator?: ITranslator;
  595. /**
  596. * A factory method for the document provider.
  597. */
  598. docProviderFactory?: IDocumentProviderFactory;
  599. /**
  600. * Whether the context should be collaborative.
  601. * If true, the context will connect through yjs_ws_server to share information if possible.
  602. */
  603. collaborative?: boolean;
  604. }
  605. /**
  606. * An interface for a widget opener.
  607. */
  608. export interface IWidgetOpener {
  609. /**
  610. * Open the given widget.
  611. */
  612. open(
  613. widget: IDocumentWidget,
  614. options?: DocumentRegistry.IOpenOptions
  615. ): void;
  616. }
  617. }
  618. /**
  619. * A namespace for private data.
  620. */
  621. namespace Private {
  622. /**
  623. * An attached property for a context save handler.
  624. */
  625. export const saveHandlerProperty = new AttachedProperty<
  626. DocumentRegistry.Context,
  627. SaveHandler | undefined
  628. >({
  629. name: 'saveHandler',
  630. create: () => undefined
  631. });
  632. /**
  633. * A type alias for a standard context.
  634. *
  635. * #### Notes
  636. * We define this as an interface of a specific implementation so that we can
  637. * use the implementation-specific functions.
  638. */
  639. export interface IContext extends Context<DocumentRegistry.IModel> {
  640. /* no op */
  641. }
  642. }