content.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647
  1. // Copyright (c) Jupyter Development Team.
  2. // Distributed under the terms of the Modified BSD License.
  3. import {
  4. KernelMessage, Session, nbformat
  5. } from '@jupyterlab/services';
  6. import {
  7. map, toArray
  8. } from 'phosphor/lib/algorithm/iteration';
  9. import {
  10. Message
  11. } from 'phosphor/lib/core/messaging';
  12. import {
  13. clearSignalData, defineSignal, ISignal
  14. } from 'phosphor/lib/core/signaling';
  15. import {
  16. Token
  17. } from 'phosphor/lib/core/token';
  18. import {
  19. Panel, PanelLayout
  20. } from 'phosphor/lib/ui/panel';
  21. import {
  22. Widget
  23. } from 'phosphor/lib/ui/widget';
  24. import {
  25. CellCompleterHandler, CompleterModel, CompleterWidget
  26. } from '../completer';
  27. import {
  28. InspectionHandler
  29. } from '../inspector';
  30. import {
  31. CodeCellWidget, RawCellWidget
  32. } from '../notebook/cells';
  33. import {
  34. EdgeLocation, ICellEditorWidget, ITextChange
  35. } from '../notebook/cells/editor';
  36. import {
  37. IRenderMime
  38. } from '../rendermime';
  39. import {
  40. ForeignHandler
  41. } from './foreign';
  42. import {
  43. ConsoleHistory, IConsoleHistory
  44. } from './history';
  45. /**
  46. * The class name added to console widgets.
  47. */
  48. const CONSOLE_CLASS = 'jp-ConsoleContent';
  49. /**
  50. * The class name added to the console banner.
  51. */
  52. const BANNER_CLASS = 'jp-ConsoleContent-banner';
  53. /**
  54. * The class name of a cell whose input originated from a foreign session.
  55. */
  56. const FOREIGN_CELL_CLASS = 'jp-ConsoleContent-foreignCell';
  57. /**
  58. * The class name of the active prompt
  59. */
  60. const PROMPT_CLASS = 'jp-ConsoleContent-prompt';
  61. /**
  62. * The class name of the panel that holds cell content.
  63. */
  64. const CONTENT_CLASS = 'jp-ConsoleContent-content';
  65. /**
  66. * The class name of the panel that holds prompts.
  67. */
  68. const INPUT_CLASS = 'jp-ConsoleContent-input';
  69. /**
  70. * The timeout in ms for execution requests to the kernel.
  71. */
  72. const EXECUTION_TIMEOUT = 250;
  73. /**
  74. * A widget containing a Jupyter console's content.
  75. *
  76. * #### Notes
  77. * The ConsoleContent class is intended to be used within a ConsolePanel
  78. * instance. Under most circumstances, it is not instantiated by user code.
  79. */
  80. export
  81. class ConsoleContent extends Widget {
  82. /**
  83. * Construct a console content widget.
  84. */
  85. constructor(options: ConsoleContent.IOptions) {
  86. super();
  87. this.addClass(CONSOLE_CLASS);
  88. // Create the panels that hold the content and input.
  89. let layout = this.layout = new PanelLayout();
  90. this._content = new Panel();
  91. this._input = new Panel();
  92. this._renderer = options.renderer;
  93. this._rendermime = options.rendermime;
  94. this._session = options.session;
  95. this._history = options.history || new ConsoleHistory({
  96. kernel: this._session.kernel
  97. });
  98. // Add top-level CSS classes.
  99. this._content.addClass(CONTENT_CLASS);
  100. this._input.addClass(INPUT_CLASS);
  101. // Insert the content and input panes into the widget.
  102. layout.addWidget(this._content);
  103. layout.addWidget(this._input);
  104. // Create the banner.
  105. let banner = this._renderer.createBanner();
  106. banner.addClass(BANNER_CLASS);
  107. banner.readOnly = true;
  108. banner.model.source = '...';
  109. this._content.addWidget(banner);
  110. // Set the banner text and the mimetype.
  111. this._initialize();
  112. // Set up the inspection handler.
  113. this._inspectionHandler = new InspectionHandler({
  114. kernel: this._session.kernel,
  115. rendermime: this._rendermime
  116. });
  117. // Set up the foreign iopub handler.
  118. this._foreignHandler = new ForeignHandler({
  119. kernel: this._session.kernel,
  120. parent: this._content,
  121. renderer: { createCell: () => this._newForeignCell() }
  122. });
  123. // Instantiate the completer.
  124. this._newCompleter(options.completer);
  125. }
  126. /*
  127. * The console content panel that holds the banner and executed cells.
  128. */
  129. get content(): Panel {
  130. return this._content;
  131. }
  132. /**
  133. * A signal emitted when the console executes its prompt.
  134. */
  135. readonly executed: ISignal<this, Date>;
  136. /**
  137. * Get the inspection handler used by the console.
  138. */
  139. get inspectionHandler(): InspectionHandler {
  140. return this._inspectionHandler;
  141. }
  142. /*
  143. * The console input prompt.
  144. */
  145. get prompt(): CodeCellWidget {
  146. let inputLayout = (this._input.layout as PanelLayout);
  147. return inputLayout.widgets.at(0) as CodeCellWidget || null;
  148. }
  149. /**
  150. * Get the session used by the console.
  151. */
  152. get session(): Session.ISession {
  153. return this._session;
  154. }
  155. /**
  156. * Clear the code cells.
  157. */
  158. clear(): void {
  159. // Dispose all the content cells except the first, which is the banner.
  160. let cells = this._content.widgets;
  161. while (cells.length > 1) {
  162. cells.at(1).dispose();
  163. }
  164. }
  165. /**
  166. * Dispose of the resources held by the widget.
  167. */
  168. dispose() {
  169. // Do nothing if already disposed.
  170. if (this.isDisposed) {
  171. return;
  172. }
  173. super.dispose();
  174. this._completerHandler.dispose();
  175. this._completerHandler = null;
  176. this._completer.dispose();
  177. this._completer = null;
  178. this._foreignHandler.dispose();
  179. this._foreignHandler = null;
  180. this._history.dispose();
  181. this._history = null;
  182. this._inspectionHandler.dispose();
  183. this._inspectionHandler = null;
  184. this._session.dispose();
  185. this._session = null;
  186. }
  187. /**
  188. * Execute the current prompt.
  189. *
  190. * @param force - Whether to force execution without checking code
  191. * completeness.
  192. *
  193. * @param timeout - The length of time, in milliseconds, that the execution
  194. * should wait for the API to determine whether code being submitted is
  195. * incomplete before attempting submission anyway. The default value is `250`.
  196. */
  197. execute(force = false, timeout = EXECUTION_TIMEOUT): Promise<void> {
  198. this._completer.reset();
  199. if (this._session.status === 'dead') {
  200. return Promise.resolve(void 0);
  201. }
  202. let prompt = this.prompt;
  203. prompt.trusted = true;
  204. if (force) {
  205. // Create a new prompt before kernel execution to allow typeahead.
  206. this.newPrompt();
  207. return this._execute(prompt);
  208. }
  209. // Check whether we should execute.
  210. return this._shouldExecute(timeout).then(should => {
  211. if (should) {
  212. // Create a new prompt before kernel execution to allow typeahead.
  213. this.newPrompt();
  214. return this._execute(prompt);
  215. }
  216. });
  217. }
  218. /**
  219. * Inject arbitrary code for the console to execute immediately.
  220. *
  221. * @param code - The code contents of the cell being injected.
  222. *
  223. * @returns A promise that indicates when the injected cell's execution ends.
  224. */
  225. inject(code: string): Promise<void> {
  226. // Create a new cell using the prompt renderer.
  227. let cell = this._renderer.createPrompt(this._rendermime);
  228. cell.model.source = code;
  229. cell.mimetype = this._mimetype;
  230. cell.readOnly = true;
  231. this._content.addWidget(cell);
  232. return this._execute(cell);
  233. }
  234. /**
  235. * Insert a line break in the prompt.
  236. */
  237. insertLinebreak(): void {
  238. let prompt = this.prompt;
  239. let model = prompt.model;
  240. model.source += '\n';
  241. prompt.editor.setCursorPosition(model.source.length);
  242. }
  243. /**
  244. * Serialize the output.
  245. */
  246. serialize(): nbformat.ICodeCell[] {
  247. let prompt = this.prompt;
  248. let layout = this._content.layout as PanelLayout;
  249. // Serialize content.
  250. let output = map(layout.widgets, widget => {
  251. return (widget as CodeCellWidget).model.toJSON() as nbformat.ICodeCell;
  252. });
  253. // Serialize prompt and return.
  254. return toArray(output).concat(prompt.model.toJSON() as nbformat.ICodeCell);
  255. }
  256. /**
  257. * Make a new prompt.
  258. */
  259. protected newPrompt(): void {
  260. let prompt = this.prompt;
  261. let content = this._content;
  262. let input = this._input;
  263. // Make the last prompt read-only, clear its signals, and move to content.
  264. if (prompt) {
  265. prompt.readOnly = true;
  266. prompt.removeClass(PROMPT_CLASS);
  267. clearSignalData(prompt.editor);
  268. content.addWidget((input.layout as PanelLayout).removeWidgetAt(0));
  269. }
  270. // Create the new prompt.
  271. prompt = this._renderer.createPrompt(this._rendermime);
  272. prompt.mimetype = this._mimetype;
  273. prompt.addClass(PROMPT_CLASS);
  274. this._input.addWidget(prompt);
  275. // Hook up history handling.
  276. let editor = prompt.editor;
  277. editor.edgeRequested.connect(this.onEdgeRequest, this);
  278. editor.textChanged.connect(this.onTextChange, this);
  279. // Associate the new prompt with the completer and inspection handlers.
  280. this._completerHandler.activeCell = prompt;
  281. this._inspectionHandler.activeCell = prompt;
  282. prompt.activate();
  283. this.update();
  284. }
  285. /**
  286. * Handle `'activate-request'` messages.
  287. */
  288. protected onActivateRequest(msg: Message): void {
  289. this.prompt.activate();
  290. this.update();
  291. }
  292. /**
  293. * Handle `'after-attach'` messages.
  294. */
  295. protected onAfterAttach(msg: Message): void {
  296. // Create a prompt if necessary.
  297. if (!this.prompt) {
  298. this.newPrompt();
  299. }
  300. // Listen for kernel change events.
  301. this._addSessionListeners();
  302. }
  303. /**
  304. * Handle an edge requested signal.
  305. */
  306. protected onEdgeRequest(editor: ICellEditorWidget, location: EdgeLocation): Promise<void> {
  307. let prompt = this.prompt;
  308. if (location === 'top') {
  309. return this._history.back(prompt.model.source).then(value => {
  310. if (!value) {
  311. return;
  312. }
  313. if (prompt.model.source === value) {
  314. return;
  315. }
  316. this._setByHistory = true;
  317. prompt.model.source = value;
  318. prompt.editor.setCursorPosition(0);
  319. });
  320. }
  321. return this._history.forward(prompt.model.source).then(value => {
  322. let text = value || this._history.placeholder;
  323. if (prompt.model.source === text) {
  324. return;
  325. }
  326. this._setByHistory = true;
  327. prompt.model.source = text;
  328. prompt.editor.setCursorPosition(text.length);
  329. });
  330. }
  331. /**
  332. * Handle a text change signal from the editor.
  333. */
  334. protected onTextChange(editor: ICellEditorWidget, args: ITextChange): void {
  335. if (this._setByHistory) {
  336. this._setByHistory = false;
  337. return;
  338. }
  339. this._history.reset();
  340. }
  341. /**
  342. * Handle `update-request` messages.
  343. */
  344. protected onUpdateRequest(msg: Message): void {
  345. super.onUpdateRequest(msg);
  346. Private.scrollToBottom(this._content.node);
  347. }
  348. /**
  349. * Handle kernel change events on the session.
  350. */
  351. private _addSessionListeners(): void {
  352. if (this._listening) {
  353. return;
  354. }
  355. this._listening = this._session.kernelChanged.connect((sender, kernel) => {
  356. this.clear();
  357. this.newPrompt();
  358. this._initialize();
  359. this._history.kernel = kernel;
  360. this._completerHandler.kernel = kernel;
  361. this._foreignHandler.kernel = kernel;
  362. this._inspectionHandler.kernel = kernel;
  363. });
  364. }
  365. /**
  366. * Initialize the banner and mimetype.
  367. */
  368. private _initialize(): void {
  369. let session = this._session;
  370. if (session.kernel.info) {
  371. this._handleInfo(this._session.kernel.info);
  372. return;
  373. }
  374. session.kernel.kernelInfo().then(msg => this._handleInfo(msg.content));
  375. }
  376. /**
  377. * Execute the code in the current prompt.
  378. */
  379. private _execute(cell: CodeCellWidget): Promise<void> {
  380. this._history.push(cell.model.source);
  381. cell.model.contentChanged.connect(this.update, this);
  382. let onSuccess = (value: KernelMessage.IExecuteReplyMsg) => {
  383. this.executed.emit(new Date());
  384. if (!value) {
  385. return;
  386. }
  387. if (value.content.status === 'ok') {
  388. let content = value.content as KernelMessage.IExecuteOkReply;
  389. // Use deprecated payloads for backwards compatibility.
  390. if (content.payload && content.payload.length) {
  391. let setNextInput = content.payload.filter(i => {
  392. return (i as any).source === 'set_next_input';
  393. })[0];
  394. if (setNextInput) {
  395. let text = (setNextInput as any).text;
  396. // Ignore the `replace` value and always set the next cell.
  397. cell.model.source = text;
  398. }
  399. }
  400. }
  401. cell.model.contentChanged.disconnect(this.update, this);
  402. this.update();
  403. };
  404. let onFailure = () => {
  405. cell.model.contentChanged.disconnect(this.update, this);
  406. this.update();
  407. };
  408. return cell.execute(this._session.kernel).then(onSuccess, onFailure);
  409. }
  410. /**
  411. * Update the console based on the kernel info.
  412. */
  413. private _handleInfo(info: KernelMessage.IInfoReply): void {
  414. let layout = this._content.layout as PanelLayout;
  415. let banner = layout.widgets.at(0) as RawCellWidget;
  416. banner.model.source = info.banner;
  417. let lang = info.language_info as nbformat.ILanguageInfoMetadata;
  418. this._mimetype = this._renderer.getCodeMimetype(lang);
  419. if (this.prompt) {
  420. this.prompt.mimetype = this._mimetype;
  421. }
  422. }
  423. /**
  424. * Create a new completer widget if necessary and initialize it.
  425. */
  426. private _newCompleter(completer: CompleterWidget): void {
  427. // Instantiate completer widget.
  428. this._completer = completer || new CompleterWidget({
  429. model: new CompleterModel()
  430. });
  431. // Set the completer widget's anchor node to peg its position.
  432. this._completer.anchor = this.node;
  433. // Because a completer widget may be passed in, check if it is attached.
  434. if (!this._completer.isAttached) {
  435. Widget.attach(this._completer, document.body);
  436. }
  437. // Set up the completer handler.
  438. this._completerHandler = new CellCompleterHandler({
  439. completer: this._completer,
  440. kernel: this._session.kernel
  441. });
  442. }
  443. /**
  444. * Create a new foreign cell.
  445. */
  446. private _newForeignCell(): CodeCellWidget {
  447. let cell = this._renderer.createForeignCell(this._rendermime);
  448. cell.readOnly = true;
  449. cell.mimetype = this._mimetype;
  450. cell.addClass(FOREIGN_CELL_CLASS);
  451. return cell;
  452. }
  453. /**
  454. * Test whether we should execute the prompt.
  455. */
  456. private _shouldExecute(timeout: number): Promise<boolean> {
  457. let prompt = this.prompt;
  458. let code = prompt.model.source + '\n';
  459. return new Promise<boolean>((resolve, reject) => {
  460. let timer = setTimeout(() => { resolve(true); }, timeout);
  461. this._session.kernel.isComplete({ code }).then(isComplete => {
  462. clearTimeout(timer);
  463. if (isComplete.content.status !== 'incomplete') {
  464. resolve(true);
  465. return;
  466. }
  467. prompt.model.source = code + isComplete.content.indent;
  468. prompt.editor.setCursorPosition(prompt.model.source.length);
  469. resolve(false);
  470. }).catch(() => { resolve(true); });
  471. });
  472. }
  473. private _completer: CompleterWidget = null;
  474. private _completerHandler: CellCompleterHandler = null;
  475. private _content: Panel = null;
  476. private _foreignHandler: ForeignHandler = null;
  477. private _history: IConsoleHistory = null;
  478. private _input: Panel = null;
  479. private _inspectionHandler: InspectionHandler = null;
  480. private _listening = false;
  481. private _mimetype = 'text/x-ipython';
  482. private _renderer: ConsoleContent.IRenderer = null;
  483. private _rendermime: IRenderMime = null;
  484. private _session: Session.ISession = null;
  485. private _setByHistory = false;
  486. }
  487. // Define the signals for the `ConsoleContent` class.
  488. defineSignal(ConsoleContent.prototype, 'executed');
  489. /**
  490. * A namespace for ConsoleContent statics.
  491. */
  492. export
  493. namespace ConsoleContent {
  494. /**
  495. * The initialization options for a console content widget.
  496. */
  497. export
  498. interface IOptions {
  499. /**
  500. * The completer widget for a console content widget.
  501. */
  502. completer?: CompleterWidget;
  503. /**
  504. * The history manager for a console content widget.
  505. */
  506. history?: IConsoleHistory;
  507. /**
  508. * The renderer for a console content widget.
  509. */
  510. renderer: IRenderer;
  511. /**
  512. * The mime renderer for the console content widget.
  513. */
  514. rendermime: IRenderMime;
  515. /**
  516. * The session for the console content widget.
  517. */
  518. session: Session.ISession;
  519. }
  520. /**
  521. * A renderer for completer widget nodes.
  522. */
  523. export
  524. interface IRenderer {
  525. /**
  526. * Create a new banner widget.
  527. */
  528. createBanner(): RawCellWidget;
  529. /**
  530. * Create a new prompt widget.
  531. */
  532. createPrompt(rendermime: IRenderMime): CodeCellWidget;
  533. /**
  534. * Create a code cell whose input originated from a foreign session.
  535. */
  536. createForeignCell(rendermine: IRenderMime): CodeCellWidget;
  537. /**
  538. * Get the preferred mimetype given language info.
  539. */
  540. getCodeMimetype(info: nbformat.ILanguageInfoMetadata): string;
  541. }
  542. /* tslint:disable */
  543. /**
  544. * The console renderer token.
  545. */
  546. export
  547. const IRenderer = new Token<IRenderer>('jupyter.services.console.renderer');
  548. /* tslint:enable */
  549. }
  550. /**
  551. * A namespace for console widget private data.
  552. */
  553. namespace Private {
  554. /**
  555. * Jump to the bottom of a node.
  556. *
  557. * @param node - The scrollable element.
  558. */
  559. export
  560. function scrollToBottom(node: HTMLElement): void {
  561. node.scrollTop = node.scrollHeight - node.clientHeight;
  562. }
  563. }