content.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612
  1. // Copyright (c) Jupyter Development Team.
  2. // Distributed under the terms of the Modified BSD License.
  3. import {
  4. ISession, KernelMessage
  5. } from 'jupyter-js-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
  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. * Display inputs/outputs initated by another session.
  146. */
  147. protected monitorForeignIOPub(): void {
  148. this._session.kernel.iopubMessage.connect((kernel, msg) => {
  149. // Check whether this message came from an external session.
  150. let session = (msg.parent_header as KernelMessage.IHeader).session;
  151. if (session === this.session.kernel.clientId) {
  152. return;
  153. }
  154. let msgType = msg.header.msg_type as nbformat.OutputType;
  155. let parentHeader = msg.parent_header as KernelMessage.IHeader;
  156. let parentMsgId = parentHeader.msg_id as string;
  157. let cell : CodeCellWidget;
  158. switch (msgType) {
  159. case 'execute_input':
  160. let inputMsg = msg as KernelMessage.IExecuteInputMsg;
  161. cell = this.newForeignCell(parentMsgId);
  162. cell.model.executionCount = inputMsg.content.execution_count;
  163. cell.model.source = inputMsg.content.code;
  164. cell.trusted = true;
  165. this.update();
  166. break;
  167. case 'execute_result':
  168. case 'clear_output':
  169. case 'display_data':
  170. case 'stream':
  171. case 'error':
  172. if (!(parentMsgId in this._foreignCells)) {
  173. // This is an output from an input that was broadcast before our
  174. // session started listening. We will ignore it.
  175. console.warn('Ignoring output with no associated input cell.');
  176. break;
  177. }
  178. cell = this._foreignCells[parentMsgId];
  179. let output = msg.content as nbformat.IOutput;
  180. output.output_type = msgType;
  181. cell.model.outputs.add(output);
  182. this.update();
  183. break;
  184. default:
  185. break;
  186. }
  187. });
  188. }
  189. /**
  190. * A signal emitted when the console executes its prompt.
  191. */
  192. executed: ISignal<ConsoleContent, Date>;
  193. /**
  194. * Get the inspection handler used by the console.
  195. *
  196. * #### Notes
  197. * This is a read-only property.
  198. */
  199. get inspectionHandler(): InspectionHandler {
  200. return this._inspectionHandler;
  201. }
  202. /*
  203. * The last cell in a console is always a `CodeCellWidget` prompt.
  204. */
  205. get prompt(): CodeCellWidget {
  206. let inputLayout = (this._input.layout as PanelLayout);
  207. return inputLayout.widgets.at(0) as CodeCellWidget || null;
  208. }
  209. /**
  210. * Get the session used by the console.
  211. *
  212. * #### Notes
  213. * This is a read-only property.
  214. */
  215. get session(): ISession {
  216. return this._session;
  217. }
  218. /**
  219. * Dispose of the resources held by the widget.
  220. */
  221. dispose() {
  222. // Do nothing if already disposed.
  223. if (this.isDisposed) {
  224. return;
  225. }
  226. this._history.dispose();
  227. this._history = null;
  228. this._completerHandler.dispose();
  229. this._completerHandler = null;
  230. this._completer.dispose();
  231. this._completer = null;
  232. this._inspectionHandler.dispose();
  233. this._inspectionHandler = null;
  234. this._session.dispose();
  235. this._session = null;
  236. this._foreignCells = null;
  237. super.dispose();
  238. }
  239. /**
  240. * Execute the current prompt.
  241. *
  242. * @param force - Whether to force execution without checking code
  243. * completeness.
  244. */
  245. execute(force=false): Promise<void> {
  246. this.dismissCompleter();
  247. if (this._session.status === 'dead') {
  248. this._inspectionHandler.handleExecuteReply(null);
  249. return;
  250. }
  251. let prompt = this.prompt;
  252. prompt.trusted = true;
  253. if (force) {
  254. return this._execute();
  255. }
  256. // Check whether we should execute.
  257. return this._shouldExecute().then(value => {
  258. if (value) {
  259. return this._execute();
  260. }
  261. });
  262. }
  263. /**
  264. * Clear the code cells.
  265. */
  266. clear(): void {
  267. while (this.prompt) {
  268. this.prompt.dispose();
  269. }
  270. this.newPrompt();
  271. }
  272. /**
  273. * Insert a line break in the prompt.
  274. */
  275. insertLinebreak(): void {
  276. let prompt = this.prompt;
  277. let model = prompt.model;
  278. model.source += '\n';
  279. prompt.editor.setCursorPosition(model.source.length);
  280. }
  281. /**
  282. * Dismiss the completer widget for a console.
  283. */
  284. dismissCompleter(): void {
  285. this._completer.reset();
  286. }
  287. /**
  288. * Serialize the output.
  289. */
  290. serialize(): nbformat.ICodeCell[] {
  291. let output: nbformat.ICodeCell[] = [];
  292. let layout = this._content.layout as PanelLayout;
  293. for (let i = 1; i < layout.widgets.length; i++) {
  294. let widget = layout.widgets.at(i) as CodeCellWidget;
  295. output.push(widget.model.toJSON());
  296. }
  297. output.push(this.prompt.model.toJSON());
  298. return output;
  299. }
  300. /**
  301. * Handle `'activate-request'` messages.
  302. */
  303. protected onActivateRequest(msg: Message): void {
  304. this.prompt.activate();
  305. }
  306. /**
  307. * Handle an edge requested signal.
  308. */
  309. protected onEdgeRequest(editor: ICellEditorWidget, location: EdgeLocation): void {
  310. let prompt = this.prompt;
  311. if (location === 'top') {
  312. this._history.back().then(value => {
  313. if (!value) {
  314. return;
  315. }
  316. prompt.model.source = value;
  317. prompt.editor.setCursorPosition(0);
  318. });
  319. } else {
  320. this._history.forward().then(value => {
  321. // If at the bottom end of history, then clear the prompt.
  322. let text = value || '';
  323. prompt.model.source = text;
  324. prompt.editor.setCursorPosition(text.length);
  325. });
  326. }
  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. * Initialize the banner and mimetype.
  337. */
  338. protected initialize(): void {
  339. let session = this._session;
  340. if (session.kernel.info) {
  341. this._handleInfo(this._session.kernel.info);
  342. return;
  343. }
  344. session.kernel.kernelInfo().then(msg => this._handleInfo(msg.content));
  345. }
  346. /**
  347. * Make a new prompt.
  348. */
  349. protected newPrompt(): void {
  350. let prompt = this.prompt;
  351. let content = this._content;
  352. let input = this._input;
  353. // Make the last prompt read-only, clear its signals, and move to content.
  354. if (prompt) {
  355. prompt.readOnly = true;
  356. prompt.removeClass(PROMPT_CLASS);
  357. clearSignalData(prompt.editor);
  358. content.addWidget((input.layout as PanelLayout).removeWidgetAt(0));
  359. }
  360. // Create the new prompt.
  361. prompt = this._renderer.createPrompt(this._rendermime);
  362. prompt.mimetype = this._mimetype;
  363. prompt.addClass(PROMPT_CLASS);
  364. this._input.addWidget(prompt);
  365. // Hook up completer and history handling.
  366. let editor = prompt.editor;
  367. editor.edgeRequested.connect(this.onEdgeRequest, this);
  368. // Associate the new prompt with the completer and inspection handlers.
  369. this._completerHandler.activeCell = prompt;
  370. this._inspectionHandler.activeCell = prompt;
  371. prompt.activate();
  372. this.update();
  373. }
  374. /**
  375. * Make a new code cell for an input originated from a foreign session.
  376. */
  377. protected newForeignCell(parentMsgId: string): CodeCellWidget {
  378. let cell = this._renderer.createForeignCell(this._rendermime);
  379. cell.mimetype = this._mimetype;
  380. cell.addClass(FOREIGN_CELL_CLASS);
  381. this._content.addWidget(cell);
  382. this.update();
  383. this._foreignCells[parentMsgId] = cell;
  384. return cell;
  385. }
  386. /**
  387. * Test whether we should execute the prompt.
  388. */
  389. private _shouldExecute(): Promise<boolean> {
  390. let prompt = this.prompt;
  391. let code = prompt.model.source + '\n';
  392. return new Promise<boolean>((resolve, reject) => {
  393. let timer = setTimeout(() => { resolve(true); }, EXECUTION_TIMEOUT);
  394. this._session.kernel.isComplete({ code }).then(isComplete => {
  395. clearTimeout(timer);
  396. if (isComplete.content.status !== 'incomplete') {
  397. resolve(true);
  398. return;
  399. }
  400. prompt.model.source = code + isComplete.content.indent;
  401. prompt.editor.setCursorPosition(prompt.model.source.length);
  402. resolve(false);
  403. }).catch(() => { resolve(true); });
  404. });
  405. }
  406. /**
  407. * Execute the code in the current prompt.
  408. */
  409. private _execute(): Promise<void> {
  410. let prompt = this.prompt;
  411. this._history.push(prompt.model.source);
  412. // Create a new prompt before kernel execution to allow typeahead.
  413. this.newPrompt();
  414. let onSuccess = (value: KernelMessage.IExecuteReplyMsg) => {
  415. this.executed.emit(new Date());
  416. if (!value) {
  417. this._inspectionHandler.handleExecuteReply(null);
  418. return;
  419. }
  420. if (value.content.status === 'ok') {
  421. let content = value.content as KernelMessage.IExecuteOkReply;
  422. this._inspectionHandler.handleExecuteReply(content);
  423. // Use deprecated payloads for backwards compatibility.
  424. if (content.payload && content.payload.length) {
  425. let setNextInput = content.payload.filter(i => {
  426. return (i as any).source === 'set_next_input';
  427. })[0];
  428. if (setNextInput) {
  429. let text = (setNextInput as any).text;
  430. // Ignore the `replace` value and always set the next prompt.
  431. this.prompt.model.source = text;
  432. }
  433. }
  434. }
  435. this.update();
  436. };
  437. let onFailure = () => { this.update(); };
  438. return prompt.execute(this._session.kernel).then(onSuccess, onFailure);
  439. }
  440. /**
  441. * Update the console based on the kernel info.
  442. */
  443. private _handleInfo(info: KernelMessage.IInfoReply): void {
  444. let layout = this._content.layout as PanelLayout;
  445. let banner = layout.widgets.at(0) as RawCellWidget;
  446. banner.model.source = info.banner;
  447. this._mimetype = mimetypeForLanguage(info.language_info);
  448. this.prompt.mimetype = this._mimetype;
  449. }
  450. private _completer: CompleterWidget = null;
  451. private _completerHandler: CellCompleterHandler = null;
  452. private _content: Panel = null;
  453. private _input: Panel = null;
  454. private _inspectionHandler: InspectionHandler = null;
  455. private _mimetype = 'text/x-ipython';
  456. private _rendermime: IRenderMime = null;
  457. private _renderer: ConsoleContent.IRenderer = null;
  458. private _history: IConsoleHistory = null;
  459. private _session: ISession = null;
  460. private _foreignCells: { [key: string]: CodeCellWidget; } = {};
  461. }
  462. // Define the signals for the `ConsoleContent` class.
  463. defineSignal(ConsoleContent.prototype, 'executed');
  464. /**
  465. * A namespace for ConsoleContent statics.
  466. */
  467. export
  468. namespace ConsoleContent {
  469. /**
  470. * The initialization options for a console content widget.
  471. */
  472. export
  473. interface IOptions {
  474. /**
  475. * The completer widget for a console content widget.
  476. */
  477. completer?: CompleterWidget;
  478. /**
  479. * The renderer for a console content widget.
  480. */
  481. renderer: IRenderer;
  482. /**
  483. * The mime renderer for the console content widget.
  484. */
  485. rendermime: IRenderMime;
  486. /**
  487. * The session for the console content widget.
  488. */
  489. session: ISession;
  490. }
  491. /**
  492. * A renderer for completer widget nodes.
  493. */
  494. export
  495. interface IRenderer {
  496. /**
  497. * Create a new banner widget.
  498. */
  499. createBanner(): RawCellWidget;
  500. /**
  501. * Create a new prompt widget.
  502. */
  503. createPrompt(rendermime: IRenderMime): CodeCellWidget;
  504. /**
  505. * Create a code cell whose input originated from a foreign session.
  506. * The implementor is expected to make this read-only.
  507. */
  508. createForeignCell(rendermine: IRenderMime): CodeCellWidget;
  509. }
  510. /* tslint:disable */
  511. /**
  512. * The console renderer token.
  513. */
  514. export
  515. const IRenderer = new Token<IRenderer>('jupyter.services.console.renderer');
  516. /* tslint:enable */
  517. }
  518. /**
  519. * A namespace for console widget private data.
  520. */
  521. namespace Private {
  522. /**
  523. * Jump to the bottom of a node.
  524. *
  525. * @param node - The scrollable element.
  526. */
  527. export
  528. function scrollToBottom(node: HTMLElement): void {
  529. node.scrollTop = node.scrollHeight;
  530. }
  531. }