manager.ts 18 KB

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