|
| 1 | +"use strict"; |
| 2 | + |
| 3 | +import { SocketClient } from './socketClient'; |
| 4 | +import { SocketServer } from '../common/comms/socketServer'; |
| 5 | +import * as child_process from 'child_process'; |
| 6 | +import * as path from 'path'; |
| 7 | +import * as vscode from 'vscode'; |
| 8 | +import { createDeferred, Deferred } from '../common/helpers'; |
| 9 | +import { IClientAdapter } from './IClientAdapter'; |
| 10 | +import { PythonSettings } from '../common/configSettings'; |
| 11 | +import { EventEmitter } from 'events'; |
| 12 | +import { formatErrorForLogging } from '../common/utils'; |
| 13 | +import { TextDocument, Position, CancellationToken } from 'vscode'; |
| 14 | +import { CompletionItem, Definition, Hover, ReferenceContext, Location, SignatureHelp, SymbolInformation } from 'vscode'; |
| 15 | +import { Commands } from "./commands"; |
| 16 | +import { CompletionParser } from './parsers/CompletionParser'; |
| 17 | +import { DefinitionParser } from './parsers/DefinitionParser'; |
| 18 | +import { HoverParser } from './parsers/HoverParser'; |
| 19 | +import { LocationParser } from './parsers/LocationParser'; |
| 20 | +import { SignatureHelpParser } from './parsers/SignatureHelpParser'; |
| 21 | +import { SymbolInformationParser } from './parsers/SymbolInformationParser'; |
| 22 | + |
| 23 | +export class ClientAdapter extends EventEmitter implements IClientAdapter { |
| 24 | + constructor(private outputChannel: vscode.OutputChannel, private rootDir: string) { |
| 25 | + super(); |
| 26 | + } |
| 27 | + |
| 28 | + public getCompletions(token: CancellationToken, fileName: string, columnIndex: number, lineIndex: number, source: string): Promise<CompletionItem[]> { |
| 29 | + return this.socketClient.getResult<any>(Commands.Completions, token, fileName, columnIndex, lineIndex, source) |
| 30 | + .then(CompletionParser.parse); |
| 31 | + } |
| 32 | + public getDefinition(token: CancellationToken, fileName: string, columnIndex: number, lineIndex: number, source: string): Promise<Definition> { |
| 33 | + return this.socketClient.getResult<any>(Commands.Completions, token, fileName, columnIndex, lineIndex, source) |
| 34 | + .then(DefinitionParser.parse); |
| 35 | + } |
| 36 | + public getHoverDefinition(token: CancellationToken, fileName: string, columnIndex: number, lineIndex: number, source: string): Promise<Hover> { |
| 37 | + return this.socketClient.getResult<any>(Commands.Completions, token, fileName, columnIndex, lineIndex, source) |
| 38 | + .then(HoverParser.parse); |
| 39 | + } |
| 40 | + public getReferences(token: CancellationToken, fileName: string, columnIndex: number, lineIndex: number, source: string): Promise<Location[]> { |
| 41 | + return this.socketClient.getResult<any>(Commands.Completions, token, fileName, columnIndex, lineIndex, source) |
| 42 | + .then(DefinitionParser.parse); |
| 43 | + } |
| 44 | + public getSignature(token: CancellationToken, fileName: string, columnIndex: number, lineIndex: number, source: string): Promise<SignatureHelp> { |
| 45 | + return this.socketClient.getResult<any>(Commands.Completions, token, fileName, columnIndex, lineIndex, source) |
| 46 | + .then(SignatureHelpParser.parse); |
| 47 | + } |
| 48 | + public getDocumentSymbols(token: CancellationToken, fileName: string, columnIndex: number, lineIndex: number, source: string): Promise<SymbolInformation[]> { |
| 49 | + return this.socketClient.getResult<any>(Commands.Completions, token, fileName, columnIndex, lineIndex, source) |
| 50 | + .then(SymbolInformationParser.parse); |
| 51 | + } |
| 52 | + |
| 53 | + private process: child_process.ChildProcess; |
| 54 | + private socketServer: SocketServer; |
| 55 | + private socketClient: SocketClient; |
| 56 | + |
| 57 | + private startDef: Deferred<any>; |
| 58 | + |
| 59 | + public dispose() { |
| 60 | + try { |
| 61 | + if (this.process) { |
| 62 | + this.process.stdin.write('\n'); |
| 63 | + } |
| 64 | + } |
| 65 | + catch (ex) { |
| 66 | + } |
| 67 | + try { |
| 68 | + this.socketClient.dispose(); |
| 69 | + } |
| 70 | + catch (ex) { |
| 71 | + } |
| 72 | + try { |
| 73 | + this.socketServer.Stop(); |
| 74 | + } |
| 75 | + catch (ex) { |
| 76 | + } |
| 77 | + this.socketClient = null; |
| 78 | + this.process = null; |
| 79 | + this.socketServer = null; |
| 80 | + this.startDef = null; |
| 81 | + } |
| 82 | + public start(envVariables?: { [key: string]: string }): Promise<any> { |
| 83 | + if (this.startDef) { |
| 84 | + return this.startDef.promise; |
| 85 | + } |
| 86 | + |
| 87 | + this.startDef = createDeferred<any>(); |
| 88 | + const pyFile = path.join(__dirname, '..', '..', '..', '..', 'pythonFiles', 'completionServer.py'); |
| 89 | + const newEnv = {}; |
| 90 | + // const newEnv = {'DEBUG_DJAYAMANNE_IPYTHON':'1'}; |
| 91 | + Object.assign(newEnv, envVariables); |
| 92 | + Object.assign(newEnv, process.env); |
| 93 | + |
| 94 | + this.startSocketServer().then(port => { |
| 95 | + const def = createDeferred<any>(); |
| 96 | + const options = { env: newEnv, cwd: this.rootDir }; |
| 97 | + this.process = child_process.spawn(PythonSettings.getInstance().pythonPath, [pyFile, port.toString()], options); |
| 98 | + this.process.stdout.setEncoding('utf8'); |
| 99 | + this.process.stderr.setEncoding('utf8'); |
| 100 | + |
| 101 | + let processStarted = false; |
| 102 | + let handshakeDone = false; |
| 103 | + let isInTestRun = newEnv['PYTHON_DONJAYAMANNE_TEST'] === "1"; |
| 104 | + const testDef = createDeferred<any>(); |
| 105 | + const promiseToResolve = isInTestRun ? testDef.resolve.bind(testDef) : def.resolve.bind(def); |
| 106 | + |
| 107 | + this.process.stdout.on('data', (data: string) => { |
| 108 | + if (!processStarted && data.split(/\r?\n/g).some(line => line === 'Started')) { |
| 109 | + processStarted = true; |
| 110 | + if (processStarted && handshakeDone) { |
| 111 | + promiseToResolve(); |
| 112 | + } |
| 113 | + return; |
| 114 | + } |
| 115 | + this.outputChannel.append(data); |
| 116 | + }); |
| 117 | + this.process.stderr.on('data', (data: string) => { |
| 118 | + this.outputChannel.append(data); |
| 119 | + }); |
| 120 | + |
| 121 | + this.socketClient.on('handshake', () => { |
| 122 | + handshakeDone = true; |
| 123 | + if (processStarted && handshakeDone) { |
| 124 | + promiseToResolve(); |
| 125 | + } |
| 126 | + }); |
| 127 | + |
| 128 | + // If we're testing, then test the ping and the pong |
| 129 | + // TODO: Better way to test sockets |
| 130 | + if (isInTestRun) { |
| 131 | + testDef.promise.then(() => { |
| 132 | + // Ok everything has started, now test ping |
| 133 | + const msg1 = 'Hello world from Type Script - Функция проверки ИНН и КПП - 长城!1'; |
| 134 | + const msg2 = 'Hello world from Type Script - Функция проверки ИНН и КПП - 长城!2'; |
| 135 | + Promise.all<string, string>([this.socketClient.ping(msg1), this.socketClient.ping(msg2)]).then(msgs => { |
| 136 | + if (msgs.indexOf(msg1) === -1 || msgs.indexOf(msg2) === -1) { |
| 137 | + def.reject('msg1 or msg2 not returned'); |
| 138 | + } |
| 139 | + else { |
| 140 | + def.resolve(); |
| 141 | + } |
| 142 | + }).catch(reason => def.reject(reason)); |
| 143 | + }); |
| 144 | + } |
| 145 | + |
| 146 | + return def.promise; |
| 147 | + }).then(() => { |
| 148 | + this.startDef.resolve(); |
| 149 | + }).catch(reason => { |
| 150 | + this.startDef.reject(reason); |
| 151 | + }); |
| 152 | + |
| 153 | + return this.startDef.promise; |
| 154 | + } |
| 155 | + private startSocketServer(): Promise<number> { |
| 156 | + this.socketServer = new SocketServer(); |
| 157 | + this.socketClient = new SocketClient(this.socketServer, this.outputChannel); |
| 158 | + this.socketClient.on('status', status => { |
| 159 | + this.emit('status', status); |
| 160 | + }); |
| 161 | + this.socketClient.on('error', error => { |
| 162 | + this.emit('error', error); |
| 163 | + console.error(error); |
| 164 | + this.outputChannel.appendLine('Error received: ' + error); |
| 165 | + }); |
| 166 | + this.socketClient.on('commanderror', (commandError: { command: string, id: string, trace: string }) => { |
| 167 | + this.outputChannel.appendLine(`Unhandled command Error from Jupyter. '${JSON.stringify(commandError)}'`); |
| 168 | + }); |
| 169 | + return this.socketServer.Start(); |
| 170 | + } |
| 171 | + |
| 172 | + public getAllKernelSpecs(): Promise<{ [key: string]: Kernelspec }> { |
| 173 | + return this.start().then(() => this.socketClient.listKernelSpecs()); |
| 174 | + } |
| 175 | + private lastStartedKernelUUID: string; |
| 176 | + public startKernel(kernelSpec: KernelspecMetadata): Promise<[string, any, string]> { |
| 177 | + return this.start().then(() => this.getAllKernelSpecs()).then(specks => { |
| 178 | + // ok given the specks, find the name of the kernelspec |
| 179 | + const kernelSpecName = Object.keys(specks).find(kernelSpecName => { |
| 180 | + const spec = specks[kernelSpecName]; |
| 181 | + return spec.spec.display_name === kernelSpec.display_name; |
| 182 | + }); |
| 183 | + return this.socketClient.startKernel(kernelSpecName).then(info => { |
| 184 | + this.lastStartedKernelUUID = info[0]; |
| 185 | + return info; |
| 186 | + }); |
| 187 | + }); |
| 188 | + } |
| 189 | + public shutdownkernel(kernelUUID: string): Promise<any> { |
| 190 | + return this.start().then(() => this.socketClient.sendKernelCommand(kernelUUID, KernelCommand.shutdown)); |
| 191 | + } |
| 192 | + public interruptKernel(kernelUUID: string): Promise<any> { |
| 193 | + return this.start().then(() => this.socketClient.sendKernelCommand(kernelUUID, KernelCommand.interrupt)); |
| 194 | + } |
| 195 | + public restartKernel(kernelUUID: string): Promise<any> { |
| 196 | + return this.start().then(() => this.socketClient.sendKernelCommand(kernelUUID, KernelCommand.restart)); |
| 197 | + } |
| 198 | + public runCode(code: string): Rx.IObservable<ParsedIOMessage> { |
| 199 | + const subject = new Rx.Subject<ParsedIOMessage>(); |
| 200 | + this.start().then(() => { |
| 201 | + const runnerObservable = this.socketClient.runCode(code); |
| 202 | + runnerObservable.subscribe(data => { |
| 203 | + subject.onNext(data); |
| 204 | + }, reason => { |
| 205 | + subject.onError(reason); |
| 206 | + }, () => { |
| 207 | + subject.onCompleted(); |
| 208 | + }); |
| 209 | + }).catch(reason => { |
| 210 | + subject.onError(reason); |
| 211 | + }); |
| 212 | + |
| 213 | + return subject; |
| 214 | + } |
| 215 | +} |
0 commit comments