manager.ts 20 KB

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