content.ts 17 KB

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