hunk
dict
file
stringlengths
0
11.8M
file_path
stringlengths
2
234
label
int64
0
1
commit_url
stringlengths
74
103
dependency_score
listlengths
5
5
{ "id": 5, "code_window": [ "var fs = require(\"fs\");\n", "var _ = require(\"lodash\");\n", "\n", "exports.util = require(\"./util\");\n", "\n", "exports.register = function () {\n", " return require(\"./register\");\n", "};\n", "\n", "exports.polyfill = function () {\n", " require(\"./polyfill\");\n", "};\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "exports.register = function (opts) {\n", " var register = require(\"./register\");\n", " if (opts != null) register(opts);\n", " return register;\n" ], "file_path": "lib/6to5/index.js", "type": "replace", "edit_start_line_idx": 6 }
function add() { return [for (i of [1, 2, 3]) i * this.multiplier]; } add.call({ multiplier: 5 });
test/fixtures/syntax/array-comprehension/this/actual.js
0
https://github.com/babel/babel/commit/45c8c29cdfebcce1e36fe2cbd6a56f14862ece2a
[ 0.00016993135795928538, 0.00016993135795928538, 0.00016993135795928538, 0.00016993135795928538, 0 ]
{ "id": 5, "code_window": [ "var fs = require(\"fs\");\n", "var _ = require(\"lodash\");\n", "\n", "exports.util = require(\"./util\");\n", "\n", "exports.register = function () {\n", " return require(\"./register\");\n", "};\n", "\n", "exports.polyfill = function () {\n", " require(\"./polyfill\");\n", "};\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "exports.register = function (opts) {\n", " var register = require(\"./register\");\n", " if (opts != null) register(opts);\n", " return register;\n" ], "file_path": "lib/6to5/index.js", "type": "replace", "edit_start_line_idx": 6 }
{ "args": ["--source-maps-inline"] }
test/fixtures/bin/6to5/stdin --source-maps-inline/options.json
0
https://github.com/babel/babel/commit/45c8c29cdfebcce1e36fe2cbd6a56f14862ece2a
[ 0.00017511429905425757, 0.00017511429905425757, 0.00017511429905425757, 0.00017511429905425757, 0 ]
{ "id": 6, "code_window": [ " node.body = b.blockStatement(block);\n", "};\n", "\n", "exports.getUid = function (parent, file) {\n", " var node;\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "exports.list = function (val) {\n", " return val ? val.split(\",\") : [];\n", "};\n", "\n" ], "file_path": "lib/6to5/util.js", "type": "add", "edit_start_line_idx": 22 }
#!/usr/bin/env node var commander = require("commander"); var Module = require("module"); var path = require("path"); var util = require("../lib/6to5/util"); var path = require("path"); var repl = require("repl"); var to5 = require("../lib/6to5"); var vm = require("vm"); var _ = require("lodash"); commander.option("-e, --eval [script]", "evaluate script"); commander.option("-p, --print", "evaluate script and print result"); var pkg = require("../package.json"); commander.version(pkg.version); commander.usage("[options] [ -e script | script.js ] [arguments]"); commander.parse(process.argv); to5.register(); var _eval = function (code, filename) { code = to5.transform(code, { filename: filename }).code; return vm.runInThisContext(code, filename); }; if (commander.eval) { var code = to5.transform(commander.eval, { filename: "eval" }).code; var result = _eval(code, "eval"); if (commander.print) console.log(result); } else { var filenames = commander.args; if (filenames.length) { _.each(filenames, function (filename) { if (!util.isAbsolute(filename)) { filename = path.join(process.cwd(), filename); } require(require.resolve(filename)); }); } else { replStart(); } } function replStart() { repl.start({ prompt: "> ", input: process.stdin, output: process.stdout, eval: replEval, useGlobal: true }); } function replEval(code, context, filename, callback) { var err; var result; try { code = code.slice(1, -2); // remove "(" and "\n)" result = _eval(code, filename); } catch (e) { err = e; } callback(err, result); }
bin/6to5-node
1
https://github.com/babel/babel/commit/45c8c29cdfebcce1e36fe2cbd6a56f14862ece2a
[ 0.00017951976042240858, 0.00017546229355502874, 0.00016731530195102096, 0.00017679797019809484, 0.0000038039011087676045 ]
{ "id": 6, "code_window": [ " node.body = b.blockStatement(block);\n", "};\n", "\n", "exports.getUid = function (parent, file) {\n", " var node;\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "exports.list = function (val) {\n", " return val ? val.split(\",\") : [];\n", "};\n", "\n" ], "file_path": "lib/6to5/util.js", "type": "add", "edit_start_line_idx": 22 }
CLASS_NAME.__proto__ = SUPER_NAME;
lib/6to5/templates/class-inherits-properties.js
0
https://github.com/babel/babel/commit/45c8c29cdfebcce1e36fe2cbd6a56f14862ece2a
[ 0.00016928123659454286, 0.00016928123659454286, 0.00016928123659454286, 0.00016928123659454286, 0 ]
{ "id": 6, "code_window": [ " node.body = b.blockStatement(block);\n", "};\n", "\n", "exports.getUid = function (parent, file) {\n", " var node;\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "exports.list = function (val) {\n", " return val ? val.split(\",\") : [];\n", "};\n", "\n" ], "file_path": "lib/6to5/util.js", "type": "add", "edit_start_line_idx": 22 }
arr.map(function (x) { return x * x; });
test/fixtures/syntax/source-maps/full/expected.js
0
https://github.com/babel/babel/commit/45c8c29cdfebcce1e36fe2cbd6a56f14862ece2a
[ 0.00017709669191390276, 0.00017709669191390276, 0.00017709669191390276, 0.00017709669191390276, 0 ]
{ "id": 6, "code_window": [ " node.body = b.blockStatement(block);\n", "};\n", "\n", "exports.getUid = function (parent, file) {\n", " var node;\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "exports.list = function (val) {\n", " return val ? val.split(\",\") : [];\n", "};\n", "\n" ], "file_path": "lib/6to5/util.js", "type": "add", "edit_start_line_idx": 22 }
module.exports = require("./lib/6to5/register");
register.js
0
https://github.com/babel/babel/commit/45c8c29cdfebcce1e36fe2cbd6a56f14862ece2a
[ 0.00017188330821227282, 0.00017188330821227282, 0.00017188330821227282, 0.00017188330821227282, 0 ]
{ "id": 0, "code_window": [ "\t\t}\n", "\t}\n", "\n", "\t(/** @type {any} */ (window)).createWebviewManager({\n", "\t\tpostMessage: hostMessaging.postMessage.bind(hostMessaging),\n", "\t\tonMessage: hostMessaging.onMessage.bind(hostMessaging),\n", "\t\tready: workerReady,\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t/** @type {import('./main').WebviewHost} */\n", "\tconst host = {\n" ], "file_path": "src/vs/workbench/contrib/webview/browser/pre/host.js", "type": "replace", "edit_start_line_idx": 92 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // @ts-check (function () { const id = document.location.search.match(/\bid=([\w-]+)/)[1]; const hostMessaging = new class HostMessaging { constructor() { this.handlers = new Map(); window.addEventListener('message', (e) => { if (e.data && (e.data.command === 'onmessage' || e.data.command === 'do-update-state')) { // Came from inner iframe this.postMessage(e.data.command, e.data.data); return; } const channel = e.data.channel; const handler = this.handlers.get(channel); if (handler) { handler(e, e.data.args); } else { console.log('no handler for ', e); } }); } postMessage(channel, data) { window.parent.postMessage({ target: id, channel, data }, '*'); } onMessage(channel, handler) { this.handlers.set(channel, handler); } }(); const workerReady = new Promise(async (resolveWorkerReady) => { if (!areServiceWorkersEnabled()) { console.log('Service Workers are not enabled. Webviews will not work properly'); return resolveWorkerReady(); } const expectedWorkerVersion = 1; navigator.serviceWorker.register('service-worker.js').then(async registration => { await navigator.serviceWorker.ready; const versionHandler = (event) => { if (event.data.channel !== 'version') { return; } navigator.serviceWorker.removeEventListener('message', versionHandler); if (event.data.version === expectedWorkerVersion) { return resolveWorkerReady(); } else { // If we have the wrong version, try once to unregister and re-register return registration.update() .then(() => navigator.serviceWorker.ready) .finally(resolveWorkerReady); } }; navigator.serviceWorker.addEventListener('message', versionHandler); registration.active.postMessage({ channel: 'version' }); }); const forwardFromHostToWorker = (channel) => { hostMessaging.onMessage(channel, event => { navigator.serviceWorker.ready.then(registration => { registration.active.postMessage({ channel: channel, data: event.data.args }); }); }); }; forwardFromHostToWorker('did-load-resource'); forwardFromHostToWorker('did-load-localhost'); navigator.serviceWorker.addEventListener('message', event => { if (['load-resource', 'load-localhost'].includes(event.data.channel)) { hostMessaging.postMessage(event.data.channel, event.data); } }); }); function areServiceWorkersEnabled() { try { return !!navigator.serviceWorker; } catch (e) { return false; } } (/** @type {any} */ (window)).createWebviewManager({ postMessage: hostMessaging.postMessage.bind(hostMessaging), onMessage: hostMessaging.onMessage.bind(hostMessaging), ready: workerReady, fakeLoad: true, rewriteCSP: (csp, endpoint) => { const endpointUrl = new URL(endpoint); csp.setAttribute('content', csp.replace(/(vscode-webview-resource|vscode-resource):(?=(\s|;|$))/g, endpointUrl.origin)); } }); }());
src/vs/workbench/contrib/webview/browser/pre/host.js
1
https://github.com/microsoft/vscode/commit/a20f2e6ba5a2114dabad5bd68a61dc549b2c9d52
[ 0.08136777579784393, 0.010152209550142288, 0.00016388358199037611, 0.00017563953588251024, 0.023326100781559944 ]
{ "id": 0, "code_window": [ "\t\t}\n", "\t}\n", "\n", "\t(/** @type {any} */ (window)).createWebviewManager({\n", "\t\tpostMessage: hostMessaging.postMessage.bind(hostMessaging),\n", "\t\tonMessage: hostMessaging.onMessage.bind(hostMessaging),\n", "\t\tready: workerReady,\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t/** @type {import('./main').WebviewHost} */\n", "\tconst host = {\n" ], "file_path": "src/vs/workbench/contrib/webview/browser/pre/host.js", "type": "replace", "edit_start_line_idx": 92 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { mkdir, open, close, read, write, fdatasync, Dirent, Stats } from 'fs'; import { promisify } from 'util'; import { IDisposable, Disposable, toDisposable, dispose, combinedDisposable } from 'vs/base/common/lifecycle'; import { FileSystemProviderCapabilities, IFileChange, IWatchOptions, IStat, FileType, FileDeleteOptions, FileOverwriteOptions, FileWriteOptions, FileOpenOptions, FileSystemProviderErrorCode, createFileSystemProviderError, FileSystemProviderError, IFileSystemProviderWithFileReadWriteCapability, IFileSystemProviderWithFileReadStreamCapability, IFileSystemProviderWithOpenReadWriteCloseCapability, FileReadStreamOptions, IFileSystemProviderWithFileFolderCopyCapability } from 'vs/platform/files/common/files'; import { URI } from 'vs/base/common/uri'; import { Event, Emitter } from 'vs/base/common/event'; import { isLinux, isWindows } from 'vs/base/common/platform'; import { statLink, unlink, move, copy, readFile, truncate, rimraf, RimRafMode, exists, readdirWithFileTypes } from 'vs/base/node/pfs'; import { normalize, basename, dirname } from 'vs/base/common/path'; import { joinPath } from 'vs/base/common/resources'; import { isEqual } from 'vs/base/common/extpath'; import { retry, ThrottledDelayer } from 'vs/base/common/async'; import { ILogService, LogLevel } from 'vs/platform/log/common/log'; import { localize } from 'vs/nls'; import { IDiskFileChange, toFileChanges, ILogMessage } from 'vs/platform/files/node/watcher/watcher'; import { FileWatcher as UnixWatcherService } from 'vs/platform/files/node/watcher/unix/watcherService'; import { FileWatcher as WindowsWatcherService } from 'vs/platform/files/node/watcher/win32/watcherService'; import { FileWatcher as NsfwWatcherService } from 'vs/platform/files/node/watcher/nsfw/watcherService'; import { FileWatcher as NodeJSWatcherService } from 'vs/platform/files/node/watcher/nodejs/watcherService'; import { CancellationToken } from 'vs/base/common/cancellation'; import { ReadableStreamEvents, newWriteableStream } from 'vs/base/common/stream'; import { readFileIntoStream } from 'vs/platform/files/common/io'; import { insert } from 'vs/base/common/arrays'; import { VSBuffer } from 'vs/base/common/buffer'; export interface IWatcherOptions { pollingInterval?: number; usePolling: boolean; } export interface IDiskFileSystemProviderOptions { bufferSize?: number; watcher?: IWatcherOptions; } export class DiskFileSystemProvider extends Disposable implements IFileSystemProviderWithFileReadWriteCapability, IFileSystemProviderWithOpenReadWriteCloseCapability, IFileSystemProviderWithFileReadStreamCapability, IFileSystemProviderWithFileFolderCopyCapability { private readonly BUFFER_SIZE = this.options?.bufferSize || 64 * 1024; constructor(private logService: ILogService, private options?: IDiskFileSystemProviderOptions) { super(); } //#region File Capabilities onDidChangeCapabilities: Event<void> = Event.None; protected _capabilities: FileSystemProviderCapabilities | undefined; get capabilities(): FileSystemProviderCapabilities { if (!this._capabilities) { this._capabilities = FileSystemProviderCapabilities.FileReadWrite | FileSystemProviderCapabilities.FileOpenReadWriteClose | FileSystemProviderCapabilities.FileReadStream | FileSystemProviderCapabilities.FileFolderCopy; if (isLinux) { this._capabilities |= FileSystemProviderCapabilities.PathCaseSensitive; } } return this._capabilities; } //#endregion //#region File Metadata Resolving async stat(resource: URI): Promise<IStat> { try { const { stat, symbolicLink } = await statLink(this.toFilePath(resource)); // cannot use fs.stat() here to support links properly return { type: this.toType(stat, symbolicLink), ctime: stat.birthtime.getTime(), // intentionally not using ctime here, we want the creation time mtime: stat.mtime.getTime(), size: stat.size }; } catch (error) { throw this.toFileSystemProviderError(error); } } async readdir(resource: URI): Promise<[string, FileType][]> { try { const children = await readdirWithFileTypes(this.toFilePath(resource)); const result: [string, FileType][] = []; await Promise.all(children.map(async child => { try { let type: FileType; if (child.isSymbolicLink()) { type = (await this.stat(joinPath(resource, child.name))).type; // always resolve target the link points to if any } else { type = this.toType(child); } result.push([child.name, type]); } catch (error) { this.logService.trace(error); // ignore errors for individual entries that can arise from permission denied } })); return result; } catch (error) { throw this.toFileSystemProviderError(error); } } private toType(entry: Stats | Dirent, symbolicLink?: { dangling: boolean }): FileType { // Signal file type by checking for file / directory, except: // - symbolic links pointing to non-existing files are FileType.Unknown // - files that are neither file nor directory are FileType.Unknown let type: FileType; if (symbolicLink?.dangling) { type = FileType.Unknown; } else if (entry.isFile()) { type = FileType.File; } else if (entry.isDirectory()) { type = FileType.Directory; } else { type = FileType.Unknown; } // Always signal symbolic link as file type additionally if (symbolicLink) { type |= FileType.SymbolicLink; } return type; } //#endregion //#region File Reading/Writing async readFile(resource: URI): Promise<Uint8Array> { try { const filePath = this.toFilePath(resource); return await readFile(filePath); } catch (error) { throw this.toFileSystemProviderError(error); } } readFileStream(resource: URI, opts: FileReadStreamOptions, token: CancellationToken): ReadableStreamEvents<Uint8Array> { const stream = newWriteableStream<Uint8Array>(data => VSBuffer.concat(data.map(data => VSBuffer.wrap(data))).buffer); readFileIntoStream(this, resource, stream, data => data.buffer, { ...opts, bufferSize: this.BUFFER_SIZE }, token); return stream; } async writeFile(resource: URI, content: Uint8Array, opts: FileWriteOptions): Promise<void> { let handle: number | undefined = undefined; try { const filePath = this.toFilePath(resource); // Validate target unless { create: true, overwrite: true } if (!opts.create || !opts.overwrite) { const fileExists = await exists(filePath); if (fileExists) { if (!opts.overwrite) { throw createFileSystemProviderError(localize('fileExists', "File already exists"), FileSystemProviderErrorCode.FileExists); } } else { if (!opts.create) { throw createFileSystemProviderError(localize('fileNotExists', "File does not exist"), FileSystemProviderErrorCode.FileNotFound); } } } // Open handle = await this.open(resource, { create: true }); // Write content at once await this.write(handle, 0, content, 0, content.byteLength); } catch (error) { throw this.toFileSystemProviderError(error); } finally { if (typeof handle === 'number') { await this.close(handle); } } } private mapHandleToPos: Map<number, number> = new Map(); private writeHandles: Set<number> = new Set(); private canFlush: boolean = true; async open(resource: URI, opts: FileOpenOptions): Promise<number> { try { const filePath = this.toFilePath(resource); let flags: string | undefined = undefined; if (opts.create) { if (isWindows && await exists(filePath)) { try { // On Windows and if the file exists, we use a different strategy of saving the file // by first truncating the file and then writing with r+ flag. This helps to save hidden files on Windows // (see https://github.com/Microsoft/vscode/issues/931) and prevent removing alternate data streams // (see https://github.com/Microsoft/vscode/issues/6363) await truncate(filePath, 0); // After a successful truncate() the flag can be set to 'r+' which will not truncate. flags = 'r+'; } catch (error) { this.logService.trace(error); } } // we take opts.create as a hint that the file is opened for writing // as such we use 'w' to truncate an existing or create the // file otherwise. we do not allow reading. if (!flags) { flags = 'w'; } } else { // otherwise we assume the file is opened for reading // as such we use 'r' to neither truncate, nor create // the file. flags = 'r'; } const handle = await promisify(open)(filePath, flags); // remember this handle to track file position of the handle // we init the position to 0 since the file descriptor was // just created and the position was not moved so far (see // also http://man7.org/linux/man-pages/man2/open.2.html - // "The file offset is set to the beginning of the file.") this.mapHandleToPos.set(handle, 0); // remember that this handle was used for writing if (opts.create) { this.writeHandles.add(handle); } return handle; } catch (error) { throw this.toFileSystemProviderError(error); } } async close(fd: number): Promise<void> { try { // remove this handle from map of positions this.mapHandleToPos.delete(fd); // if a handle is closed that was used for writing, ensure // to flush the contents to disk if possible. if (this.writeHandles.delete(fd) && this.canFlush) { try { await promisify(fdatasync)(fd); } catch (error) { // In some exotic setups it is well possible that node fails to sync // In that case we disable flushing and log the error to our logger this.canFlush = false; this.logService.error(error); } } return await promisify(close)(fd); } catch (error) { throw this.toFileSystemProviderError(error); } } async read(fd: number, pos: number, data: Uint8Array, offset: number, length: number): Promise<number> { const normalizedPos = this.normalizePos(fd, pos); let bytesRead: number | null = null; try { const result = await promisify(read)(fd, data, offset, length, normalizedPos); if (typeof result === 'number') { bytesRead = result; // node.d.ts fail } else { bytesRead = result.bytesRead; } return bytesRead; } catch (error) { throw this.toFileSystemProviderError(error); } finally { this.updatePos(fd, normalizedPos, bytesRead); } } private normalizePos(fd: number, pos: number): number | null { // when calling fs.read/write we try to avoid passing in the "pos" argument and // rather prefer to pass in "null" because this avoids an extra seek(pos) // call that in some cases can even fail (e.g. when opening a file over FTP - // see https://github.com/microsoft/vscode/issues/73884). // // as such, we compare the passed in position argument with our last known // position for the file descriptor and use "null" if they match. if (pos === this.mapHandleToPos.get(fd)) { return null; } return pos; } private updatePos(fd: number, pos: number | null, bytesLength: number | null): void { const lastKnownPos = this.mapHandleToPos.get(fd); if (typeof lastKnownPos === 'number') { // pos !== null signals that previously a position was used that is // not null. node.js documentation explains, that in this case // the internal file pointer is not moving and as such we do not move // our position pointer. // // Docs: "If position is null, data will be read from the current file position, // and the file position will be updated. If position is an integer, the file position // will remain unchanged." if (typeof pos === 'number') { // do not modify the position } // bytesLength = number is a signal that the read/write operation was // successful and as such we need to advance the position in the Map // // Docs (http://man7.org/linux/man-pages/man2/read.2.html): // "On files that support seeking, the read operation commences at the // file offset, and the file offset is incremented by the number of // bytes read." // // Docs (http://man7.org/linux/man-pages/man2/write.2.html): // "For a seekable file (i.e., one to which lseek(2) may be applied, for // example, a regular file) writing takes place at the file offset, and // the file offset is incremented by the number of bytes actually // written." else if (typeof bytesLength === 'number') { this.mapHandleToPos.set(fd, lastKnownPos + bytesLength); } // bytesLength = null signals an error in the read/write operation // and as such we drop the handle from the Map because the position // is unspecificed at this point. else { this.mapHandleToPos.delete(fd); } } } async write(fd: number, pos: number, data: Uint8Array, offset: number, length: number): Promise<number> { // we know at this point that the file to write to is truncated and thus empty // if the write now fails, the file remains empty. as such we really try hard // to ensure the write succeeds by retrying up to three times. return retry(() => this.doWrite(fd, pos, data, offset, length), 100 /* ms delay */, 3 /* retries */); } private async doWrite(fd: number, pos: number, data: Uint8Array, offset: number, length: number): Promise<number> { const normalizedPos = this.normalizePos(fd, pos); let bytesWritten: number | null = null; try { const result = await promisify(write)(fd, data, offset, length, normalizedPos); if (typeof result === 'number') { bytesWritten = result; // node.d.ts fail } else { bytesWritten = result.bytesWritten; } return bytesWritten; } catch (error) { throw this.toFileSystemProviderError(error); } finally { this.updatePos(fd, normalizedPos, bytesWritten); } } //#endregion //#region Move/Copy/Delete/Create Folder async mkdir(resource: URI): Promise<void> { try { await promisify(mkdir)(this.toFilePath(resource)); } catch (error) { throw this.toFileSystemProviderError(error); } } async delete(resource: URI, opts: FileDeleteOptions): Promise<void> { try { const filePath = this.toFilePath(resource); await this.doDelete(filePath, opts); } catch (error) { throw this.toFileSystemProviderError(error); } } protected async doDelete(filePath: string, opts: FileDeleteOptions): Promise<void> { if (opts.recursive) { await rimraf(filePath, RimRafMode.MOVE); } else { await unlink(filePath); } } async rename(from: URI, to: URI, opts: FileOverwriteOptions): Promise<void> { const fromFilePath = this.toFilePath(from); const toFilePath = this.toFilePath(to); if (fromFilePath === toFilePath) { return; // simulate node.js behaviour here and do a no-op if paths match } try { // Ensure target does not exist await this.validateTargetDeleted(from, to, 'move', opts.overwrite); // Move await move(fromFilePath, toFilePath); } catch (error) { // rewrite some typical errors that can happen especially around symlinks // to something the user can better understand if (error.code === 'EINVAL' || error.code === 'EBUSY' || error.code === 'ENAMETOOLONG') { error = new Error(localize('moveError', "Unable to move '{0}' into '{1}' ({2}).", basename(fromFilePath), basename(dirname(toFilePath)), error.toString())); } throw this.toFileSystemProviderError(error); } } async copy(from: URI, to: URI, opts: FileOverwriteOptions): Promise<void> { const fromFilePath = this.toFilePath(from); const toFilePath = this.toFilePath(to); if (fromFilePath === toFilePath) { return; // simulate node.js behaviour here and do a no-op if paths match } try { // Ensure target does not exist await this.validateTargetDeleted(from, to, 'copy', opts.overwrite); // Copy await copy(fromFilePath, toFilePath); } catch (error) { // rewrite some typical errors that can happen especially around symlinks // to something the user can better understand if (error.code === 'EINVAL' || error.code === 'EBUSY' || error.code === 'ENAMETOOLONG') { error = new Error(localize('copyError', "Unable to copy '{0}' into '{1}' ({2}).", basename(fromFilePath), basename(dirname(toFilePath)), error.toString())); } throw this.toFileSystemProviderError(error); } } private async validateTargetDeleted(from: URI, to: URI, mode: 'move' | 'copy', overwrite?: boolean): Promise<void> { const fromFilePath = this.toFilePath(from); const toFilePath = this.toFilePath(to); let isSameResourceWithDifferentPathCase = false; const isPathCaseSensitive = !!(this.capabilities & FileSystemProviderCapabilities.PathCaseSensitive); if (!isPathCaseSensitive) { isSameResourceWithDifferentPathCase = isEqual(fromFilePath, toFilePath, true /* ignore case */); } if (isSameResourceWithDifferentPathCase && mode === 'copy') { throw createFileSystemProviderError(localize('fileCopyErrorPathCase', "'File cannot be copied to same path with different path case"), FileSystemProviderErrorCode.FileExists); } // handle existing target (unless this is a case change) if (!isSameResourceWithDifferentPathCase && await exists(toFilePath)) { if (!overwrite) { throw createFileSystemProviderError(localize('fileCopyErrorExists', "File at target already exists"), FileSystemProviderErrorCode.FileExists); } // Delete target await this.delete(to, { recursive: true, useTrash: false }); } } //#endregion //#region File Watching private _onDidWatchErrorOccur = this._register(new Emitter<string>()); readonly onDidErrorOccur = this._onDidWatchErrorOccur.event; private _onDidChangeFile = this._register(new Emitter<readonly IFileChange[]>()); readonly onDidChangeFile = this._onDidChangeFile.event; private recursiveWatcher: WindowsWatcherService | UnixWatcherService | NsfwWatcherService | undefined; private recursiveFoldersToWatch: { path: string, excludes: string[] }[] = []; private recursiveWatchRequestDelayer = this._register(new ThrottledDelayer<void>(0)); private recursiveWatcherLogLevelListener: IDisposable | undefined; watch(resource: URI, opts: IWatchOptions): IDisposable { if (opts.recursive) { return this.watchRecursive(resource, opts.excludes); } return this.watchNonRecursive(resource); // TODO@ben ideally the same watcher can be used in both cases } private watchRecursive(resource: URI, excludes: string[]): IDisposable { // Add to list of folders to watch recursively const folderToWatch = { path: this.toFilePath(resource), excludes }; const remove = insert(this.recursiveFoldersToWatch, folderToWatch); // Trigger update this.refreshRecursiveWatchers(); return toDisposable(() => { // Remove from list of folders to watch recursively remove(); // Trigger update this.refreshRecursiveWatchers(); }); } private refreshRecursiveWatchers(): void { // Buffer requests for recursive watching to decide on right watcher // that supports potentially watching more than one folder at once this.recursiveWatchRequestDelayer.trigger(async () => { this.doRefreshRecursiveWatchers(); }); } private doRefreshRecursiveWatchers(): void { // Reuse existing if (this.recursiveWatcher instanceof NsfwWatcherService) { this.recursiveWatcher.setFolders(this.recursiveFoldersToWatch); } // Create new else { // Dispose old dispose(this.recursiveWatcher); this.recursiveWatcher = undefined; // Create new if we actually have folders to watch if (this.recursiveFoldersToWatch.length > 0) { let watcherImpl: { new( folders: { path: string, excludes: string[] }[], onChange: (changes: IDiskFileChange[]) => void, onLogMessage: (msg: ILogMessage) => void, verboseLogging: boolean, watcherOptions?: IWatcherOptions ): WindowsWatcherService | UnixWatcherService | NsfwWatcherService }; let watcherOptions: IWatcherOptions | undefined = undefined; // requires a polling watcher if (this.options?.watcher?.usePolling) { watcherImpl = UnixWatcherService; watcherOptions = this.options?.watcher; } // Single Folder Watcher else { if (this.recursiveFoldersToWatch.length === 1) { if (isWindows) { watcherImpl = WindowsWatcherService; } else { watcherImpl = UnixWatcherService; } } // Multi Folder Watcher else { watcherImpl = NsfwWatcherService; } } // Create and start watching this.recursiveWatcher = new watcherImpl( this.recursiveFoldersToWatch, event => this._onDidChangeFile.fire(toFileChanges(event)), msg => { if (msg.type === 'error') { this._onDidWatchErrorOccur.fire(msg.message); } this.logService[msg.type](msg.message); }, this.logService.getLevel() === LogLevel.Trace, watcherOptions ); if (!this.recursiveWatcherLogLevelListener) { this.recursiveWatcherLogLevelListener = this.logService.onDidChangeLogLevel(() => { if (this.recursiveWatcher) { this.recursiveWatcher.setVerboseLogging(this.logService.getLevel() === LogLevel.Trace); } }); } } } } private watchNonRecursive(resource: URI): IDisposable { const watcherService = new NodeJSWatcherService( this.toFilePath(resource), changes => this._onDidChangeFile.fire(toFileChanges(changes)), msg => { if (msg.type === 'error') { this._onDidWatchErrorOccur.fire(msg.message); } this.logService[msg.type](msg.message); }, this.logService.getLevel() === LogLevel.Trace ); const logLevelListener = this.logService.onDidChangeLogLevel(() => { watcherService.setVerboseLogging(this.logService.getLevel() === LogLevel.Trace); }); return combinedDisposable(watcherService, logLevelListener); } //#endregion //#region Helpers protected toFilePath(resource: URI): string { return normalize(resource.fsPath); } private toFileSystemProviderError(error: NodeJS.ErrnoException): FileSystemProviderError { if (error instanceof FileSystemProviderError) { return error; // avoid double conversion } let code: FileSystemProviderErrorCode; switch (error.code) { case 'ENOENT': code = FileSystemProviderErrorCode.FileNotFound; break; case 'EISDIR': code = FileSystemProviderErrorCode.FileIsADirectory; break; case 'ENOTDIR': code = FileSystemProviderErrorCode.FileNotADirectory; break; case 'EEXIST': code = FileSystemProviderErrorCode.FileExists; break; case 'EPERM': case 'EACCES': code = FileSystemProviderErrorCode.NoPermissions; break; default: code = FileSystemProviderErrorCode.Unknown; } return createFileSystemProviderError(error, code); } //#endregion dispose(): void { super.dispose(); dispose(this.recursiveWatcher); this.recursiveWatcher = undefined; dispose(this.recursiveWatcherLogLevelListener); this.recursiveWatcherLogLevelListener = undefined; } }
src/vs/platform/files/node/diskFileSystemProvider.ts
0
https://github.com/microsoft/vscode/commit/a20f2e6ba5a2114dabad5bd68a61dc549b2c9d52
[ 0.0003149515832774341, 0.00017244988703168929, 0.00016240746481344104, 0.00017071253387257457, 0.000017393302186974324 ]
{ "id": 0, "code_window": [ "\t\t}\n", "\t}\n", "\n", "\t(/** @type {any} */ (window)).createWebviewManager({\n", "\t\tpostMessage: hostMessaging.postMessage.bind(hostMessaging),\n", "\t\tonMessage: hostMessaging.onMessage.bind(hostMessaging),\n", "\t\tready: workerReady,\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t/** @type {import('./main').WebviewHost} */\n", "\tconst host = {\n" ], "file_path": "src/vs/workbench/contrib/webview/browser/pre/host.js", "type": "replace", "edit_start_line_idx": 92 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Selection } from 'vs/editor/common/core/selection'; import { ICommand, IEditOperationBuilder, ICursorStateComputerData } from 'vs/editor/common/editorCommon'; import { Range } from 'vs/editor/common/core/range'; import { ITextModel } from 'vs/editor/common/model'; export class InPlaceReplaceCommand implements ICommand { private readonly _editRange: Range; private readonly _originalSelection: Selection; private readonly _text: string; constructor(editRange: Range, originalSelection: Selection, text: string) { this._editRange = editRange; this._originalSelection = originalSelection; this._text = text; } public getEditOperations(model: ITextModel, builder: IEditOperationBuilder): void { builder.addTrackedEditOperation(this._editRange, this._text); } public computeCursorState(model: ITextModel, helper: ICursorStateComputerData): Selection { const inverseEditOperations = helper.getInverseEditOperations(); const srcRange = inverseEditOperations[0].range; if (!this._originalSelection.isEmpty()) { // Preserve selection and extends to typed text return new Selection( srcRange.endLineNumber, srcRange.endColumn - this._text.length, srcRange.endLineNumber, srcRange.endColumn ); } return new Selection( srcRange.endLineNumber, Math.min(this._originalSelection.positionColumn, srcRange.endColumn), srcRange.endLineNumber, Math.min(this._originalSelection.positionColumn, srcRange.endColumn) ); } }
src/vs/editor/contrib/inPlaceReplace/inPlaceReplaceCommand.ts
0
https://github.com/microsoft/vscode/commit/a20f2e6ba5a2114dabad5bd68a61dc549b2c9d52
[ 0.00017605350876692683, 0.00017320015467703342, 0.00016944791423156857, 0.00017412925080861896, 0.000002264289150843979 ]
{ "id": 0, "code_window": [ "\t\t}\n", "\t}\n", "\n", "\t(/** @type {any} */ (window)).createWebviewManager({\n", "\t\tpostMessage: hostMessaging.postMessage.bind(hostMessaging),\n", "\t\tonMessage: hostMessaging.onMessage.bind(hostMessaging),\n", "\t\tready: workerReady,\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t/** @type {import('./main').WebviewHost} */\n", "\tconst host = {\n" ], "file_path": "src/vs/workbench/contrib/webview/browser/pre/host.js", "type": "replace", "edit_start_line_idx": 92 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as vscode from 'vscode'; import { ITypeScriptServiceClient } from '../typescriptService'; import DefinitionProviderBase from './definitionProviderBase'; class TypeScriptImplementationProvider extends DefinitionProviderBase implements vscode.ImplementationProvider { public provideImplementation(document: vscode.TextDocument, position: vscode.Position, token: vscode.CancellationToken): Promise<vscode.Definition | undefined> { return this.getSymbolLocations('implementation', document, position, token); } } export function register( selector: vscode.DocumentSelector, client: ITypeScriptServiceClient, ) { return vscode.languages.registerImplementationProvider(selector, new TypeScriptImplementationProvider(client)); }
extensions/typescript-language-features/src/features/implementations.ts
0
https://github.com/microsoft/vscode/commit/a20f2e6ba5a2114dabad5bd68a61dc549b2c9d52
[ 0.00017555347585584968, 0.00017333061259705573, 0.0001714874670142308, 0.00017295092402491719, 0.000001681514163465181 ]
{ "id": 1, "code_window": [ "\t\tonMessage: hostMessaging.onMessage.bind(hostMessaging),\n", "\t\tready: workerReady,\n", "\t\tfakeLoad: true,\n", "\t\trewriteCSP: (csp, endpoint) => {\n", "\t\t\tconst endpointUrl = new URL(endpoint);\n", "\t\t\tcsp.setAttribute('content', csp.replace(/(vscode-webview-resource|vscode-resource):(?=(\\s|;|$))/g, endpointUrl.origin));\n", "\t\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "\t\t\treturn csp.replace(/(vscode-webview-resource|vscode-resource):(?=(\\s|;|$))/g, endpointUrl.origin);\n" ], "file_path": "src/vs/workbench/contrib/webview/browser/pre/host.js", "type": "replace", "edit_start_line_idx": 99 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // @ts-check (function () { const id = document.location.search.match(/\bid=([\w-]+)/)[1]; const hostMessaging = new class HostMessaging { constructor() { this.handlers = new Map(); window.addEventListener('message', (e) => { if (e.data && (e.data.command === 'onmessage' || e.data.command === 'do-update-state')) { // Came from inner iframe this.postMessage(e.data.command, e.data.data); return; } const channel = e.data.channel; const handler = this.handlers.get(channel); if (handler) { handler(e, e.data.args); } else { console.log('no handler for ', e); } }); } postMessage(channel, data) { window.parent.postMessage({ target: id, channel, data }, '*'); } onMessage(channel, handler) { this.handlers.set(channel, handler); } }(); const workerReady = new Promise(async (resolveWorkerReady) => { if (!areServiceWorkersEnabled()) { console.log('Service Workers are not enabled. Webviews will not work properly'); return resolveWorkerReady(); } const expectedWorkerVersion = 1; navigator.serviceWorker.register('service-worker.js').then(async registration => { await navigator.serviceWorker.ready; const versionHandler = (event) => { if (event.data.channel !== 'version') { return; } navigator.serviceWorker.removeEventListener('message', versionHandler); if (event.data.version === expectedWorkerVersion) { return resolveWorkerReady(); } else { // If we have the wrong version, try once to unregister and re-register return registration.update() .then(() => navigator.serviceWorker.ready) .finally(resolveWorkerReady); } }; navigator.serviceWorker.addEventListener('message', versionHandler); registration.active.postMessage({ channel: 'version' }); }); const forwardFromHostToWorker = (channel) => { hostMessaging.onMessage(channel, event => { navigator.serviceWorker.ready.then(registration => { registration.active.postMessage({ channel: channel, data: event.data.args }); }); }); }; forwardFromHostToWorker('did-load-resource'); forwardFromHostToWorker('did-load-localhost'); navigator.serviceWorker.addEventListener('message', event => { if (['load-resource', 'load-localhost'].includes(event.data.channel)) { hostMessaging.postMessage(event.data.channel, event.data); } }); }); function areServiceWorkersEnabled() { try { return !!navigator.serviceWorker; } catch (e) { return false; } } (/** @type {any} */ (window)).createWebviewManager({ postMessage: hostMessaging.postMessage.bind(hostMessaging), onMessage: hostMessaging.onMessage.bind(hostMessaging), ready: workerReady, fakeLoad: true, rewriteCSP: (csp, endpoint) => { const endpointUrl = new URL(endpoint); csp.setAttribute('content', csp.replace(/(vscode-webview-resource|vscode-resource):(?=(\s|;|$))/g, endpointUrl.origin)); } }); }());
src/vs/workbench/contrib/webview/browser/pre/host.js
1
https://github.com/microsoft/vscode/commit/a20f2e6ba5a2114dabad5bd68a61dc549b2c9d52
[ 0.9986227750778198, 0.09207101166248322, 0.0001657616376178339, 0.000171421910636127, 0.28668805956840515 ]
{ "id": 1, "code_window": [ "\t\tonMessage: hostMessaging.onMessage.bind(hostMessaging),\n", "\t\tready: workerReady,\n", "\t\tfakeLoad: true,\n", "\t\trewriteCSP: (csp, endpoint) => {\n", "\t\t\tconst endpointUrl = new URL(endpoint);\n", "\t\t\tcsp.setAttribute('content', csp.replace(/(vscode-webview-resource|vscode-resource):(?=(\\s|;|$))/g, endpointUrl.origin));\n", "\t\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "\t\t\treturn csp.replace(/(vscode-webview-resource|vscode-resource):(?=(\\s|;|$))/g, endpointUrl.origin);\n" ], "file_path": "src/vs/workbench/contrib/webview/browser/pre/host.js", "type": "replace", "edit_start_line_idx": 99 }
# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. # yarn lockfile v1 "@types/[email protected]": version "0.0.2" resolved "https://registry.yarnpkg.com/@types/markdown-it/-/markdown-it-0.0.2.tgz#5d9ad19e6e6508cdd2f2596df86fd0aade598660" integrity sha1-XZrRnm5lCM3S8llt+G/Qqt5ZhmA= "@types/node@^12.11.7": version "12.11.7" resolved "https://registry.yarnpkg.com/@types/node/-/node-12.11.7.tgz#57682a9771a3f7b09c2497f28129a0462966524a" integrity sha512-JNbGaHFCLwgHn/iCckiGSOZ1XYHsKFwREtzPwSGCVld1SGhOlmZw2D4ZI94HQCrBHbADzW9m4LER/8olJTRGHA== "@types/node@^6.0.46": version "6.0.78" resolved "https://registry.yarnpkg.com/@types/node/-/node-6.0.78.tgz#5d4a3f579c1524e01ee21bf474e6fba09198f470" integrity sha512-+vD6E8ixntRzzZukoF3uP1iV+ZjVN3koTcaeK+BEoc/kSfGbLDIGC7RmCaUgVpUfN6cWvfczFRERCyKM9mkvXg== argparse@^1.0.7: version "1.0.9" resolved "https://registry.yarnpkg.com/argparse/-/argparse-1.0.9.tgz#73d83bc263f86e97f8cc4f6bae1b0e90a7d22c86" integrity sha1-c9g7wmP4bpf4zE9rrhsOkKfSLIY= dependencies: sprintf-js "~1.0.2" entities@~1.1.1: version "1.1.1" resolved "https://registry.yarnpkg.com/entities/-/entities-1.1.1.tgz#6e5c2d0a5621b5dadaecef80b90edfb5cd7772f0" integrity sha1-blwtClYhtdra7O+AuQ7ftc13cvA= jsonc-parser@^2.2.1: version "2.2.1" resolved "https://registry.yarnpkg.com/jsonc-parser/-/jsonc-parser-2.2.1.tgz#db73cd59d78cce28723199466b2a03d1be1df2bc" integrity sha512-o6/yDBYccGvTz1+QFevz6l6OBZ2+fMVu2JZ9CIhzsYRX4mjaK5IyX9eldUdCmga16zlgQxyrj5pt9kzuj2C02w== linkify-it@^2.0.0: version "2.0.3" resolved "https://registry.yarnpkg.com/linkify-it/-/linkify-it-2.0.3.tgz#d94a4648f9b1c179d64fa97291268bdb6ce9434f" integrity sha1-2UpGSPmxwXnWT6lykSaL22zpQ08= dependencies: uc.micro "^1.0.1" markdown-it@^8.3.1: version "8.4.0" resolved "https://registry.yarnpkg.com/markdown-it/-/markdown-it-8.4.0.tgz#e2400881bf171f7018ed1bd9da441dac8af6306d" integrity sha512-tNuOCCfunY5v5uhcO2AUMArvKAyKMygX8tfup/JrgnsDqcCATQsAExBq7o5Ml9iMmO82bk6jYNLj6khcrl0JGA== dependencies: argparse "^1.0.7" entities "~1.1.1" linkify-it "^2.0.0" mdurl "^1.0.1" uc.micro "^1.0.3" mdurl@^1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/mdurl/-/mdurl-1.0.1.tgz#fe85b2ec75a59037f2adfec100fd6c601761152e" integrity sha1-/oWy7HWlkDfyrf7BAP1sYBdhFS4= parse5@^3.0.2: version "3.0.2" resolved "https://registry.yarnpkg.com/parse5/-/parse5-3.0.2.tgz#05eff57f0ef4577fb144a79f8b9a967a6cc44510" integrity sha1-Be/1fw70V3+xRKefi5qWemzERRA= dependencies: "@types/node" "^6.0.46" sprintf-js@~1.0.2: version "1.0.3" resolved "https://registry.yarnpkg.com/sprintf-js/-/sprintf-js-1.0.3.tgz#04e6926f662895354f3dd015203633b857297e2c" integrity sha1-BOaSb2YolTVPPdAVIDYzuFcpfiw= uc.micro@^1.0.1, uc.micro@^1.0.3: version "1.0.3" resolved "https://registry.yarnpkg.com/uc.micro/-/uc.micro-1.0.3.tgz#7ed50d5e0f9a9fb0a573379259f2a77458d50192" integrity sha1-ftUNXg+an7ClczeSWfKndFjVAZI= vscode-nls@^4.1.1: version "4.1.1" resolved "https://registry.yarnpkg.com/vscode-nls/-/vscode-nls-4.1.1.tgz#f9916b64e4947b20322defb1e676a495861f133c" integrity sha512-4R+2UoUUU/LdnMnFjePxfLqNhBS8lrAFyX7pjb2ud/lqDkrUavFUTcG7wR0HBZFakae0Q6KLBFjMS6W93F403A==
extensions/extension-editing/yarn.lock
0
https://github.com/microsoft/vscode/commit/a20f2e6ba5a2114dabad5bd68a61dc549b2c9d52
[ 0.00017259213200304657, 0.00016759001300670207, 0.00016284894081763923, 0.0001663300208747387, 0.0000034853198940254515 ]
{ "id": 1, "code_window": [ "\t\tonMessage: hostMessaging.onMessage.bind(hostMessaging),\n", "\t\tready: workerReady,\n", "\t\tfakeLoad: true,\n", "\t\trewriteCSP: (csp, endpoint) => {\n", "\t\t\tconst endpointUrl = new URL(endpoint);\n", "\t\t\tcsp.setAttribute('content', csp.replace(/(vscode-webview-resource|vscode-resource):(?=(\\s|;|$))/g, endpointUrl.origin));\n", "\t\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "\t\t\treturn csp.replace(/(vscode-webview-resource|vscode-resource):(?=(\\s|;|$))/g, endpointUrl.origin);\n" ], "file_path": "src/vs/workbench/contrib/webview/browser/pre/host.js", "type": "replace", "edit_start_line_idx": 99 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { defaultGenerator } from 'vs/base/common/idGenerator'; import { IFileQuery } from 'vs/workbench/services/search/common/search'; import { assign, equals } from 'vs/base/common/objects'; enum LoadingPhase { Created = 1, Loading = 2, Loaded = 3, Errored = 4, Disposed = 5 } export class FileQueryCacheState { private readonly _cacheKey = defaultGenerator.nextId(); get cacheKey(): string { if (this.loadingPhase === LoadingPhase.Loaded || !this.previousCacheState) { return this._cacheKey; } return this.previousCacheState.cacheKey; } get isLoaded(): boolean { const isLoaded = this.loadingPhase === LoadingPhase.Loaded; return isLoaded || !this.previousCacheState ? isLoaded : this.previousCacheState.isLoaded; } get isUpdating(): boolean { const isUpdating = this.loadingPhase === LoadingPhase.Loading; return isUpdating || !this.previousCacheState ? isUpdating : this.previousCacheState.isUpdating; } private readonly query = this.cacheQuery(this._cacheKey); private loadingPhase = LoadingPhase.Created; private loadPromise: Promise<void> | undefined; constructor( private cacheQuery: (cacheKey: string) => IFileQuery, private loadFn: (query: IFileQuery) => Promise<any>, private disposeFn: (cacheKey: string) => Promise<void>, private previousCacheState: FileQueryCacheState | undefined ) { if (this.previousCacheState) { const current = assign({}, this.query, { cacheKey: null }); const previous = assign({}, this.previousCacheState.query, { cacheKey: null }); if (!equals(current, previous)) { this.previousCacheState.dispose(); this.previousCacheState = undefined; } } } load(): FileQueryCacheState { if (this.isUpdating) { return this; } this.loadingPhase = LoadingPhase.Loading; this.loadPromise = (async () => { try { await this.loadFn(this.query); this.loadingPhase = LoadingPhase.Loaded; if (this.previousCacheState) { this.previousCacheState.dispose(); this.previousCacheState = undefined; } } catch (error) { this.loadingPhase = LoadingPhase.Errored; throw error; } })(); return this; } dispose(): void { if (this.loadPromise) { (async () => { try { await this.loadPromise; } catch (error) { // ignore } this.loadingPhase = LoadingPhase.Disposed; this.disposeFn(this._cacheKey); })(); } else { this.loadingPhase = LoadingPhase.Disposed; } if (this.previousCacheState) { this.previousCacheState.dispose(); this.previousCacheState = undefined; } } }
src/vs/workbench/contrib/search/common/cacheState.ts
0
https://github.com/microsoft/vscode/commit/a20f2e6ba5a2114dabad5bd68a61dc549b2c9d52
[ 0.00017501429829280823, 0.0001708324416540563, 0.0001662672293605283, 0.00017096320516429842, 0.0000023287780095415656 ]
{ "id": 1, "code_window": [ "\t\tonMessage: hostMessaging.onMessage.bind(hostMessaging),\n", "\t\tready: workerReady,\n", "\t\tfakeLoad: true,\n", "\t\trewriteCSP: (csp, endpoint) => {\n", "\t\t\tconst endpointUrl = new URL(endpoint);\n", "\t\t\tcsp.setAttribute('content', csp.replace(/(vscode-webview-resource|vscode-resource):(?=(\\s|;|$))/g, endpointUrl.origin));\n", "\t\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "\t\t\treturn csp.replace(/(vscode-webview-resource|vscode-resource):(?=(\\s|;|$))/g, endpointUrl.origin);\n" ], "file_path": "src/vs/workbench/contrib/webview/browser/pre/host.js", "type": "replace", "edit_start_line_idx": 99 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ .monaco-editor .margin-view-overlays .line-numbers { font-variant-numeric: tabular-nums; position: absolute; text-align: right; display: inline-block; vertical-align: middle; box-sizing: border-box; cursor: default; height: 100%; } .monaco-editor .relative-current-line-number { text-align: left; display: inline-block; width: 100%; } .monaco-editor .margin-view-overlays .line-numbers.lh-odd { margin-top: 1px; }
src/vs/editor/browser/viewParts/lineNumbers/lineNumbers.css
0
https://github.com/microsoft/vscode/commit/a20f2e6ba5a2114dabad5bd68a61dc549b2c9d52
[ 0.00017230273806490004, 0.00017061112157534808, 0.00016746549226809293, 0.0001720651489449665, 0.0000022264132439886453 ]
{ "id": 2, "code_window": [ "\t\t}\n", "\t});\n", "}());" ], "labels": [ "keep", "replace", "keep" ], "after_edit": [ "\t};\n", "\n", "\t(/** @type {any} */ (window)).createWebviewManager(host);\n" ], "file_path": "src/vs/workbench/contrib/webview/browser/pre/host.js", "type": "replace", "edit_start_line_idx": 101 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // @ts-check /** * @typedef {{ * postMessage: (channel: string, data?: any) => void, * onMessage: (channel: string, handler: any) => void, * focusIframeOnCreate?: boolean, * ready?: Promise<void>, * onIframeLoaded?: (iframe: HTMLIFrameElement) => void, * fakeLoad?: boolean, * rewriteCSP: (existingCSP: string, endpoint?: string) => string, * }} WebviewHost */ (function () { 'use strict'; /** * Use polling to track focus of main webview and iframes within the webview * * @param {Object} handlers * @param {() => void} handlers.onFocus * @param {() => void} handlers.onBlur */ const trackFocus = ({ onFocus, onBlur }) => { const interval = 50; let isFocused = document.hasFocus(); setInterval(() => { const isCurrentlyFocused = document.hasFocus(); if (isCurrentlyFocused === isFocused) { return; } isFocused = isCurrentlyFocused; if (isCurrentlyFocused) { onFocus(); } else { onBlur(); } }, interval); }; const getActiveFrame = () => { return /** @type {HTMLIFrameElement} */ (document.getElementById('active-frame')); }; const getPendingFrame = () => { return /** @type {HTMLIFrameElement} */ (document.getElementById('pending-frame')); }; const defaultCssRules = ` body { background-color: var(--vscode-editor-background); color: var(--vscode-editor-foreground); font-family: var(--vscode-font-family); font-weight: var(--vscode-font-weight); font-size: var(--vscode-font-size); margin: 0; padding: 0 20px; } img { max-width: 100%; max-height: 100%; } a { color: var(--vscode-textLink-foreground); } a:hover { color: var(--vscode-textLink-activeForeground); } a:focus, input:focus, select:focus, textarea:focus { outline: 1px solid -webkit-focus-ring-color; outline-offset: -1px; } code { color: var(--vscode-textPreformat-foreground); } blockquote { background: var(--vscode-textBlockQuote-background); border-color: var(--vscode-textBlockQuote-border); } kbd { color: var(--vscode-editor-foreground); border-radius: 3px; vertical-align: middle; padding: 1px 3px; background-color: hsla(0,0%,50%,.17); border: 1px solid rgba(71,71,71,.4); border-bottom-color: rgba(88,88,88,.4); box-shadow: inset 0 -1px 0 rgba(88,88,88,.4); } .vscode-light kbd { background-color: hsla(0,0%,87%,.5); border: 1px solid hsla(0,0%,80%,.7); border-bottom-color: hsla(0,0%,73%,.7); box-shadow: inset 0 -1px 0 hsla(0,0%,73%,.7); } ::-webkit-scrollbar { width: 10px; height: 10px; } ::-webkit-scrollbar-corner { background-color: var(--vscode-editor-background); } ::-webkit-scrollbar-thumb { background-color: var(--vscode-scrollbarSlider-background); } ::-webkit-scrollbar-thumb:hover { background-color: var(--vscode-scrollbarSlider-hoverBackground); } ::-webkit-scrollbar-thumb:active { background-color: var(--vscode-scrollbarSlider-activeBackground); }`; /** * @param {boolean} allowMultipleAPIAcquire * @param {*} [state] * @return {string} */ function getVsCodeApiScript(allowMultipleAPIAcquire, state) { return ` const acquireVsCodeApi = (function() { const originalPostMessage = window.parent.postMessage.bind(window.parent); const targetOrigin = '*'; let acquired = false; let state = ${state ? `JSON.parse(${JSON.stringify(state)})` : undefined}; return () => { if (acquired && !${allowMultipleAPIAcquire}) { throw new Error('An instance of the VS Code API has already been acquired'); } acquired = true; return Object.freeze({ postMessage: function(msg) { return originalPostMessage({ command: 'onmessage', data: msg }, targetOrigin); }, setState: function(newState) { state = newState; originalPostMessage({ command: 'do-update-state', data: JSON.stringify(newState) }, targetOrigin); return newState; }, getState: function() { return state; } }); }; })(); delete window.parent; delete window.top; delete window.frameElement; `; } /** * @param {WebviewHost} host */ function createWebviewManager(host) { // state let firstLoad = true; let loadTimeout; let pendingMessages = []; const initData = { initialScrollProgress: undefined, }; /** * @param {HTMLDocument?} document * @param {HTMLElement?} body */ const applyStyles = (document, body) => { if (!document) { return; } if (body) { body.classList.remove('vscode-light', 'vscode-dark', 'vscode-high-contrast'); body.classList.add(initData.activeTheme); body.dataset.vscodeThemeKind = initData.activeTheme; body.dataset.vscodeThemeName = initData.themeName || ''; } if (initData.styles) { const documentStyle = document.documentElement.style; // Remove stale properties for (let i = documentStyle.length - 1; i >= 0; i--) { const property = documentStyle[i]; // Don't remove properties that the webview might have added separately if (property && property.startsWith('--vscode-')) { documentStyle.removeProperty(property); } } // Re-add new properties for (const variable of Object.keys(initData.styles)) { documentStyle.setProperty(`--${variable}`, initData.styles[variable]); } } }; /** * @param {MouseEvent} event */ const handleInnerClick = (event) => { if (!event || !event.view || !event.view.document) { return; } let baseElement = event.view.document.getElementsByTagName('base')[0]; /** @type {any} */ let node = event.target; while (node) { if (node.tagName && node.tagName.toLowerCase() === 'a' && node.href) { if (node.getAttribute('href') === '#') { event.view.scrollTo(0, 0); } else if (node.hash && (node.getAttribute('href') === node.hash || (baseElement && node.href.indexOf(baseElement.href) >= 0))) { let scrollTarget = event.view.document.getElementById(node.hash.substr(1, node.hash.length - 1)); if (scrollTarget) { scrollTarget.scrollIntoView(); } } else { host.postMessage('did-click-link', node.href.baseVal || node.href); } event.preventDefault(); break; } node = node.parentNode; } }; /** * @param {MouseEvent} event */ const handleAuxClick = (event) => { // Prevent middle clicks opening a broken link in the browser if (!event.view || !event.view.document) { return; } if (event.button === 1) { let node = /** @type {any} */ (event.target); while (node) { if (node.tagName && node.tagName.toLowerCase() === 'a' && node.href) { event.preventDefault(); break; } node = node.parentNode; } } }; /** * @param {KeyboardEvent} e */ const handleInnerKeydown = (e) => { host.postMessage('did-keydown', { key: e.key, keyCode: e.keyCode, code: e.code, shiftKey: e.shiftKey, altKey: e.altKey, ctrlKey: e.ctrlKey, metaKey: e.metaKey, repeat: e.repeat }); }; let isHandlingScroll = false; const handleWheel = (event) => { if (isHandlingScroll) { return; } host.postMessage('did-scroll-wheel', { deltaMode: event.deltaMode, deltaX: event.deltaX, deltaY: event.deltaY, deltaZ: event.deltaZ, detail: event.detail, type: event.type }); }; const handleInnerScroll = (event) => { if (!event.target || !event.target.body) { return; } if (isHandlingScroll) { return; } const progress = event.currentTarget.scrollY / event.target.body.clientHeight; if (isNaN(progress)) { return; } isHandlingScroll = true; window.requestAnimationFrame(() => { try { host.postMessage('did-scroll', progress); } catch (e) { // noop } isHandlingScroll = false; }); }; /** * @return {string} */ function toContentHtml(data) { const options = data.options; const text = data.contents; const newDocument = new DOMParser().parseFromString(text, 'text/html'); newDocument.querySelectorAll('a').forEach(a => { if (!a.title) { a.title = a.getAttribute('href'); } }); // apply default script if (options.allowScripts) { const defaultScript = newDocument.createElement('script'); defaultScript.id = '_vscodeApiScript'; defaultScript.textContent = getVsCodeApiScript(options.allowMultipleAPIAcquire, data.state); newDocument.head.prepend(defaultScript); } // apply default styles const defaultStyles = newDocument.createElement('style'); defaultStyles.id = '_defaultStyles'; defaultStyles.innerHTML = defaultCssRules; newDocument.head.prepend(defaultStyles); applyStyles(newDocument, newDocument.body); // Check for CSP const csp = newDocument.querySelector('meta[http-equiv="Content-Security-Policy"]'); if (!csp) { host.postMessage('no-csp-found'); } else { try { csp.setAttribute('content', host.rewriteCSP(csp.getAttribute('content'), data.endpoint)); } catch (e) { console.error('Could not rewrite csp'); } } // set DOCTYPE for newDocument explicitly as DOMParser.parseFromString strips it off // and DOCTYPE is needed in the iframe to ensure that the user agent stylesheet is correctly overridden return '<!DOCTYPE html>\n' + newDocument.documentElement.outerHTML; } document.addEventListener('DOMContentLoaded', () => { const idMatch = document.location.search.match(/\bid=([\w-]+)/); const ID = idMatch ? idMatch[1] : undefined; if (!document.body) { return; } host.onMessage('styles', (_event, data) => { initData.styles = data.styles; initData.activeTheme = data.activeTheme; initData.themeName = data.themeName; const target = getActiveFrame(); if (!target) { return; } if (target.contentDocument) { applyStyles(target.contentDocument, target.contentDocument.body); } }); // propagate focus host.onMessage('focus', () => { const target = getActiveFrame(); if (target) { target.contentWindow.focus(); } }); // update iframe-contents let updateId = 0; host.onMessage('content', async (_event, data) => { const currentUpdateId = ++updateId; await host.ready; if (currentUpdateId !== updateId) { return; } const options = data.options; const newDocument = toContentHtml(data); const frame = getActiveFrame(); const wasFirstLoad = firstLoad; // keep current scrollY around and use later let setInitialScrollPosition; if (firstLoad) { firstLoad = false; setInitialScrollPosition = (body, window) => { if (!isNaN(initData.initialScrollProgress)) { if (window.scrollY === 0) { window.scroll(0, body.clientHeight * initData.initialScrollProgress); } } }; } else { const scrollY = frame && frame.contentDocument && frame.contentDocument.body ? frame.contentWindow.scrollY : 0; setInitialScrollPosition = (body, window) => { if (window.scrollY === 0) { window.scroll(0, scrollY); } }; } // Clean up old pending frames and set current one as new one const previousPendingFrame = getPendingFrame(); if (previousPendingFrame) { previousPendingFrame.setAttribute('id', ''); document.body.removeChild(previousPendingFrame); } if (!wasFirstLoad) { pendingMessages = []; } const newFrame = document.createElement('iframe'); newFrame.setAttribute('id', 'pending-frame'); newFrame.setAttribute('frameborder', '0'); newFrame.setAttribute('sandbox', options.allowScripts ? 'allow-scripts allow-forms allow-same-origin' : 'allow-same-origin'); if (host.fakeLoad) { // We should just be able to use srcdoc, but I wasn't // seeing the service worker applying properly. // Fake load an empty on the correct origin and then write real html // into it to get around this. newFrame.src = `./fake.html?id=${ID}`; } newFrame.style.cssText = 'display: block; margin: 0; overflow: hidden; position: absolute; width: 100%; height: 100%; visibility: hidden'; document.body.appendChild(newFrame); if (!host.fakeLoad) { // write new content onto iframe newFrame.contentDocument.open(); } newFrame.contentWindow.addEventListener('DOMContentLoaded', e => { // Workaround for https://bugs.chromium.org/p/chromium/issues/detail?id=978325 setTimeout(() => { if (host.fakeLoad) { newFrame.contentDocument.open(); newFrame.contentDocument.write(newDocument); newFrame.contentDocument.close(); hookupOnLoadHandlers(newFrame); } const contentDocument = e.target ? (/** @type {HTMLDocument} */ (e.target)) : undefined; if (contentDocument) { applyStyles(contentDocument, contentDocument.body); } }, 0); }); /** * @param {Document} contentDocument * @param {Window} contentWindow */ const onLoad = (contentDocument, contentWindow) => { if (contentDocument && contentDocument.body) { // Workaround for https://github.com/Microsoft/vscode/issues/12865 // check new scrollY and reset if necessary setInitialScrollPosition(contentDocument.body, contentWindow); } const newFrame = getPendingFrame(); if (newFrame && newFrame.contentDocument && newFrame.contentDocument === contentDocument) { const oldActiveFrame = getActiveFrame(); if (oldActiveFrame) { document.body.removeChild(oldActiveFrame); } // Styles may have changed since we created the element. Make sure we re-style applyStyles(newFrame.contentDocument, newFrame.contentDocument.body); newFrame.setAttribute('id', 'active-frame'); newFrame.style.visibility = 'visible'; if (host.focusIframeOnCreate) { newFrame.contentWindow.focus(); } contentWindow.addEventListener('scroll', handleInnerScroll); contentWindow.addEventListener('wheel', handleWheel); pendingMessages.forEach((data) => { contentWindow.postMessage(data, '*'); }); pendingMessages = []; } host.postMessage('did-load'); }; /** * @param {HTMLIFrameElement} newFrame */ function hookupOnLoadHandlers(newFrame) { clearTimeout(loadTimeout); loadTimeout = undefined; loadTimeout = setTimeout(() => { clearTimeout(loadTimeout); loadTimeout = undefined; onLoad(newFrame.contentDocument, newFrame.contentWindow); }, 200); newFrame.contentWindow.addEventListener('load', function (e) { const contentDocument = /** @type {Document} */ (e.target); if (loadTimeout) { clearTimeout(loadTimeout); loadTimeout = undefined; onLoad(contentDocument, this); } }); // Bubble out various events newFrame.contentWindow.addEventListener('click', handleInnerClick); newFrame.contentWindow.addEventListener('auxclick', handleAuxClick); newFrame.contentWindow.addEventListener('keydown', handleInnerKeydown); newFrame.contentWindow.addEventListener('contextmenu', e => e.preventDefault()); if (host.onIframeLoaded) { host.onIframeLoaded(newFrame); } } if (!host.fakeLoad) { hookupOnLoadHandlers(newFrame); } if (!host.fakeLoad) { newFrame.contentDocument.write(newDocument); newFrame.contentDocument.close(); } host.postMessage('did-set-content', undefined); }); // Forward message to the embedded iframe host.onMessage('message', (_event, data) => { const pending = getPendingFrame(); if (!pending) { const target = getActiveFrame(); if (target) { target.contentWindow.postMessage(data, '*'); return; } } pendingMessages.push(data); }); host.onMessage('initial-scroll-position', (_event, progress) => { initData.initialScrollProgress = progress; }); host.onMessage('execCommand', (_event, data) => { const target = getActiveFrame(); if (!target) { return; } target.contentDocument.execCommand(data); }); trackFocus({ onFocus: () => host.postMessage('did-focus'), onBlur: () => host.postMessage('did-blur') }); // signal ready host.postMessage('webview-ready', {}); }); } if (typeof module !== 'undefined') { module.exports = createWebviewManager; } else { (/** @type {any} */ (window)).createWebviewManager = createWebviewManager; } }());
src/vs/workbench/contrib/webview/browser/pre/main.js
1
https://github.com/microsoft/vscode/commit/a20f2e6ba5a2114dabad5bd68a61dc549b2c9d52
[ 0.0005075642256997526, 0.00018199191254097968, 0.00016386389324907213, 0.00016968915588222444, 0.000050963310059159994 ]
{ "id": 2, "code_window": [ "\t\t}\n", "\t});\n", "}());" ], "labels": [ "keep", "replace", "keep" ], "after_edit": [ "\t};\n", "\n", "\t(/** @type {any} */ (window)).createWebviewManager(host);\n" ], "file_path": "src/vs/workbench/contrib/webview/browser/pre/host.js", "type": "replace", "edit_start_line_idx": 101 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { createConnection, Connection } from 'vscode-languageserver/node'; import { formatError } from '../utils/runner'; import { startServer } from '../jsonServer'; import { RequestService } from '../requests'; import { xhr, XHRResponse, configure as configureHttpRequests, getErrorStatusDescription } from 'request-light'; import { URI as Uri } from 'vscode-uri'; import * as fs from 'fs'; // Create a connection for the server. const connection: Connection = createConnection(); console.log = connection.console.log.bind(connection.console); console.error = connection.console.error.bind(connection.console); process.on('unhandledRejection', (e: any) => { connection.console.error(formatError(`Unhandled exception`, e)); }); function getHTTPRequestService(): RequestService { return { getContent(uri: string, _encoding?: string) { const headers = { 'Accept-Encoding': 'gzip, deflate' }; return xhr({ url: uri, followRedirects: 5, headers }).then(response => { return response.responseText; }, (error: XHRResponse) => { return Promise.reject(error.responseText || getErrorStatusDescription(error.status) || error.toString()); }); } }; } function getFileRequestService(): RequestService { return { getContent(location: string, encoding?: string) { return new Promise((c, e) => { const uri = Uri.parse(location); fs.readFile(uri.fsPath, encoding, (err, buf) => { if (err) { return e(err); } c(buf.toString()); }); }); } }; } startServer(connection, { file: getFileRequestService(), http: getHTTPRequestService(), configureHttpRequests });
extensions/json-language-features/server/src/node/jsonServerMain.ts
0
https://github.com/microsoft/vscode/commit/a20f2e6ba5a2114dabad5bd68a61dc549b2c9d52
[ 0.00018454193195793778, 0.00017204559117089957, 0.00016597387730143964, 0.00016972990124486387, 0.00000636771073914133 ]
{ "id": 2, "code_window": [ "\t\t}\n", "\t});\n", "}());" ], "labels": [ "keep", "replace", "keep" ], "after_edit": [ "\t};\n", "\n", "\t(/** @type {any} */ (window)).createWebviewManager(host);\n" ], "file_path": "src/vs/workbench/contrib/webview/browser/pre/host.js", "type": "replace", "edit_start_line_idx": 101 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { CharCode } from 'vs/base/common/charCode'; import { onUnexpectedError } from 'vs/base/common/errors'; import * as strings from 'vs/base/common/strings'; import { EditorAutoClosingStrategy, EditorAutoSurroundStrategy, ConfigurationChangedEvent, EditorAutoClosingOvertypeStrategy, EditorOption, EditorAutoIndentStrategy } from 'vs/editor/common/config/editorOptions'; import { Position } from 'vs/editor/common/core/position'; import { Range } from 'vs/editor/common/core/range'; import { ISelection, Selection } from 'vs/editor/common/core/selection'; import { ICommand, IConfiguration } from 'vs/editor/common/editorCommon'; import { ITextModel, TextModelResolvedOptions } from 'vs/editor/common/model'; import { TextModel } from 'vs/editor/common/model/textModel'; import { LanguageIdentifier } from 'vs/editor/common/modes'; import { IAutoClosingPair, StandardAutoClosingPairConditional } from 'vs/editor/common/modes/languageConfiguration'; import { LanguageConfigurationRegistry } from 'vs/editor/common/modes/languageConfigurationRegistry'; import { ICoordinatesConverter } from 'vs/editor/common/viewModel/viewModel'; import { Constants } from 'vs/base/common/uint'; export interface IColumnSelectData { isReal: boolean; fromViewLineNumber: number; fromViewVisualColumn: number; toViewLineNumber: number; toViewVisualColumn: number; } export const enum RevealTarget { Primary = 0, TopMost = 1, BottomMost = 2 } /** * This is an operation type that will be recorded for undo/redo purposes. * The goal is to introduce an undo stop when the controller switches between different operation types. */ export const enum EditOperationType { Other = 0, Typing = 1, DeletingLeft = 2, DeletingRight = 3 } export interface CharacterMap { [char: string]: string; } export interface MultipleCharacterMap { [char: string]: string[]; } const autoCloseAlways = () => true; const autoCloseNever = () => false; const autoCloseBeforeWhitespace = (chr: string) => (chr === ' ' || chr === '\t'); function appendEntry<K, V>(target: Map<K, V[]>, key: K, value: V): void { if (target.has(key)) { target.get(key)!.push(value); } else { target.set(key, [value]); } } export class CursorConfiguration { _cursorMoveConfigurationBrand: void; public readonly readOnly: boolean; public readonly tabSize: number; public readonly indentSize: number; public readonly insertSpaces: boolean; public readonly pageSize: number; public readonly lineHeight: number; public readonly useTabStops: boolean; public readonly wordSeparators: string; public readonly emptySelectionClipboard: boolean; public readonly copyWithSyntaxHighlighting: boolean; public readonly multiCursorMergeOverlapping: boolean; public readonly multiCursorPaste: 'spread' | 'full'; public readonly autoClosingBrackets: EditorAutoClosingStrategy; public readonly autoClosingQuotes: EditorAutoClosingStrategy; public readonly autoClosingOvertype: EditorAutoClosingOvertypeStrategy; public readonly autoSurround: EditorAutoSurroundStrategy; public readonly autoIndent: EditorAutoIndentStrategy; public readonly autoClosingPairsOpen2: Map<string, StandardAutoClosingPairConditional[]>; public readonly autoClosingPairsClose2: Map<string, StandardAutoClosingPairConditional[]>; public readonly surroundingPairs: CharacterMap; public readonly shouldAutoCloseBefore: { quote: (ch: string) => boolean, bracket: (ch: string) => boolean }; private readonly _languageIdentifier: LanguageIdentifier; private _electricChars: { [key: string]: boolean; } | null; public static shouldRecreate(e: ConfigurationChangedEvent): boolean { return ( e.hasChanged(EditorOption.layoutInfo) || e.hasChanged(EditorOption.wordSeparators) || e.hasChanged(EditorOption.emptySelectionClipboard) || e.hasChanged(EditorOption.multiCursorMergeOverlapping) || e.hasChanged(EditorOption.multiCursorPaste) || e.hasChanged(EditorOption.autoClosingBrackets) || e.hasChanged(EditorOption.autoClosingQuotes) || e.hasChanged(EditorOption.autoClosingOvertype) || e.hasChanged(EditorOption.autoSurround) || e.hasChanged(EditorOption.useTabStops) || e.hasChanged(EditorOption.lineHeight) || e.hasChanged(EditorOption.readOnly) ); } constructor( languageIdentifier: LanguageIdentifier, modelOptions: TextModelResolvedOptions, configuration: IConfiguration ) { this._languageIdentifier = languageIdentifier; const options = configuration.options; const layoutInfo = options.get(EditorOption.layoutInfo); this.readOnly = options.get(EditorOption.readOnly); this.tabSize = modelOptions.tabSize; this.indentSize = modelOptions.indentSize; this.insertSpaces = modelOptions.insertSpaces; this.lineHeight = options.get(EditorOption.lineHeight); this.pageSize = Math.max(1, Math.floor(layoutInfo.height / this.lineHeight) - 2); this.useTabStops = options.get(EditorOption.useTabStops); this.wordSeparators = options.get(EditorOption.wordSeparators); this.emptySelectionClipboard = options.get(EditorOption.emptySelectionClipboard); this.copyWithSyntaxHighlighting = options.get(EditorOption.copyWithSyntaxHighlighting); this.multiCursorMergeOverlapping = options.get(EditorOption.multiCursorMergeOverlapping); this.multiCursorPaste = options.get(EditorOption.multiCursorPaste); this.autoClosingBrackets = options.get(EditorOption.autoClosingBrackets); this.autoClosingQuotes = options.get(EditorOption.autoClosingQuotes); this.autoClosingOvertype = options.get(EditorOption.autoClosingOvertype); this.autoSurround = options.get(EditorOption.autoSurround); this.autoIndent = options.get(EditorOption.autoIndent); this.autoClosingPairsOpen2 = new Map<string, StandardAutoClosingPairConditional[]>(); this.autoClosingPairsClose2 = new Map<string, StandardAutoClosingPairConditional[]>(); this.surroundingPairs = {}; this._electricChars = null; this.shouldAutoCloseBefore = { quote: CursorConfiguration._getShouldAutoClose(languageIdentifier, this.autoClosingQuotes), bracket: CursorConfiguration._getShouldAutoClose(languageIdentifier, this.autoClosingBrackets) }; let autoClosingPairs = CursorConfiguration._getAutoClosingPairs(languageIdentifier); if (autoClosingPairs) { for (const pair of autoClosingPairs) { appendEntry(this.autoClosingPairsOpen2, pair.open.charAt(pair.open.length - 1), pair); if (pair.close.length === 1) { appendEntry(this.autoClosingPairsClose2, pair.close, pair); } } } let surroundingPairs = CursorConfiguration._getSurroundingPairs(languageIdentifier); if (surroundingPairs) { for (const pair of surroundingPairs) { this.surroundingPairs[pair.open] = pair.close; } } } public get electricChars() { if (!this._electricChars) { this._electricChars = {}; let electricChars = CursorConfiguration._getElectricCharacters(this._languageIdentifier); if (electricChars) { for (const char of electricChars) { this._electricChars[char] = true; } } } return this._electricChars; } public normalizeIndentation(str: string): string { return TextModel.normalizeIndentation(str, this.indentSize, this.insertSpaces); } private static _getElectricCharacters(languageIdentifier: LanguageIdentifier): string[] | null { try { return LanguageConfigurationRegistry.getElectricCharacters(languageIdentifier.id); } catch (e) { onUnexpectedError(e); return null; } } private static _getAutoClosingPairs(languageIdentifier: LanguageIdentifier): StandardAutoClosingPairConditional[] | null { try { return LanguageConfigurationRegistry.getAutoClosingPairs(languageIdentifier.id); } catch (e) { onUnexpectedError(e); return null; } } private static _getShouldAutoClose(languageIdentifier: LanguageIdentifier, autoCloseConfig: EditorAutoClosingStrategy): (ch: string) => boolean { switch (autoCloseConfig) { case 'beforeWhitespace': return autoCloseBeforeWhitespace; case 'languageDefined': return CursorConfiguration._getLanguageDefinedShouldAutoClose(languageIdentifier); case 'always': return autoCloseAlways; case 'never': return autoCloseNever; } } private static _getLanguageDefinedShouldAutoClose(languageIdentifier: LanguageIdentifier): (ch: string) => boolean { try { const autoCloseBeforeSet = LanguageConfigurationRegistry.getAutoCloseBeforeSet(languageIdentifier.id); return c => autoCloseBeforeSet.indexOf(c) !== -1; } catch (e) { onUnexpectedError(e); return autoCloseNever; } } private static _getSurroundingPairs(languageIdentifier: LanguageIdentifier): IAutoClosingPair[] | null { try { return LanguageConfigurationRegistry.getSurroundingPairs(languageIdentifier.id); } catch (e) { onUnexpectedError(e); return null; } } } /** * Represents a simple model (either the model or the view model). */ export interface ICursorSimpleModel { getLineCount(): number; getLineContent(lineNumber: number): string; getLineMinColumn(lineNumber: number): number; getLineMaxColumn(lineNumber: number): number; getLineFirstNonWhitespaceColumn(lineNumber: number): number; getLineLastNonWhitespaceColumn(lineNumber: number): number; } /** * Represents the cursor state on either the model or on the view model. */ export class SingleCursorState { _singleCursorStateBrand: void; // --- selection can start as a range (think double click and drag) public readonly selectionStart: Range; public readonly selectionStartLeftoverVisibleColumns: number; public readonly position: Position; public readonly leftoverVisibleColumns: number; public readonly selection: Selection; constructor( selectionStart: Range, selectionStartLeftoverVisibleColumns: number, position: Position, leftoverVisibleColumns: number, ) { this.selectionStart = selectionStart; this.selectionStartLeftoverVisibleColumns = selectionStartLeftoverVisibleColumns; this.position = position; this.leftoverVisibleColumns = leftoverVisibleColumns; this.selection = SingleCursorState._computeSelection(this.selectionStart, this.position); } public equals(other: SingleCursorState) { return ( this.selectionStartLeftoverVisibleColumns === other.selectionStartLeftoverVisibleColumns && this.leftoverVisibleColumns === other.leftoverVisibleColumns && this.position.equals(other.position) && this.selectionStart.equalsRange(other.selectionStart) ); } public hasSelection(): boolean { return (!this.selection.isEmpty() || !this.selectionStart.isEmpty()); } public move(inSelectionMode: boolean, lineNumber: number, column: number, leftoverVisibleColumns: number): SingleCursorState { if (inSelectionMode) { // move just position return new SingleCursorState( this.selectionStart, this.selectionStartLeftoverVisibleColumns, new Position(lineNumber, column), leftoverVisibleColumns ); } else { // move everything return new SingleCursorState( new Range(lineNumber, column, lineNumber, column), leftoverVisibleColumns, new Position(lineNumber, column), leftoverVisibleColumns ); } } private static _computeSelection(selectionStart: Range, position: Position): Selection { let startLineNumber: number, startColumn: number, endLineNumber: number, endColumn: number; if (selectionStart.isEmpty()) { startLineNumber = selectionStart.startLineNumber; startColumn = selectionStart.startColumn; endLineNumber = position.lineNumber; endColumn = position.column; } else { if (position.isBeforeOrEqual(selectionStart.getStartPosition())) { startLineNumber = selectionStart.endLineNumber; startColumn = selectionStart.endColumn; endLineNumber = position.lineNumber; endColumn = position.column; } else { startLineNumber = selectionStart.startLineNumber; startColumn = selectionStart.startColumn; endLineNumber = position.lineNumber; endColumn = position.column; } } return new Selection( startLineNumber, startColumn, endLineNumber, endColumn ); } } export class CursorContext { _cursorContextBrand: void; public readonly model: ITextModel; public readonly coordinatesConverter: ICoordinatesConverter; public readonly cursorConfig: CursorConfiguration; constructor(model: ITextModel, coordinatesConverter: ICoordinatesConverter, cursorConfig: CursorConfiguration) { this.model = model; this.coordinatesConverter = coordinatesConverter; this.cursorConfig = cursorConfig; } } export class PartialModelCursorState { readonly modelState: SingleCursorState; readonly viewState: null; constructor(modelState: SingleCursorState) { this.modelState = modelState; this.viewState = null; } } export class PartialViewCursorState { readonly modelState: null; readonly viewState: SingleCursorState; constructor(viewState: SingleCursorState) { this.modelState = null; this.viewState = viewState; } } export type PartialCursorState = CursorState | PartialModelCursorState | PartialViewCursorState; export class CursorState { _cursorStateBrand: void; public static fromModelState(modelState: SingleCursorState): PartialModelCursorState { return new PartialModelCursorState(modelState); } public static fromViewState(viewState: SingleCursorState): PartialViewCursorState { return new PartialViewCursorState(viewState); } public static fromModelSelection(modelSelection: ISelection): PartialModelCursorState { const selectionStartLineNumber = modelSelection.selectionStartLineNumber; const selectionStartColumn = modelSelection.selectionStartColumn; const positionLineNumber = modelSelection.positionLineNumber; const positionColumn = modelSelection.positionColumn; const modelState = new SingleCursorState( new Range(selectionStartLineNumber, selectionStartColumn, selectionStartLineNumber, selectionStartColumn), 0, new Position(positionLineNumber, positionColumn), 0 ); return CursorState.fromModelState(modelState); } public static fromModelSelections(modelSelections: readonly ISelection[]): PartialModelCursorState[] { let states: PartialModelCursorState[] = []; for (let i = 0, len = modelSelections.length; i < len; i++) { states[i] = this.fromModelSelection(modelSelections[i]); } return states; } readonly modelState: SingleCursorState; readonly viewState: SingleCursorState; constructor(modelState: SingleCursorState, viewState: SingleCursorState) { this.modelState = modelState; this.viewState = viewState; } public equals(other: CursorState): boolean { return (this.viewState.equals(other.viewState) && this.modelState.equals(other.modelState)); } } export class EditOperationResult { _editOperationResultBrand: void; readonly type: EditOperationType; readonly commands: Array<ICommand | null>; readonly shouldPushStackElementBefore: boolean; readonly shouldPushStackElementAfter: boolean; constructor( type: EditOperationType, commands: Array<ICommand | null>, opts: { shouldPushStackElementBefore: boolean; shouldPushStackElementAfter: boolean; } ) { this.type = type; this.commands = commands; this.shouldPushStackElementBefore = opts.shouldPushStackElementBefore; this.shouldPushStackElementAfter = opts.shouldPushStackElementAfter; } } /** * Common operations that work and make sense both on the model and on the view model. */ export class CursorColumns { public static visibleColumnFromColumn(lineContent: string, column: number, tabSize: number): number { const lineContentLength = lineContent.length; const endOffset = column - 1 < lineContentLength ? column - 1 : lineContentLength; let result = 0; let i = 0; while (i < endOffset) { const codePoint = strings.getNextCodePoint(lineContent, endOffset, i); i += (codePoint >= Constants.UNICODE_SUPPLEMENTARY_PLANE_BEGIN ? 2 : 1); if (codePoint === CharCode.Tab) { result = CursorColumns.nextRenderTabStop(result, tabSize); } else { let graphemeBreakType = strings.getGraphemeBreakType(codePoint); while (i < endOffset) { const nextCodePoint = strings.getNextCodePoint(lineContent, endOffset, i); const nextGraphemeBreakType = strings.getGraphemeBreakType(nextCodePoint); if (strings.breakBetweenGraphemeBreakType(graphemeBreakType, nextGraphemeBreakType)) { break; } i += (nextCodePoint >= Constants.UNICODE_SUPPLEMENTARY_PLANE_BEGIN ? 2 : 1); graphemeBreakType = nextGraphemeBreakType; } if (strings.isFullWidthCharacter(codePoint) || strings.isEmojiImprecise(codePoint)) { result = result + 2; } else { result = result + 1; } } } return result; } public static toStatusbarColumn(lineContent: string, column: number, tabSize: number): number { const lineContentLength = lineContent.length; const endOffset = column - 1 < lineContentLength ? column - 1 : lineContentLength; let result = 0; let i = 0; while (i < endOffset) { const codePoint = strings.getNextCodePoint(lineContent, endOffset, i); i += (codePoint >= Constants.UNICODE_SUPPLEMENTARY_PLANE_BEGIN ? 2 : 1); if (codePoint === CharCode.Tab) { result = CursorColumns.nextRenderTabStop(result, tabSize); } else { result = result + 1; } } return result + 1; } public static visibleColumnFromColumn2(config: CursorConfiguration, model: ICursorSimpleModel, position: Position): number { return this.visibleColumnFromColumn(model.getLineContent(position.lineNumber), position.column, config.tabSize); } public static columnFromVisibleColumn(lineContent: string, visibleColumn: number, tabSize: number): number { if (visibleColumn <= 0) { return 1; } const lineLength = lineContent.length; let beforeVisibleColumn = 0; let beforeColumn = 1; let i = 0; while (i < lineLength) { const codePoint = strings.getNextCodePoint(lineContent, lineLength, i); i += (codePoint >= Constants.UNICODE_SUPPLEMENTARY_PLANE_BEGIN ? 2 : 1); let afterVisibleColumn: number; if (codePoint === CharCode.Tab) { afterVisibleColumn = CursorColumns.nextRenderTabStop(beforeVisibleColumn, tabSize); } else { let graphemeBreakType = strings.getGraphemeBreakType(codePoint); while (i < lineLength) { const nextCodePoint = strings.getNextCodePoint(lineContent, lineLength, i); const nextGraphemeBreakType = strings.getGraphemeBreakType(nextCodePoint); if (strings.breakBetweenGraphemeBreakType(graphemeBreakType, nextGraphemeBreakType)) { break; } i += (nextCodePoint >= Constants.UNICODE_SUPPLEMENTARY_PLANE_BEGIN ? 2 : 1); graphemeBreakType = nextGraphemeBreakType; } if (strings.isFullWidthCharacter(codePoint) || strings.isEmojiImprecise(codePoint)) { afterVisibleColumn = beforeVisibleColumn + 2; } else { afterVisibleColumn = beforeVisibleColumn + 1; } } const afterColumn = i + 1; if (afterVisibleColumn >= visibleColumn) { const beforeDelta = visibleColumn - beforeVisibleColumn; const afterDelta = afterVisibleColumn - visibleColumn; if (afterDelta < beforeDelta) { return afterColumn; } else { return beforeColumn; } } beforeVisibleColumn = afterVisibleColumn; beforeColumn = afterColumn; } // walked the entire string return lineLength + 1; } public static columnFromVisibleColumn2(config: CursorConfiguration, model: ICursorSimpleModel, lineNumber: number, visibleColumn: number): number { let result = this.columnFromVisibleColumn(model.getLineContent(lineNumber), visibleColumn, config.tabSize); let minColumn = model.getLineMinColumn(lineNumber); if (result < minColumn) { return minColumn; } let maxColumn = model.getLineMaxColumn(lineNumber); if (result > maxColumn) { return maxColumn; } return result; } /** * ATTENTION: This works with 0-based columns (as oposed to the regular 1-based columns) */ public static nextRenderTabStop(visibleColumn: number, tabSize: number): number { return visibleColumn + tabSize - visibleColumn % tabSize; } /** * ATTENTION: This works with 0-based columns (as oposed to the regular 1-based columns) */ public static nextIndentTabStop(visibleColumn: number, indentSize: number): number { return visibleColumn + indentSize - visibleColumn % indentSize; } /** * ATTENTION: This works with 0-based columns (as oposed to the regular 1-based columns) */ public static prevRenderTabStop(column: number, tabSize: number): number { return column - 1 - (column - 1) % tabSize; } /** * ATTENTION: This works with 0-based columns (as oposed to the regular 1-based columns) */ public static prevIndentTabStop(column: number, indentSize: number): number { return column - 1 - (column - 1) % indentSize; } } export function isQuote(ch: string): boolean { return (ch === '\'' || ch === '"' || ch === '`'); }
src/vs/editor/common/controller/cursorCommon.ts
0
https://github.com/microsoft/vscode/commit/a20f2e6ba5a2114dabad5bd68a61dc549b2c9d52
[ 0.001307029975578189, 0.00020405530813150108, 0.00016448160749860108, 0.00016998565115500242, 0.00015213896404020488 ]
{ "id": 2, "code_window": [ "\t\t}\n", "\t});\n", "}());" ], "labels": [ "keep", "replace", "keep" ], "after_edit": [ "\t};\n", "\n", "\t(/** @type {any} */ (window)).createWebviewManager(host);\n" ], "file_path": "src/vs/workbench/contrib/webview/browser/pre/host.js", "type": "replace", "edit_start_line_idx": 101 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { KeyboardLayoutContribution } from 'vs/workbench/services/keybinding/browser/keyboardLayouts/_.contribution'; KeyboardLayoutContribution.INSTANCE.registerKeyboardLayout({ layout: { model: 'pc104', layout: 'de', variant: '', options: '', rules: 'base' }, secondaryLayouts: [], mapping: { Sleep: [], WakeUp: [], KeyA: ['a', 'A', 'æ', 'Æ', 0], KeyB: ['b', 'B', '“', '‘', 0], KeyC: ['c', 'C', '¢', '©', 0], KeyD: ['d', 'D', 'ð', 'Ð', 0], KeyE: ['e', 'E', '€', '€', 0], KeyF: ['f', 'F', 'đ', 'ª', 0], KeyG: ['g', 'G', 'ŋ', 'Ŋ', 0], KeyH: ['h', 'H', 'ħ', 'Ħ', 0], KeyI: ['i', 'I', '→', 'ı', 0], KeyJ: ['j', 'J', '̣', '̇', 0], KeyK: ['k', 'K', 'ĸ', '&', 0], KeyL: ['l', 'L', 'ł', 'Ł', 0], KeyM: ['m', 'M', 'µ', 'º', 0], KeyN: ['n', 'N', '”', '’', 0], KeyO: ['o', 'O', 'ø', 'Ø', 0], KeyP: ['p', 'P', 'þ', 'Þ', 0], KeyQ: ['q', 'Q', '@', 'Ω', 0], KeyR: ['r', 'R', '¶', '®', 0], KeyS: ['s', 'S', 'ſ', 'ẞ', 0], KeyT: ['t', 'T', 'ŧ', 'Ŧ', 0], KeyU: ['u', 'U', '↓', '↑', 0], KeyV: ['v', 'V', '„', '‚', 0], KeyW: ['w', 'W', 'ł', 'Ł', 0], KeyX: ['x', 'X', '«', '‹', 0], KeyY: ['z', 'Z', '←', '¥', 0], KeyZ: ['y', 'Y', '»', '›', 0], Digit1: ['1', '!', '¹', '¡', 0], Digit2: ['2', '"', '²', '⅛', 0], Digit3: ['3', '§', '³', '£', 0], Digit4: ['4', '$', '¼', '¤', 0], Digit5: ['5', '%', '½', '⅜', 0], Digit6: ['6', '&', '¬', '⅝', 0], Digit7: ['7', '/', '{', '⅞', 0], Digit8: ['8', '(', '[', '™', 0], Digit9: ['9', ')', ']', '±', 0], Digit0: ['0', '=', '}', '°', 0], Enter: ['\r', '\r', '\r', '\r', 0], Escape: ['\u001b', '\u001b', '\u001b', '\u001b', 0], Backspace: ['\b', '\b', '\b', '\b', 0], Tab: ['\t', '', '\t', '', 0], Space: [' ', ' ', ' ', ' ', 0], Minus: ['ß', '?', '\\', '¿', 0], Equal: ['́', '̀', '̧', '̨', 0], BracketLeft: ['ü', 'Ü', '̈', '̊', 0], BracketRight: ['+', '*', '~', '¯', 0], Backslash: ['#', '\'', '’', '̆', 0], Semicolon: ['ö', 'Ö', '̋', '̣', 0], Quote: ['ä', 'Ä', '̂', '̌', 0], Backquote: ['̂', '°', '′', '″', 0], Comma: [',', ';', '·', '×', 0], Period: ['.', ':', '…', '÷', 0], Slash: ['-', '_', '–', '—', 0], CapsLock: [], F1: [], F2: [], F3: [], F4: [], F5: [], F6: [], F7: [], F8: [], F9: [], F10: [], F11: [], F12: [], PrintScreen: ['', '', '', '', 0], ScrollLock: [], Pause: [], Insert: [], Home: [], PageUp: ['/', '/', '/', '/', 0], Delete: [], End: [], PageDown: [], ArrowRight: [], ArrowLeft: [], ArrowDown: [], ArrowUp: [], NumLock: [], NumpadDivide: [], NumpadMultiply: ['*', '*', '*', '*', 0], NumpadSubtract: ['-', '-', '-', '-', 0], NumpadAdd: ['+', '+', '+', '+', 0], NumpadEnter: [], Numpad1: ['', '1', '', '1', 0], Numpad2: ['', '2', '', '2', 0], Numpad3: ['', '3', '', '3', 0], Numpad4: ['', '4', '', '4', 0], Numpad5: ['', '5', '', '5', 0], Numpad6: ['', '6', '', '6', 0], Numpad7: ['', '7', '', '7', 0], Numpad8: ['', '8', '', '8', 0], Numpad9: ['', '9', '', '9', 0], Numpad0: ['', '0', '', '0', 0], NumpadDecimal: ['', ',', '', ',', 0], IntlBackslash: ['<', '>', '|', '̱', 0], ContextMenu: [], Power: [], NumpadEqual: [], F13: [], F14: [], F15: [], F16: [], F17: [], F18: [], F19: [], F20: [], F21: [], F22: [], F23: [], F24: [], Open: [], Help: [], Select: [], Again: [], Undo: [], Cut: [], Copy: [], Paste: [], Find: [], AudioVolumeMute: [], AudioVolumeUp: [], AudioVolumeDown: [], NumpadComma: [], IntlRo: [], KanaMode: [], IntlYen: [], Convert: [], NonConvert: [], Lang1: [], Lang2: [], Lang3: [], Lang4: [], Lang5: [], NumpadParenLeft: [], NumpadParenRight: [], ControlLeft: [], ShiftLeft: [], AltLeft: [], MetaLeft: [], ControlRight: [], ShiftRight: [], AltRight: ['\r', '\r', '\r', '\r', 0], MetaRight: ['.', '.', '.', '.', 0], BrightnessUp: [], BrightnessDown: [], MediaPlay: [], MediaRecord: [], MediaFastForward: [], MediaRewind: [], MediaTrackNext: [], MediaTrackPrevious: [], MediaStop: [], Eject: [], MediaPlayPause: [], MediaSelect: [], LaunchMail: [], LaunchApp2: [], LaunchApp1: [], SelectTask: [], LaunchScreenSaver: [], BrowserSearch: [], BrowserHome: [], BrowserBack: [], BrowserForward: [], BrowserStop: [], BrowserRefresh: [], BrowserFavorites: [], MailReply: [], MailForward: [], MailSend: [] } });
src/vs/workbench/services/keybinding/browser/keyboardLayouts/de.linux.ts
0
https://github.com/microsoft/vscode/commit/a20f2e6ba5a2114dabad5bd68a61dc549b2c9d52
[ 0.00017754441068973392, 0.00016863805649336427, 0.00016533276357222348, 0.00016728689661249518, 0.0000034450497423677007 ]
{ "id": 3, "code_window": [ "\t\t\t\thost.postMessage('no-csp-found');\n", "\t\t\t} else {\n", "\t\t\t\ttry {\n", "\t\t\t\t\tcsp.setAttribute('content', host.rewriteCSP(csp.getAttribute('content'), data.endpoint));\n", "\t\t\t\t} catch (e) {\n", "\t\t\t\t\tconsole.error('Could not rewrite csp');\n", "\t\t\t\t}\n", "\t\t\t}\n", "\n", "\t\t\t// set DOCTYPE for newDocument explicitly as DOMParser.parseFromString strips it off\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\t\tconsole.error(`Could not rewrite csp: ${e}`);\n" ], "file_path": "src/vs/workbench/contrib/webview/browser/pre/main.js", "type": "replace", "edit_start_line_idx": 369 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // @ts-check /** * @typedef {{ * postMessage: (channel: string, data?: any) => void, * onMessage: (channel: string, handler: any) => void, * focusIframeOnCreate?: boolean, * ready?: Promise<void>, * onIframeLoaded?: (iframe: HTMLIFrameElement) => void, * fakeLoad?: boolean, * rewriteCSP: (existingCSP: string, endpoint?: string) => string, * }} WebviewHost */ (function () { 'use strict'; /** * Use polling to track focus of main webview and iframes within the webview * * @param {Object} handlers * @param {() => void} handlers.onFocus * @param {() => void} handlers.onBlur */ const trackFocus = ({ onFocus, onBlur }) => { const interval = 50; let isFocused = document.hasFocus(); setInterval(() => { const isCurrentlyFocused = document.hasFocus(); if (isCurrentlyFocused === isFocused) { return; } isFocused = isCurrentlyFocused; if (isCurrentlyFocused) { onFocus(); } else { onBlur(); } }, interval); }; const getActiveFrame = () => { return /** @type {HTMLIFrameElement} */ (document.getElementById('active-frame')); }; const getPendingFrame = () => { return /** @type {HTMLIFrameElement} */ (document.getElementById('pending-frame')); }; const defaultCssRules = ` body { background-color: var(--vscode-editor-background); color: var(--vscode-editor-foreground); font-family: var(--vscode-font-family); font-weight: var(--vscode-font-weight); font-size: var(--vscode-font-size); margin: 0; padding: 0 20px; } img { max-width: 100%; max-height: 100%; } a { color: var(--vscode-textLink-foreground); } a:hover { color: var(--vscode-textLink-activeForeground); } a:focus, input:focus, select:focus, textarea:focus { outline: 1px solid -webkit-focus-ring-color; outline-offset: -1px; } code { color: var(--vscode-textPreformat-foreground); } blockquote { background: var(--vscode-textBlockQuote-background); border-color: var(--vscode-textBlockQuote-border); } kbd { color: var(--vscode-editor-foreground); border-radius: 3px; vertical-align: middle; padding: 1px 3px; background-color: hsla(0,0%,50%,.17); border: 1px solid rgba(71,71,71,.4); border-bottom-color: rgba(88,88,88,.4); box-shadow: inset 0 -1px 0 rgba(88,88,88,.4); } .vscode-light kbd { background-color: hsla(0,0%,87%,.5); border: 1px solid hsla(0,0%,80%,.7); border-bottom-color: hsla(0,0%,73%,.7); box-shadow: inset 0 -1px 0 hsla(0,0%,73%,.7); } ::-webkit-scrollbar { width: 10px; height: 10px; } ::-webkit-scrollbar-corner { background-color: var(--vscode-editor-background); } ::-webkit-scrollbar-thumb { background-color: var(--vscode-scrollbarSlider-background); } ::-webkit-scrollbar-thumb:hover { background-color: var(--vscode-scrollbarSlider-hoverBackground); } ::-webkit-scrollbar-thumb:active { background-color: var(--vscode-scrollbarSlider-activeBackground); }`; /** * @param {boolean} allowMultipleAPIAcquire * @param {*} [state] * @return {string} */ function getVsCodeApiScript(allowMultipleAPIAcquire, state) { return ` const acquireVsCodeApi = (function() { const originalPostMessage = window.parent.postMessage.bind(window.parent); const targetOrigin = '*'; let acquired = false; let state = ${state ? `JSON.parse(${JSON.stringify(state)})` : undefined}; return () => { if (acquired && !${allowMultipleAPIAcquire}) { throw new Error('An instance of the VS Code API has already been acquired'); } acquired = true; return Object.freeze({ postMessage: function(msg) { return originalPostMessage({ command: 'onmessage', data: msg }, targetOrigin); }, setState: function(newState) { state = newState; originalPostMessage({ command: 'do-update-state', data: JSON.stringify(newState) }, targetOrigin); return newState; }, getState: function() { return state; } }); }; })(); delete window.parent; delete window.top; delete window.frameElement; `; } /** * @param {WebviewHost} host */ function createWebviewManager(host) { // state let firstLoad = true; let loadTimeout; let pendingMessages = []; const initData = { initialScrollProgress: undefined, }; /** * @param {HTMLDocument?} document * @param {HTMLElement?} body */ const applyStyles = (document, body) => { if (!document) { return; } if (body) { body.classList.remove('vscode-light', 'vscode-dark', 'vscode-high-contrast'); body.classList.add(initData.activeTheme); body.dataset.vscodeThemeKind = initData.activeTheme; body.dataset.vscodeThemeName = initData.themeName || ''; } if (initData.styles) { const documentStyle = document.documentElement.style; // Remove stale properties for (let i = documentStyle.length - 1; i >= 0; i--) { const property = documentStyle[i]; // Don't remove properties that the webview might have added separately if (property && property.startsWith('--vscode-')) { documentStyle.removeProperty(property); } } // Re-add new properties for (const variable of Object.keys(initData.styles)) { documentStyle.setProperty(`--${variable}`, initData.styles[variable]); } } }; /** * @param {MouseEvent} event */ const handleInnerClick = (event) => { if (!event || !event.view || !event.view.document) { return; } let baseElement = event.view.document.getElementsByTagName('base')[0]; /** @type {any} */ let node = event.target; while (node) { if (node.tagName && node.tagName.toLowerCase() === 'a' && node.href) { if (node.getAttribute('href') === '#') { event.view.scrollTo(0, 0); } else if (node.hash && (node.getAttribute('href') === node.hash || (baseElement && node.href.indexOf(baseElement.href) >= 0))) { let scrollTarget = event.view.document.getElementById(node.hash.substr(1, node.hash.length - 1)); if (scrollTarget) { scrollTarget.scrollIntoView(); } } else { host.postMessage('did-click-link', node.href.baseVal || node.href); } event.preventDefault(); break; } node = node.parentNode; } }; /** * @param {MouseEvent} event */ const handleAuxClick = (event) => { // Prevent middle clicks opening a broken link in the browser if (!event.view || !event.view.document) { return; } if (event.button === 1) { let node = /** @type {any} */ (event.target); while (node) { if (node.tagName && node.tagName.toLowerCase() === 'a' && node.href) { event.preventDefault(); break; } node = node.parentNode; } } }; /** * @param {KeyboardEvent} e */ const handleInnerKeydown = (e) => { host.postMessage('did-keydown', { key: e.key, keyCode: e.keyCode, code: e.code, shiftKey: e.shiftKey, altKey: e.altKey, ctrlKey: e.ctrlKey, metaKey: e.metaKey, repeat: e.repeat }); }; let isHandlingScroll = false; const handleWheel = (event) => { if (isHandlingScroll) { return; } host.postMessage('did-scroll-wheel', { deltaMode: event.deltaMode, deltaX: event.deltaX, deltaY: event.deltaY, deltaZ: event.deltaZ, detail: event.detail, type: event.type }); }; const handleInnerScroll = (event) => { if (!event.target || !event.target.body) { return; } if (isHandlingScroll) { return; } const progress = event.currentTarget.scrollY / event.target.body.clientHeight; if (isNaN(progress)) { return; } isHandlingScroll = true; window.requestAnimationFrame(() => { try { host.postMessage('did-scroll', progress); } catch (e) { // noop } isHandlingScroll = false; }); }; /** * @return {string} */ function toContentHtml(data) { const options = data.options; const text = data.contents; const newDocument = new DOMParser().parseFromString(text, 'text/html'); newDocument.querySelectorAll('a').forEach(a => { if (!a.title) { a.title = a.getAttribute('href'); } }); // apply default script if (options.allowScripts) { const defaultScript = newDocument.createElement('script'); defaultScript.id = '_vscodeApiScript'; defaultScript.textContent = getVsCodeApiScript(options.allowMultipleAPIAcquire, data.state); newDocument.head.prepend(defaultScript); } // apply default styles const defaultStyles = newDocument.createElement('style'); defaultStyles.id = '_defaultStyles'; defaultStyles.innerHTML = defaultCssRules; newDocument.head.prepend(defaultStyles); applyStyles(newDocument, newDocument.body); // Check for CSP const csp = newDocument.querySelector('meta[http-equiv="Content-Security-Policy"]'); if (!csp) { host.postMessage('no-csp-found'); } else { try { csp.setAttribute('content', host.rewriteCSP(csp.getAttribute('content'), data.endpoint)); } catch (e) { console.error('Could not rewrite csp'); } } // set DOCTYPE for newDocument explicitly as DOMParser.parseFromString strips it off // and DOCTYPE is needed in the iframe to ensure that the user agent stylesheet is correctly overridden return '<!DOCTYPE html>\n' + newDocument.documentElement.outerHTML; } document.addEventListener('DOMContentLoaded', () => { const idMatch = document.location.search.match(/\bid=([\w-]+)/); const ID = idMatch ? idMatch[1] : undefined; if (!document.body) { return; } host.onMessage('styles', (_event, data) => { initData.styles = data.styles; initData.activeTheme = data.activeTheme; initData.themeName = data.themeName; const target = getActiveFrame(); if (!target) { return; } if (target.contentDocument) { applyStyles(target.contentDocument, target.contentDocument.body); } }); // propagate focus host.onMessage('focus', () => { const target = getActiveFrame(); if (target) { target.contentWindow.focus(); } }); // update iframe-contents let updateId = 0; host.onMessage('content', async (_event, data) => { const currentUpdateId = ++updateId; await host.ready; if (currentUpdateId !== updateId) { return; } const options = data.options; const newDocument = toContentHtml(data); const frame = getActiveFrame(); const wasFirstLoad = firstLoad; // keep current scrollY around and use later let setInitialScrollPosition; if (firstLoad) { firstLoad = false; setInitialScrollPosition = (body, window) => { if (!isNaN(initData.initialScrollProgress)) { if (window.scrollY === 0) { window.scroll(0, body.clientHeight * initData.initialScrollProgress); } } }; } else { const scrollY = frame && frame.contentDocument && frame.contentDocument.body ? frame.contentWindow.scrollY : 0; setInitialScrollPosition = (body, window) => { if (window.scrollY === 0) { window.scroll(0, scrollY); } }; } // Clean up old pending frames and set current one as new one const previousPendingFrame = getPendingFrame(); if (previousPendingFrame) { previousPendingFrame.setAttribute('id', ''); document.body.removeChild(previousPendingFrame); } if (!wasFirstLoad) { pendingMessages = []; } const newFrame = document.createElement('iframe'); newFrame.setAttribute('id', 'pending-frame'); newFrame.setAttribute('frameborder', '0'); newFrame.setAttribute('sandbox', options.allowScripts ? 'allow-scripts allow-forms allow-same-origin' : 'allow-same-origin'); if (host.fakeLoad) { // We should just be able to use srcdoc, but I wasn't // seeing the service worker applying properly. // Fake load an empty on the correct origin and then write real html // into it to get around this. newFrame.src = `./fake.html?id=${ID}`; } newFrame.style.cssText = 'display: block; margin: 0; overflow: hidden; position: absolute; width: 100%; height: 100%; visibility: hidden'; document.body.appendChild(newFrame); if (!host.fakeLoad) { // write new content onto iframe newFrame.contentDocument.open(); } newFrame.contentWindow.addEventListener('DOMContentLoaded', e => { // Workaround for https://bugs.chromium.org/p/chromium/issues/detail?id=978325 setTimeout(() => { if (host.fakeLoad) { newFrame.contentDocument.open(); newFrame.contentDocument.write(newDocument); newFrame.contentDocument.close(); hookupOnLoadHandlers(newFrame); } const contentDocument = e.target ? (/** @type {HTMLDocument} */ (e.target)) : undefined; if (contentDocument) { applyStyles(contentDocument, contentDocument.body); } }, 0); }); /** * @param {Document} contentDocument * @param {Window} contentWindow */ const onLoad = (contentDocument, contentWindow) => { if (contentDocument && contentDocument.body) { // Workaround for https://github.com/Microsoft/vscode/issues/12865 // check new scrollY and reset if necessary setInitialScrollPosition(contentDocument.body, contentWindow); } const newFrame = getPendingFrame(); if (newFrame && newFrame.contentDocument && newFrame.contentDocument === contentDocument) { const oldActiveFrame = getActiveFrame(); if (oldActiveFrame) { document.body.removeChild(oldActiveFrame); } // Styles may have changed since we created the element. Make sure we re-style applyStyles(newFrame.contentDocument, newFrame.contentDocument.body); newFrame.setAttribute('id', 'active-frame'); newFrame.style.visibility = 'visible'; if (host.focusIframeOnCreate) { newFrame.contentWindow.focus(); } contentWindow.addEventListener('scroll', handleInnerScroll); contentWindow.addEventListener('wheel', handleWheel); pendingMessages.forEach((data) => { contentWindow.postMessage(data, '*'); }); pendingMessages = []; } host.postMessage('did-load'); }; /** * @param {HTMLIFrameElement} newFrame */ function hookupOnLoadHandlers(newFrame) { clearTimeout(loadTimeout); loadTimeout = undefined; loadTimeout = setTimeout(() => { clearTimeout(loadTimeout); loadTimeout = undefined; onLoad(newFrame.contentDocument, newFrame.contentWindow); }, 200); newFrame.contentWindow.addEventListener('load', function (e) { const contentDocument = /** @type {Document} */ (e.target); if (loadTimeout) { clearTimeout(loadTimeout); loadTimeout = undefined; onLoad(contentDocument, this); } }); // Bubble out various events newFrame.contentWindow.addEventListener('click', handleInnerClick); newFrame.contentWindow.addEventListener('auxclick', handleAuxClick); newFrame.contentWindow.addEventListener('keydown', handleInnerKeydown); newFrame.contentWindow.addEventListener('contextmenu', e => e.preventDefault()); if (host.onIframeLoaded) { host.onIframeLoaded(newFrame); } } if (!host.fakeLoad) { hookupOnLoadHandlers(newFrame); } if (!host.fakeLoad) { newFrame.contentDocument.write(newDocument); newFrame.contentDocument.close(); } host.postMessage('did-set-content', undefined); }); // Forward message to the embedded iframe host.onMessage('message', (_event, data) => { const pending = getPendingFrame(); if (!pending) { const target = getActiveFrame(); if (target) { target.contentWindow.postMessage(data, '*'); return; } } pendingMessages.push(data); }); host.onMessage('initial-scroll-position', (_event, progress) => { initData.initialScrollProgress = progress; }); host.onMessage('execCommand', (_event, data) => { const target = getActiveFrame(); if (!target) { return; } target.contentDocument.execCommand(data); }); trackFocus({ onFocus: () => host.postMessage('did-focus'), onBlur: () => host.postMessage('did-blur') }); // signal ready host.postMessage('webview-ready', {}); }); } if (typeof module !== 'undefined') { module.exports = createWebviewManager; } else { (/** @type {any} */ (window)).createWebviewManager = createWebviewManager; } }());
src/vs/workbench/contrib/webview/browser/pre/main.js
1
https://github.com/microsoft/vscode/commit/a20f2e6ba5a2114dabad5bd68a61dc549b2c9d52
[ 0.9978498220443726, 0.017198320478200912, 0.0001614022912690416, 0.00017299791215918958, 0.12563616037368774 ]
{ "id": 3, "code_window": [ "\t\t\t\thost.postMessage('no-csp-found');\n", "\t\t\t} else {\n", "\t\t\t\ttry {\n", "\t\t\t\t\tcsp.setAttribute('content', host.rewriteCSP(csp.getAttribute('content'), data.endpoint));\n", "\t\t\t\t} catch (e) {\n", "\t\t\t\t\tconsole.error('Could not rewrite csp');\n", "\t\t\t\t}\n", "\t\t\t}\n", "\n", "\t\t\t// set DOCTYPE for newDocument explicitly as DOMParser.parseFromString strips it off\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\t\tconsole.error(`Could not rewrite csp: ${e}`);\n" ], "file_path": "src/vs/workbench/contrib/webview/browser/pre/main.js", "type": "replace", "edit_start_line_idx": 369 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { MarkdownIt, Token } from 'markdown-it'; import * as path from 'path'; import * as vscode from 'vscode'; import { MarkdownContributionProvider as MarkdownContributionProvider } from './markdownExtensions'; import { Slugifier } from './slugify'; import { SkinnyTextDocument } from './tableOfContentsProvider'; import { hash } from './util/hash'; import { isOfScheme, MarkdownFileExtensions, Schemes } from './util/links'; const UNICODE_NEWLINE_REGEX = /\u2028|\u2029/g; interface MarkdownItConfig { readonly breaks: boolean; readonly linkify: boolean; } class TokenCache { private cachedDocument?: { readonly uri: vscode.Uri; readonly version: number; readonly config: MarkdownItConfig; }; private tokens?: Token[]; public tryGetCached(document: SkinnyTextDocument, config: MarkdownItConfig): Token[] | undefined { if (this.cachedDocument && this.cachedDocument.uri.toString() === document.uri.toString() && this.cachedDocument.version === document.version && this.cachedDocument.config.breaks === config.breaks && this.cachedDocument.config.linkify === config.linkify ) { return this.tokens; } return undefined; } public update(document: SkinnyTextDocument, config: MarkdownItConfig, tokens: Token[]) { this.cachedDocument = { uri: document.uri, version: document.version, config, }; this.tokens = tokens; } public clean(): void { this.cachedDocument = undefined; this.tokens = undefined; } } export class MarkdownEngine { private md?: Promise<MarkdownIt>; private currentDocument?: vscode.Uri; private _slugCount = new Map<string, number>(); private _tokenCache = new TokenCache(); public constructor( private readonly contributionProvider: MarkdownContributionProvider, private readonly slugifier: Slugifier, ) { contributionProvider.onContributionsChanged(() => { // Markdown plugin contributions may have changed this.md = undefined; }); } private async getEngine(config: MarkdownItConfig): Promise<MarkdownIt> { if (!this.md) { this.md = import('markdown-it').then(async markdownIt => { let md: MarkdownIt = markdownIt(await getMarkdownOptions(() => md)); for (const plugin of this.contributionProvider.contributions.markdownItPlugins.values()) { try { md = (await plugin)(md); } catch { // noop } } const frontMatterPlugin = require('markdown-it-front-matter'); // Extract rules from front matter plugin and apply at a lower precedence let fontMatterRule: any; frontMatterPlugin({ block: { ruler: { before: (_id: any, _id2: any, rule: any) => { fontMatterRule = rule; } } } }, () => { /* noop */ }); md.block.ruler.before('fence', 'front_matter', fontMatterRule, { alt: ['paragraph', 'reference', 'blockquote', 'list'] }); for (const renderName of ['paragraph_open', 'heading_open', 'image', 'code_block', 'fence', 'blockquote_open', 'list_item_open']) { this.addLineNumberRenderer(md, renderName); } this.addImageStabilizer(md); this.addFencedRenderer(md); this.addLinkNormalizer(md); this.addLinkValidator(md); this.addNamedHeaders(md); this.addLinkRenderer(md); return md; }); } const md = await this.md!; md.set(config); return md; } private tokenizeDocument( document: SkinnyTextDocument, config: MarkdownItConfig, engine: MarkdownIt ): Token[] { const cached = this._tokenCache.tryGetCached(document, config); if (cached) { return cached; } this.currentDocument = document.uri; this._slugCount = new Map<string, number>(); const tokens = this.tokenizeString(document.getText(), engine); this._tokenCache.update(document, config, tokens); return tokens; } private tokenizeString(text: string, engine: MarkdownIt) { return engine.parse(text.replace(UNICODE_NEWLINE_REGEX, ''), {}); } public async render(input: SkinnyTextDocument | string): Promise<string> { const config = this.getConfig(typeof input === 'string' ? undefined : input.uri); const engine = await this.getEngine(config); const tokens = typeof input === 'string' ? this.tokenizeString(input, engine) : this.tokenizeDocument(input, config, engine); return engine.renderer.render(tokens, { ...(engine as any).options, ...config }, {}); } public async parse(document: SkinnyTextDocument): Promise<Token[]> { const config = this.getConfig(document.uri); const engine = await this.getEngine(config); return this.tokenizeDocument(document, config, engine); } public cleanCache(): void { this._tokenCache.clean(); } private getConfig(resource?: vscode.Uri): MarkdownItConfig { const config = vscode.workspace.getConfiguration('markdown', resource); return { breaks: config.get<boolean>('preview.breaks', false), linkify: config.get<boolean>('preview.linkify', true) }; } private addLineNumberRenderer(md: any, ruleName: string): void { const original = md.renderer.rules[ruleName]; md.renderer.rules[ruleName] = (tokens: any, idx: number, options: any, env: any, self: any) => { const token = tokens[idx]; if (token.map && token.map.length) { token.attrSet('data-line', token.map[0]); token.attrJoin('class', 'code-line'); } if (original) { return original(tokens, idx, options, env, self); } else { return self.renderToken(tokens, idx, options, env, self); } }; } private addImageStabilizer(md: any): void { const original = md.renderer.rules.image; md.renderer.rules.image = (tokens: any, idx: number, options: any, env: any, self: any) => { const token = tokens[idx]; token.attrJoin('class', 'loading'); const src = token.attrGet('src'); if (src) { const imgHash = hash(src); token.attrSet('id', `image-hash-${imgHash}`); } if (original) { return original(tokens, idx, options, env, self); } else { return self.renderToken(tokens, idx, options, env, self); } }; } private addFencedRenderer(md: any): void { const original = md.renderer.rules['fenced']; md.renderer.rules['fenced'] = (tokens: any, idx: number, options: any, env: any, self: any) => { const token = tokens[idx]; if (token.map && token.map.length) { token.attrJoin('class', 'hljs'); } return original(tokens, idx, options, env, self); }; } private addLinkNormalizer(md: any): void { const normalizeLink = md.normalizeLink; md.normalizeLink = (link: string) => { try { // Normalize VS Code schemes to target the current version if (isOfScheme(Schemes.vscode, link) || isOfScheme(Schemes['vscode-insiders'], link)) { return normalizeLink(vscode.Uri.parse(link).with({ scheme: vscode.env.uriScheme }).toString()); } // If original link doesn't look like a url with a scheme, assume it must be a link to a file in workspace if (!/^[a-z\-]+:/i.test(link)) { // Use a fake scheme for parsing let uri = vscode.Uri.parse('markdown-link:' + link); // Relative paths should be resolved correctly inside the preview but we need to // handle absolute paths specially (for images) to resolve them relative to the workspace root if (uri.path[0] === '/') { const root = vscode.workspace.getWorkspaceFolder(this.currentDocument!); if (root) { const fileUri = vscode.Uri.joinPath(root.uri, uri.fsPath); uri = fileUri.with({ scheme: uri.scheme, fragment: uri.fragment, query: uri.query, }); } } const extname = path.extname(uri.fsPath); if (uri.fragment && (extname === '' || MarkdownFileExtensions.includes(extname))) { uri = uri.with({ fragment: this.slugifier.fromHeading(uri.fragment).value }); } return normalizeLink(uri.toString(true).replace(/^markdown-link:/, '')); } } catch (e) { // noop } return normalizeLink(link); }; } private addLinkValidator(md: any): void { const validateLink = md.validateLink; md.validateLink = (link: string) => { // support file:// links return validateLink(link) || isOfScheme(Schemes.file, link) || isOfScheme(Schemes.vscode, link) || isOfScheme(Schemes['vscode-insiders'], link) || /^data:image\/.*?;/.test(link); }; } private addNamedHeaders(md: any): void { const original = md.renderer.rules.heading_open; md.renderer.rules.heading_open = (tokens: any, idx: number, options: any, env: any, self: any) => { const title = tokens[idx + 1].children.reduce((acc: string, t: any) => acc + t.content, ''); let slug = this.slugifier.fromHeading(title); if (this._slugCount.has(slug.value)) { const count = this._slugCount.get(slug.value)!; this._slugCount.set(slug.value, count + 1); slug = this.slugifier.fromHeading(slug.value + '-' + (count + 1)); } else { this._slugCount.set(slug.value, 0); } tokens[idx].attrs = tokens[idx].attrs || []; tokens[idx].attrs.push(['id', slug.value]); if (original) { return original(tokens, idx, options, env, self); } else { return self.renderToken(tokens, idx, options, env, self); } }; } private addLinkRenderer(md: any): void { const old_render = md.renderer.rules.link_open || ((tokens: any, idx: number, options: any, _env: any, self: any) => { return self.renderToken(tokens, idx, options); }); md.renderer.rules.link_open = (tokens: any, idx: number, options: any, env: any, self: any) => { const token = tokens[idx]; const hrefIndex = token.attrIndex('href'); if (hrefIndex >= 0) { const href = token.attrs[hrefIndex][1]; token.attrPush(['data-href', href]); } return old_render(tokens, idx, options, env, self); }; } } async function getMarkdownOptions(md: () => MarkdownIt) { const hljs = await import('highlight.js'); return { html: true, highlight: (str: string, lang?: string) => { lang = normalizeHighlightLang(lang); if (lang && hljs.getLanguage(lang)) { try { return `<div>${hljs.highlight(lang, str, true).value}</div>`; } catch (error) { } } return `<code><div>${md().utils.escapeHtml(str)}</div></code>`; } }; } function normalizeHighlightLang(lang: string | undefined) { switch (lang && lang.toLowerCase()) { case 'tsx': case 'typescriptreact': // Workaround for highlight not supporting tsx: https://github.com/isagalaev/highlight.js/issues/1155 return 'jsx'; case 'json5': case 'jsonc': return 'json'; case 'c#': case 'csharp': return 'cs'; default: return lang; } }
extensions/markdown-language-features/src/markdownEngine.ts
0
https://github.com/microsoft/vscode/commit/a20f2e6ba5a2114dabad5bd68a61dc549b2c9d52
[ 0.00017631356604397297, 0.0001707737537799403, 0.00016479509940836579, 0.0001710683573037386, 0.000003015434003827977 ]
{ "id": 3, "code_window": [ "\t\t\t\thost.postMessage('no-csp-found');\n", "\t\t\t} else {\n", "\t\t\t\ttry {\n", "\t\t\t\t\tcsp.setAttribute('content', host.rewriteCSP(csp.getAttribute('content'), data.endpoint));\n", "\t\t\t\t} catch (e) {\n", "\t\t\t\t\tconsole.error('Could not rewrite csp');\n", "\t\t\t\t}\n", "\t\t\t}\n", "\n", "\t\t\t// set DOCTYPE for newDocument explicitly as DOMParser.parseFromString strips it off\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\t\tconsole.error(`Could not rewrite csp: ${e}`);\n" ], "file_path": "src/vs/workbench/contrib/webview/browser/pre/main.js", "type": "replace", "edit_start_line_idx": 369 }
.DS_Store npm-debug.log Thumbs.db node_modules/ out/ keybindings.*.json src/driver.d.ts *.tgz
test/automation/.gitignore
0
https://github.com/microsoft/vscode/commit/a20f2e6ba5a2114dabad5bd68a61dc549b2c9d52
[ 0.00017330468108411878, 0.00017330468108411878, 0.00017330468108411878, 0.00017330468108411878, 0 ]
{ "id": 3, "code_window": [ "\t\t\t\thost.postMessage('no-csp-found');\n", "\t\t\t} else {\n", "\t\t\t\ttry {\n", "\t\t\t\t\tcsp.setAttribute('content', host.rewriteCSP(csp.getAttribute('content'), data.endpoint));\n", "\t\t\t\t} catch (e) {\n", "\t\t\t\t\tconsole.error('Could not rewrite csp');\n", "\t\t\t\t}\n", "\t\t\t}\n", "\n", "\t\t\t// set DOCTYPE for newDocument explicitly as DOMParser.parseFromString strips it off\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\t\tconsole.error(`Could not rewrite csp: ${e}`);\n" ], "file_path": "src/vs/workbench/contrib/webview/browser/pre/main.js", "type": "replace", "edit_start_line_idx": 369 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ //@ts-check 'use strict'; const perf = (function () { let sharedObj; if (typeof global === 'object') { // nodejs sharedObj = global; } else if (typeof self === 'object') { // browser sharedObj = self; } else { sharedObj = {}; } // @ts-ignore sharedObj._performanceEntries = sharedObj._performanceEntries || []; return { /** * @param {string} name */ mark(name) { sharedObj._performanceEntries.push(name, Date.now()); } }; })(); perf.mark('renderer/started'); const bootstrapWindow = require('../../../../bootstrap-window'); // Setup shell environment process['lazyEnv'] = getLazyEnv(); // Load workbench main JS, CSS and NLS all in parallel. This is an // optimization to prevent a waterfall of loading to happen, because // we know for a fact that workbench.desktop.main will depend on // the related CSS and NLS counterparts. bootstrapWindow.load([ 'vs/workbench/workbench.desktop.main', 'vs/nls!vs/workbench/workbench.desktop.main', 'vs/css!vs/workbench/workbench.desktop.main' ], function (workbench, configuration) { perf.mark('didLoadWorkbenchMain'); return process['lazyEnv'].then(function () { perf.mark('main/startup'); // @ts-ignore return require('vs/workbench/electron-browser/desktop.main').main(configuration); }); }, { removeDeveloperKeybindingsAfterLoad: true, canModifyDOM: function (windowConfig) { showPartsSplash(windowConfig); }, beforeLoaderConfig: function (windowConfig, loaderConfig) { loaderConfig.recordStats = true; }, beforeRequire: function () { perf.mark('willLoadWorkbenchMain'); } }); /** * @param {{ * partsSplashPath?: string, * highContrast?: boolean, * defaultThemeType?: string, * extensionDevelopmentPath?: string[], * folderUri?: object, * workspace?: object * }} configuration */ function showPartsSplash(configuration) { perf.mark('willShowPartsSplash'); let data; if (typeof configuration.partsSplashPath === 'string') { try { data = JSON.parse(require('fs').readFileSync(configuration.partsSplashPath, 'utf8')); } catch (e) { // ignore } } // high contrast mode has been turned on from the outside, e.g. OS -> ignore stored colors and layouts if (data && configuration.highContrast && data.baseTheme !== 'hc-black') { data = undefined; } // developing an extension -> ignore stored layouts if (data && configuration.extensionDevelopmentPath) { data.layoutInfo = undefined; } // minimal color configuration (works with or without persisted data) let baseTheme, shellBackground, shellForeground; if (data) { baseTheme = data.baseTheme; shellBackground = data.colorInfo.editorBackground; shellForeground = data.colorInfo.foreground; } else if (configuration.highContrast || configuration.defaultThemeType === 'hc') { baseTheme = 'hc-black'; shellBackground = '#000000'; shellForeground = '#FFFFFF'; } else if (configuration.defaultThemeType === 'vs') { baseTheme = 'vs'; shellBackground = '#FFFFFF'; shellForeground = '#000000'; } else { baseTheme = 'vs-dark'; shellBackground = '#1E1E1E'; shellForeground = '#CCCCCC'; } const style = document.createElement('style'); style.className = 'initialShellColors'; document.head.appendChild(style); style.innerHTML = `body { background-color: ${shellBackground}; color: ${shellForeground}; margin: 0; padding: 0; }`; if (data && data.layoutInfo) { // restore parts if possible (we might not always store layout info) const { id, layoutInfo, colorInfo } = data; const splash = document.createElement('div'); splash.id = id; splash.className = baseTheme; if (layoutInfo.windowBorder) { splash.style.position = 'relative'; splash.style.height = 'calc(100vh - 2px)'; splash.style.width = 'calc(100vw - 2px)'; splash.style.border = '1px solid var(--window-border-color)'; splash.style.setProperty('--window-border-color', colorInfo.windowBorder); if (layoutInfo.windowBorderRadius) { splash.style.borderRadius = layoutInfo.windowBorderRadius; } } // ensure there is enough space layoutInfo.sideBarWidth = Math.min(layoutInfo.sideBarWidth, window.innerWidth - (layoutInfo.activityBarWidth + layoutInfo.editorPartMinWidth)); if (configuration.folderUri || configuration.workspace) { // folder or workspace -> status bar color, sidebar splash.innerHTML = ` <div style="position: absolute; width: 100%; left: 0; top: 0; height: ${layoutInfo.titleBarHeight}px; background-color: ${colorInfo.titleBarBackground}; -webkit-app-region: drag;"></div> <div style="position: absolute; height: calc(100% - ${layoutInfo.titleBarHeight}px); top: ${layoutInfo.titleBarHeight}px; ${layoutInfo.sideBarSide}: 0; width: ${layoutInfo.activityBarWidth}px; background-color: ${colorInfo.activityBarBackground};"></div> <div style="position: absolute; height: calc(100% - ${layoutInfo.titleBarHeight}px); top: ${layoutInfo.titleBarHeight}px; ${layoutInfo.sideBarSide}: ${layoutInfo.activityBarWidth}px; width: ${layoutInfo.sideBarWidth}px; background-color: ${colorInfo.sideBarBackground};"></div> <div style="position: absolute; width: 100%; bottom: 0; left: 0; height: ${layoutInfo.statusBarHeight}px; background-color: ${colorInfo.statusBarBackground};"></div> `; } else { // empty -> speical status bar color, no sidebar splash.innerHTML = ` <div style="position: absolute; width: 100%; left: 0; top: 0; height: ${layoutInfo.titleBarHeight}px; background-color: ${colorInfo.titleBarBackground}; -webkit-app-region: drag;"></div> <div style="position: absolute; height: calc(100% - ${layoutInfo.titleBarHeight}px); top: ${layoutInfo.titleBarHeight}px; ${layoutInfo.sideBarSide}: 0; width: ${layoutInfo.activityBarWidth}px; background-color: ${colorInfo.activityBarBackground};"></div> <div style="position: absolute; width: 100%; bottom: 0; left: 0; height: ${layoutInfo.statusBarHeight}px; background-color: ${colorInfo.statusBarNoFolderBackground};"></div> `; } document.body.appendChild(splash); } perf.mark('didShowPartsSplash'); } /** * @returns {Promise<void>} */ function getLazyEnv() { const ipc = require('electron').ipcRenderer; return new Promise(function (resolve) { const handle = setTimeout(function () { resolve(); console.warn('renderer did not receive lazyEnv in time'); }, 10000); ipc.once('vscode:acceptShellEnv', function (event, shellEnv) { clearTimeout(handle); bootstrapWindow.assign(process.env, shellEnv); // @ts-ignore resolve(process.env); }); ipc.send('vscode:fetchShellEnv'); }); }
src/vs/code/electron-browser/workbench/workbench.js
0
https://github.com/microsoft/vscode/commit/a20f2e6ba5a2114dabad5bd68a61dc549b2c9d52
[ 0.001227329601533711, 0.0002409601875115186, 0.00016587894060648978, 0.00017246362403966486, 0.00023713475093245506 ]
{ "id": 0, "code_window": [ "\t\t\t}\n", "\t\t}\n", "\n", "\t\tarrays.coalesce([\n", "\t\t\tproduct.documentationUrl ? new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miDocumentation', comment: ['&& denotes a mnemonic'] }, \"&&Documentation\")), click: () => this.openUrl(product.documentationUrl, 'openDocumentationUrl') }) : null,\n", "\t\t\tproduct.releaseNotesUrl ? new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miReleaseNotes', comment: ['&& denotes a mnemonic'] }, \"&&Release Notes\")), click: () => this.windowsService.sendToFocused('vscode:runAction', 'update.showCurrentReleaseNotes') }) : null,\n", "\t\t\t(product.documentationUrl || product.releaseNotesUrl) ? __separator__() : null,\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tconst keyboardShortcutsUrl = platform.isLinux ? product.keyboardShortcutsUrlLinux : platform.isMacintosh ? product.keyboardShortcutsUrlMac : product.keyboardShortcutsUrlWin;\n" ], "file_path": "src/vs/code/electron-main/menus.ts", "type": "add", "edit_start_line_idx": 695 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import * as nls from 'vs/nls'; import * as platform from 'vs/base/common/platform'; import * as arrays from 'vs/base/common/arrays'; import { IEnvironmentService } from 'vs/platform/environment/common/environment'; import { ipcMain as ipc, app, shell, dialog, Menu, MenuItem } from 'electron'; import { IWindowsService } from 'vs/code/electron-main/windows'; import { IPath, VSCodeWindow } from 'vs/code/electron-main/window'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IStorageService } from 'vs/code/electron-main/storage'; import { IFilesConfiguration, AutoSaveConfiguration } from 'vs/platform/files/common/files'; import { IUpdateService, State as UpdateState } from 'vs/code/electron-main/update-manager'; import { Keybinding } from 'vs/base/common/keybinding'; import product from 'vs/platform/product'; interface IResolvedKeybinding { id: string; binding: number; } interface IConfiguration extends IFilesConfiguration { workbench: { sideBar: { location: 'left' | 'right'; }, statusBar: { visible: boolean; } }; } export class VSCodeMenu { private static lastKnownKeybindingsMapStorageKey = 'lastKnownKeybindings'; private static MAX_MENU_RECENT_ENTRIES = 10; private currentAutoSaveSetting: string; private currentSidebarLocation: 'left' | 'right'; private currentStatusbarVisible: boolean; private isQuitting: boolean; private appMenuInstalled: boolean; private actionIdKeybindingRequests: string[]; private mapLastKnownKeybindingToActionId: { [id: string]: string; }; private mapResolvedKeybindingToActionId: { [id: string]: string; }; private keybindingsResolved: boolean; constructor( @IStorageService private storageService: IStorageService, @IUpdateService private updateService: IUpdateService, @IConfigurationService private configurationService: IConfigurationService, @IWindowsService private windowsService: IWindowsService, @IEnvironmentService private environmentService: IEnvironmentService ) { this.actionIdKeybindingRequests = []; this.mapResolvedKeybindingToActionId = Object.create(null); this.mapLastKnownKeybindingToActionId = this.storageService.getItem<{ [id: string]: string; }>(VSCodeMenu.lastKnownKeybindingsMapStorageKey) || Object.create(null); this.onConfigurationUpdated(this.configurationService.getConfiguration<IConfiguration>()); } public ready(): void { this.registerListeners(); this.install(); } private registerListeners(): void { // Keep flag when app quits app.on('will-quit', () => { this.isQuitting = true; }); // Listen to "open" & "close" event from window service this.windowsService.onOpen(paths => this.onOpen(paths)); this.windowsService.onClose(_ => this.onClose(this.windowsService.getWindowCount())); // Resolve keybindings when any first workbench is loaded this.windowsService.onReady(win => this.resolveKeybindings(win)); // Listen to resolved keybindings ipc.on('vscode:keybindingsResolved', (event, rawKeybindings) => { let keybindings: IResolvedKeybinding[] = []; try { keybindings = JSON.parse(rawKeybindings); } catch (error) { // Should not happen } // Fill hash map of resolved keybindings let needsMenuUpdate = false; keybindings.forEach(keybinding => { const accelerator = new Keybinding(keybinding.binding)._toElectronAccelerator(); if (accelerator) { this.mapResolvedKeybindingToActionId[keybinding.id] = accelerator; if (this.mapLastKnownKeybindingToActionId[keybinding.id] !== accelerator) { needsMenuUpdate = true; // we only need to update when something changed! } } }); // A keybinding might have been unassigned, so we have to account for that too if (Object.keys(this.mapLastKnownKeybindingToActionId).length !== Object.keys(this.mapResolvedKeybindingToActionId).length) { needsMenuUpdate = true; } if (needsMenuUpdate) { this.storageService.setItem(VSCodeMenu.lastKnownKeybindingsMapStorageKey, this.mapResolvedKeybindingToActionId); // keep to restore instantly after restart this.mapLastKnownKeybindingToActionId = this.mapResolvedKeybindingToActionId; // update our last known map this.updateMenu(); } }); // Update when auto save config changes this.configurationService.onDidUpdateConfiguration(e => this.onConfigurationUpdated(e.config, true /* update menu if changed */)); // Listen to update service this.updateService.on('change', () => this.updateMenu()); } private onConfigurationUpdated(config: IConfiguration, handleMenu?: boolean): void { let updateMenu = false; const newAutoSaveSetting = config && config.files && config.files.autoSave; if (newAutoSaveSetting !== this.currentAutoSaveSetting) { this.currentAutoSaveSetting = newAutoSaveSetting; updateMenu = true; } if (config && config.workbench) { const newSidebarLocation = config.workbench.sideBar && config.workbench.sideBar.location || 'left'; if (newSidebarLocation !== this.currentSidebarLocation) { this.currentSidebarLocation = newSidebarLocation; updateMenu = true; } let newStatusbarVisible = config.workbench.statusBar && config.workbench.statusBar.visible; if (typeof newStatusbarVisible !== 'boolean') { newStatusbarVisible = true; } if (newStatusbarVisible !== this.currentStatusbarVisible) { this.currentStatusbarVisible = newStatusbarVisible; updateMenu = true; } } if (handleMenu && updateMenu) { this.updateMenu(); } } private resolveKeybindings(win: VSCodeWindow): void { if (this.keybindingsResolved) { return; // only resolve once } this.keybindingsResolved = true; // Resolve keybindings when workbench window is up if (this.actionIdKeybindingRequests.length) { win.send('vscode:resolveKeybindings', JSON.stringify(this.actionIdKeybindingRequests)); } } private updateMenu(): void { // Due to limitations in Electron, it is not possible to update menu items dynamically. The suggested // workaround from Electron is to set the application menu again. // See also https://github.com/electron/electron/issues/846 // // Run delayed to prevent updating menu while it is open if (!this.isQuitting) { setTimeout(() => { if (!this.isQuitting) { this.install(); } }, 10 /* delay this because there is an issue with updating a menu when it is open */); } } private onOpen(path: IPath): void { this.updateMenu(); } private onClose(remainingWindowCount: number): void { if (remainingWindowCount === 0 && platform.isMacintosh) { this.updateMenu(); } } private install(): void { // Menus const menubar = new Menu(); // Mac: Application let macApplicationMenuItem: Electron.MenuItem; if (platform.isMacintosh) { const applicationMenu = new Menu(); macApplicationMenuItem = new MenuItem({ label: product.nameShort, submenu: applicationMenu }); this.setMacApplicationMenu(applicationMenu); } // File const fileMenu = new Menu(); const fileMenuItem = new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'mFile', comment: ['&& denotes a mnemonic'] }, "&&File")), submenu: fileMenu }); this.setFileMenu(fileMenu); // Edit const editMenu = new Menu(); const editMenuItem = new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'mEdit', comment: ['&& denotes a mnemonic'] }, "&&Edit")), submenu: editMenu }); this.setEditMenu(editMenu); // View const viewMenu = new Menu(); const viewMenuItem = new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'mView', comment: ['&& denotes a mnemonic'] }, "&&View")), submenu: viewMenu }); this.setViewMenu(viewMenu); // Goto const gotoMenu = new Menu(); const gotoMenuItem = new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'mGoto', comment: ['&& denotes a mnemonic'] }, "&&Go")), submenu: gotoMenu }); this.setGotoMenu(gotoMenu); // Mac: Window let macWindowMenuItem: Electron.MenuItem; if (platform.isMacintosh) { const windowMenu = new Menu(); macWindowMenuItem = new MenuItem({ label: mnemonicLabel(nls.localize('mWindow', "Window")), submenu: windowMenu, role: 'window' }); this.setMacWindowMenu(windowMenu); } // Help const helpMenu = new Menu(); const helpMenuItem = new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'mHelp', comment: ['&& denotes a mnemonic'] }, "&&Help")), submenu: helpMenu, role: 'help' }); this.setHelpMenu(helpMenu); // Menu Structure if (macApplicationMenuItem) { menubar.append(macApplicationMenuItem); } menubar.append(fileMenuItem); menubar.append(editMenuItem); menubar.append(viewMenuItem); menubar.append(gotoMenuItem); if (macWindowMenuItem) { menubar.append(macWindowMenuItem); } menubar.append(helpMenuItem); Menu.setApplicationMenu(menubar); // Dock Menu if (platform.isMacintosh && !this.appMenuInstalled) { this.appMenuInstalled = true; const dockMenu = new Menu(); dockMenu.append(new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miNewWindow', comment: ['&& denotes a mnemonic'] }, "&&New Window")), click: () => this.windowsService.openNewWindow() })); app.dock.setMenu(dockMenu); } } private setMacApplicationMenu(macApplicationMenu: Electron.Menu): void { const about = new MenuItem({ label: nls.localize('mAbout', "About {0}", product.nameLong), role: 'about' }); const checkForUpdates = this.getUpdateMenuItems(); const preferences = this.getPreferencesMenu(); const hide = new MenuItem({ label: nls.localize('mHide', "Hide {0}", product.nameLong), role: 'hide', accelerator: 'Command+H' }); const hideOthers = new MenuItem({ label: nls.localize('mHideOthers', "Hide Others"), role: 'hideothers', accelerator: 'Command+Alt+H' }); const showAll = new MenuItem({ label: nls.localize('mShowAll', "Show All"), role: 'unhide' }); const quit = new MenuItem({ label: nls.localize('miQuit', "Quit {0}", product.nameLong), click: () => this.quit(), accelerator: 'Command+Q' }); const actions = [about]; actions.push(...checkForUpdates); actions.push(...[ __separator__(), preferences, __separator__(), hide, hideOthers, showAll, __separator__(), quit ]); actions.forEach(i => macApplicationMenu.append(i)); } private setFileMenu(fileMenu: Electron.Menu): void { const hasNoWindows = (this.windowsService.getWindowCount() === 0); let newFile: Electron.MenuItem; if (hasNoWindows) { newFile = new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miNewFile', comment: ['&& denotes a mnemonic'] }, "&&New File")), accelerator: this.getAccelerator('workbench.action.files.newUntitledFile'), click: () => this.windowsService.openNewWindow() }); } else { newFile = this.createMenuItem(nls.localize({ key: 'miNewFile', comment: ['&& denotes a mnemonic'] }, "&&New File"), 'workbench.action.files.newUntitledFile'); } const open = new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miOpen', comment: ['&& denotes a mnemonic'] }, "&&Open...")), accelerator: this.getAccelerator('workbench.action.files.openFileFolder'), click: () => this.windowsService.openFileFolderPicker() }); const openFolder = new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miOpenFolder', comment: ['&& denotes a mnemonic'] }, "Open &&Folder...")), accelerator: this.getAccelerator('workbench.action.files.openFolder'), click: () => this.windowsService.openFolderPicker() }); let openFile: Electron.MenuItem; if (hasNoWindows) { openFile = new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miOpenFile', comment: ['&& denotes a mnemonic'] }, "&&Open File...")), accelerator: this.getAccelerator('workbench.action.files.openFile'), click: () => this.windowsService.openFilePicker() }); } else { openFile = this.createMenuItem(nls.localize({ key: 'miOpenFile', comment: ['&& denotes a mnemonic'] }, "&&Open File..."), 'workbench.action.files.openFile'); } const openRecentMenu = new Menu(); this.setOpenRecentMenu(openRecentMenu); const openRecent = new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miOpenRecent', comment: ['&& denotes a mnemonic'] }, "Open &&Recent")), submenu: openRecentMenu, enabled: openRecentMenu.items.length > 0 }); const saveFile = this.createMenuItem(nls.localize({ key: 'miSave', comment: ['&& denotes a mnemonic'] }, "&&Save"), 'workbench.action.files.save', this.windowsService.getWindowCount() > 0); const saveFileAs = this.createMenuItem(nls.localize({ key: 'miSaveAs', comment: ['&& denotes a mnemonic'] }, "Save &&As..."), 'workbench.action.files.saveAs', this.windowsService.getWindowCount() > 0); const saveAllFiles = this.createMenuItem(nls.localize({ key: 'miSaveAll', comment: ['&& denotes a mnemonic'] }, "Save A&&ll"), 'workbench.action.files.saveAll', this.windowsService.getWindowCount() > 0); const autoSaveEnabled = [AutoSaveConfiguration.AFTER_DELAY, AutoSaveConfiguration.ON_FOCUS_CHANGE, AutoSaveConfiguration.ON_WINDOW_CHANGE].some(s => this.currentAutoSaveSetting === s); const autoSave = new MenuItem({ label: mnemonicLabel(nls.localize('miAutoSave', "Auto Save")), type: 'checkbox', checked: autoSaveEnabled, enabled: this.windowsService.getWindowCount() > 0, click: () => this.windowsService.sendToFocused('vscode.toggleAutoSave') }); const preferences = this.getPreferencesMenu(); const newWindow = new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miNewWindow', comment: ['&& denotes a mnemonic'] }, "&&New Window")), accelerator: this.getAccelerator('workbench.action.newWindow'), click: () => this.windowsService.openNewWindow() }); const revertFile = this.createMenuItem(nls.localize({ key: 'miRevert', comment: ['&& denotes a mnemonic'] }, "Revert F&&ile"), 'workbench.action.files.revert', this.windowsService.getWindowCount() > 0); const closeWindow = new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miCloseWindow', comment: ['&& denotes a mnemonic'] }, "Close &&Window")), accelerator: this.getAccelerator('workbench.action.closeWindow'), click: () => this.windowsService.getLastActiveWindow().win.close(), enabled: this.windowsService.getWindowCount() > 0 }); const closeFolder = this.createMenuItem(nls.localize({ key: 'miCloseFolder', comment: ['&& denotes a mnemonic'] }, "Close &&Folder"), 'workbench.action.closeFolder'); const closeEditor = this.createMenuItem(nls.localize({ key: 'miCloseEditor', comment: ['&& denotes a mnemonic'] }, "Close &&Editor"), 'workbench.action.closeActiveEditor'); const exit = this.createMenuItem(nls.localize({ key: 'miExit', comment: ['&& denotes a mnemonic'] }, "E&&xit"), () => this.quit()); arrays.coalesce([ newFile, newWindow, __separator__(), platform.isMacintosh ? open : null, !platform.isMacintosh ? openFile : null, !platform.isMacintosh ? openFolder : null, openRecent, __separator__(), saveFile, saveFileAs, saveAllFiles, __separator__(), autoSave, __separator__(), !platform.isMacintosh ? preferences : null, !platform.isMacintosh ? __separator__() : null, revertFile, closeEditor, closeFolder, !platform.isMacintosh ? closeWindow : null, !platform.isMacintosh ? __separator__() : null, !platform.isMacintosh ? exit : null ]).forEach(item => fileMenu.append(item)); } private getPreferencesMenu(): Electron.MenuItem { const userSettings = this.createMenuItem(nls.localize({ key: 'miOpenSettings', comment: ['&& denotes a mnemonic'] }, "&&User Settings"), 'workbench.action.openGlobalSettings'); const workspaceSettings = this.createMenuItem(nls.localize({ key: 'miOpenWorkspaceSettings', comment: ['&& denotes a mnemonic'] }, "&&Workspace Settings"), 'workbench.action.openWorkspaceSettings'); const kebindingSettings = this.createMenuItem(nls.localize({ key: 'miOpenKeymap', comment: ['&& denotes a mnemonic'] }, "&&Keyboard Shortcuts"), 'workbench.action.openGlobalKeybindings'); const snippetsSettings = this.createMenuItem(nls.localize({ key: 'miOpenSnippets', comment: ['&& denotes a mnemonic'] }, "User &&Snippets"), 'workbench.action.openSnippets'); const colorThemeSelection = this.createMenuItem(nls.localize({ key: 'miSelectColorTheme', comment: ['&& denotes a mnemonic'] }, "&&Color Theme"), 'workbench.action.selectTheme'); const iconThemeSelection = this.createMenuItem(nls.localize({ key: 'miSelectIconTheme', comment: ['&& denotes a mnemonic'] }, "File &&Icon Theme"), 'workbench.action.selectIconTheme'); const preferencesMenu = new Menu(); preferencesMenu.append(userSettings); preferencesMenu.append(workspaceSettings); preferencesMenu.append(__separator__()); preferencesMenu.append(kebindingSettings); preferencesMenu.append(__separator__()); preferencesMenu.append(snippetsSettings); preferencesMenu.append(__separator__()); preferencesMenu.append(colorThemeSelection); preferencesMenu.append(iconThemeSelection); return new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miPreferences', comment: ['&& denotes a mnemonic'] }, "&&Preferences")), submenu: preferencesMenu }); } private quit(): void { // If the user selected to exit from an extension development host window, do not quit, but just // close the window unless this is the last window that is opened. const vscodeWindow = this.windowsService.getFocusedWindow(); if (vscodeWindow && vscodeWindow.isPluginDevelopmentHost && this.windowsService.getWindowCount() > 1) { vscodeWindow.win.close(); } // Otherwise: normal quit else { setTimeout(() => { this.isQuitting = true; app.quit(); }, 10 /* delay this because there is an issue with quitting while the menu is open */); } } private setOpenRecentMenu(openRecentMenu: Electron.Menu): void { openRecentMenu.append(this.createMenuItem(nls.localize({ key: 'miReopenClosedEditor', comment: ['&& denotes a mnemonic'] }, "&&Reopen Closed Editor"), 'workbench.action.reopenClosedEditor')); const {folders, files} = this.windowsService.getRecentPathsList(); // Folders if (folders.length > 0) { openRecentMenu.append(__separator__()); for (let i = 0; i < VSCodeMenu.MAX_MENU_RECENT_ENTRIES && i < folders.length; i++) { openRecentMenu.append(this.createOpenRecentMenuItem(folders[i])); } } // Files if (files.length > 0) { openRecentMenu.append(__separator__()); for (let i = 0; i < VSCodeMenu.MAX_MENU_RECENT_ENTRIES && i < files.length; i++) { openRecentMenu.append(this.createOpenRecentMenuItem(files[i])); } } if (folders.length || files.length) { openRecentMenu.append(__separator__()); openRecentMenu.append(new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miClearItems', comment: ['&& denotes a mnemonic'] }, "&&Clear Items")), click: () => { this.windowsService.clearRecentPathsList(); this.updateMenu(); } })); } } private createOpenRecentMenuItem(path: string): Electron.MenuItem { return new MenuItem({ label: unMnemonicLabel(path), click: (menuItem, win, event) => { const openInNewWindow = event && ((!platform.isMacintosh && event.ctrlKey) || (platform.isMacintosh && event.metaKey)); const success = !!this.windowsService.open({ cli: this.environmentService.args, pathsToOpen: [path], forceNewWindow: openInNewWindow }); if (!success) { this.windowsService.removeFromRecentPathsList(path); this.updateMenu(); } } }); } private createRoleMenuItem(label: string, actionId: string, role: Electron.MenuItemRole): Electron.MenuItem { const options: Electron.MenuItemOptions = { label: mnemonicLabel(label), accelerator: this.getAccelerator(actionId), role, enabled: true }; return new MenuItem(options); } private setEditMenu(winLinuxEditMenu: Electron.Menu): void { let undo: Electron.MenuItem; let redo: Electron.MenuItem; let cut: Electron.MenuItem; let copy: Electron.MenuItem; let paste: Electron.MenuItem; let selectAll: Electron.MenuItem; if (platform.isMacintosh) { undo = this.createDevToolsAwareMenuItem(nls.localize({ key: 'miUndo', comment: ['&& denotes a mnemonic'] }, "&&Undo"), 'undo', devTools => devTools.undo()); redo = this.createDevToolsAwareMenuItem(nls.localize({ key: 'miRedo', comment: ['&& denotes a mnemonic'] }, "&&Redo"), 'redo', devTools => devTools.redo()); cut = this.createRoleMenuItem(nls.localize({ key: 'miCut', comment: ['&& denotes a mnemonic'] }, "&&Cut"), 'editor.action.clipboardCutAction', 'cut'); copy = this.createRoleMenuItem(nls.localize({ key: 'miCopy', comment: ['&& denotes a mnemonic'] }, "C&&opy"), 'editor.action.clipboardCopyAction', 'copy'); paste = this.createRoleMenuItem(nls.localize({ key: 'miPaste', comment: ['&& denotes a mnemonic'] }, "&&Paste"), 'editor.action.clipboardPasteAction', 'paste'); selectAll = this.createDevToolsAwareMenuItem(nls.localize({ key: 'miSelectAll', comment: ['&& denotes a mnemonic'] }, "&&Select All"), 'editor.action.selectAll', (devTools) => devTools.selectAll()); } else { undo = this.createMenuItem(nls.localize({ key: 'miUndo', comment: ['&& denotes a mnemonic'] }, "&&Undo"), 'undo'); redo = this.createMenuItem(nls.localize({ key: 'miRedo', comment: ['&& denotes a mnemonic'] }, "&&Redo"), 'redo'); cut = this.createMenuItem(nls.localize({ key: 'miCut', comment: ['&& denotes a mnemonic'] }, "&&Cut"), 'editor.action.clipboardCutAction'); copy = this.createMenuItem(nls.localize({ key: 'miCopy', comment: ['&& denotes a mnemonic'] }, "C&&opy"), 'editor.action.clipboardCopyAction'); paste = this.createMenuItem(nls.localize({ key: 'miPaste', comment: ['&& denotes a mnemonic'] }, "&&Paste"), 'editor.action.clipboardPasteAction'); selectAll = this.createMenuItem(nls.localize({ key: 'miSelectAll', comment: ['&& denotes a mnemonic'] }, "&&Select All"), 'editor.action.selectAll'); } const find = this.createMenuItem(nls.localize({ key: 'miFind', comment: ['&& denotes a mnemonic'] }, "&&Find"), 'actions.find'); const replace = this.createMenuItem(nls.localize({ key: 'miReplace', comment: ['&& denotes a mnemonic'] }, "&&Replace"), 'editor.action.startFindReplaceAction'); const findInFiles = this.createMenuItem(nls.localize({ key: 'miFindInFiles', comment: ['&& denotes a mnemonic'] }, "Find &&in Files"), 'workbench.action.findInFiles'); const replaceInFiles = this.createMenuItem(nls.localize({ key: 'miReplaceInFiles', comment: ['&& denotes a mnemonic'] }, "Replace &&in Files"), 'workbench.action.replaceInFiles'); [ undo, redo, __separator__(), cut, copy, paste, selectAll, __separator__(), find, replace, __separator__(), findInFiles, replaceInFiles ].forEach(item => winLinuxEditMenu.append(item)); } private setViewMenu(viewMenu: Electron.Menu): void { const explorer = this.createMenuItem(nls.localize({ key: 'miViewExplorer', comment: ['&& denotes a mnemonic'] }, "&&Explorer"), 'workbench.view.explorer'); const search = this.createMenuItem(nls.localize({ key: 'miViewSearch', comment: ['&& denotes a mnemonic'] }, "&&Search"), 'workbench.view.search'); const git = this.createMenuItem(nls.localize({ key: 'miViewGit', comment: ['&& denotes a mnemonic'] }, "&&Git"), 'workbench.view.git'); const debug = this.createMenuItem(nls.localize({ key: 'miViewDebug', comment: ['&& denotes a mnemonic'] }, "&&Debug"), 'workbench.view.debug'); const extensions = this.createMenuItem(nls.localize({ key: 'miViewExtensions', comment: ['&& denotes a mnemonic'] }, "E&&xtensions"), 'workbench.view.extensions'); const output = this.createMenuItem(nls.localize({ key: 'miToggleOutput', comment: ['&& denotes a mnemonic'] }, "&&Output"), 'workbench.action.output.toggleOutput'); const debugConsole = this.createMenuItem(nls.localize({ key: 'miToggleDebugConsole', comment: ['&& denotes a mnemonic'] }, "De&&bug Console"), 'workbench.debug.action.toggleRepl'); const integratedTerminal = this.createMenuItem(nls.localize({ key: 'miToggleIntegratedTerminal', comment: ['&& denotes a mnemonic'] }, "&&Integrated Terminal"), 'workbench.action.terminal.toggleTerminal'); const problems = this.createMenuItem(nls.localize({ key: 'miMarker', comment: ['&& denotes a mnemonic'] }, "&&Problems"), 'workbench.actions.view.problems'); const commands = this.createMenuItem(nls.localize({ key: 'miCommandPalette', comment: ['&& denotes a mnemonic'] }, "&&Command Palette..."), 'workbench.action.showCommands'); const fullscreen = new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miToggleFullScreen', comment: ['&& denotes a mnemonic'] }, "Toggle &&Full Screen")), accelerator: this.getAccelerator('workbench.action.toggleFullScreen'), click: () => this.windowsService.getLastActiveWindow().toggleFullScreen(), enabled: this.windowsService.getWindowCount() > 0 }); const toggleMenuBar = this.createMenuItem(nls.localize({ key: 'miToggleMenuBar', comment: ['&& denotes a mnemonic'] }, "Toggle Menu &&Bar"), 'workbench.action.toggleMenuBar'); const splitEditor = this.createMenuItem(nls.localize({ key: 'miSplitEditor', comment: ['&& denotes a mnemonic'] }, "Split &&Editor"), 'workbench.action.splitEditor'); const toggleEditorLayout = this.createMenuItem(nls.localize({ key: 'miToggleEditorLayout', comment: ['&& denotes a mnemonic'] }, "Toggle Editor Group &&Layout"), 'workbench.action.toggleEditorGroupLayout'); const toggleSidebar = this.createMenuItem(nls.localize({ key: 'miToggleSidebar', comment: ['&& denotes a mnemonic'] }, "&&Toggle Side Bar"), 'workbench.action.toggleSidebarVisibility'); let moveSideBarLabel: string; if (this.currentSidebarLocation !== 'right') { moveSideBarLabel = nls.localize({ key: 'miMoveSidebarRight', comment: ['&& denotes a mnemonic'] }, "&&Move Side Bar Right"); } else { moveSideBarLabel = nls.localize({ key: 'miMoveSidebarLeft', comment: ['&& denotes a mnemonic'] }, "&&Move Side Bar Left"); } const moveSidebar = this.createMenuItem(moveSideBarLabel, 'workbench.action.toggleSidebarPosition'); const togglePanel = this.createMenuItem(nls.localize({ key: 'miTogglePanel', comment: ['&& denotes a mnemonic'] }, "Toggle &&Panel"), 'workbench.action.togglePanel'); let statusBarLabel: string; if (this.currentStatusbarVisible) { statusBarLabel = nls.localize({ key: 'miHideStatusbar', comment: ['&& denotes a mnemonic'] }, "&&Hide Status Bar"); } else { statusBarLabel = nls.localize({ key: 'miShowStatusbar', comment: ['&& denotes a mnemonic'] }, "&&Show Status Bar"); } const toggleStatusbar = this.createMenuItem(statusBarLabel, 'workbench.action.toggleStatusbarVisibility'); const toggleWordWrap = this.createMenuItem(nls.localize({ key: 'miToggleWordWrap', comment: ['&& denotes a mnemonic'] }, "Toggle &&Word Wrap"), 'editor.action.toggleWordWrap'); const toggleRenderWhitespace = this.createMenuItem(nls.localize({ key: 'miToggleRenderWhitespace', comment: ['&& denotes a mnemonic'] }, "Toggle &&Render Whitespace"), 'editor.action.toggleRenderWhitespace'); const toggleRenderControlCharacters = this.createMenuItem(nls.localize({ key: 'miToggleRenderControlCharacters', comment: ['&& denotes a mnemonic'] }, "Toggle &&Control Characters"), 'editor.action.toggleRenderControlCharacter'); const zoomIn = this.createMenuItem(nls.localize({ key: 'miZoomIn', comment: ['&& denotes a mnemonic'] }, "&&Zoom In"), 'workbench.action.zoomIn'); const zoomOut = this.createMenuItem(nls.localize({ key: 'miZoomOut', comment: ['&& denotes a mnemonic'] }, "Zoom O&&ut"), 'workbench.action.zoomOut'); const resetZoom = this.createMenuItem(nls.localize({ key: 'miZoomReset', comment: ['&& denotes a mnemonic'] }, "&&Reset Zoom"), 'workbench.action.zoomReset'); arrays.coalesce([ commands, __separator__(), explorer, search, git, debug, extensions, __separator__(), output, problems, debugConsole, integratedTerminal, __separator__(), fullscreen, platform.isWindows || platform.isLinux ? toggleMenuBar : void 0, __separator__(), splitEditor, toggleEditorLayout, moveSidebar, toggleSidebar, togglePanel, toggleStatusbar, __separator__(), toggleWordWrap, toggleRenderWhitespace, toggleRenderControlCharacters, __separator__(), zoomIn, zoomOut, resetZoom ]).forEach(item => viewMenu.append(item)); } private setGotoMenu(gotoMenu: Electron.Menu): void { const back = this.createMenuItem(nls.localize({ key: 'miBack', comment: ['&& denotes a mnemonic'] }, "&&Back"), 'workbench.action.navigateBack'); const forward = this.createMenuItem(nls.localize({ key: 'miForward', comment: ['&& denotes a mnemonic'] }, "&&Forward"), 'workbench.action.navigateForward'); const switchEditorMenu = new Menu(); const nextEditor = this.createMenuItem(nls.localize({ key: 'miNextEditor', comment: ['&& denotes a mnemonic'] }, "&&Next Editor"), 'workbench.action.nextEditor'); const previousEditor = this.createMenuItem(nls.localize({ key: 'miPreviousEditor', comment: ['&& denotes a mnemonic'] }, "&&Previous Editor"), 'workbench.action.previousEditor'); const nextEditorInGroup = this.createMenuItem(nls.localize({ key: 'miNextEditorInGroup', comment: ['&& denotes a mnemonic'] }, "&&Next Used Editor in Group"), 'workbench.action.openNextRecentlyUsedEditorInGroup'); const previousEditorInGroup = this.createMenuItem(nls.localize({ key: 'miPreviousEditorInGroup', comment: ['&& denotes a mnemonic'] }, "&&Previous Used Editor in Group"), 'workbench.action.openPreviousRecentlyUsedEditorInGroup'); [ nextEditor, previousEditor, __separator__(), nextEditorInGroup, previousEditorInGroup ].forEach(item => switchEditorMenu.append(item)); const switchEditor = new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miSwitchEditor', comment: ['&& denotes a mnemonic'] }, "Switch &&Editor")), submenu: switchEditorMenu, enabled: true }); const switchGroupMenu = new Menu(); const focusFirstGroup = this.createMenuItem(nls.localize({ key: 'miFocusFirstGroup', comment: ['&& denotes a mnemonic'] }, "&&First Group"), 'workbench.action.focusFirstEditorGroup'); const focusSecondGroup = this.createMenuItem(nls.localize({ key: 'miFocusSecondGroup', comment: ['&& denotes a mnemonic'] }, "&&Second Group"), 'workbench.action.focusSecondEditorGroup'); const focusThirdGroup = this.createMenuItem(nls.localize({ key: 'miFocusThirdGroup', comment: ['&& denotes a mnemonic'] }, "&&Third Group"), 'workbench.action.focusThirdEditorGroup'); const nextGroup = this.createMenuItem(nls.localize({ key: 'miNextGroup', comment: ['&& denotes a mnemonic'] }, "&&Next Group"), 'workbench.action.focusNextGroup'); const previousGroup = this.createMenuItem(nls.localize({ key: 'miPreviousGroup', comment: ['&& denotes a mnemonic'] }, "&&Previous Group"), 'workbench.action.focusPreviousGroup'); [ focusFirstGroup, focusSecondGroup, focusThirdGroup, __separator__(), nextGroup, previousGroup ].forEach(item => switchGroupMenu.append(item)); const switchGroup = new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miSwitchGroup', comment: ['&& denotes a mnemonic'] }, "Switch &&Group")), submenu: switchGroupMenu, enabled: true }); const gotoFile = this.createMenuItem(nls.localize({ key: 'miGotoFile', comment: ['&& denotes a mnemonic'] }, "Go to &&File..."), 'workbench.action.quickOpen'); const gotoSymbolInFile = this.createMenuItem(nls.localize({ key: 'miGotoSymbolInFile', comment: ['&& denotes a mnemonic'] }, "Go to &&Symbol in File..."), 'workbench.action.gotoSymbol'); const gotoSymbolInWorkspace = this.createMenuItem(nls.localize({ key: 'miGotoSymbolInWorkspace', comment: ['&& denotes a mnemonic'] }, "Go to Symbol in &&Workspace..."), 'workbench.action.showAllSymbols'); const gotoDefinition = this.createMenuItem(nls.localize({ key: 'miGotoDefinition', comment: ['&& denotes a mnemonic'] }, "Go to &&Definition"), 'editor.action.goToDeclaration'); const gotoLine = this.createMenuItem(nls.localize({ key: 'miGotoLine', comment: ['&& denotes a mnemonic'] }, "Go to &&Line..."), 'workbench.action.gotoLine'); [ back, forward, __separator__(), switchEditor, switchGroup, __separator__(), gotoFile, gotoSymbolInFile, gotoSymbolInWorkspace, gotoDefinition, gotoLine ].forEach(item => gotoMenu.append(item)); } private setMacWindowMenu(macWindowMenu: Electron.Menu): void { const minimize = new MenuItem({ label: nls.localize('mMinimize', "Minimize"), role: 'minimize', accelerator: 'Command+M', enabled: this.windowsService.getWindowCount() > 0 }); const close = new MenuItem({ label: nls.localize('mClose', "Close"), role: 'close', accelerator: 'Command+W', enabled: this.windowsService.getWindowCount() > 0 }); const bringAllToFront = new MenuItem({ label: nls.localize('mBringToFront', "Bring All to Front"), role: 'front', enabled: this.windowsService.getWindowCount() > 0 }); [ minimize, close, __separator__(), bringAllToFront ].forEach(item => macWindowMenu.append(item)); } private toggleDevTools(): void { const w = this.windowsService.getFocusedWindow(); if (w && w.win) { w.win.webContents.toggleDevTools(); } } private setHelpMenu(helpMenu: Electron.Menu): void { const toggleDevToolsItem = new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miToggleDevTools', comment: ['&& denotes a mnemonic'] }, "&&Toggle Developer Tools")), accelerator: this.getAccelerator('workbench.action.toggleDevTools'), click: () => this.toggleDevTools(), enabled: (this.windowsService.getWindowCount() > 0) }); const showAccessibilityOptions = new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miAccessibilityOptions', comment: ['&& denotes a mnemonic'] }, "Accessibility &&Options")), accelerator: null, click: () => { this.windowsService.openAccessibilityOptions(); } }); let reportIssuesItem: Electron.MenuItem = null; if (product.reportIssueUrl) { const label = nls.localize({ key: 'miReportIssues', comment: ['&& denotes a mnemonic'] }, "Report &&Issues"); if (this.windowsService.getWindowCount() > 0) { reportIssuesItem = this.createMenuItem(label, 'workbench.action.reportIssues'); } else { reportIssuesItem = new MenuItem({ label: mnemonicLabel(label), click: () => this.openUrl(product.reportIssueUrl, 'openReportIssues') }); } } arrays.coalesce([ product.documentationUrl ? new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miDocumentation', comment: ['&& denotes a mnemonic'] }, "&&Documentation")), click: () => this.openUrl(product.documentationUrl, 'openDocumentationUrl') }) : null, product.releaseNotesUrl ? new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miReleaseNotes', comment: ['&& denotes a mnemonic'] }, "&&Release Notes")), click: () => this.windowsService.sendToFocused('vscode:runAction', 'update.showCurrentReleaseNotes') }) : null, (product.documentationUrl || product.releaseNotesUrl) ? __separator__() : null, product.twitterUrl ? new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miTwitter', comment: ['&& denotes a mnemonic'] }, "&&Join us on Twitter")), click: () => this.openUrl(product.twitterUrl, 'openTwitterUrl') }) : null, product.requestFeatureUrl ? new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miUserVoice', comment: ['&& denotes a mnemonic'] }, "&&Search Feature Requests")), click: () => this.openUrl(product.requestFeatureUrl, 'openUserVoiceUrl') }) : null, reportIssuesItem, (product.twitterUrl || product.requestFeatureUrl || product.reportIssueUrl) ? __separator__() : null, product.licenseUrl ? new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miLicense', comment: ['&& denotes a mnemonic'] }, "&&View License")), click: () => { if (platform.language) { const queryArgChar = product.licenseUrl.indexOf('?') > 0 ? '&' : '?'; this.openUrl(`${product.licenseUrl}${queryArgChar}lang=${platform.language}`, 'openLicenseUrl'); } else { this.openUrl(product.licenseUrl, 'openLicenseUrl'); } } }) : null, product.privacyStatementUrl ? new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miPrivacyStatement', comment: ['&& denotes a mnemonic'] }, "&&Privacy Statement")), click: () => { if (platform.language) { const queryArgChar = product.licenseUrl.indexOf('?') > 0 ? '&' : '?'; this.openUrl(`${product.privacyStatementUrl}${queryArgChar}lang=${platform.language}`, 'openPrivacyStatement'); } else { this.openUrl(product.privacyStatementUrl, 'openPrivacyStatement'); } } }) : null, (product.licenseUrl || product.privacyStatementUrl) ? __separator__() : null, toggleDevToolsItem, platform.isWindows && product.quality !== 'stable' ? showAccessibilityOptions : null ]).forEach(item => helpMenu.append(item)); if (!platform.isMacintosh) { const updateMenuItems = this.getUpdateMenuItems(); if (updateMenuItems.length) { helpMenu.append(__separator__()); updateMenuItems.forEach(i => helpMenu.append(i)); } helpMenu.append(__separator__()); helpMenu.append(new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miAbout', comment: ['&& denotes a mnemonic'] }, "&&About")), click: () => this.openAboutDialog() })); } } private getUpdateMenuItems(): Electron.MenuItem[] { switch (this.updateService.state) { case UpdateState.Uninitialized: return []; case UpdateState.UpdateDownloaded: const update = this.updateService.availableUpdate; return [new MenuItem({ label: nls.localize('miRestartToUpdate', "Restart To Update..."), click: () => { this.reportMenuActionTelemetry('RestartToUpdate'); update.quitAndUpdate(); } })]; case UpdateState.CheckingForUpdate: return [new MenuItem({ label: nls.localize('miCheckingForUpdates', "Checking For Updates..."), enabled: false })]; case UpdateState.UpdateAvailable: if (platform.isLinux) { const update = this.updateService.availableUpdate; return [new MenuItem({ label: nls.localize('miDownloadUpdate', "Download Available Update"), click: () => { update.quitAndUpdate(); } })]; } const updateAvailableLabel = platform.isWindows ? nls.localize('miDownloadingUpdate', "Downloading Update...") : nls.localize('miInstallingUpdate', "Installing Update..."); return [new MenuItem({ label: updateAvailableLabel, enabled: false })]; default: const result = [new MenuItem({ label: nls.localize('miCheckForUpdates', "Check For Updates..."), click: () => setTimeout(() => { this.reportMenuActionTelemetry('CheckForUpdate'); this.updateService.checkForUpdates(true); }, 0) })]; return result; } } private createMenuItem(label: string, actionId: string, enabled?: boolean, checked?: boolean): Electron.MenuItem; private createMenuItem(label: string, click: () => void, enabled?: boolean, checked?: boolean): Electron.MenuItem; private createMenuItem(arg1: string, arg2: any, arg3?: boolean, arg4?: boolean): Electron.MenuItem { const label = mnemonicLabel(arg1); const click: () => void = (typeof arg2 === 'function') ? arg2 : () => this.windowsService.sendToFocused('vscode:runAction', arg2); const enabled = typeof arg3 === 'boolean' ? arg3 : this.windowsService.getWindowCount() > 0; const checked = typeof arg4 === 'boolean' ? arg4 : false; let actionId: string; if (typeof arg2 === 'string') { actionId = arg2; } const options: Electron.MenuItemOptions = { label, accelerator: this.getAccelerator(actionId), click, enabled }; if (checked) { options['type'] = 'checkbox'; options['checked'] = checked; } return new MenuItem(options); } private createDevToolsAwareMenuItem(label: string, actionId: string, devToolsFocusedFn: (contents: Electron.WebContents) => void): Electron.MenuItem { return new MenuItem({ label: mnemonicLabel(label), accelerator: this.getAccelerator(actionId), enabled: this.windowsService.getWindowCount() > 0, click: () => { const windowInFocus = this.windowsService.getFocusedWindow(); if (!windowInFocus) { return; } if (windowInFocus.win.webContents.isDevToolsFocused()) { devToolsFocusedFn(windowInFocus.win.webContents.devToolsWebContents); } else { this.windowsService.sendToFocused('vscode:runAction', actionId); } } }); } private getAccelerator(actionId: string): string { if (actionId) { const resolvedKeybinding = this.mapResolvedKeybindingToActionId[actionId]; if (resolvedKeybinding) { return resolvedKeybinding; // keybinding is fully resolved } if (!this.keybindingsResolved) { this.actionIdKeybindingRequests.push(actionId); // keybinding needs to be resolved } const lastKnownKeybinding = this.mapLastKnownKeybindingToActionId[actionId]; return lastKnownKeybinding; // return the last known keybining (chance of mismatch is very low unless it changed) } return void (0); } private openAboutDialog(): void { const lastActiveWindow = this.windowsService.getFocusedWindow() || this.windowsService.getLastActiveWindow(); dialog.showMessageBox(lastActiveWindow && lastActiveWindow.win, { title: product.nameLong, type: 'info', message: product.nameLong, detail: nls.localize('aboutDetail', "\nVersion {0}\nCommit {1}\nDate {2}\nShell {3}\nRenderer {4}\nNode {5}", app.getVersion(), product.commit || 'Unknown', product.date || 'Unknown', process.versions['electron'], process.versions['chrome'], process.versions['node'] ), buttons: [nls.localize('okButton', "OK")], noLink: true }, result => null); this.reportMenuActionTelemetry('showAboutDialog'); } private openUrl(url: string, id: string): void { shell.openExternal(url); this.reportMenuActionTelemetry(id); } private reportMenuActionTelemetry(id: string): void { this.windowsService.sendToFocused('vscode:telemetry', { eventName: 'workbenchActionExecuted', data: { id, from: 'menu' } }); } } function __separator__(): Electron.MenuItem { return new MenuItem({ type: 'separator' }); } function mnemonicLabel(label: string): string { if (platform.isMacintosh) { return label.replace(/\(&&\w\)|&&/g, ''); // no mnemonic support on mac } return label.replace(/&&/g, '&'); } function unMnemonicLabel(label: string): string { if (platform.isMacintosh) { return label; // no mnemonic support on mac } return label.replace(/&/g, '&&'); }
src/vs/code/electron-main/menus.ts
1
https://github.com/microsoft/vscode/commit/866dd02825a199f4d6cb275e9090a66ebaece9b2
[ 0.7453721761703491, 0.00844364520162344, 0.0001604200224392116, 0.0001753209508024156, 0.07767946273088455 ]
{ "id": 0, "code_window": [ "\t\t\t}\n", "\t\t}\n", "\n", "\t\tarrays.coalesce([\n", "\t\t\tproduct.documentationUrl ? new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miDocumentation', comment: ['&& denotes a mnemonic'] }, \"&&Documentation\")), click: () => this.openUrl(product.documentationUrl, 'openDocumentationUrl') }) : null,\n", "\t\t\tproduct.releaseNotesUrl ? new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miReleaseNotes', comment: ['&& denotes a mnemonic'] }, \"&&Release Notes\")), click: () => this.windowsService.sendToFocused('vscode:runAction', 'update.showCurrentReleaseNotes') }) : null,\n", "\t\t\t(product.documentationUrl || product.releaseNotesUrl) ? __separator__() : null,\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tconst keyboardShortcutsUrl = platform.isLinux ? product.keyboardShortcutsUrlLinux : platform.isMacintosh ? product.keyboardShortcutsUrlMac : product.keyboardShortcutsUrlWin;\n" ], "file_path": "src/vs/code/electron-main/menus.ts", "type": "add", "edit_start_line_idx": 695 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import { TPromise } from 'vs/base/common/winjs.base'; import { ServiceCollection } from './serviceCollection'; import * as descriptors from './descriptors'; // ------ internal util export namespace _util { export const DI_TARGET = '$di$target'; export const DI_DEPENDENCIES = '$di$dependencies'; export function getServiceDependencies(ctor: any): { id: ServiceIdentifier<any>, index: number, optional: boolean }[] { return ctor[DI_DEPENDENCIES] || []; } } // --- interfaces ------ export interface IConstructorSignature0<T> { new (...services: { _serviceBrand: any; }[]): T; } export interface IConstructorSignature1<A1, T> { new (first: A1, ...services: { _serviceBrand: any; }[]): T; } export interface IConstructorSignature2<A1, A2, T> { new (first: A1, second: A2, ...services: { _serviceBrand: any; }[]): T; } export interface IConstructorSignature3<A1, A2, A3, T> { new (first: A1, second: A2, third: A3, ...services: { _serviceBrand: any; }[]): T; } export interface IConstructorSignature4<A1, A2, A3, A4, T> { new (first: A1, second: A2, third: A3, forth: A4, ...services: { _serviceBrand: any; }[]): T; } export interface IConstructorSignature5<A1, A2, A3, A4, A5, T> { new (first: A1, second: A2, third: A3, forth: A4, fifth: A5, ...services: { _serviceBrand: any; }[]): T; } export interface IConstructorSignature6<A1, A2, A3, A4, A5, A6, T> { new (first: A1, second: A2, third: A3, forth: A4, fifth: A5, sixth: A6, ...services: { _serviceBrand: any; }[]): T; } export interface IConstructorSignature7<A1, A2, A3, A4, A5, A6, A7, T> { new (first: A1, second: A2, third: A3, forth: A4, fifth: A5, sixth: A6, seventh: A7, ...services: { _serviceBrand: any; }[]): T; } export interface IConstructorSignature8<A1, A2, A3, A4, A5, A6, A7, A8, T> { new (first: A1, second: A2, third: A3, forth: A4, fifth: A5, sixth: A6, seventh: A7, eigth: A8, ...services: { _serviceBrand: any; }[]): T; } export interface ServicesAccessor { get<T>(id: ServiceIdentifier<T>, isOptional?: typeof optional): T; } export interface IFunctionSignature0<R> { (accessor: ServicesAccessor): R; } export interface IFunctionSignature1<A1, R> { (accessor: ServicesAccessor, first: A1): R; } export interface IFunctionSignature2<A1, A2, R> { (accessor: ServicesAccessor, first: A1, second: A2): R; } export interface IFunctionSignature3<A1, A2, A3, R> { (accessor: ServicesAccessor, first: A1, second: A2, third: A3): R; } export interface IFunctionSignature4<A1, A2, A3, A4, R> { (accessor: ServicesAccessor, first: A1, second: A2, third: A3, forth: A4): R; } export interface IFunctionSignature5<A1, A2, A3, A4, A5, R> { (accessor: ServicesAccessor, first: A1, second: A2, third: A3, forth: A4, fifth: A5): R; } export interface IFunctionSignature6<A1, A2, A3, A4, A5, A6, R> { (accessor: ServicesAccessor, first: A1, second: A2, third: A3, forth: A4, fifth: A5, sixth: A6): R; } export interface IFunctionSignature7<A1, A2, A3, A4, A5, A6, A7, R> { (accessor: ServicesAccessor, first: A1, second: A2, third: A3, forth: A4, fifth: A5, sixth: A6, seventh: A7): R; } export interface IFunctionSignature8<A1, A2, A3, A4, A5, A6, A7, A8, R> { (accessor: ServicesAccessor, first: A1, second: A2, third: A3, forth: A4, fifth: A5, sixth: A6, seventh: A7, eigth: A8): R; } export var IInstantiationService = createDecorator<IInstantiationService>('instantiationService'); export interface IInstantiationService { _serviceBrand: any; /** * Synchronously creates an instance that is denoted by * the descriptor */ createInstance<T>(descriptor: descriptors.SyncDescriptor0<T>): T; createInstance<A1, T>(descriptor: descriptors.SyncDescriptor1<A1, T>, a1: A1): T; createInstance<A1, A2, T>(descriptor: descriptors.SyncDescriptor2<A1, A2, T>, a1: A1, a2: A2): T; createInstance<A1, A2, A3, T>(descriptor: descriptors.SyncDescriptor3<A1, A2, A3, T>, a1: A1, a2: A2, a3: A3): T; createInstance<A1, A2, A3, A4, T>(descriptor: descriptors.SyncDescriptor4<A1, A2, A3, A4, T>, a1: A1, a2: A2, a3: A3, a4: A4): T; createInstance<A1, A2, A3, A4, A5, T>(descriptor: descriptors.SyncDescriptor5<A1, A2, A3, A4, A5, T>, a1: A1, a2: A2, a3: A3, a4: A4, a5: A5): T; createInstance<A1, A2, A3, A4, A5, A6, T>(descriptor: descriptors.SyncDescriptor6<A1, A2, A3, A4, A5, A6, T>, a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6): T; createInstance<A1, A2, A3, A4, A5, A6, A7, T>(descriptor: descriptors.SyncDescriptor7<A1, A2, A3, A4, A5, A6, A7, T>, a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6, a7: A7): T; createInstance<A1, A2, A3, A4, A5, A6, A7, A8, T>(descriptor: descriptors.SyncDescriptor8<A1, A2, A3, A4, A5, A6, A7, A8, T>, a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6, a7: A7, a8: A8): T; createInstance<T>(ctor: IConstructorSignature0<T>): T; createInstance<A1, T>(ctor: IConstructorSignature1<A1, T>, first: A1): T; createInstance<A1, A2, T>(ctor: IConstructorSignature2<A1, A2, T>, first: A1, second: A2): T; createInstance<A1, A2, A3, T>(ctor: IConstructorSignature3<A1, A2, A3, T>, first: A1, second: A2, third: A3): T; createInstance<A1, A2, A3, A4, T>(ctor: IConstructorSignature4<A1, A2, A3, A4, T>, first: A1, second: A2, third: A3, fourth: A4): T; createInstance<A1, A2, A3, A4, A5, T>(ctor: IConstructorSignature5<A1, A2, A3, A4, A5, T>, first: A1, second: A2, third: A3, fourth: A4, fifth: A5): T; createInstance<A1, A2, A3, A4, A5, A6, T>(ctor: IConstructorSignature6<A1, A2, A3, A4, A5, A6, T>, first: A1, second: A2, third: A3, fourth: A4, fifth: A5, sixth: A6): T; createInstance<A1, A2, A3, A4, A5, A6, A7, T>(ctor: IConstructorSignature7<A1, A2, A3, A4, A5, A6, A7, T>, first: A1, second: A2, third: A3, fourth: A4, fifth: A5, sixth: A6, seventh: A7): T; createInstance<A1, A2, A3, A4, A5, A6, A7, A8, T>(ctor: IConstructorSignature8<A1, A2, A3, A4, A5, A6, A7, A8, T>, first: A1, second: A2, third: A3, fourth: A4, fifth: A5, sixth: A6, seventh: A7, eigth: A8): T; /** * Asynchronously creates an instance that is denoted by * the descriptor */ createInstance<T>(descriptor: descriptors.AsyncDescriptor0<T>): TPromise<T>; createInstance<A1, T>(descriptor: descriptors.AsyncDescriptor1<A1, T>, a1: A1): TPromise<T>; createInstance<A1, A2, T>(descriptor: descriptors.AsyncDescriptor2<A1, A2, T>, a1: A1, a2: A2): TPromise<T>; createInstance<A1, A2, A3, T>(descriptor: descriptors.AsyncDescriptor3<A1, A2, A3, T>, a1: A1, a2: A2, a3: A3): TPromise<T>; createInstance<A1, A2, A3, A4, T>(descriptor: descriptors.AsyncDescriptor4<A1, A2, A3, A4, T>, a1: A1, a2: A2, a3: A3, a4: A4): TPromise<T>; createInstance<A1, A2, A3, A4, A5, T>(descriptor: descriptors.AsyncDescriptor5<A1, A2, A3, A4, A5, T>, a1: A1, a2: A2, a3: A3, a4: A4, a5: A5): TPromise<T>; createInstance<A1, A2, A3, A4, A5, A6, T>(descriptor: descriptors.AsyncDescriptor6<A1, A2, A3, A4, A5, A6, T>, a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6): TPromise<T>; createInstance<A1, A2, A3, A4, A5, A6, A7, T>(descriptor: descriptors.AsyncDescriptor7<A1, A2, A3, A4, A5, A6, A7, T>, a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6, a7: A7): TPromise<T>; createInstance<A1, A2, A3, A4, A5, A6, A7, A8, T>(descriptor: descriptors.AsyncDescriptor8<A1, A2, A3, A4, A5, A6, A7, A8, T>, a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6, a7: A7, a8: A8): TPromise<T>; /** * */ invokeFunction<R>(ctor: IFunctionSignature0<R>): R; invokeFunction<A1, R>(ctor: IFunctionSignature1<A1, R>, first: A1): R; invokeFunction<A1, A2, R>(ctor: IFunctionSignature2<A1, A2, R>, first: A1, second: A2): R; invokeFunction<A1, A2, A3, R>(ctor: IFunctionSignature3<A1, A2, A3, R>, first: A1, second: A2, third: A3): R; invokeFunction<A1, A2, A3, A4, R>(ctor: IFunctionSignature4<A1, A2, A3, A4, R>, first: A1, second: A2, third: A3, fourth: A4): R; invokeFunction<A1, A2, A3, A4, A5, R>(ctor: IFunctionSignature5<A1, A2, A3, A4, A5, R>, first: A1, second: A2, third: A3, fourth: A4, fifth: A5): R; invokeFunction<A1, A2, A3, A4, A5, A6, R>(ctor: IFunctionSignature6<A1, A2, A3, A4, A5, A6, R>, first: A1, second: A2, third: A3, fourth: A4, fifth: A5, sixth: A6): R; invokeFunction<A1, A2, A3, A4, A5, A6, A7, R>(ctor: IFunctionSignature7<A1, A2, A3, A4, A5, A6, A7, R>, first: A1, second: A2, third: A3, fourth: A4, fifth: A5, sixth: A6, seventh: A7): R; invokeFunction<A1, A2, A3, A4, A5, A6, A7, A8, R>(ctor: IFunctionSignature8<A1, A2, A3, A4, A5, A6, A7, A8, R>, first: A1, second: A2, third: A3, fourth: A4, fifth: A5, sixth: A6, seventh: A7, eigth: A8): R; /** * Creates a child of this service which inherts all current services * and adds/overwrites the given services */ createChild(services: ServiceCollection): IInstantiationService; } /** * Identifies a service of type T */ export interface ServiceIdentifier<T> { (...args: any[]): void; type: T; } function storeServiceDependency(id: Function, target: Function, index: number, optional: boolean): void { if (target[_util.DI_TARGET] === target) { target[_util.DI_DEPENDENCIES].push({ id, index, optional }); } else { target[_util.DI_DEPENDENCIES] = [{ id, index, optional }]; target[_util.DI_TARGET] = target; } } /** * A *only* valid way to create a {{ServiceIdentifier}}. */ export function createDecorator<T>(serviceId: string): { (...args: any[]): void; type: T; } { let id = function (target: Function, key: string, index: number): any { if (arguments.length !== 3) { throw new Error('@IServiceName-decorator can only be used to decorate a parameter'); } storeServiceDependency(id, target, index, false); }; id.toString = () => serviceId; return <any>id; } /** * Mark a service dependency as optional. */ export function optional<T>(serviceIdentifier: ServiceIdentifier<T>) { return function (target: Function, key: string, index: number) { if (arguments.length !== 3) { throw new Error('@optional-decorator can only be used to decorate a parameter'); } storeServiceDependency(serviceIdentifier, target, index, true); }; }
src/vs/platform/instantiation/common/instantiation.ts
0
https://github.com/microsoft/vscode/commit/866dd02825a199f4d6cb275e9090a66ebaece9b2
[ 0.00017488384037278593, 0.00017134567315224558, 0.00016432970005553216, 0.00017303753702435642, 0.0000033179660476889694 ]
{ "id": 0, "code_window": [ "\t\t\t}\n", "\t\t}\n", "\n", "\t\tarrays.coalesce([\n", "\t\t\tproduct.documentationUrl ? new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miDocumentation', comment: ['&& denotes a mnemonic'] }, \"&&Documentation\")), click: () => this.openUrl(product.documentationUrl, 'openDocumentationUrl') }) : null,\n", "\t\t\tproduct.releaseNotesUrl ? new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miReleaseNotes', comment: ['&& denotes a mnemonic'] }, \"&&Release Notes\")), click: () => this.windowsService.sendToFocused('vscode:runAction', 'update.showCurrentReleaseNotes') }) : null,\n", "\t\t\t(product.documentationUrl || product.releaseNotesUrl) ? __separator__() : null,\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tconst keyboardShortcutsUrl = platform.isLinux ? product.keyboardShortcutsUrlLinux : platform.isMacintosh ? product.keyboardShortcutsUrlMac : product.keyboardShortcutsUrlWin;\n" ], "file_path": "src/vs/code/electron-main/menus.ts", "type": "add", "edit_start_line_idx": 695 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "configuredTabSize": "Taille des tabulations configurée", "detectIndentation": "Détecter la mise en retrait à partir du contenu", "indentUsingSpaces": "Mettre en retrait avec des espaces", "indentUsingTabs": "Mettre en retrait avec des tabulations", "indentationToSpaces": "Convertir les retraits en espaces", "indentationToTabs": "Convertir les retraits en tabulations", "selectTabWidth": "Sélectionner la taille des tabulations pour le fichier actuel", "toggleRenderControlCharacters": "Activer/désactiver les caractères de contrôle", "toggleRenderWhitespace": "Activer/désactiver Restituer l'espace" }
i18n/fra/src/vs/editor/contrib/indentation/common/indentation.i18n.json
0
https://github.com/microsoft/vscode/commit/866dd02825a199f4d6cb275e9090a66ebaece9b2
[ 0.00017201085574924946, 0.00017068511806428432, 0.0001693593803793192, 0.00017068511806428432, 0.0000013257376849651337 ]
{ "id": 0, "code_window": [ "\t\t\t}\n", "\t\t}\n", "\n", "\t\tarrays.coalesce([\n", "\t\t\tproduct.documentationUrl ? new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miDocumentation', comment: ['&& denotes a mnemonic'] }, \"&&Documentation\")), click: () => this.openUrl(product.documentationUrl, 'openDocumentationUrl') }) : null,\n", "\t\t\tproduct.releaseNotesUrl ? new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miReleaseNotes', comment: ['&& denotes a mnemonic'] }, \"&&Release Notes\")), click: () => this.windowsService.sendToFocused('vscode:runAction', 'update.showCurrentReleaseNotes') }) : null,\n", "\t\t\t(product.documentationUrl || product.releaseNotesUrl) ? __separator__() : null,\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tconst keyboardShortcutsUrl = platform.isLinux ? product.keyboardShortcutsUrlLinux : platform.isMacintosh ? product.keyboardShortcutsUrlMac : product.keyboardShortcutsUrlWin;\n" ], "file_path": "src/vs/code/electron-main/menus.ts", "type": "add", "edit_start_line_idx": 695 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "outputPanelAriaLabel": "Ausgabebereich", "outputPanelWithInputAriaLabel": "{0}, Ausgabebereich" }
i18n/deu/src/vs/workbench/parts/output/browser/outputPanel.i18n.json
0
https://github.com/microsoft/vscode/commit/866dd02825a199f4d6cb275e9090a66ebaece9b2
[ 0.0001727340422803536, 0.0001727340422803536, 0.0001727340422803536, 0.0001727340422803536, 0 ]
{ "id": 1, "code_window": [ "\t\tarrays.coalesce([\n", "\t\t\tproduct.documentationUrl ? new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miDocumentation', comment: ['&& denotes a mnemonic'] }, \"&&Documentation\")), click: () => this.openUrl(product.documentationUrl, 'openDocumentationUrl') }) : null,\n", "\t\t\tproduct.releaseNotesUrl ? new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miReleaseNotes', comment: ['&& denotes a mnemonic'] }, \"&&Release Notes\")), click: () => this.windowsService.sendToFocused('vscode:runAction', 'update.showCurrentReleaseNotes') }) : null,\n", "\t\t\t(product.documentationUrl || product.releaseNotesUrl) ? __separator__() : null,\n", "\t\t\tproduct.twitterUrl ? new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miTwitter', comment: ['&& denotes a mnemonic'] }, \"&&Join us on Twitter\")), click: () => this.openUrl(product.twitterUrl, 'openTwitterUrl') }) : null,\n", "\t\t\tproduct.requestFeatureUrl ? new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miUserVoice', comment: ['&& denotes a mnemonic'] }, \"&&Search Feature Requests\")), click: () => this.openUrl(product.requestFeatureUrl, 'openUserVoiceUrl') }) : null,\n", "\t\t\treportIssuesItem,\n", "\t\t\t(product.twitterUrl || product.requestFeatureUrl || product.reportIssueUrl) ? __separator__() : null,\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tkeyboardShortcutsUrl ? new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miKeyboardShortcuts', comment: ['&& denotes a mnemonic'] }, \"&&Keyboard Shortcuts Reference\")), click: () => this.openUrl(keyboardShortcutsUrl, 'openKeyboardShortcutsUrl') }) : null,\n", "\t\t\tproduct.introductoryVideosUrl ? new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miIntroductoryVideos', comment: ['&& denotes a mnemonic'] }, \"Introductory &&Videos\")), click: () => this.openUrl(product.introductoryVideosUrl, 'openIntroductoryVideosUrl') }) : null,\n" ], "file_path": "src/vs/code/electron-main/menus.ts", "type": "add", "edit_start_line_idx": 699 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import * as nls from 'vs/nls'; import * as platform from 'vs/base/common/platform'; import * as arrays from 'vs/base/common/arrays'; import { IEnvironmentService } from 'vs/platform/environment/common/environment'; import { ipcMain as ipc, app, shell, dialog, Menu, MenuItem } from 'electron'; import { IWindowsService } from 'vs/code/electron-main/windows'; import { IPath, VSCodeWindow } from 'vs/code/electron-main/window'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IStorageService } from 'vs/code/electron-main/storage'; import { IFilesConfiguration, AutoSaveConfiguration } from 'vs/platform/files/common/files'; import { IUpdateService, State as UpdateState } from 'vs/code/electron-main/update-manager'; import { Keybinding } from 'vs/base/common/keybinding'; import product from 'vs/platform/product'; interface IResolvedKeybinding { id: string; binding: number; } interface IConfiguration extends IFilesConfiguration { workbench: { sideBar: { location: 'left' | 'right'; }, statusBar: { visible: boolean; } }; } export class VSCodeMenu { private static lastKnownKeybindingsMapStorageKey = 'lastKnownKeybindings'; private static MAX_MENU_RECENT_ENTRIES = 10; private currentAutoSaveSetting: string; private currentSidebarLocation: 'left' | 'right'; private currentStatusbarVisible: boolean; private isQuitting: boolean; private appMenuInstalled: boolean; private actionIdKeybindingRequests: string[]; private mapLastKnownKeybindingToActionId: { [id: string]: string; }; private mapResolvedKeybindingToActionId: { [id: string]: string; }; private keybindingsResolved: boolean; constructor( @IStorageService private storageService: IStorageService, @IUpdateService private updateService: IUpdateService, @IConfigurationService private configurationService: IConfigurationService, @IWindowsService private windowsService: IWindowsService, @IEnvironmentService private environmentService: IEnvironmentService ) { this.actionIdKeybindingRequests = []; this.mapResolvedKeybindingToActionId = Object.create(null); this.mapLastKnownKeybindingToActionId = this.storageService.getItem<{ [id: string]: string; }>(VSCodeMenu.lastKnownKeybindingsMapStorageKey) || Object.create(null); this.onConfigurationUpdated(this.configurationService.getConfiguration<IConfiguration>()); } public ready(): void { this.registerListeners(); this.install(); } private registerListeners(): void { // Keep flag when app quits app.on('will-quit', () => { this.isQuitting = true; }); // Listen to "open" & "close" event from window service this.windowsService.onOpen(paths => this.onOpen(paths)); this.windowsService.onClose(_ => this.onClose(this.windowsService.getWindowCount())); // Resolve keybindings when any first workbench is loaded this.windowsService.onReady(win => this.resolveKeybindings(win)); // Listen to resolved keybindings ipc.on('vscode:keybindingsResolved', (event, rawKeybindings) => { let keybindings: IResolvedKeybinding[] = []; try { keybindings = JSON.parse(rawKeybindings); } catch (error) { // Should not happen } // Fill hash map of resolved keybindings let needsMenuUpdate = false; keybindings.forEach(keybinding => { const accelerator = new Keybinding(keybinding.binding)._toElectronAccelerator(); if (accelerator) { this.mapResolvedKeybindingToActionId[keybinding.id] = accelerator; if (this.mapLastKnownKeybindingToActionId[keybinding.id] !== accelerator) { needsMenuUpdate = true; // we only need to update when something changed! } } }); // A keybinding might have been unassigned, so we have to account for that too if (Object.keys(this.mapLastKnownKeybindingToActionId).length !== Object.keys(this.mapResolvedKeybindingToActionId).length) { needsMenuUpdate = true; } if (needsMenuUpdate) { this.storageService.setItem(VSCodeMenu.lastKnownKeybindingsMapStorageKey, this.mapResolvedKeybindingToActionId); // keep to restore instantly after restart this.mapLastKnownKeybindingToActionId = this.mapResolvedKeybindingToActionId; // update our last known map this.updateMenu(); } }); // Update when auto save config changes this.configurationService.onDidUpdateConfiguration(e => this.onConfigurationUpdated(e.config, true /* update menu if changed */)); // Listen to update service this.updateService.on('change', () => this.updateMenu()); } private onConfigurationUpdated(config: IConfiguration, handleMenu?: boolean): void { let updateMenu = false; const newAutoSaveSetting = config && config.files && config.files.autoSave; if (newAutoSaveSetting !== this.currentAutoSaveSetting) { this.currentAutoSaveSetting = newAutoSaveSetting; updateMenu = true; } if (config && config.workbench) { const newSidebarLocation = config.workbench.sideBar && config.workbench.sideBar.location || 'left'; if (newSidebarLocation !== this.currentSidebarLocation) { this.currentSidebarLocation = newSidebarLocation; updateMenu = true; } let newStatusbarVisible = config.workbench.statusBar && config.workbench.statusBar.visible; if (typeof newStatusbarVisible !== 'boolean') { newStatusbarVisible = true; } if (newStatusbarVisible !== this.currentStatusbarVisible) { this.currentStatusbarVisible = newStatusbarVisible; updateMenu = true; } } if (handleMenu && updateMenu) { this.updateMenu(); } } private resolveKeybindings(win: VSCodeWindow): void { if (this.keybindingsResolved) { return; // only resolve once } this.keybindingsResolved = true; // Resolve keybindings when workbench window is up if (this.actionIdKeybindingRequests.length) { win.send('vscode:resolveKeybindings', JSON.stringify(this.actionIdKeybindingRequests)); } } private updateMenu(): void { // Due to limitations in Electron, it is not possible to update menu items dynamically. The suggested // workaround from Electron is to set the application menu again. // See also https://github.com/electron/electron/issues/846 // // Run delayed to prevent updating menu while it is open if (!this.isQuitting) { setTimeout(() => { if (!this.isQuitting) { this.install(); } }, 10 /* delay this because there is an issue with updating a menu when it is open */); } } private onOpen(path: IPath): void { this.updateMenu(); } private onClose(remainingWindowCount: number): void { if (remainingWindowCount === 0 && platform.isMacintosh) { this.updateMenu(); } } private install(): void { // Menus const menubar = new Menu(); // Mac: Application let macApplicationMenuItem: Electron.MenuItem; if (platform.isMacintosh) { const applicationMenu = new Menu(); macApplicationMenuItem = new MenuItem({ label: product.nameShort, submenu: applicationMenu }); this.setMacApplicationMenu(applicationMenu); } // File const fileMenu = new Menu(); const fileMenuItem = new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'mFile', comment: ['&& denotes a mnemonic'] }, "&&File")), submenu: fileMenu }); this.setFileMenu(fileMenu); // Edit const editMenu = new Menu(); const editMenuItem = new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'mEdit', comment: ['&& denotes a mnemonic'] }, "&&Edit")), submenu: editMenu }); this.setEditMenu(editMenu); // View const viewMenu = new Menu(); const viewMenuItem = new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'mView', comment: ['&& denotes a mnemonic'] }, "&&View")), submenu: viewMenu }); this.setViewMenu(viewMenu); // Goto const gotoMenu = new Menu(); const gotoMenuItem = new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'mGoto', comment: ['&& denotes a mnemonic'] }, "&&Go")), submenu: gotoMenu }); this.setGotoMenu(gotoMenu); // Mac: Window let macWindowMenuItem: Electron.MenuItem; if (platform.isMacintosh) { const windowMenu = new Menu(); macWindowMenuItem = new MenuItem({ label: mnemonicLabel(nls.localize('mWindow', "Window")), submenu: windowMenu, role: 'window' }); this.setMacWindowMenu(windowMenu); } // Help const helpMenu = new Menu(); const helpMenuItem = new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'mHelp', comment: ['&& denotes a mnemonic'] }, "&&Help")), submenu: helpMenu, role: 'help' }); this.setHelpMenu(helpMenu); // Menu Structure if (macApplicationMenuItem) { menubar.append(macApplicationMenuItem); } menubar.append(fileMenuItem); menubar.append(editMenuItem); menubar.append(viewMenuItem); menubar.append(gotoMenuItem); if (macWindowMenuItem) { menubar.append(macWindowMenuItem); } menubar.append(helpMenuItem); Menu.setApplicationMenu(menubar); // Dock Menu if (platform.isMacintosh && !this.appMenuInstalled) { this.appMenuInstalled = true; const dockMenu = new Menu(); dockMenu.append(new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miNewWindow', comment: ['&& denotes a mnemonic'] }, "&&New Window")), click: () => this.windowsService.openNewWindow() })); app.dock.setMenu(dockMenu); } } private setMacApplicationMenu(macApplicationMenu: Electron.Menu): void { const about = new MenuItem({ label: nls.localize('mAbout', "About {0}", product.nameLong), role: 'about' }); const checkForUpdates = this.getUpdateMenuItems(); const preferences = this.getPreferencesMenu(); const hide = new MenuItem({ label: nls.localize('mHide', "Hide {0}", product.nameLong), role: 'hide', accelerator: 'Command+H' }); const hideOthers = new MenuItem({ label: nls.localize('mHideOthers', "Hide Others"), role: 'hideothers', accelerator: 'Command+Alt+H' }); const showAll = new MenuItem({ label: nls.localize('mShowAll', "Show All"), role: 'unhide' }); const quit = new MenuItem({ label: nls.localize('miQuit', "Quit {0}", product.nameLong), click: () => this.quit(), accelerator: 'Command+Q' }); const actions = [about]; actions.push(...checkForUpdates); actions.push(...[ __separator__(), preferences, __separator__(), hide, hideOthers, showAll, __separator__(), quit ]); actions.forEach(i => macApplicationMenu.append(i)); } private setFileMenu(fileMenu: Electron.Menu): void { const hasNoWindows = (this.windowsService.getWindowCount() === 0); let newFile: Electron.MenuItem; if (hasNoWindows) { newFile = new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miNewFile', comment: ['&& denotes a mnemonic'] }, "&&New File")), accelerator: this.getAccelerator('workbench.action.files.newUntitledFile'), click: () => this.windowsService.openNewWindow() }); } else { newFile = this.createMenuItem(nls.localize({ key: 'miNewFile', comment: ['&& denotes a mnemonic'] }, "&&New File"), 'workbench.action.files.newUntitledFile'); } const open = new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miOpen', comment: ['&& denotes a mnemonic'] }, "&&Open...")), accelerator: this.getAccelerator('workbench.action.files.openFileFolder'), click: () => this.windowsService.openFileFolderPicker() }); const openFolder = new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miOpenFolder', comment: ['&& denotes a mnemonic'] }, "Open &&Folder...")), accelerator: this.getAccelerator('workbench.action.files.openFolder'), click: () => this.windowsService.openFolderPicker() }); let openFile: Electron.MenuItem; if (hasNoWindows) { openFile = new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miOpenFile', comment: ['&& denotes a mnemonic'] }, "&&Open File...")), accelerator: this.getAccelerator('workbench.action.files.openFile'), click: () => this.windowsService.openFilePicker() }); } else { openFile = this.createMenuItem(nls.localize({ key: 'miOpenFile', comment: ['&& denotes a mnemonic'] }, "&&Open File..."), 'workbench.action.files.openFile'); } const openRecentMenu = new Menu(); this.setOpenRecentMenu(openRecentMenu); const openRecent = new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miOpenRecent', comment: ['&& denotes a mnemonic'] }, "Open &&Recent")), submenu: openRecentMenu, enabled: openRecentMenu.items.length > 0 }); const saveFile = this.createMenuItem(nls.localize({ key: 'miSave', comment: ['&& denotes a mnemonic'] }, "&&Save"), 'workbench.action.files.save', this.windowsService.getWindowCount() > 0); const saveFileAs = this.createMenuItem(nls.localize({ key: 'miSaveAs', comment: ['&& denotes a mnemonic'] }, "Save &&As..."), 'workbench.action.files.saveAs', this.windowsService.getWindowCount() > 0); const saveAllFiles = this.createMenuItem(nls.localize({ key: 'miSaveAll', comment: ['&& denotes a mnemonic'] }, "Save A&&ll"), 'workbench.action.files.saveAll', this.windowsService.getWindowCount() > 0); const autoSaveEnabled = [AutoSaveConfiguration.AFTER_DELAY, AutoSaveConfiguration.ON_FOCUS_CHANGE, AutoSaveConfiguration.ON_WINDOW_CHANGE].some(s => this.currentAutoSaveSetting === s); const autoSave = new MenuItem({ label: mnemonicLabel(nls.localize('miAutoSave', "Auto Save")), type: 'checkbox', checked: autoSaveEnabled, enabled: this.windowsService.getWindowCount() > 0, click: () => this.windowsService.sendToFocused('vscode.toggleAutoSave') }); const preferences = this.getPreferencesMenu(); const newWindow = new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miNewWindow', comment: ['&& denotes a mnemonic'] }, "&&New Window")), accelerator: this.getAccelerator('workbench.action.newWindow'), click: () => this.windowsService.openNewWindow() }); const revertFile = this.createMenuItem(nls.localize({ key: 'miRevert', comment: ['&& denotes a mnemonic'] }, "Revert F&&ile"), 'workbench.action.files.revert', this.windowsService.getWindowCount() > 0); const closeWindow = new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miCloseWindow', comment: ['&& denotes a mnemonic'] }, "Close &&Window")), accelerator: this.getAccelerator('workbench.action.closeWindow'), click: () => this.windowsService.getLastActiveWindow().win.close(), enabled: this.windowsService.getWindowCount() > 0 }); const closeFolder = this.createMenuItem(nls.localize({ key: 'miCloseFolder', comment: ['&& denotes a mnemonic'] }, "Close &&Folder"), 'workbench.action.closeFolder'); const closeEditor = this.createMenuItem(nls.localize({ key: 'miCloseEditor', comment: ['&& denotes a mnemonic'] }, "Close &&Editor"), 'workbench.action.closeActiveEditor'); const exit = this.createMenuItem(nls.localize({ key: 'miExit', comment: ['&& denotes a mnemonic'] }, "E&&xit"), () => this.quit()); arrays.coalesce([ newFile, newWindow, __separator__(), platform.isMacintosh ? open : null, !platform.isMacintosh ? openFile : null, !platform.isMacintosh ? openFolder : null, openRecent, __separator__(), saveFile, saveFileAs, saveAllFiles, __separator__(), autoSave, __separator__(), !platform.isMacintosh ? preferences : null, !platform.isMacintosh ? __separator__() : null, revertFile, closeEditor, closeFolder, !platform.isMacintosh ? closeWindow : null, !platform.isMacintosh ? __separator__() : null, !platform.isMacintosh ? exit : null ]).forEach(item => fileMenu.append(item)); } private getPreferencesMenu(): Electron.MenuItem { const userSettings = this.createMenuItem(nls.localize({ key: 'miOpenSettings', comment: ['&& denotes a mnemonic'] }, "&&User Settings"), 'workbench.action.openGlobalSettings'); const workspaceSettings = this.createMenuItem(nls.localize({ key: 'miOpenWorkspaceSettings', comment: ['&& denotes a mnemonic'] }, "&&Workspace Settings"), 'workbench.action.openWorkspaceSettings'); const kebindingSettings = this.createMenuItem(nls.localize({ key: 'miOpenKeymap', comment: ['&& denotes a mnemonic'] }, "&&Keyboard Shortcuts"), 'workbench.action.openGlobalKeybindings'); const snippetsSettings = this.createMenuItem(nls.localize({ key: 'miOpenSnippets', comment: ['&& denotes a mnemonic'] }, "User &&Snippets"), 'workbench.action.openSnippets'); const colorThemeSelection = this.createMenuItem(nls.localize({ key: 'miSelectColorTheme', comment: ['&& denotes a mnemonic'] }, "&&Color Theme"), 'workbench.action.selectTheme'); const iconThemeSelection = this.createMenuItem(nls.localize({ key: 'miSelectIconTheme', comment: ['&& denotes a mnemonic'] }, "File &&Icon Theme"), 'workbench.action.selectIconTheme'); const preferencesMenu = new Menu(); preferencesMenu.append(userSettings); preferencesMenu.append(workspaceSettings); preferencesMenu.append(__separator__()); preferencesMenu.append(kebindingSettings); preferencesMenu.append(__separator__()); preferencesMenu.append(snippetsSettings); preferencesMenu.append(__separator__()); preferencesMenu.append(colorThemeSelection); preferencesMenu.append(iconThemeSelection); return new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miPreferences', comment: ['&& denotes a mnemonic'] }, "&&Preferences")), submenu: preferencesMenu }); } private quit(): void { // If the user selected to exit from an extension development host window, do not quit, but just // close the window unless this is the last window that is opened. const vscodeWindow = this.windowsService.getFocusedWindow(); if (vscodeWindow && vscodeWindow.isPluginDevelopmentHost && this.windowsService.getWindowCount() > 1) { vscodeWindow.win.close(); } // Otherwise: normal quit else { setTimeout(() => { this.isQuitting = true; app.quit(); }, 10 /* delay this because there is an issue with quitting while the menu is open */); } } private setOpenRecentMenu(openRecentMenu: Electron.Menu): void { openRecentMenu.append(this.createMenuItem(nls.localize({ key: 'miReopenClosedEditor', comment: ['&& denotes a mnemonic'] }, "&&Reopen Closed Editor"), 'workbench.action.reopenClosedEditor')); const {folders, files} = this.windowsService.getRecentPathsList(); // Folders if (folders.length > 0) { openRecentMenu.append(__separator__()); for (let i = 0; i < VSCodeMenu.MAX_MENU_RECENT_ENTRIES && i < folders.length; i++) { openRecentMenu.append(this.createOpenRecentMenuItem(folders[i])); } } // Files if (files.length > 0) { openRecentMenu.append(__separator__()); for (let i = 0; i < VSCodeMenu.MAX_MENU_RECENT_ENTRIES && i < files.length; i++) { openRecentMenu.append(this.createOpenRecentMenuItem(files[i])); } } if (folders.length || files.length) { openRecentMenu.append(__separator__()); openRecentMenu.append(new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miClearItems', comment: ['&& denotes a mnemonic'] }, "&&Clear Items")), click: () => { this.windowsService.clearRecentPathsList(); this.updateMenu(); } })); } } private createOpenRecentMenuItem(path: string): Electron.MenuItem { return new MenuItem({ label: unMnemonicLabel(path), click: (menuItem, win, event) => { const openInNewWindow = event && ((!platform.isMacintosh && event.ctrlKey) || (platform.isMacintosh && event.metaKey)); const success = !!this.windowsService.open({ cli: this.environmentService.args, pathsToOpen: [path], forceNewWindow: openInNewWindow }); if (!success) { this.windowsService.removeFromRecentPathsList(path); this.updateMenu(); } } }); } private createRoleMenuItem(label: string, actionId: string, role: Electron.MenuItemRole): Electron.MenuItem { const options: Electron.MenuItemOptions = { label: mnemonicLabel(label), accelerator: this.getAccelerator(actionId), role, enabled: true }; return new MenuItem(options); } private setEditMenu(winLinuxEditMenu: Electron.Menu): void { let undo: Electron.MenuItem; let redo: Electron.MenuItem; let cut: Electron.MenuItem; let copy: Electron.MenuItem; let paste: Electron.MenuItem; let selectAll: Electron.MenuItem; if (platform.isMacintosh) { undo = this.createDevToolsAwareMenuItem(nls.localize({ key: 'miUndo', comment: ['&& denotes a mnemonic'] }, "&&Undo"), 'undo', devTools => devTools.undo()); redo = this.createDevToolsAwareMenuItem(nls.localize({ key: 'miRedo', comment: ['&& denotes a mnemonic'] }, "&&Redo"), 'redo', devTools => devTools.redo()); cut = this.createRoleMenuItem(nls.localize({ key: 'miCut', comment: ['&& denotes a mnemonic'] }, "&&Cut"), 'editor.action.clipboardCutAction', 'cut'); copy = this.createRoleMenuItem(nls.localize({ key: 'miCopy', comment: ['&& denotes a mnemonic'] }, "C&&opy"), 'editor.action.clipboardCopyAction', 'copy'); paste = this.createRoleMenuItem(nls.localize({ key: 'miPaste', comment: ['&& denotes a mnemonic'] }, "&&Paste"), 'editor.action.clipboardPasteAction', 'paste'); selectAll = this.createDevToolsAwareMenuItem(nls.localize({ key: 'miSelectAll', comment: ['&& denotes a mnemonic'] }, "&&Select All"), 'editor.action.selectAll', (devTools) => devTools.selectAll()); } else { undo = this.createMenuItem(nls.localize({ key: 'miUndo', comment: ['&& denotes a mnemonic'] }, "&&Undo"), 'undo'); redo = this.createMenuItem(nls.localize({ key: 'miRedo', comment: ['&& denotes a mnemonic'] }, "&&Redo"), 'redo'); cut = this.createMenuItem(nls.localize({ key: 'miCut', comment: ['&& denotes a mnemonic'] }, "&&Cut"), 'editor.action.clipboardCutAction'); copy = this.createMenuItem(nls.localize({ key: 'miCopy', comment: ['&& denotes a mnemonic'] }, "C&&opy"), 'editor.action.clipboardCopyAction'); paste = this.createMenuItem(nls.localize({ key: 'miPaste', comment: ['&& denotes a mnemonic'] }, "&&Paste"), 'editor.action.clipboardPasteAction'); selectAll = this.createMenuItem(nls.localize({ key: 'miSelectAll', comment: ['&& denotes a mnemonic'] }, "&&Select All"), 'editor.action.selectAll'); } const find = this.createMenuItem(nls.localize({ key: 'miFind', comment: ['&& denotes a mnemonic'] }, "&&Find"), 'actions.find'); const replace = this.createMenuItem(nls.localize({ key: 'miReplace', comment: ['&& denotes a mnemonic'] }, "&&Replace"), 'editor.action.startFindReplaceAction'); const findInFiles = this.createMenuItem(nls.localize({ key: 'miFindInFiles', comment: ['&& denotes a mnemonic'] }, "Find &&in Files"), 'workbench.action.findInFiles'); const replaceInFiles = this.createMenuItem(nls.localize({ key: 'miReplaceInFiles', comment: ['&& denotes a mnemonic'] }, "Replace &&in Files"), 'workbench.action.replaceInFiles'); [ undo, redo, __separator__(), cut, copy, paste, selectAll, __separator__(), find, replace, __separator__(), findInFiles, replaceInFiles ].forEach(item => winLinuxEditMenu.append(item)); } private setViewMenu(viewMenu: Electron.Menu): void { const explorer = this.createMenuItem(nls.localize({ key: 'miViewExplorer', comment: ['&& denotes a mnemonic'] }, "&&Explorer"), 'workbench.view.explorer'); const search = this.createMenuItem(nls.localize({ key: 'miViewSearch', comment: ['&& denotes a mnemonic'] }, "&&Search"), 'workbench.view.search'); const git = this.createMenuItem(nls.localize({ key: 'miViewGit', comment: ['&& denotes a mnemonic'] }, "&&Git"), 'workbench.view.git'); const debug = this.createMenuItem(nls.localize({ key: 'miViewDebug', comment: ['&& denotes a mnemonic'] }, "&&Debug"), 'workbench.view.debug'); const extensions = this.createMenuItem(nls.localize({ key: 'miViewExtensions', comment: ['&& denotes a mnemonic'] }, "E&&xtensions"), 'workbench.view.extensions'); const output = this.createMenuItem(nls.localize({ key: 'miToggleOutput', comment: ['&& denotes a mnemonic'] }, "&&Output"), 'workbench.action.output.toggleOutput'); const debugConsole = this.createMenuItem(nls.localize({ key: 'miToggleDebugConsole', comment: ['&& denotes a mnemonic'] }, "De&&bug Console"), 'workbench.debug.action.toggleRepl'); const integratedTerminal = this.createMenuItem(nls.localize({ key: 'miToggleIntegratedTerminal', comment: ['&& denotes a mnemonic'] }, "&&Integrated Terminal"), 'workbench.action.terminal.toggleTerminal'); const problems = this.createMenuItem(nls.localize({ key: 'miMarker', comment: ['&& denotes a mnemonic'] }, "&&Problems"), 'workbench.actions.view.problems'); const commands = this.createMenuItem(nls.localize({ key: 'miCommandPalette', comment: ['&& denotes a mnemonic'] }, "&&Command Palette..."), 'workbench.action.showCommands'); const fullscreen = new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miToggleFullScreen', comment: ['&& denotes a mnemonic'] }, "Toggle &&Full Screen")), accelerator: this.getAccelerator('workbench.action.toggleFullScreen'), click: () => this.windowsService.getLastActiveWindow().toggleFullScreen(), enabled: this.windowsService.getWindowCount() > 0 }); const toggleMenuBar = this.createMenuItem(nls.localize({ key: 'miToggleMenuBar', comment: ['&& denotes a mnemonic'] }, "Toggle Menu &&Bar"), 'workbench.action.toggleMenuBar'); const splitEditor = this.createMenuItem(nls.localize({ key: 'miSplitEditor', comment: ['&& denotes a mnemonic'] }, "Split &&Editor"), 'workbench.action.splitEditor'); const toggleEditorLayout = this.createMenuItem(nls.localize({ key: 'miToggleEditorLayout', comment: ['&& denotes a mnemonic'] }, "Toggle Editor Group &&Layout"), 'workbench.action.toggleEditorGroupLayout'); const toggleSidebar = this.createMenuItem(nls.localize({ key: 'miToggleSidebar', comment: ['&& denotes a mnemonic'] }, "&&Toggle Side Bar"), 'workbench.action.toggleSidebarVisibility'); let moveSideBarLabel: string; if (this.currentSidebarLocation !== 'right') { moveSideBarLabel = nls.localize({ key: 'miMoveSidebarRight', comment: ['&& denotes a mnemonic'] }, "&&Move Side Bar Right"); } else { moveSideBarLabel = nls.localize({ key: 'miMoveSidebarLeft', comment: ['&& denotes a mnemonic'] }, "&&Move Side Bar Left"); } const moveSidebar = this.createMenuItem(moveSideBarLabel, 'workbench.action.toggleSidebarPosition'); const togglePanel = this.createMenuItem(nls.localize({ key: 'miTogglePanel', comment: ['&& denotes a mnemonic'] }, "Toggle &&Panel"), 'workbench.action.togglePanel'); let statusBarLabel: string; if (this.currentStatusbarVisible) { statusBarLabel = nls.localize({ key: 'miHideStatusbar', comment: ['&& denotes a mnemonic'] }, "&&Hide Status Bar"); } else { statusBarLabel = nls.localize({ key: 'miShowStatusbar', comment: ['&& denotes a mnemonic'] }, "&&Show Status Bar"); } const toggleStatusbar = this.createMenuItem(statusBarLabel, 'workbench.action.toggleStatusbarVisibility'); const toggleWordWrap = this.createMenuItem(nls.localize({ key: 'miToggleWordWrap', comment: ['&& denotes a mnemonic'] }, "Toggle &&Word Wrap"), 'editor.action.toggleWordWrap'); const toggleRenderWhitespace = this.createMenuItem(nls.localize({ key: 'miToggleRenderWhitespace', comment: ['&& denotes a mnemonic'] }, "Toggle &&Render Whitespace"), 'editor.action.toggleRenderWhitespace'); const toggleRenderControlCharacters = this.createMenuItem(nls.localize({ key: 'miToggleRenderControlCharacters', comment: ['&& denotes a mnemonic'] }, "Toggle &&Control Characters"), 'editor.action.toggleRenderControlCharacter'); const zoomIn = this.createMenuItem(nls.localize({ key: 'miZoomIn', comment: ['&& denotes a mnemonic'] }, "&&Zoom In"), 'workbench.action.zoomIn'); const zoomOut = this.createMenuItem(nls.localize({ key: 'miZoomOut', comment: ['&& denotes a mnemonic'] }, "Zoom O&&ut"), 'workbench.action.zoomOut'); const resetZoom = this.createMenuItem(nls.localize({ key: 'miZoomReset', comment: ['&& denotes a mnemonic'] }, "&&Reset Zoom"), 'workbench.action.zoomReset'); arrays.coalesce([ commands, __separator__(), explorer, search, git, debug, extensions, __separator__(), output, problems, debugConsole, integratedTerminal, __separator__(), fullscreen, platform.isWindows || platform.isLinux ? toggleMenuBar : void 0, __separator__(), splitEditor, toggleEditorLayout, moveSidebar, toggleSidebar, togglePanel, toggleStatusbar, __separator__(), toggleWordWrap, toggleRenderWhitespace, toggleRenderControlCharacters, __separator__(), zoomIn, zoomOut, resetZoom ]).forEach(item => viewMenu.append(item)); } private setGotoMenu(gotoMenu: Electron.Menu): void { const back = this.createMenuItem(nls.localize({ key: 'miBack', comment: ['&& denotes a mnemonic'] }, "&&Back"), 'workbench.action.navigateBack'); const forward = this.createMenuItem(nls.localize({ key: 'miForward', comment: ['&& denotes a mnemonic'] }, "&&Forward"), 'workbench.action.navigateForward'); const switchEditorMenu = new Menu(); const nextEditor = this.createMenuItem(nls.localize({ key: 'miNextEditor', comment: ['&& denotes a mnemonic'] }, "&&Next Editor"), 'workbench.action.nextEditor'); const previousEditor = this.createMenuItem(nls.localize({ key: 'miPreviousEditor', comment: ['&& denotes a mnemonic'] }, "&&Previous Editor"), 'workbench.action.previousEditor'); const nextEditorInGroup = this.createMenuItem(nls.localize({ key: 'miNextEditorInGroup', comment: ['&& denotes a mnemonic'] }, "&&Next Used Editor in Group"), 'workbench.action.openNextRecentlyUsedEditorInGroup'); const previousEditorInGroup = this.createMenuItem(nls.localize({ key: 'miPreviousEditorInGroup', comment: ['&& denotes a mnemonic'] }, "&&Previous Used Editor in Group"), 'workbench.action.openPreviousRecentlyUsedEditorInGroup'); [ nextEditor, previousEditor, __separator__(), nextEditorInGroup, previousEditorInGroup ].forEach(item => switchEditorMenu.append(item)); const switchEditor = new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miSwitchEditor', comment: ['&& denotes a mnemonic'] }, "Switch &&Editor")), submenu: switchEditorMenu, enabled: true }); const switchGroupMenu = new Menu(); const focusFirstGroup = this.createMenuItem(nls.localize({ key: 'miFocusFirstGroup', comment: ['&& denotes a mnemonic'] }, "&&First Group"), 'workbench.action.focusFirstEditorGroup'); const focusSecondGroup = this.createMenuItem(nls.localize({ key: 'miFocusSecondGroup', comment: ['&& denotes a mnemonic'] }, "&&Second Group"), 'workbench.action.focusSecondEditorGroup'); const focusThirdGroup = this.createMenuItem(nls.localize({ key: 'miFocusThirdGroup', comment: ['&& denotes a mnemonic'] }, "&&Third Group"), 'workbench.action.focusThirdEditorGroup'); const nextGroup = this.createMenuItem(nls.localize({ key: 'miNextGroup', comment: ['&& denotes a mnemonic'] }, "&&Next Group"), 'workbench.action.focusNextGroup'); const previousGroup = this.createMenuItem(nls.localize({ key: 'miPreviousGroup', comment: ['&& denotes a mnemonic'] }, "&&Previous Group"), 'workbench.action.focusPreviousGroup'); [ focusFirstGroup, focusSecondGroup, focusThirdGroup, __separator__(), nextGroup, previousGroup ].forEach(item => switchGroupMenu.append(item)); const switchGroup = new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miSwitchGroup', comment: ['&& denotes a mnemonic'] }, "Switch &&Group")), submenu: switchGroupMenu, enabled: true }); const gotoFile = this.createMenuItem(nls.localize({ key: 'miGotoFile', comment: ['&& denotes a mnemonic'] }, "Go to &&File..."), 'workbench.action.quickOpen'); const gotoSymbolInFile = this.createMenuItem(nls.localize({ key: 'miGotoSymbolInFile', comment: ['&& denotes a mnemonic'] }, "Go to &&Symbol in File..."), 'workbench.action.gotoSymbol'); const gotoSymbolInWorkspace = this.createMenuItem(nls.localize({ key: 'miGotoSymbolInWorkspace', comment: ['&& denotes a mnemonic'] }, "Go to Symbol in &&Workspace..."), 'workbench.action.showAllSymbols'); const gotoDefinition = this.createMenuItem(nls.localize({ key: 'miGotoDefinition', comment: ['&& denotes a mnemonic'] }, "Go to &&Definition"), 'editor.action.goToDeclaration'); const gotoLine = this.createMenuItem(nls.localize({ key: 'miGotoLine', comment: ['&& denotes a mnemonic'] }, "Go to &&Line..."), 'workbench.action.gotoLine'); [ back, forward, __separator__(), switchEditor, switchGroup, __separator__(), gotoFile, gotoSymbolInFile, gotoSymbolInWorkspace, gotoDefinition, gotoLine ].forEach(item => gotoMenu.append(item)); } private setMacWindowMenu(macWindowMenu: Electron.Menu): void { const minimize = new MenuItem({ label: nls.localize('mMinimize', "Minimize"), role: 'minimize', accelerator: 'Command+M', enabled: this.windowsService.getWindowCount() > 0 }); const close = new MenuItem({ label: nls.localize('mClose', "Close"), role: 'close', accelerator: 'Command+W', enabled: this.windowsService.getWindowCount() > 0 }); const bringAllToFront = new MenuItem({ label: nls.localize('mBringToFront', "Bring All to Front"), role: 'front', enabled: this.windowsService.getWindowCount() > 0 }); [ minimize, close, __separator__(), bringAllToFront ].forEach(item => macWindowMenu.append(item)); } private toggleDevTools(): void { const w = this.windowsService.getFocusedWindow(); if (w && w.win) { w.win.webContents.toggleDevTools(); } } private setHelpMenu(helpMenu: Electron.Menu): void { const toggleDevToolsItem = new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miToggleDevTools', comment: ['&& denotes a mnemonic'] }, "&&Toggle Developer Tools")), accelerator: this.getAccelerator('workbench.action.toggleDevTools'), click: () => this.toggleDevTools(), enabled: (this.windowsService.getWindowCount() > 0) }); const showAccessibilityOptions = new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miAccessibilityOptions', comment: ['&& denotes a mnemonic'] }, "Accessibility &&Options")), accelerator: null, click: () => { this.windowsService.openAccessibilityOptions(); } }); let reportIssuesItem: Electron.MenuItem = null; if (product.reportIssueUrl) { const label = nls.localize({ key: 'miReportIssues', comment: ['&& denotes a mnemonic'] }, "Report &&Issues"); if (this.windowsService.getWindowCount() > 0) { reportIssuesItem = this.createMenuItem(label, 'workbench.action.reportIssues'); } else { reportIssuesItem = new MenuItem({ label: mnemonicLabel(label), click: () => this.openUrl(product.reportIssueUrl, 'openReportIssues') }); } } arrays.coalesce([ product.documentationUrl ? new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miDocumentation', comment: ['&& denotes a mnemonic'] }, "&&Documentation")), click: () => this.openUrl(product.documentationUrl, 'openDocumentationUrl') }) : null, product.releaseNotesUrl ? new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miReleaseNotes', comment: ['&& denotes a mnemonic'] }, "&&Release Notes")), click: () => this.windowsService.sendToFocused('vscode:runAction', 'update.showCurrentReleaseNotes') }) : null, (product.documentationUrl || product.releaseNotesUrl) ? __separator__() : null, product.twitterUrl ? new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miTwitter', comment: ['&& denotes a mnemonic'] }, "&&Join us on Twitter")), click: () => this.openUrl(product.twitterUrl, 'openTwitterUrl') }) : null, product.requestFeatureUrl ? new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miUserVoice', comment: ['&& denotes a mnemonic'] }, "&&Search Feature Requests")), click: () => this.openUrl(product.requestFeatureUrl, 'openUserVoiceUrl') }) : null, reportIssuesItem, (product.twitterUrl || product.requestFeatureUrl || product.reportIssueUrl) ? __separator__() : null, product.licenseUrl ? new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miLicense', comment: ['&& denotes a mnemonic'] }, "&&View License")), click: () => { if (platform.language) { const queryArgChar = product.licenseUrl.indexOf('?') > 0 ? '&' : '?'; this.openUrl(`${product.licenseUrl}${queryArgChar}lang=${platform.language}`, 'openLicenseUrl'); } else { this.openUrl(product.licenseUrl, 'openLicenseUrl'); } } }) : null, product.privacyStatementUrl ? new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miPrivacyStatement', comment: ['&& denotes a mnemonic'] }, "&&Privacy Statement")), click: () => { if (platform.language) { const queryArgChar = product.licenseUrl.indexOf('?') > 0 ? '&' : '?'; this.openUrl(`${product.privacyStatementUrl}${queryArgChar}lang=${platform.language}`, 'openPrivacyStatement'); } else { this.openUrl(product.privacyStatementUrl, 'openPrivacyStatement'); } } }) : null, (product.licenseUrl || product.privacyStatementUrl) ? __separator__() : null, toggleDevToolsItem, platform.isWindows && product.quality !== 'stable' ? showAccessibilityOptions : null ]).forEach(item => helpMenu.append(item)); if (!platform.isMacintosh) { const updateMenuItems = this.getUpdateMenuItems(); if (updateMenuItems.length) { helpMenu.append(__separator__()); updateMenuItems.forEach(i => helpMenu.append(i)); } helpMenu.append(__separator__()); helpMenu.append(new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miAbout', comment: ['&& denotes a mnemonic'] }, "&&About")), click: () => this.openAboutDialog() })); } } private getUpdateMenuItems(): Electron.MenuItem[] { switch (this.updateService.state) { case UpdateState.Uninitialized: return []; case UpdateState.UpdateDownloaded: const update = this.updateService.availableUpdate; return [new MenuItem({ label: nls.localize('miRestartToUpdate', "Restart To Update..."), click: () => { this.reportMenuActionTelemetry('RestartToUpdate'); update.quitAndUpdate(); } })]; case UpdateState.CheckingForUpdate: return [new MenuItem({ label: nls.localize('miCheckingForUpdates', "Checking For Updates..."), enabled: false })]; case UpdateState.UpdateAvailable: if (platform.isLinux) { const update = this.updateService.availableUpdate; return [new MenuItem({ label: nls.localize('miDownloadUpdate', "Download Available Update"), click: () => { update.quitAndUpdate(); } })]; } const updateAvailableLabel = platform.isWindows ? nls.localize('miDownloadingUpdate', "Downloading Update...") : nls.localize('miInstallingUpdate', "Installing Update..."); return [new MenuItem({ label: updateAvailableLabel, enabled: false })]; default: const result = [new MenuItem({ label: nls.localize('miCheckForUpdates', "Check For Updates..."), click: () => setTimeout(() => { this.reportMenuActionTelemetry('CheckForUpdate'); this.updateService.checkForUpdates(true); }, 0) })]; return result; } } private createMenuItem(label: string, actionId: string, enabled?: boolean, checked?: boolean): Electron.MenuItem; private createMenuItem(label: string, click: () => void, enabled?: boolean, checked?: boolean): Electron.MenuItem; private createMenuItem(arg1: string, arg2: any, arg3?: boolean, arg4?: boolean): Electron.MenuItem { const label = mnemonicLabel(arg1); const click: () => void = (typeof arg2 === 'function') ? arg2 : () => this.windowsService.sendToFocused('vscode:runAction', arg2); const enabled = typeof arg3 === 'boolean' ? arg3 : this.windowsService.getWindowCount() > 0; const checked = typeof arg4 === 'boolean' ? arg4 : false; let actionId: string; if (typeof arg2 === 'string') { actionId = arg2; } const options: Electron.MenuItemOptions = { label, accelerator: this.getAccelerator(actionId), click, enabled }; if (checked) { options['type'] = 'checkbox'; options['checked'] = checked; } return new MenuItem(options); } private createDevToolsAwareMenuItem(label: string, actionId: string, devToolsFocusedFn: (contents: Electron.WebContents) => void): Electron.MenuItem { return new MenuItem({ label: mnemonicLabel(label), accelerator: this.getAccelerator(actionId), enabled: this.windowsService.getWindowCount() > 0, click: () => { const windowInFocus = this.windowsService.getFocusedWindow(); if (!windowInFocus) { return; } if (windowInFocus.win.webContents.isDevToolsFocused()) { devToolsFocusedFn(windowInFocus.win.webContents.devToolsWebContents); } else { this.windowsService.sendToFocused('vscode:runAction', actionId); } } }); } private getAccelerator(actionId: string): string { if (actionId) { const resolvedKeybinding = this.mapResolvedKeybindingToActionId[actionId]; if (resolvedKeybinding) { return resolvedKeybinding; // keybinding is fully resolved } if (!this.keybindingsResolved) { this.actionIdKeybindingRequests.push(actionId); // keybinding needs to be resolved } const lastKnownKeybinding = this.mapLastKnownKeybindingToActionId[actionId]; return lastKnownKeybinding; // return the last known keybining (chance of mismatch is very low unless it changed) } return void (0); } private openAboutDialog(): void { const lastActiveWindow = this.windowsService.getFocusedWindow() || this.windowsService.getLastActiveWindow(); dialog.showMessageBox(lastActiveWindow && lastActiveWindow.win, { title: product.nameLong, type: 'info', message: product.nameLong, detail: nls.localize('aboutDetail', "\nVersion {0}\nCommit {1}\nDate {2}\nShell {3}\nRenderer {4}\nNode {5}", app.getVersion(), product.commit || 'Unknown', product.date || 'Unknown', process.versions['electron'], process.versions['chrome'], process.versions['node'] ), buttons: [nls.localize('okButton', "OK")], noLink: true }, result => null); this.reportMenuActionTelemetry('showAboutDialog'); } private openUrl(url: string, id: string): void { shell.openExternal(url); this.reportMenuActionTelemetry(id); } private reportMenuActionTelemetry(id: string): void { this.windowsService.sendToFocused('vscode:telemetry', { eventName: 'workbenchActionExecuted', data: { id, from: 'menu' } }); } } function __separator__(): Electron.MenuItem { return new MenuItem({ type: 'separator' }); } function mnemonicLabel(label: string): string { if (platform.isMacintosh) { return label.replace(/\(&&\w\)|&&/g, ''); // no mnemonic support on mac } return label.replace(/&&/g, '&'); } function unMnemonicLabel(label: string): string { if (platform.isMacintosh) { return label; // no mnemonic support on mac } return label.replace(/&/g, '&&'); }
src/vs/code/electron-main/menus.ts
1
https://github.com/microsoft/vscode/commit/866dd02825a199f4d6cb275e9090a66ebaece9b2
[ 0.12416476011276245, 0.0036497246474027634, 0.00015927718777675182, 0.0005315284361131489, 0.016688095405697823 ]
{ "id": 1, "code_window": [ "\t\tarrays.coalesce([\n", "\t\t\tproduct.documentationUrl ? new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miDocumentation', comment: ['&& denotes a mnemonic'] }, \"&&Documentation\")), click: () => this.openUrl(product.documentationUrl, 'openDocumentationUrl') }) : null,\n", "\t\t\tproduct.releaseNotesUrl ? new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miReleaseNotes', comment: ['&& denotes a mnemonic'] }, \"&&Release Notes\")), click: () => this.windowsService.sendToFocused('vscode:runAction', 'update.showCurrentReleaseNotes') }) : null,\n", "\t\t\t(product.documentationUrl || product.releaseNotesUrl) ? __separator__() : null,\n", "\t\t\tproduct.twitterUrl ? new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miTwitter', comment: ['&& denotes a mnemonic'] }, \"&&Join us on Twitter\")), click: () => this.openUrl(product.twitterUrl, 'openTwitterUrl') }) : null,\n", "\t\t\tproduct.requestFeatureUrl ? new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miUserVoice', comment: ['&& denotes a mnemonic'] }, \"&&Search Feature Requests\")), click: () => this.openUrl(product.requestFeatureUrl, 'openUserVoiceUrl') }) : null,\n", "\t\t\treportIssuesItem,\n", "\t\t\t(product.twitterUrl || product.requestFeatureUrl || product.reportIssueUrl) ? __separator__() : null,\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tkeyboardShortcutsUrl ? new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miKeyboardShortcuts', comment: ['&& denotes a mnemonic'] }, \"&&Keyboard Shortcuts Reference\")), click: () => this.openUrl(keyboardShortcutsUrl, 'openKeyboardShortcutsUrl') }) : null,\n", "\t\t\tproduct.introductoryVideosUrl ? new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miIntroductoryVideos', comment: ['&& denotes a mnemonic'] }, \"Introductory &&Videos\")), click: () => this.openUrl(product.introductoryVideosUrl, 'openIntroductoryVideosUrl') }) : null,\n" ], "file_path": "src/vs/code/electron-main/menus.ts", "type": "add", "edit_start_line_idx": 699 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import * as assert from 'assert'; import * as errors from 'vs/base/common/errors'; import * as objects from 'vs/base/common/objects'; import { TPromise } from 'vs/base/common/winjs.base'; import { CacheState } from 'vs/workbench/parts/search/browser/openFileHandler'; import { DeferredTPromise } from 'vs/test/utils/promiseTestUtils'; import { QueryType, ISearchQuery } from 'vs/platform/search/common/search'; suite('CacheState', () => { test('reuse old cacheKey until new cache is loaded', function () { const cache = new MockCache(); const first = createCacheState(cache); const firstKey = first.cacheKey; assert.strictEqual(first.isLoaded, false); assert.strictEqual(first.isUpdating, false); first.load(); assert.strictEqual(first.isLoaded, false); assert.strictEqual(first.isUpdating, true); cache.loading[firstKey].complete(null); assert.strictEqual(first.isLoaded, true); assert.strictEqual(first.isUpdating, false); const second = createCacheState(cache, first); second.load(); assert.strictEqual(second.isLoaded, true); assert.strictEqual(second.isUpdating, true); assert.strictEqual(Object.keys(cache.disposing).length, 0); assert.strictEqual(second.cacheKey, firstKey); // still using old cacheKey const secondKey = cache.cacheKeys[1]; cache.loading[secondKey].complete(null); assert.strictEqual(second.isLoaded, true); assert.strictEqual(second.isUpdating, false); assert.strictEqual(Object.keys(cache.disposing).length, 1); assert.strictEqual(second.cacheKey, secondKey); }); test('do not spawn additional load if previous is still loading', function () { const cache = new MockCache(); const first = createCacheState(cache); const firstKey = first.cacheKey; first.load(); assert.strictEqual(first.isLoaded, false); assert.strictEqual(first.isUpdating, true); assert.strictEqual(Object.keys(cache.loading).length, 1); const second = createCacheState(cache, first); second.load(); assert.strictEqual(second.isLoaded, false); assert.strictEqual(second.isUpdating, true); assert.strictEqual(cache.cacheKeys.length, 2); assert.strictEqual(Object.keys(cache.loading).length, 1); // still only one loading assert.strictEqual(second.cacheKey, firstKey); cache.loading[firstKey].complete(null); assert.strictEqual(second.isLoaded, true); assert.strictEqual(second.isUpdating, false); assert.strictEqual(Object.keys(cache.disposing).length, 0); }); test('do not use previous cacheKey if query changed', function () { const cache = new MockCache(); const first = createCacheState(cache); const firstKey = first.cacheKey; first.load(); cache.loading[firstKey].complete(null); assert.strictEqual(first.isLoaded, true); assert.strictEqual(first.isUpdating, false); assert.strictEqual(Object.keys(cache.disposing).length, 0); cache.baseQuery.excludePattern = { '**/node_modules': true }; const second = createCacheState(cache, first); assert.strictEqual(second.isLoaded, false); assert.strictEqual(second.isUpdating, false); assert.strictEqual(Object.keys(cache.disposing).length, 1); second.load(); assert.strictEqual(second.isLoaded, false); assert.strictEqual(second.isUpdating, true); assert.notStrictEqual(second.cacheKey, firstKey); // not using old cacheKey const secondKey = cache.cacheKeys[1]; assert.strictEqual(second.cacheKey, secondKey); cache.loading[secondKey].complete(null); assert.strictEqual(second.isLoaded, true); assert.strictEqual(second.isUpdating, false); assert.strictEqual(Object.keys(cache.disposing).length, 1); }); test('dispose propagates', function () { const cache = new MockCache(); const first = createCacheState(cache); const firstKey = first.cacheKey; first.load(); cache.loading[firstKey].complete(null); const second = createCacheState(cache, first); assert.strictEqual(second.isLoaded, true); assert.strictEqual(second.isUpdating, false); assert.strictEqual(Object.keys(cache.disposing).length, 0); second.dispose(); assert.strictEqual(second.isLoaded, false); assert.strictEqual(second.isUpdating, false); assert.strictEqual(Object.keys(cache.disposing).length, 1); assert.ok(cache.disposing[firstKey]); }); test('keep using old cacheKey when loading fails', function () { const cache = new MockCache(); const first = createCacheState(cache); const firstKey = first.cacheKey; first.load(); cache.loading[firstKey].complete(null); const second = createCacheState(cache, first); second.load(); const secondKey = cache.cacheKeys[1]; var origErrorHandler = errors.errorHandler.getUnexpectedErrorHandler(); try { errors.setUnexpectedErrorHandler(() => null); cache.loading[secondKey].error('loading failed'); } finally { errors.setUnexpectedErrorHandler(origErrorHandler); } assert.strictEqual(second.isLoaded, true); assert.strictEqual(second.isUpdating, false); assert.strictEqual(Object.keys(cache.loading).length, 2); assert.strictEqual(Object.keys(cache.disposing).length, 0); assert.strictEqual(second.cacheKey, firstKey); // keep using old cacheKey const third = createCacheState(cache, second); third.load(); assert.strictEqual(third.isLoaded, true); assert.strictEqual(third.isUpdating, true); assert.strictEqual(Object.keys(cache.loading).length, 3); assert.strictEqual(Object.keys(cache.disposing).length, 0); assert.strictEqual(third.cacheKey, firstKey); const thirdKey = cache.cacheKeys[2]; cache.loading[thirdKey].complete(null); assert.strictEqual(third.isLoaded, true); assert.strictEqual(third.isUpdating, false); assert.strictEqual(Object.keys(cache.loading).length, 3); assert.strictEqual(Object.keys(cache.disposing).length, 2); assert.strictEqual(third.cacheKey, thirdKey); // recover with next successful load }); function createCacheState(cache: MockCache, previous?: CacheState): CacheState { return new CacheState( cacheKey => cache.query(cacheKey), query => cache.load(query), cacheKey => cache.dispose(cacheKey), previous ); } class MockCache { public cacheKeys: string[] = []; public loading: { [cacheKey: string]: DeferredTPromise<any> } = {}; public disposing: { [cacheKey: string]: DeferredTPromise<void> } = {}; public baseQuery: ISearchQuery = { type: QueryType.File }; public query(cacheKey: string): ISearchQuery { this.cacheKeys.push(cacheKey); return objects.assign({ cacheKey: cacheKey }, this.baseQuery); } public load(query: ISearchQuery): TPromise<any> { const promise = new DeferredTPromise<any>(); this.loading[query.cacheKey] = promise; return promise; } public dispose(cacheKey: string): TPromise<void> { const promise = new DeferredTPromise<void>(); this.disposing[cacheKey] = promise; return promise; } } });
src/vs/workbench/parts/search/test/browser/openFileHandler.test.ts
0
https://github.com/microsoft/vscode/commit/866dd02825a199f4d6cb275e9090a66ebaece9b2
[ 0.0001703205198282376, 0.00016700923151802272, 0.00016025491640903056, 0.00016734609380364418, 0.00000243911927100271 ]
{ "id": 1, "code_window": [ "\t\tarrays.coalesce([\n", "\t\t\tproduct.documentationUrl ? new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miDocumentation', comment: ['&& denotes a mnemonic'] }, \"&&Documentation\")), click: () => this.openUrl(product.documentationUrl, 'openDocumentationUrl') }) : null,\n", "\t\t\tproduct.releaseNotesUrl ? new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miReleaseNotes', comment: ['&& denotes a mnemonic'] }, \"&&Release Notes\")), click: () => this.windowsService.sendToFocused('vscode:runAction', 'update.showCurrentReleaseNotes') }) : null,\n", "\t\t\t(product.documentationUrl || product.releaseNotesUrl) ? __separator__() : null,\n", "\t\t\tproduct.twitterUrl ? new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miTwitter', comment: ['&& denotes a mnemonic'] }, \"&&Join us on Twitter\")), click: () => this.openUrl(product.twitterUrl, 'openTwitterUrl') }) : null,\n", "\t\t\tproduct.requestFeatureUrl ? new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miUserVoice', comment: ['&& denotes a mnemonic'] }, \"&&Search Feature Requests\")), click: () => this.openUrl(product.requestFeatureUrl, 'openUserVoiceUrl') }) : null,\n", "\t\t\treportIssuesItem,\n", "\t\t\t(product.twitterUrl || product.requestFeatureUrl || product.reportIssueUrl) ? __separator__() : null,\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tkeyboardShortcutsUrl ? new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miKeyboardShortcuts', comment: ['&& denotes a mnemonic'] }, \"&&Keyboard Shortcuts Reference\")), click: () => this.openUrl(keyboardShortcutsUrl, 'openKeyboardShortcutsUrl') }) : null,\n", "\t\t\tproduct.introductoryVideosUrl ? new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miIntroductoryVideos', comment: ['&& denotes a mnemonic'] }, \"Introductory &&Videos\")), click: () => this.openUrl(product.introductoryVideosUrl, 'openIntroductoryVideosUrl') }) : null,\n" ], "file_path": "src/vs/code/electron-main/menus.ts", "type": "add", "edit_start_line_idx": 699 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "status.400": "잘못된 요청. 잘못된 구문으로 인해 요청을 수행할 수 없습니다.", "status.401": "권한이 없음. 서버에서 응답을 거부합니다.", "status.403": "금지됨. 서버에서 응답을 거부합니다.", "status.404": "찾을 수 없음. 요청된 위치를 찾을 수 없습니다.", "status.405": "메서드가 허용되지 않음. 요청 메서드를 사용하여 생성된 요청은 해당 위치에서 지원되지 않습니다.", "status.406": "허용되지 않음. 서버는 클라이언트에서 허용하지 않는 응답만 생성할 수 있습니다.", "status.407": "프록시 인증 필요. 클라이언트에서 먼저 프록시에 자체적으로 인증해야 합니다.", "status.408": "요청 시간 초과. 서버에서 요청을 기다리는 동안 시간이 초과되었습니다.", "status.409": "충돌이 발생했습니다. 요청에 충돌이 발생하여 요청을 완료할 수 없습니다.", "status.410": "없음. 요청된 페이지를 더 이상 사용할 수 없습니다.", "status.411": "길이 필요. \"Content-Length\"가 정의되지 않았습니다.", "status.412": "사전 조건 실패. 요청에 지정된 사전 조건이 서버에서 false로 평가되었습니다.", "status.413": "요청 엔터티가 너무 큼. 요청 엔터티가 너무 크므로 서버에서 요청을 수락하지 않습니다.", "status.414": "요청 URI가 너무 깁니다. URL이 너무 길어 서버에서 요청을 수락하지 않습니다.", "status.415": "지원되지 않는 미디어 유형. 미디어 유형이 지원되지 않으므로 서버에서 요청을 수락하지 않습니다.", "status.416": "HTTP 상태 코드 {0}", "status.500": "내부 서버 오류.", "status.501": "구현되지 않음. 서버가 요청 메서드를 인식하지 않거나 요청을 수행할 수 있는 기능이 없습니다.", "status.503": "서비스를 사용할 수 없음. 서버를 현재 사용할 수 없습니다(오버로드 또는 다운됨)." }
i18n/kor/extensions/json/server/out/utils/httpRequest.i18n.json
0
https://github.com/microsoft/vscode/commit/866dd02825a199f4d6cb275e9090a66ebaece9b2
[ 0.00016585111734457314, 0.0001634219806874171, 0.00016220704128500074, 0.00016220781253650784, 0.0000017176521396322642 ]
{ "id": 1, "code_window": [ "\t\tarrays.coalesce([\n", "\t\t\tproduct.documentationUrl ? new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miDocumentation', comment: ['&& denotes a mnemonic'] }, \"&&Documentation\")), click: () => this.openUrl(product.documentationUrl, 'openDocumentationUrl') }) : null,\n", "\t\t\tproduct.releaseNotesUrl ? new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miReleaseNotes', comment: ['&& denotes a mnemonic'] }, \"&&Release Notes\")), click: () => this.windowsService.sendToFocused('vscode:runAction', 'update.showCurrentReleaseNotes') }) : null,\n", "\t\t\t(product.documentationUrl || product.releaseNotesUrl) ? __separator__() : null,\n", "\t\t\tproduct.twitterUrl ? new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miTwitter', comment: ['&& denotes a mnemonic'] }, \"&&Join us on Twitter\")), click: () => this.openUrl(product.twitterUrl, 'openTwitterUrl') }) : null,\n", "\t\t\tproduct.requestFeatureUrl ? new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miUserVoice', comment: ['&& denotes a mnemonic'] }, \"&&Search Feature Requests\")), click: () => this.openUrl(product.requestFeatureUrl, 'openUserVoiceUrl') }) : null,\n", "\t\t\treportIssuesItem,\n", "\t\t\t(product.twitterUrl || product.requestFeatureUrl || product.reportIssueUrl) ? __separator__() : null,\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tkeyboardShortcutsUrl ? new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miKeyboardShortcuts', comment: ['&& denotes a mnemonic'] }, \"&&Keyboard Shortcuts Reference\")), click: () => this.openUrl(keyboardShortcutsUrl, 'openKeyboardShortcutsUrl') }) : null,\n", "\t\t\tproduct.introductoryVideosUrl ? new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miIntroductoryVideos', comment: ['&& denotes a mnemonic'] }, \"Introductory &&Videos\")), click: () => this.openUrl(product.introductoryVideosUrl, 'openIntroductoryVideosUrl') }) : null,\n" ], "file_path": "src/vs/code/electron-main/menus.ts", "type": "add", "edit_start_line_idx": 699 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "araLabelEditorActions": "Acciones del editor", "close": "Cerrar", "closeAll": "Cerrar todo", "closeOthers": "Cerrar otros", "closeRight": "Cerrar a la derecha", "keepOpen": "Mantener abierto", "showOpenedEditors": "Mostrar editores abiertos" }
i18n/esn/src/vs/workbench/browser/parts/editor/titleControl.i18n.json
0
https://github.com/microsoft/vscode/commit/866dd02825a199f4d6cb275e9090a66ebaece9b2
[ 0.0001670247147558257, 0.00016674853395670652, 0.00016647235315758735, 0.00016674853395670652, 2.761807991191745e-7 ]
{ "id": 2, "code_window": [ "\t\t\tproduct.requestFeatureUrl ? new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miUserVoice', comment: ['&& denotes a mnemonic'] }, \"&&Search Feature Requests\")), click: () => this.openUrl(product.requestFeatureUrl, 'openUserVoiceUrl') }) : null,\n", "\t\t\treportIssuesItem,\n", "\t\t\t(product.twitterUrl || product.requestFeatureUrl || product.reportIssueUrl) ? __separator__() : null,\n", "\t\t\tproduct.licenseUrl ? new MenuItem({\n", "\t\t\t\tlabel: mnemonicLabel(nls.localize({ key: 'miLicense', comment: ['&& denotes a mnemonic'] }, \"&&View License\")), click: () => {\n", "\t\t\t\t\tif (platform.language) {\n", "\t\t\t\t\t\tconst queryArgChar = product.licenseUrl.indexOf('?') > 0 ? '&' : '?';\n", "\t\t\t\t\t\tthis.openUrl(`${product.licenseUrl}${queryArgChar}lang=${platform.language}`, 'openLicenseUrl');\n", "\t\t\t\t\t} else {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\tlabel: mnemonicLabel(nls.localize({ key: 'miLicense', comment: ['&& denotes a mnemonic'] }, \"View &&License\")), click: () => {\n" ], "file_path": "src/vs/code/electron-main/menus.ts", "type": "replace", "edit_start_line_idx": 704 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as path from 'path'; import uri from 'vs/base/common/uri'; export interface IProductConfiguration { nameShort: string; nameLong: string; applicationName: string; win32AppUserModelId: string; win32MutexName: string; darwinBundleIdentifier: string; urlProtocol: string; dataFolderName: string; downloadUrl: string; updateUrl?: string; quality?: string; commit: string; date: string; extensionsGallery: { serviceUrl: string; itemUrl: string; }; extensionTips: { [id: string]: string; }; extensionImportantTips: { [id: string]: { name: string; pattern: string; }; }; crashReporter: Electron.CrashReporterStartOptions; welcomePage: string; enableTelemetry: boolean; aiConfig: { key: string; asimovKey: string; }; sendASmile: { reportIssueUrl: string, requestFeatureUrl: string }; documentationUrl: string; releaseNotesUrl: string; twitterUrl: string; requestFeatureUrl: string; reportIssueUrl: string; licenseUrl: string; privacyStatementUrl: string; npsSurveyUrl: string; checksums: { [path: string]: string; }; checksumFailMoreInfoUrl: string; } const rootPath = path.dirname(uri.parse(require.toUrl('')).fsPath); const productJsonPath = path.join(rootPath, 'product.json'); const product = require.__$__nodeRequire(productJsonPath) as IProductConfiguration; if (process.env['VSCODE_DEV']) { product.nameShort += ' Dev'; product.nameLong += ' Dev'; product.dataFolderName += '-dev'; } export default product;
src/vs/platform/product.ts
1
https://github.com/microsoft/vscode/commit/866dd02825a199f4d6cb275e9090a66ebaece9b2
[ 0.001677946886047721, 0.0007397035951726139, 0.0001636555971344933, 0.00017399499483872205, 0.0006655905744992197 ]
{ "id": 2, "code_window": [ "\t\t\tproduct.requestFeatureUrl ? new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miUserVoice', comment: ['&& denotes a mnemonic'] }, \"&&Search Feature Requests\")), click: () => this.openUrl(product.requestFeatureUrl, 'openUserVoiceUrl') }) : null,\n", "\t\t\treportIssuesItem,\n", "\t\t\t(product.twitterUrl || product.requestFeatureUrl || product.reportIssueUrl) ? __separator__() : null,\n", "\t\t\tproduct.licenseUrl ? new MenuItem({\n", "\t\t\t\tlabel: mnemonicLabel(nls.localize({ key: 'miLicense', comment: ['&& denotes a mnemonic'] }, \"&&View License\")), click: () => {\n", "\t\t\t\t\tif (platform.language) {\n", "\t\t\t\t\t\tconst queryArgChar = product.licenseUrl.indexOf('?') > 0 ? '&' : '?';\n", "\t\t\t\t\t\tthis.openUrl(`${product.licenseUrl}${queryArgChar}lang=${platform.language}`, 'openLicenseUrl');\n", "\t\t\t\t\t} else {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\tlabel: mnemonicLabel(nls.localize({ key: 'miLicense', comment: ['&& denotes a mnemonic'] }, \"View &&License\")), click: () => {\n" ], "file_path": "src/vs/code/electron-main/menus.ts", "type": "replace", "edit_start_line_idx": 704 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "appCrashed": "La ventana se bloqueó", "appCrashedDetail": "Sentimos las molestias. Puede volver a abrir la ventana para continuar donde se detuvo.", "appStalled": "La ventana ha dejado de responder.", "appStalledDetail": "Puede volver a abrir la ventana, cerrarla o seguir esperando.", "close": "Cerrar", "hiddenMenuBar": "Para acceder a la barra de menús, también puedes presionar la tecla **Alt**.", "ok": "Aceptar", "pathNotExistDetail": "Parece que la ruta '{0}' ya no existe en el disco.", "pathNotExistTitle": "La ruta no existe", "reopen": "Volver a abrir", "wait": "Siga esperando" }
i18n/esn/src/vs/workbench/electron-main/windows.i18n.json
0
https://github.com/microsoft/vscode/commit/866dd02825a199f4d6cb275e9090a66ebaece9b2
[ 0.00017276352446060628, 0.00017214551917277277, 0.00017152752843685448, 0.00017214551917277277, 6.179980118758976e-7 ]
{ "id": 2, "code_window": [ "\t\t\tproduct.requestFeatureUrl ? new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miUserVoice', comment: ['&& denotes a mnemonic'] }, \"&&Search Feature Requests\")), click: () => this.openUrl(product.requestFeatureUrl, 'openUserVoiceUrl') }) : null,\n", "\t\t\treportIssuesItem,\n", "\t\t\t(product.twitterUrl || product.requestFeatureUrl || product.reportIssueUrl) ? __separator__() : null,\n", "\t\t\tproduct.licenseUrl ? new MenuItem({\n", "\t\t\t\tlabel: mnemonicLabel(nls.localize({ key: 'miLicense', comment: ['&& denotes a mnemonic'] }, \"&&View License\")), click: () => {\n", "\t\t\t\t\tif (platform.language) {\n", "\t\t\t\t\t\tconst queryArgChar = product.licenseUrl.indexOf('?') > 0 ? '&' : '?';\n", "\t\t\t\t\t\tthis.openUrl(`${product.licenseUrl}${queryArgChar}lang=${platform.language}`, 'openLicenseUrl');\n", "\t\t\t\t\t} else {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\tlabel: mnemonicLabel(nls.localize({ key: 'miLicense', comment: ['&& denotes a mnemonic'] }, \"View &&License\")), click: () => {\n" ], "file_path": "src/vs/code/electron-main/menus.ts", "type": "replace", "edit_start_line_idx": 704 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "invalid.properties": "'configuration.properties' deve essere un oggetto", "invalid.title": "'configuration.title' deve essere una stringa", "invalid.type": "se impostato, 'configuration.type' deve essere impostato su 'object", "vscode.extension.contributes.configuration": "Impostazioni di configurazione di contributes.", "vscode.extension.contributes.configuration.properties": "Descrizione delle proprietà di configurazione.", "vscode.extension.contributes.configuration.title": "Riepilogo delle impostazioni. Questa etichetta verrà usata nel file di impostazioni come commento di separazione." }
i18n/ita/src/vs/platform/configuration/common/configurationRegistry.i18n.json
0
https://github.com/microsoft/vscode/commit/866dd02825a199f4d6cb275e9090a66ebaece9b2
[ 0.0001722756278468296, 0.00017211740487255156, 0.00017195919645018876, 0.00017211740487255156, 1.582156983204186e-7 ]
{ "id": 2, "code_window": [ "\t\t\tproduct.requestFeatureUrl ? new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miUserVoice', comment: ['&& denotes a mnemonic'] }, \"&&Search Feature Requests\")), click: () => this.openUrl(product.requestFeatureUrl, 'openUserVoiceUrl') }) : null,\n", "\t\t\treportIssuesItem,\n", "\t\t\t(product.twitterUrl || product.requestFeatureUrl || product.reportIssueUrl) ? __separator__() : null,\n", "\t\t\tproduct.licenseUrl ? new MenuItem({\n", "\t\t\t\tlabel: mnemonicLabel(nls.localize({ key: 'miLicense', comment: ['&& denotes a mnemonic'] }, \"&&View License\")), click: () => {\n", "\t\t\t\t\tif (platform.language) {\n", "\t\t\t\t\t\tconst queryArgChar = product.licenseUrl.indexOf('?') > 0 ? '&' : '?';\n", "\t\t\t\t\t\tthis.openUrl(`${product.licenseUrl}${queryArgChar}lang=${platform.language}`, 'openLicenseUrl');\n", "\t\t\t\t\t} else {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\tlabel: mnemonicLabel(nls.localize({ key: 'miLicense', comment: ['&& denotes a mnemonic'] }, \"View &&License\")), click: () => {\n" ], "file_path": "src/vs/code/electron-main/menus.ts", "type": "replace", "edit_start_line_idx": 704 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "watermark.addCursor": "在上方/下方新增資料指標", "watermark.moveLines": "將行上移/下移", "watermark.quickOpen": "前往檔案", "watermark.showCommands": "命令選擇區", "watermark.toggleTerminal": "切換終端機", "watermark.unboundCommand": "未繫結" }
i18n/cht/src/vs/workbench/parts/watermark/watermark.i18n.json
0
https://github.com/microsoft/vscode/commit/866dd02825a199f4d6cb275e9090a66ebaece9b2
[ 0.00017254950944334269, 0.00017132028006017208, 0.00017009103612508625, 0.00017132028006017208, 0.0000012292366591282189 ]
{ "id": 3, "code_window": [ "\t\trequestFeatureUrl: string\n", "\t};\n", "\tdocumentationUrl: string;\n", "\treleaseNotesUrl: string;\n", "\ttwitterUrl: string;\n", "\trequestFeatureUrl: string;\n", "\treportIssueUrl: string;\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\tkeyboardShortcutsUrlMac: string;\n", "\tkeyboardShortcutsUrlLinux: string;\n", "\tkeyboardShortcutsUrlWin: string;\n", "\tintroductoryVideosUrl: string;\n" ], "file_path": "src/vs/platform/product.ts", "type": "add", "edit_start_line_idx": 41 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import * as nls from 'vs/nls'; import * as platform from 'vs/base/common/platform'; import * as arrays from 'vs/base/common/arrays'; import { IEnvironmentService } from 'vs/platform/environment/common/environment'; import { ipcMain as ipc, app, shell, dialog, Menu, MenuItem } from 'electron'; import { IWindowsService } from 'vs/code/electron-main/windows'; import { IPath, VSCodeWindow } from 'vs/code/electron-main/window'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IStorageService } from 'vs/code/electron-main/storage'; import { IFilesConfiguration, AutoSaveConfiguration } from 'vs/platform/files/common/files'; import { IUpdateService, State as UpdateState } from 'vs/code/electron-main/update-manager'; import { Keybinding } from 'vs/base/common/keybinding'; import product from 'vs/platform/product'; interface IResolvedKeybinding { id: string; binding: number; } interface IConfiguration extends IFilesConfiguration { workbench: { sideBar: { location: 'left' | 'right'; }, statusBar: { visible: boolean; } }; } export class VSCodeMenu { private static lastKnownKeybindingsMapStorageKey = 'lastKnownKeybindings'; private static MAX_MENU_RECENT_ENTRIES = 10; private currentAutoSaveSetting: string; private currentSidebarLocation: 'left' | 'right'; private currentStatusbarVisible: boolean; private isQuitting: boolean; private appMenuInstalled: boolean; private actionIdKeybindingRequests: string[]; private mapLastKnownKeybindingToActionId: { [id: string]: string; }; private mapResolvedKeybindingToActionId: { [id: string]: string; }; private keybindingsResolved: boolean; constructor( @IStorageService private storageService: IStorageService, @IUpdateService private updateService: IUpdateService, @IConfigurationService private configurationService: IConfigurationService, @IWindowsService private windowsService: IWindowsService, @IEnvironmentService private environmentService: IEnvironmentService ) { this.actionIdKeybindingRequests = []; this.mapResolvedKeybindingToActionId = Object.create(null); this.mapLastKnownKeybindingToActionId = this.storageService.getItem<{ [id: string]: string; }>(VSCodeMenu.lastKnownKeybindingsMapStorageKey) || Object.create(null); this.onConfigurationUpdated(this.configurationService.getConfiguration<IConfiguration>()); } public ready(): void { this.registerListeners(); this.install(); } private registerListeners(): void { // Keep flag when app quits app.on('will-quit', () => { this.isQuitting = true; }); // Listen to "open" & "close" event from window service this.windowsService.onOpen(paths => this.onOpen(paths)); this.windowsService.onClose(_ => this.onClose(this.windowsService.getWindowCount())); // Resolve keybindings when any first workbench is loaded this.windowsService.onReady(win => this.resolveKeybindings(win)); // Listen to resolved keybindings ipc.on('vscode:keybindingsResolved', (event, rawKeybindings) => { let keybindings: IResolvedKeybinding[] = []; try { keybindings = JSON.parse(rawKeybindings); } catch (error) { // Should not happen } // Fill hash map of resolved keybindings let needsMenuUpdate = false; keybindings.forEach(keybinding => { const accelerator = new Keybinding(keybinding.binding)._toElectronAccelerator(); if (accelerator) { this.mapResolvedKeybindingToActionId[keybinding.id] = accelerator; if (this.mapLastKnownKeybindingToActionId[keybinding.id] !== accelerator) { needsMenuUpdate = true; // we only need to update when something changed! } } }); // A keybinding might have been unassigned, so we have to account for that too if (Object.keys(this.mapLastKnownKeybindingToActionId).length !== Object.keys(this.mapResolvedKeybindingToActionId).length) { needsMenuUpdate = true; } if (needsMenuUpdate) { this.storageService.setItem(VSCodeMenu.lastKnownKeybindingsMapStorageKey, this.mapResolvedKeybindingToActionId); // keep to restore instantly after restart this.mapLastKnownKeybindingToActionId = this.mapResolvedKeybindingToActionId; // update our last known map this.updateMenu(); } }); // Update when auto save config changes this.configurationService.onDidUpdateConfiguration(e => this.onConfigurationUpdated(e.config, true /* update menu if changed */)); // Listen to update service this.updateService.on('change', () => this.updateMenu()); } private onConfigurationUpdated(config: IConfiguration, handleMenu?: boolean): void { let updateMenu = false; const newAutoSaveSetting = config && config.files && config.files.autoSave; if (newAutoSaveSetting !== this.currentAutoSaveSetting) { this.currentAutoSaveSetting = newAutoSaveSetting; updateMenu = true; } if (config && config.workbench) { const newSidebarLocation = config.workbench.sideBar && config.workbench.sideBar.location || 'left'; if (newSidebarLocation !== this.currentSidebarLocation) { this.currentSidebarLocation = newSidebarLocation; updateMenu = true; } let newStatusbarVisible = config.workbench.statusBar && config.workbench.statusBar.visible; if (typeof newStatusbarVisible !== 'boolean') { newStatusbarVisible = true; } if (newStatusbarVisible !== this.currentStatusbarVisible) { this.currentStatusbarVisible = newStatusbarVisible; updateMenu = true; } } if (handleMenu && updateMenu) { this.updateMenu(); } } private resolveKeybindings(win: VSCodeWindow): void { if (this.keybindingsResolved) { return; // only resolve once } this.keybindingsResolved = true; // Resolve keybindings when workbench window is up if (this.actionIdKeybindingRequests.length) { win.send('vscode:resolveKeybindings', JSON.stringify(this.actionIdKeybindingRequests)); } } private updateMenu(): void { // Due to limitations in Electron, it is not possible to update menu items dynamically. The suggested // workaround from Electron is to set the application menu again. // See also https://github.com/electron/electron/issues/846 // // Run delayed to prevent updating menu while it is open if (!this.isQuitting) { setTimeout(() => { if (!this.isQuitting) { this.install(); } }, 10 /* delay this because there is an issue with updating a menu when it is open */); } } private onOpen(path: IPath): void { this.updateMenu(); } private onClose(remainingWindowCount: number): void { if (remainingWindowCount === 0 && platform.isMacintosh) { this.updateMenu(); } } private install(): void { // Menus const menubar = new Menu(); // Mac: Application let macApplicationMenuItem: Electron.MenuItem; if (platform.isMacintosh) { const applicationMenu = new Menu(); macApplicationMenuItem = new MenuItem({ label: product.nameShort, submenu: applicationMenu }); this.setMacApplicationMenu(applicationMenu); } // File const fileMenu = new Menu(); const fileMenuItem = new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'mFile', comment: ['&& denotes a mnemonic'] }, "&&File")), submenu: fileMenu }); this.setFileMenu(fileMenu); // Edit const editMenu = new Menu(); const editMenuItem = new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'mEdit', comment: ['&& denotes a mnemonic'] }, "&&Edit")), submenu: editMenu }); this.setEditMenu(editMenu); // View const viewMenu = new Menu(); const viewMenuItem = new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'mView', comment: ['&& denotes a mnemonic'] }, "&&View")), submenu: viewMenu }); this.setViewMenu(viewMenu); // Goto const gotoMenu = new Menu(); const gotoMenuItem = new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'mGoto', comment: ['&& denotes a mnemonic'] }, "&&Go")), submenu: gotoMenu }); this.setGotoMenu(gotoMenu); // Mac: Window let macWindowMenuItem: Electron.MenuItem; if (platform.isMacintosh) { const windowMenu = new Menu(); macWindowMenuItem = new MenuItem({ label: mnemonicLabel(nls.localize('mWindow', "Window")), submenu: windowMenu, role: 'window' }); this.setMacWindowMenu(windowMenu); } // Help const helpMenu = new Menu(); const helpMenuItem = new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'mHelp', comment: ['&& denotes a mnemonic'] }, "&&Help")), submenu: helpMenu, role: 'help' }); this.setHelpMenu(helpMenu); // Menu Structure if (macApplicationMenuItem) { menubar.append(macApplicationMenuItem); } menubar.append(fileMenuItem); menubar.append(editMenuItem); menubar.append(viewMenuItem); menubar.append(gotoMenuItem); if (macWindowMenuItem) { menubar.append(macWindowMenuItem); } menubar.append(helpMenuItem); Menu.setApplicationMenu(menubar); // Dock Menu if (platform.isMacintosh && !this.appMenuInstalled) { this.appMenuInstalled = true; const dockMenu = new Menu(); dockMenu.append(new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miNewWindow', comment: ['&& denotes a mnemonic'] }, "&&New Window")), click: () => this.windowsService.openNewWindow() })); app.dock.setMenu(dockMenu); } } private setMacApplicationMenu(macApplicationMenu: Electron.Menu): void { const about = new MenuItem({ label: nls.localize('mAbout', "About {0}", product.nameLong), role: 'about' }); const checkForUpdates = this.getUpdateMenuItems(); const preferences = this.getPreferencesMenu(); const hide = new MenuItem({ label: nls.localize('mHide', "Hide {0}", product.nameLong), role: 'hide', accelerator: 'Command+H' }); const hideOthers = new MenuItem({ label: nls.localize('mHideOthers', "Hide Others"), role: 'hideothers', accelerator: 'Command+Alt+H' }); const showAll = new MenuItem({ label: nls.localize('mShowAll', "Show All"), role: 'unhide' }); const quit = new MenuItem({ label: nls.localize('miQuit', "Quit {0}", product.nameLong), click: () => this.quit(), accelerator: 'Command+Q' }); const actions = [about]; actions.push(...checkForUpdates); actions.push(...[ __separator__(), preferences, __separator__(), hide, hideOthers, showAll, __separator__(), quit ]); actions.forEach(i => macApplicationMenu.append(i)); } private setFileMenu(fileMenu: Electron.Menu): void { const hasNoWindows = (this.windowsService.getWindowCount() === 0); let newFile: Electron.MenuItem; if (hasNoWindows) { newFile = new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miNewFile', comment: ['&& denotes a mnemonic'] }, "&&New File")), accelerator: this.getAccelerator('workbench.action.files.newUntitledFile'), click: () => this.windowsService.openNewWindow() }); } else { newFile = this.createMenuItem(nls.localize({ key: 'miNewFile', comment: ['&& denotes a mnemonic'] }, "&&New File"), 'workbench.action.files.newUntitledFile'); } const open = new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miOpen', comment: ['&& denotes a mnemonic'] }, "&&Open...")), accelerator: this.getAccelerator('workbench.action.files.openFileFolder'), click: () => this.windowsService.openFileFolderPicker() }); const openFolder = new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miOpenFolder', comment: ['&& denotes a mnemonic'] }, "Open &&Folder...")), accelerator: this.getAccelerator('workbench.action.files.openFolder'), click: () => this.windowsService.openFolderPicker() }); let openFile: Electron.MenuItem; if (hasNoWindows) { openFile = new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miOpenFile', comment: ['&& denotes a mnemonic'] }, "&&Open File...")), accelerator: this.getAccelerator('workbench.action.files.openFile'), click: () => this.windowsService.openFilePicker() }); } else { openFile = this.createMenuItem(nls.localize({ key: 'miOpenFile', comment: ['&& denotes a mnemonic'] }, "&&Open File..."), 'workbench.action.files.openFile'); } const openRecentMenu = new Menu(); this.setOpenRecentMenu(openRecentMenu); const openRecent = new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miOpenRecent', comment: ['&& denotes a mnemonic'] }, "Open &&Recent")), submenu: openRecentMenu, enabled: openRecentMenu.items.length > 0 }); const saveFile = this.createMenuItem(nls.localize({ key: 'miSave', comment: ['&& denotes a mnemonic'] }, "&&Save"), 'workbench.action.files.save', this.windowsService.getWindowCount() > 0); const saveFileAs = this.createMenuItem(nls.localize({ key: 'miSaveAs', comment: ['&& denotes a mnemonic'] }, "Save &&As..."), 'workbench.action.files.saveAs', this.windowsService.getWindowCount() > 0); const saveAllFiles = this.createMenuItem(nls.localize({ key: 'miSaveAll', comment: ['&& denotes a mnemonic'] }, "Save A&&ll"), 'workbench.action.files.saveAll', this.windowsService.getWindowCount() > 0); const autoSaveEnabled = [AutoSaveConfiguration.AFTER_DELAY, AutoSaveConfiguration.ON_FOCUS_CHANGE, AutoSaveConfiguration.ON_WINDOW_CHANGE].some(s => this.currentAutoSaveSetting === s); const autoSave = new MenuItem({ label: mnemonicLabel(nls.localize('miAutoSave', "Auto Save")), type: 'checkbox', checked: autoSaveEnabled, enabled: this.windowsService.getWindowCount() > 0, click: () => this.windowsService.sendToFocused('vscode.toggleAutoSave') }); const preferences = this.getPreferencesMenu(); const newWindow = new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miNewWindow', comment: ['&& denotes a mnemonic'] }, "&&New Window")), accelerator: this.getAccelerator('workbench.action.newWindow'), click: () => this.windowsService.openNewWindow() }); const revertFile = this.createMenuItem(nls.localize({ key: 'miRevert', comment: ['&& denotes a mnemonic'] }, "Revert F&&ile"), 'workbench.action.files.revert', this.windowsService.getWindowCount() > 0); const closeWindow = new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miCloseWindow', comment: ['&& denotes a mnemonic'] }, "Close &&Window")), accelerator: this.getAccelerator('workbench.action.closeWindow'), click: () => this.windowsService.getLastActiveWindow().win.close(), enabled: this.windowsService.getWindowCount() > 0 }); const closeFolder = this.createMenuItem(nls.localize({ key: 'miCloseFolder', comment: ['&& denotes a mnemonic'] }, "Close &&Folder"), 'workbench.action.closeFolder'); const closeEditor = this.createMenuItem(nls.localize({ key: 'miCloseEditor', comment: ['&& denotes a mnemonic'] }, "Close &&Editor"), 'workbench.action.closeActiveEditor'); const exit = this.createMenuItem(nls.localize({ key: 'miExit', comment: ['&& denotes a mnemonic'] }, "E&&xit"), () => this.quit()); arrays.coalesce([ newFile, newWindow, __separator__(), platform.isMacintosh ? open : null, !platform.isMacintosh ? openFile : null, !platform.isMacintosh ? openFolder : null, openRecent, __separator__(), saveFile, saveFileAs, saveAllFiles, __separator__(), autoSave, __separator__(), !platform.isMacintosh ? preferences : null, !platform.isMacintosh ? __separator__() : null, revertFile, closeEditor, closeFolder, !platform.isMacintosh ? closeWindow : null, !platform.isMacintosh ? __separator__() : null, !platform.isMacintosh ? exit : null ]).forEach(item => fileMenu.append(item)); } private getPreferencesMenu(): Electron.MenuItem { const userSettings = this.createMenuItem(nls.localize({ key: 'miOpenSettings', comment: ['&& denotes a mnemonic'] }, "&&User Settings"), 'workbench.action.openGlobalSettings'); const workspaceSettings = this.createMenuItem(nls.localize({ key: 'miOpenWorkspaceSettings', comment: ['&& denotes a mnemonic'] }, "&&Workspace Settings"), 'workbench.action.openWorkspaceSettings'); const kebindingSettings = this.createMenuItem(nls.localize({ key: 'miOpenKeymap', comment: ['&& denotes a mnemonic'] }, "&&Keyboard Shortcuts"), 'workbench.action.openGlobalKeybindings'); const snippetsSettings = this.createMenuItem(nls.localize({ key: 'miOpenSnippets', comment: ['&& denotes a mnemonic'] }, "User &&Snippets"), 'workbench.action.openSnippets'); const colorThemeSelection = this.createMenuItem(nls.localize({ key: 'miSelectColorTheme', comment: ['&& denotes a mnemonic'] }, "&&Color Theme"), 'workbench.action.selectTheme'); const iconThemeSelection = this.createMenuItem(nls.localize({ key: 'miSelectIconTheme', comment: ['&& denotes a mnemonic'] }, "File &&Icon Theme"), 'workbench.action.selectIconTheme'); const preferencesMenu = new Menu(); preferencesMenu.append(userSettings); preferencesMenu.append(workspaceSettings); preferencesMenu.append(__separator__()); preferencesMenu.append(kebindingSettings); preferencesMenu.append(__separator__()); preferencesMenu.append(snippetsSettings); preferencesMenu.append(__separator__()); preferencesMenu.append(colorThemeSelection); preferencesMenu.append(iconThemeSelection); return new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miPreferences', comment: ['&& denotes a mnemonic'] }, "&&Preferences")), submenu: preferencesMenu }); } private quit(): void { // If the user selected to exit from an extension development host window, do not quit, but just // close the window unless this is the last window that is opened. const vscodeWindow = this.windowsService.getFocusedWindow(); if (vscodeWindow && vscodeWindow.isPluginDevelopmentHost && this.windowsService.getWindowCount() > 1) { vscodeWindow.win.close(); } // Otherwise: normal quit else { setTimeout(() => { this.isQuitting = true; app.quit(); }, 10 /* delay this because there is an issue with quitting while the menu is open */); } } private setOpenRecentMenu(openRecentMenu: Electron.Menu): void { openRecentMenu.append(this.createMenuItem(nls.localize({ key: 'miReopenClosedEditor', comment: ['&& denotes a mnemonic'] }, "&&Reopen Closed Editor"), 'workbench.action.reopenClosedEditor')); const {folders, files} = this.windowsService.getRecentPathsList(); // Folders if (folders.length > 0) { openRecentMenu.append(__separator__()); for (let i = 0; i < VSCodeMenu.MAX_MENU_RECENT_ENTRIES && i < folders.length; i++) { openRecentMenu.append(this.createOpenRecentMenuItem(folders[i])); } } // Files if (files.length > 0) { openRecentMenu.append(__separator__()); for (let i = 0; i < VSCodeMenu.MAX_MENU_RECENT_ENTRIES && i < files.length; i++) { openRecentMenu.append(this.createOpenRecentMenuItem(files[i])); } } if (folders.length || files.length) { openRecentMenu.append(__separator__()); openRecentMenu.append(new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miClearItems', comment: ['&& denotes a mnemonic'] }, "&&Clear Items")), click: () => { this.windowsService.clearRecentPathsList(); this.updateMenu(); } })); } } private createOpenRecentMenuItem(path: string): Electron.MenuItem { return new MenuItem({ label: unMnemonicLabel(path), click: (menuItem, win, event) => { const openInNewWindow = event && ((!platform.isMacintosh && event.ctrlKey) || (platform.isMacintosh && event.metaKey)); const success = !!this.windowsService.open({ cli: this.environmentService.args, pathsToOpen: [path], forceNewWindow: openInNewWindow }); if (!success) { this.windowsService.removeFromRecentPathsList(path); this.updateMenu(); } } }); } private createRoleMenuItem(label: string, actionId: string, role: Electron.MenuItemRole): Electron.MenuItem { const options: Electron.MenuItemOptions = { label: mnemonicLabel(label), accelerator: this.getAccelerator(actionId), role, enabled: true }; return new MenuItem(options); } private setEditMenu(winLinuxEditMenu: Electron.Menu): void { let undo: Electron.MenuItem; let redo: Electron.MenuItem; let cut: Electron.MenuItem; let copy: Electron.MenuItem; let paste: Electron.MenuItem; let selectAll: Electron.MenuItem; if (platform.isMacintosh) { undo = this.createDevToolsAwareMenuItem(nls.localize({ key: 'miUndo', comment: ['&& denotes a mnemonic'] }, "&&Undo"), 'undo', devTools => devTools.undo()); redo = this.createDevToolsAwareMenuItem(nls.localize({ key: 'miRedo', comment: ['&& denotes a mnemonic'] }, "&&Redo"), 'redo', devTools => devTools.redo()); cut = this.createRoleMenuItem(nls.localize({ key: 'miCut', comment: ['&& denotes a mnemonic'] }, "&&Cut"), 'editor.action.clipboardCutAction', 'cut'); copy = this.createRoleMenuItem(nls.localize({ key: 'miCopy', comment: ['&& denotes a mnemonic'] }, "C&&opy"), 'editor.action.clipboardCopyAction', 'copy'); paste = this.createRoleMenuItem(nls.localize({ key: 'miPaste', comment: ['&& denotes a mnemonic'] }, "&&Paste"), 'editor.action.clipboardPasteAction', 'paste'); selectAll = this.createDevToolsAwareMenuItem(nls.localize({ key: 'miSelectAll', comment: ['&& denotes a mnemonic'] }, "&&Select All"), 'editor.action.selectAll', (devTools) => devTools.selectAll()); } else { undo = this.createMenuItem(nls.localize({ key: 'miUndo', comment: ['&& denotes a mnemonic'] }, "&&Undo"), 'undo'); redo = this.createMenuItem(nls.localize({ key: 'miRedo', comment: ['&& denotes a mnemonic'] }, "&&Redo"), 'redo'); cut = this.createMenuItem(nls.localize({ key: 'miCut', comment: ['&& denotes a mnemonic'] }, "&&Cut"), 'editor.action.clipboardCutAction'); copy = this.createMenuItem(nls.localize({ key: 'miCopy', comment: ['&& denotes a mnemonic'] }, "C&&opy"), 'editor.action.clipboardCopyAction'); paste = this.createMenuItem(nls.localize({ key: 'miPaste', comment: ['&& denotes a mnemonic'] }, "&&Paste"), 'editor.action.clipboardPasteAction'); selectAll = this.createMenuItem(nls.localize({ key: 'miSelectAll', comment: ['&& denotes a mnemonic'] }, "&&Select All"), 'editor.action.selectAll'); } const find = this.createMenuItem(nls.localize({ key: 'miFind', comment: ['&& denotes a mnemonic'] }, "&&Find"), 'actions.find'); const replace = this.createMenuItem(nls.localize({ key: 'miReplace', comment: ['&& denotes a mnemonic'] }, "&&Replace"), 'editor.action.startFindReplaceAction'); const findInFiles = this.createMenuItem(nls.localize({ key: 'miFindInFiles', comment: ['&& denotes a mnemonic'] }, "Find &&in Files"), 'workbench.action.findInFiles'); const replaceInFiles = this.createMenuItem(nls.localize({ key: 'miReplaceInFiles', comment: ['&& denotes a mnemonic'] }, "Replace &&in Files"), 'workbench.action.replaceInFiles'); [ undo, redo, __separator__(), cut, copy, paste, selectAll, __separator__(), find, replace, __separator__(), findInFiles, replaceInFiles ].forEach(item => winLinuxEditMenu.append(item)); } private setViewMenu(viewMenu: Electron.Menu): void { const explorer = this.createMenuItem(nls.localize({ key: 'miViewExplorer', comment: ['&& denotes a mnemonic'] }, "&&Explorer"), 'workbench.view.explorer'); const search = this.createMenuItem(nls.localize({ key: 'miViewSearch', comment: ['&& denotes a mnemonic'] }, "&&Search"), 'workbench.view.search'); const git = this.createMenuItem(nls.localize({ key: 'miViewGit', comment: ['&& denotes a mnemonic'] }, "&&Git"), 'workbench.view.git'); const debug = this.createMenuItem(nls.localize({ key: 'miViewDebug', comment: ['&& denotes a mnemonic'] }, "&&Debug"), 'workbench.view.debug'); const extensions = this.createMenuItem(nls.localize({ key: 'miViewExtensions', comment: ['&& denotes a mnemonic'] }, "E&&xtensions"), 'workbench.view.extensions'); const output = this.createMenuItem(nls.localize({ key: 'miToggleOutput', comment: ['&& denotes a mnemonic'] }, "&&Output"), 'workbench.action.output.toggleOutput'); const debugConsole = this.createMenuItem(nls.localize({ key: 'miToggleDebugConsole', comment: ['&& denotes a mnemonic'] }, "De&&bug Console"), 'workbench.debug.action.toggleRepl'); const integratedTerminal = this.createMenuItem(nls.localize({ key: 'miToggleIntegratedTerminal', comment: ['&& denotes a mnemonic'] }, "&&Integrated Terminal"), 'workbench.action.terminal.toggleTerminal'); const problems = this.createMenuItem(nls.localize({ key: 'miMarker', comment: ['&& denotes a mnemonic'] }, "&&Problems"), 'workbench.actions.view.problems'); const commands = this.createMenuItem(nls.localize({ key: 'miCommandPalette', comment: ['&& denotes a mnemonic'] }, "&&Command Palette..."), 'workbench.action.showCommands'); const fullscreen = new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miToggleFullScreen', comment: ['&& denotes a mnemonic'] }, "Toggle &&Full Screen")), accelerator: this.getAccelerator('workbench.action.toggleFullScreen'), click: () => this.windowsService.getLastActiveWindow().toggleFullScreen(), enabled: this.windowsService.getWindowCount() > 0 }); const toggleMenuBar = this.createMenuItem(nls.localize({ key: 'miToggleMenuBar', comment: ['&& denotes a mnemonic'] }, "Toggle Menu &&Bar"), 'workbench.action.toggleMenuBar'); const splitEditor = this.createMenuItem(nls.localize({ key: 'miSplitEditor', comment: ['&& denotes a mnemonic'] }, "Split &&Editor"), 'workbench.action.splitEditor'); const toggleEditorLayout = this.createMenuItem(nls.localize({ key: 'miToggleEditorLayout', comment: ['&& denotes a mnemonic'] }, "Toggle Editor Group &&Layout"), 'workbench.action.toggleEditorGroupLayout'); const toggleSidebar = this.createMenuItem(nls.localize({ key: 'miToggleSidebar', comment: ['&& denotes a mnemonic'] }, "&&Toggle Side Bar"), 'workbench.action.toggleSidebarVisibility'); let moveSideBarLabel: string; if (this.currentSidebarLocation !== 'right') { moveSideBarLabel = nls.localize({ key: 'miMoveSidebarRight', comment: ['&& denotes a mnemonic'] }, "&&Move Side Bar Right"); } else { moveSideBarLabel = nls.localize({ key: 'miMoveSidebarLeft', comment: ['&& denotes a mnemonic'] }, "&&Move Side Bar Left"); } const moveSidebar = this.createMenuItem(moveSideBarLabel, 'workbench.action.toggleSidebarPosition'); const togglePanel = this.createMenuItem(nls.localize({ key: 'miTogglePanel', comment: ['&& denotes a mnemonic'] }, "Toggle &&Panel"), 'workbench.action.togglePanel'); let statusBarLabel: string; if (this.currentStatusbarVisible) { statusBarLabel = nls.localize({ key: 'miHideStatusbar', comment: ['&& denotes a mnemonic'] }, "&&Hide Status Bar"); } else { statusBarLabel = nls.localize({ key: 'miShowStatusbar', comment: ['&& denotes a mnemonic'] }, "&&Show Status Bar"); } const toggleStatusbar = this.createMenuItem(statusBarLabel, 'workbench.action.toggleStatusbarVisibility'); const toggleWordWrap = this.createMenuItem(nls.localize({ key: 'miToggleWordWrap', comment: ['&& denotes a mnemonic'] }, "Toggle &&Word Wrap"), 'editor.action.toggleWordWrap'); const toggleRenderWhitespace = this.createMenuItem(nls.localize({ key: 'miToggleRenderWhitespace', comment: ['&& denotes a mnemonic'] }, "Toggle &&Render Whitespace"), 'editor.action.toggleRenderWhitespace'); const toggleRenderControlCharacters = this.createMenuItem(nls.localize({ key: 'miToggleRenderControlCharacters', comment: ['&& denotes a mnemonic'] }, "Toggle &&Control Characters"), 'editor.action.toggleRenderControlCharacter'); const zoomIn = this.createMenuItem(nls.localize({ key: 'miZoomIn', comment: ['&& denotes a mnemonic'] }, "&&Zoom In"), 'workbench.action.zoomIn'); const zoomOut = this.createMenuItem(nls.localize({ key: 'miZoomOut', comment: ['&& denotes a mnemonic'] }, "Zoom O&&ut"), 'workbench.action.zoomOut'); const resetZoom = this.createMenuItem(nls.localize({ key: 'miZoomReset', comment: ['&& denotes a mnemonic'] }, "&&Reset Zoom"), 'workbench.action.zoomReset'); arrays.coalesce([ commands, __separator__(), explorer, search, git, debug, extensions, __separator__(), output, problems, debugConsole, integratedTerminal, __separator__(), fullscreen, platform.isWindows || platform.isLinux ? toggleMenuBar : void 0, __separator__(), splitEditor, toggleEditorLayout, moveSidebar, toggleSidebar, togglePanel, toggleStatusbar, __separator__(), toggleWordWrap, toggleRenderWhitespace, toggleRenderControlCharacters, __separator__(), zoomIn, zoomOut, resetZoom ]).forEach(item => viewMenu.append(item)); } private setGotoMenu(gotoMenu: Electron.Menu): void { const back = this.createMenuItem(nls.localize({ key: 'miBack', comment: ['&& denotes a mnemonic'] }, "&&Back"), 'workbench.action.navigateBack'); const forward = this.createMenuItem(nls.localize({ key: 'miForward', comment: ['&& denotes a mnemonic'] }, "&&Forward"), 'workbench.action.navigateForward'); const switchEditorMenu = new Menu(); const nextEditor = this.createMenuItem(nls.localize({ key: 'miNextEditor', comment: ['&& denotes a mnemonic'] }, "&&Next Editor"), 'workbench.action.nextEditor'); const previousEditor = this.createMenuItem(nls.localize({ key: 'miPreviousEditor', comment: ['&& denotes a mnemonic'] }, "&&Previous Editor"), 'workbench.action.previousEditor'); const nextEditorInGroup = this.createMenuItem(nls.localize({ key: 'miNextEditorInGroup', comment: ['&& denotes a mnemonic'] }, "&&Next Used Editor in Group"), 'workbench.action.openNextRecentlyUsedEditorInGroup'); const previousEditorInGroup = this.createMenuItem(nls.localize({ key: 'miPreviousEditorInGroup', comment: ['&& denotes a mnemonic'] }, "&&Previous Used Editor in Group"), 'workbench.action.openPreviousRecentlyUsedEditorInGroup'); [ nextEditor, previousEditor, __separator__(), nextEditorInGroup, previousEditorInGroup ].forEach(item => switchEditorMenu.append(item)); const switchEditor = new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miSwitchEditor', comment: ['&& denotes a mnemonic'] }, "Switch &&Editor")), submenu: switchEditorMenu, enabled: true }); const switchGroupMenu = new Menu(); const focusFirstGroup = this.createMenuItem(nls.localize({ key: 'miFocusFirstGroup', comment: ['&& denotes a mnemonic'] }, "&&First Group"), 'workbench.action.focusFirstEditorGroup'); const focusSecondGroup = this.createMenuItem(nls.localize({ key: 'miFocusSecondGroup', comment: ['&& denotes a mnemonic'] }, "&&Second Group"), 'workbench.action.focusSecondEditorGroup'); const focusThirdGroup = this.createMenuItem(nls.localize({ key: 'miFocusThirdGroup', comment: ['&& denotes a mnemonic'] }, "&&Third Group"), 'workbench.action.focusThirdEditorGroup'); const nextGroup = this.createMenuItem(nls.localize({ key: 'miNextGroup', comment: ['&& denotes a mnemonic'] }, "&&Next Group"), 'workbench.action.focusNextGroup'); const previousGroup = this.createMenuItem(nls.localize({ key: 'miPreviousGroup', comment: ['&& denotes a mnemonic'] }, "&&Previous Group"), 'workbench.action.focusPreviousGroup'); [ focusFirstGroup, focusSecondGroup, focusThirdGroup, __separator__(), nextGroup, previousGroup ].forEach(item => switchGroupMenu.append(item)); const switchGroup = new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miSwitchGroup', comment: ['&& denotes a mnemonic'] }, "Switch &&Group")), submenu: switchGroupMenu, enabled: true }); const gotoFile = this.createMenuItem(nls.localize({ key: 'miGotoFile', comment: ['&& denotes a mnemonic'] }, "Go to &&File..."), 'workbench.action.quickOpen'); const gotoSymbolInFile = this.createMenuItem(nls.localize({ key: 'miGotoSymbolInFile', comment: ['&& denotes a mnemonic'] }, "Go to &&Symbol in File..."), 'workbench.action.gotoSymbol'); const gotoSymbolInWorkspace = this.createMenuItem(nls.localize({ key: 'miGotoSymbolInWorkspace', comment: ['&& denotes a mnemonic'] }, "Go to Symbol in &&Workspace..."), 'workbench.action.showAllSymbols'); const gotoDefinition = this.createMenuItem(nls.localize({ key: 'miGotoDefinition', comment: ['&& denotes a mnemonic'] }, "Go to &&Definition"), 'editor.action.goToDeclaration'); const gotoLine = this.createMenuItem(nls.localize({ key: 'miGotoLine', comment: ['&& denotes a mnemonic'] }, "Go to &&Line..."), 'workbench.action.gotoLine'); [ back, forward, __separator__(), switchEditor, switchGroup, __separator__(), gotoFile, gotoSymbolInFile, gotoSymbolInWorkspace, gotoDefinition, gotoLine ].forEach(item => gotoMenu.append(item)); } private setMacWindowMenu(macWindowMenu: Electron.Menu): void { const minimize = new MenuItem({ label: nls.localize('mMinimize', "Minimize"), role: 'minimize', accelerator: 'Command+M', enabled: this.windowsService.getWindowCount() > 0 }); const close = new MenuItem({ label: nls.localize('mClose', "Close"), role: 'close', accelerator: 'Command+W', enabled: this.windowsService.getWindowCount() > 0 }); const bringAllToFront = new MenuItem({ label: nls.localize('mBringToFront', "Bring All to Front"), role: 'front', enabled: this.windowsService.getWindowCount() > 0 }); [ minimize, close, __separator__(), bringAllToFront ].forEach(item => macWindowMenu.append(item)); } private toggleDevTools(): void { const w = this.windowsService.getFocusedWindow(); if (w && w.win) { w.win.webContents.toggleDevTools(); } } private setHelpMenu(helpMenu: Electron.Menu): void { const toggleDevToolsItem = new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miToggleDevTools', comment: ['&& denotes a mnemonic'] }, "&&Toggle Developer Tools")), accelerator: this.getAccelerator('workbench.action.toggleDevTools'), click: () => this.toggleDevTools(), enabled: (this.windowsService.getWindowCount() > 0) }); const showAccessibilityOptions = new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miAccessibilityOptions', comment: ['&& denotes a mnemonic'] }, "Accessibility &&Options")), accelerator: null, click: () => { this.windowsService.openAccessibilityOptions(); } }); let reportIssuesItem: Electron.MenuItem = null; if (product.reportIssueUrl) { const label = nls.localize({ key: 'miReportIssues', comment: ['&& denotes a mnemonic'] }, "Report &&Issues"); if (this.windowsService.getWindowCount() > 0) { reportIssuesItem = this.createMenuItem(label, 'workbench.action.reportIssues'); } else { reportIssuesItem = new MenuItem({ label: mnemonicLabel(label), click: () => this.openUrl(product.reportIssueUrl, 'openReportIssues') }); } } arrays.coalesce([ product.documentationUrl ? new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miDocumentation', comment: ['&& denotes a mnemonic'] }, "&&Documentation")), click: () => this.openUrl(product.documentationUrl, 'openDocumentationUrl') }) : null, product.releaseNotesUrl ? new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miReleaseNotes', comment: ['&& denotes a mnemonic'] }, "&&Release Notes")), click: () => this.windowsService.sendToFocused('vscode:runAction', 'update.showCurrentReleaseNotes') }) : null, (product.documentationUrl || product.releaseNotesUrl) ? __separator__() : null, product.twitterUrl ? new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miTwitter', comment: ['&& denotes a mnemonic'] }, "&&Join us on Twitter")), click: () => this.openUrl(product.twitterUrl, 'openTwitterUrl') }) : null, product.requestFeatureUrl ? new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miUserVoice', comment: ['&& denotes a mnemonic'] }, "&&Search Feature Requests")), click: () => this.openUrl(product.requestFeatureUrl, 'openUserVoiceUrl') }) : null, reportIssuesItem, (product.twitterUrl || product.requestFeatureUrl || product.reportIssueUrl) ? __separator__() : null, product.licenseUrl ? new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miLicense', comment: ['&& denotes a mnemonic'] }, "&&View License")), click: () => { if (platform.language) { const queryArgChar = product.licenseUrl.indexOf('?') > 0 ? '&' : '?'; this.openUrl(`${product.licenseUrl}${queryArgChar}lang=${platform.language}`, 'openLicenseUrl'); } else { this.openUrl(product.licenseUrl, 'openLicenseUrl'); } } }) : null, product.privacyStatementUrl ? new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miPrivacyStatement', comment: ['&& denotes a mnemonic'] }, "&&Privacy Statement")), click: () => { if (platform.language) { const queryArgChar = product.licenseUrl.indexOf('?') > 0 ? '&' : '?'; this.openUrl(`${product.privacyStatementUrl}${queryArgChar}lang=${platform.language}`, 'openPrivacyStatement'); } else { this.openUrl(product.privacyStatementUrl, 'openPrivacyStatement'); } } }) : null, (product.licenseUrl || product.privacyStatementUrl) ? __separator__() : null, toggleDevToolsItem, platform.isWindows && product.quality !== 'stable' ? showAccessibilityOptions : null ]).forEach(item => helpMenu.append(item)); if (!platform.isMacintosh) { const updateMenuItems = this.getUpdateMenuItems(); if (updateMenuItems.length) { helpMenu.append(__separator__()); updateMenuItems.forEach(i => helpMenu.append(i)); } helpMenu.append(__separator__()); helpMenu.append(new MenuItem({ label: mnemonicLabel(nls.localize({ key: 'miAbout', comment: ['&& denotes a mnemonic'] }, "&&About")), click: () => this.openAboutDialog() })); } } private getUpdateMenuItems(): Electron.MenuItem[] { switch (this.updateService.state) { case UpdateState.Uninitialized: return []; case UpdateState.UpdateDownloaded: const update = this.updateService.availableUpdate; return [new MenuItem({ label: nls.localize('miRestartToUpdate', "Restart To Update..."), click: () => { this.reportMenuActionTelemetry('RestartToUpdate'); update.quitAndUpdate(); } })]; case UpdateState.CheckingForUpdate: return [new MenuItem({ label: nls.localize('miCheckingForUpdates', "Checking For Updates..."), enabled: false })]; case UpdateState.UpdateAvailable: if (platform.isLinux) { const update = this.updateService.availableUpdate; return [new MenuItem({ label: nls.localize('miDownloadUpdate', "Download Available Update"), click: () => { update.quitAndUpdate(); } })]; } const updateAvailableLabel = platform.isWindows ? nls.localize('miDownloadingUpdate', "Downloading Update...") : nls.localize('miInstallingUpdate', "Installing Update..."); return [new MenuItem({ label: updateAvailableLabel, enabled: false })]; default: const result = [new MenuItem({ label: nls.localize('miCheckForUpdates', "Check For Updates..."), click: () => setTimeout(() => { this.reportMenuActionTelemetry('CheckForUpdate'); this.updateService.checkForUpdates(true); }, 0) })]; return result; } } private createMenuItem(label: string, actionId: string, enabled?: boolean, checked?: boolean): Electron.MenuItem; private createMenuItem(label: string, click: () => void, enabled?: boolean, checked?: boolean): Electron.MenuItem; private createMenuItem(arg1: string, arg2: any, arg3?: boolean, arg4?: boolean): Electron.MenuItem { const label = mnemonicLabel(arg1); const click: () => void = (typeof arg2 === 'function') ? arg2 : () => this.windowsService.sendToFocused('vscode:runAction', arg2); const enabled = typeof arg3 === 'boolean' ? arg3 : this.windowsService.getWindowCount() > 0; const checked = typeof arg4 === 'boolean' ? arg4 : false; let actionId: string; if (typeof arg2 === 'string') { actionId = arg2; } const options: Electron.MenuItemOptions = { label, accelerator: this.getAccelerator(actionId), click, enabled }; if (checked) { options['type'] = 'checkbox'; options['checked'] = checked; } return new MenuItem(options); } private createDevToolsAwareMenuItem(label: string, actionId: string, devToolsFocusedFn: (contents: Electron.WebContents) => void): Electron.MenuItem { return new MenuItem({ label: mnemonicLabel(label), accelerator: this.getAccelerator(actionId), enabled: this.windowsService.getWindowCount() > 0, click: () => { const windowInFocus = this.windowsService.getFocusedWindow(); if (!windowInFocus) { return; } if (windowInFocus.win.webContents.isDevToolsFocused()) { devToolsFocusedFn(windowInFocus.win.webContents.devToolsWebContents); } else { this.windowsService.sendToFocused('vscode:runAction', actionId); } } }); } private getAccelerator(actionId: string): string { if (actionId) { const resolvedKeybinding = this.mapResolvedKeybindingToActionId[actionId]; if (resolvedKeybinding) { return resolvedKeybinding; // keybinding is fully resolved } if (!this.keybindingsResolved) { this.actionIdKeybindingRequests.push(actionId); // keybinding needs to be resolved } const lastKnownKeybinding = this.mapLastKnownKeybindingToActionId[actionId]; return lastKnownKeybinding; // return the last known keybining (chance of mismatch is very low unless it changed) } return void (0); } private openAboutDialog(): void { const lastActiveWindow = this.windowsService.getFocusedWindow() || this.windowsService.getLastActiveWindow(); dialog.showMessageBox(lastActiveWindow && lastActiveWindow.win, { title: product.nameLong, type: 'info', message: product.nameLong, detail: nls.localize('aboutDetail', "\nVersion {0}\nCommit {1}\nDate {2}\nShell {3}\nRenderer {4}\nNode {5}", app.getVersion(), product.commit || 'Unknown', product.date || 'Unknown', process.versions['electron'], process.versions['chrome'], process.versions['node'] ), buttons: [nls.localize('okButton', "OK")], noLink: true }, result => null); this.reportMenuActionTelemetry('showAboutDialog'); } private openUrl(url: string, id: string): void { shell.openExternal(url); this.reportMenuActionTelemetry(id); } private reportMenuActionTelemetry(id: string): void { this.windowsService.sendToFocused('vscode:telemetry', { eventName: 'workbenchActionExecuted', data: { id, from: 'menu' } }); } } function __separator__(): Electron.MenuItem { return new MenuItem({ type: 'separator' }); } function mnemonicLabel(label: string): string { if (platform.isMacintosh) { return label.replace(/\(&&\w\)|&&/g, ''); // no mnemonic support on mac } return label.replace(/&&/g, '&'); } function unMnemonicLabel(label: string): string { if (platform.isMacintosh) { return label; // no mnemonic support on mac } return label.replace(/&/g, '&&'); }
src/vs/code/electron-main/menus.ts
1
https://github.com/microsoft/vscode/commit/866dd02825a199f4d6cb275e9090a66ebaece9b2
[ 0.9934797286987305, 0.026045026257634163, 0.0001674384984653443, 0.0001719828142086044, 0.14997029304504395 ]
{ "id": 3, "code_window": [ "\t\trequestFeatureUrl: string\n", "\t};\n", "\tdocumentationUrl: string;\n", "\treleaseNotesUrl: string;\n", "\ttwitterUrl: string;\n", "\trequestFeatureUrl: string;\n", "\treportIssueUrl: string;\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\tkeyboardShortcutsUrlMac: string;\n", "\tkeyboardShortcutsUrlLinux: string;\n", "\tkeyboardShortcutsUrlWin: string;\n", "\tintroductoryVideosUrl: string;\n" ], "file_path": "src/vs/platform/product.ts", "type": "add", "edit_start_line_idx": 41 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "expected.from": "se esperaba 'from'", "expected.in": "Se esperaba 'in'", "expected.through": "se esperaba 'through' o 'to'" }
i18n/esn/src/vs/languages/sass/common/parser/sassErrors.i18n.json
0
https://github.com/microsoft/vscode/commit/866dd02825a199f4d6cb275e9090a66ebaece9b2
[ 0.00017926213331520557, 0.00017742160707712173, 0.00017558109539095312, 0.00017742160707712173, 0.0000018405189621262252 ]
{ "id": 3, "code_window": [ "\t\trequestFeatureUrl: string\n", "\t};\n", "\tdocumentationUrl: string;\n", "\treleaseNotesUrl: string;\n", "\ttwitterUrl: string;\n", "\trequestFeatureUrl: string;\n", "\treportIssueUrl: string;\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\tkeyboardShortcutsUrlMac: string;\n", "\tkeyboardShortcutsUrlLinux: string;\n", "\tkeyboardShortcutsUrlWin: string;\n", "\tintroductoryVideosUrl: string;\n" ], "file_path": "src/vs/platform/product.ts", "type": "add", "edit_start_line_idx": 41 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import 'vs/css!./indentGuides'; import * as editorCommon from 'vs/editor/common/editorCommon'; import { DynamicViewOverlay } from 'vs/editor/browser/view/dynamicViewOverlay'; import { ViewContext } from 'vs/editor/common/view/viewContext'; import { IRenderingContext } from 'vs/editor/common/view/renderingContext'; export class IndentGuidesOverlay extends DynamicViewOverlay { private _context: ViewContext; private _lineHeight: number; private _spaceWidth: number; private _renderResult: string[]; private _enabled: boolean; constructor(context: ViewContext) { super(); this._context = context; this._lineHeight = this._context.configuration.editor.lineHeight; this._spaceWidth = this._context.configuration.editor.fontInfo.spaceWidth; this._enabled = this._context.configuration.editor.viewInfo.renderIndentGuides; this._renderResult = null; this._context.addEventHandler(this); } public dispose(): void { this._context.removeEventHandler(this); this._context = null; this._renderResult = null; } // --- begin event handlers public onModelFlushed(): boolean { return true; } public onModelLinesDeleted(e: editorCommon.IViewLinesDeletedEvent): boolean { return true; } public onModelLineChanged(e: editorCommon.IViewLineChangedEvent): boolean { return true; } public onModelLinesInserted(e: editorCommon.IViewLinesInsertedEvent): boolean { return true; } public onConfigurationChanged(e: editorCommon.IConfigurationChangedEvent): boolean { if (e.lineHeight) { this._lineHeight = this._context.configuration.editor.lineHeight; } if (e.fontInfo) { this._spaceWidth = this._context.configuration.editor.fontInfo.spaceWidth; } if (e.viewInfo.renderIndentGuides) { this._enabled = this._context.configuration.editor.viewInfo.renderIndentGuides; } return true; } public onLayoutChanged(layoutInfo: editorCommon.EditorLayoutInfo): boolean { return true; } public onScrollChanged(e: editorCommon.IScrollEvent): boolean { return e.scrollTopChanged;// || e.scrollWidthChanged; } public onZonesChanged(): boolean { return true; } // --- end event handlers public prepareRender(ctx: IRenderingContext): void { if (!this.shouldRender()) { throw new Error('I did not ask to render!'); } if (!this._enabled) { this._renderResult = null; return; } const visibleStartLineNumber = ctx.visibleRange.startLineNumber; const visibleEndLineNumber = ctx.visibleRange.endLineNumber; const tabSize = this._context.model.getTabSize(); const tabWidth = tabSize * this._spaceWidth; const lineHeight = this._lineHeight; let output: string[] = []; for (let lineNumber = visibleStartLineNumber; lineNumber <= visibleEndLineNumber; lineNumber++) { let lineIndex = lineNumber - visibleStartLineNumber; let indent = this._context.model.getLineIndentGuide(lineNumber); let result = ''; let left = 0; for (let i = 0; i < indent; i++) { result += `<div class="cigr" style="left:${left}px;height:${lineHeight}px;"></div>`; left += tabWidth; } output[lineIndex] = result; } this._renderResult = output; } public render(startLineNumber: number, lineNumber: number): string { if (!this._renderResult) { return ''; } let lineIndex = lineNumber - startLineNumber; if (lineIndex < 0 || lineIndex >= this._renderResult.length) { throw new Error('Unexpected render request'); } return this._renderResult[lineIndex]; } }
src/vs/editor/browser/viewParts/indentGuides/indentGuides.ts
0
https://github.com/microsoft/vscode/commit/866dd02825a199f4d6cb275e9090a66ebaece9b2
[ 0.0001753722899593413, 0.00017110830231104046, 0.00016411658725701272, 0.0001703889574855566, 0.0000030453857107204385 ]
{ "id": 3, "code_window": [ "\t\trequestFeatureUrl: string\n", "\t};\n", "\tdocumentationUrl: string;\n", "\treleaseNotesUrl: string;\n", "\ttwitterUrl: string;\n", "\trequestFeatureUrl: string;\n", "\treportIssueUrl: string;\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\tkeyboardShortcutsUrlMac: string;\n", "\tkeyboardShortcutsUrlLinux: string;\n", "\tkeyboardShortcutsUrlWin: string;\n", "\tintroductoryVideosUrl: string;\n" ], "file_path": "src/vs/platform/product.ts", "type": "add", "edit_start_line_idx": 41 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "invalid.injectTo": "`contributes.{0}.injectTo` 中的值無效。必須是語言範圍名稱的陣列。提供的值: {1}", "invalid.language": "`contributes.{0}.language` 中的不明語言。提供的值: {1}", "invalid.path.0": "`contributes.{0}.path` 中的預期字串。提供的值: {1}", "invalid.path.1": "要包含在擴充功能資料夾 ({2}) 中的預期 `contributes.{0}.path` ({1})。這可能會使擴充功能無法移植。", "invalid.scopeName": "`contributes.{0}.scopeName` 中的預期字串。提供的值: {1}", "vscode.extension.contributes.grammars": "提供 textmate 權杖化工具。", "vscode.extension.contributes.grammars.injectTo": "要插入此文法的語言範圍名稱清單。", "vscode.extension.contributes.grammars.language": "要予以提供此語法的語言識別碼。", "vscode.extension.contributes.grammars.path": "tmLanguage 檔案的路徑。此路徑是擴充功能資料夾的相對路徑,而且一般會以 './syntaxes/' 開頭。", "vscode.extension.contributes.grammars.scopeName": "tmLanguage 檔案所使用的 textmate 範圍名稱。" }
i18n/cht/src/vs/editor/node/textMate/TMSyntax.i18n.json
0
https://github.com/microsoft/vscode/commit/866dd02825a199f4d6cb275e9090a66ebaece9b2
[ 0.00016836145368870348, 0.00016750727081671357, 0.00016665308794472367, 0.00016750727081671357, 8.541828719899058e-7 ]
{ "id": 0, "code_window": [ " let {parentPath} = path;\n", " let grandparentPath = parentPath.parentPath;\n", "\n", " // ex: args[0]\n", " if (\n", " parentPath.isMemberExpression({ computed: true, object: node }) &&\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " // ex: [rest[0]] = [rest[1]]\n", " if (grandparentPath.isLVal()) {\n", " state.deopted = true;\n", " return;\n", " }\n", "\n" ], "file_path": "packages/babel-plugin-transform-es2015-parameters/src/rest.js", "type": "add", "edit_start_line_idx": 62 }
/* eslint indent: 0 */ import template from "babel-template"; import * as t from "babel-types"; let buildRest = template(` for (var LEN = ARGUMENTS.length, ARRAY = Array(ARRAY_LEN), KEY = START; KEY < LEN; KEY++) { ARRAY[ARRAY_KEY] = ARGUMENTS[KEY]; } `); let loadRest = template(` ARGUMENTS.length <= INDEX ? undefined : ARGUMENTS[INDEX] `); let memberExpressionOptimisationVisitor = { Scope(path, state) { // check if this scope has a local binding that will shadow the rest parameter if (!path.scope.bindingIdentifierEquals(state.name, state.outerBinding)) { path.skip(); } }, Flow(path) { // don't touch reference in type annotations path.skip(); }, Function(path, state) { // Detect whether any reference to rest is contained in nested functions to // determine if deopt is necessary. let oldNoOptimise = state.noOptimise; state.noOptimise = true; path.traverse(memberExpressionOptimisationVisitor, state); state.noOptimise = oldNoOptimise; // Skip because optimizing references to rest would refer to the `arguments` // of the nested function. path.skip(); }, ReferencedIdentifier(path, state) { let { node } = path; // we can't guarantee the purity of arguments if (node.name === "arguments") { state.deopted = true; } // is this a referenced identifier and is it referencing the rest parameter? if (node.name !== state.name) return; if (state.noOptimise) { state.deopted = true; } else { let {parentPath} = path; let grandparentPath = parentPath.parentPath; // ex: args[0] if ( parentPath.isMemberExpression({ computed: true, object: node }) && // ex: `args[0] = "whatever"` !( grandparentPath.isAssignmentExpression() && parentPath.node === grandparentPath.node.left ) ) { // if we know that this member expression is referencing a number then // we can safely optimise it let prop = parentPath.get("property"); if (prop.isBaseType("number")) { state.candidates.push({cause: "indexGetter", path}); return; } } // ex: args.length if (parentPath.isMemberExpression({ computed: false, object: node })) { let prop = parentPath.get("property"); if (prop.node.name === "length") { state.candidates.push({cause: "lengthGetter", path}); return; } } // we can only do these optimizations if the rest variable would match // the arguments exactly // optimise single spread args in calls // ex: fn(...args) if (state.offset === 0 && parentPath.isSpreadElement()) { let call = parentPath.parentPath; if (call.isCallExpression() && call.node.arguments.length === 1) { state.candidates.push({cause: "argSpread", path}); return; } } state.references.push(path); } }, /** * Deopt on use of a binding identifier with the same name as our rest param. * * See https://github.com/babel/babel/issues/2091 */ BindingIdentifier({ node }, state) { if (node.name === state.name) { state.deopted = true; } } }; function hasRest(node) { return t.isRestElement(node.params[node.params.length - 1]); } function optimiseIndexGetter(path, argsId, offset) { let index; if (t.isNumericLiteral(path.parent.property)) { index = t.numericLiteral(path.parent.property.value + offset); } else { index = t.binaryExpression("+", path.parent.property, t.numericLiteral(offset)); } path.parentPath.replaceWith(loadRest({ ARGUMENTS: argsId, INDEX: index, })); } function optimiseLengthGetter(path, argsLengthExpression, argsId, offset) { if (offset) { path.parentPath.replaceWith( t.binaryExpression( "-", argsLengthExpression, t.numericLiteral(offset), ) ); } else { path.replaceWith(argsId); } } export let visitor = { Function(path) { let { node, scope } = path; if (!hasRest(node)) return; let rest = node.params.pop().argument; let argsId = t.identifier("arguments"); let argsLengthExpression = t.memberExpression( argsId, t.identifier("length"), ); // otherwise `arguments` will be remapped in arrow functions argsId._shadowedFunctionLiteral = path; // check and optimise for extremely common cases let state = { references: [], offset: node.params.length, argumentsNode: argsId, outerBinding: scope.getBindingIdentifier(rest.name), // candidate member expressions we could optimise if there are no other references candidates: [], // local rest binding name name: rest.name, /* It may be possible to optimize the output code in certain ways, such as not generating code to initialize an array (perhaps substituting direct references to arguments[i] or arguments.length for reads of the corresponding rest parameter property) or positioning the initialization code so that it may not have to execute depending on runtime conditions. This property tracks eligibility for optimization. "deopted" means give up and don't perform optimization. For example, when any of rest's elements / properties is assigned to at the top level, or referenced at all in a nested function. */ deopted: false, }; path.traverse(memberExpressionOptimisationVisitor, state); // There are only "shorthand" references if (!state.deopted && !state.references.length) { for (let {path, cause} of (state.candidates: Array)) { switch (cause) { case "indexGetter": optimiseIndexGetter(path, argsId, state.offset); break; case "lengthGetter": optimiseLengthGetter(path, argsLengthExpression, argsId, state.offset); break; default: path.replaceWith(argsId); } } return; } state.references = state.references.concat( state.candidates.map(({ path }) => path) ); // deopt shadowed functions as transforms like regenerator may try touch the allocation loop state.deopted = state.deopted || !!node.shadow; let start = t.numericLiteral(node.params.length); let key = scope.generateUidIdentifier("key"); let len = scope.generateUidIdentifier("len"); let arrKey = key; let arrLen = len; if (node.params.length) { // this method has additional params, so we need to subtract // the index of the current argument position from the // position in the array that we want to populate arrKey = t.binaryExpression("-", key, start); // we need to work out the size of the array that we're // going to store all the rest parameters // // we need to add a check to avoid constructing the array // with <0 if there are less arguments than params as it'll // cause an error arrLen = t.conditionalExpression( t.binaryExpression(">", len, start), t.binaryExpression("-", len, start), t.numericLiteral(0) ); } let loop = buildRest({ ARGUMENTS: argsId, ARRAY_KEY: arrKey, ARRAY_LEN: arrLen, START: start, ARRAY: rest, KEY: key, LEN: len, }); if (state.deopted) { loop._blockHoist = node.params.length + 1; node.body.body.unshift(loop); } else { // perform allocation at the lowest common ancestor of all references loop._blockHoist = 1; let target = path.getEarliestCommonAncestorFrom(state.references).getStatementParent(); // don't perform the allocation inside a loop target.findParent((path) => { if (path.isLoop()) { target = path; } else { // Stop crawling up if this is a function. return path.isFunction(); } }); target.insertBefore(loop); } } };
packages/babel-plugin-transform-es2015-parameters/src/rest.js
1
https://github.com/babel/babel/commit/183fbab967cce7d6fc7ad61c26673928caef9322
[ 0.9980822801589966, 0.17229261994361877, 0.00016513944137841463, 0.00025223050033673644, 0.3724636435508728 ]
{ "id": 0, "code_window": [ " let {parentPath} = path;\n", " let grandparentPath = parentPath.parentPath;\n", "\n", " // ex: args[0]\n", " if (\n", " parentPath.isMemberExpression({ computed: true, object: node }) &&\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " // ex: [rest[0]] = [rest[1]]\n", " if (grandparentPath.isLVal()) {\n", " state.deopted = true;\n", " return;\n", " }\n", "\n" ], "file_path": "packages/babel-plugin-transform-es2015-parameters/src/rest.js", "type": "add", "edit_start_line_idx": 62 }
{ "throws": "Binding arguments in strict mode (1:41)" }
packages/babylon/test/fixtures/core/uncategorised/483/options.json
0
https://github.com/babel/babel/commit/183fbab967cce7d6fc7ad61c26673928caef9322
[ 0.0001699232670944184, 0.0001699232670944184, 0.0001699232670944184, 0.0001699232670944184, 0 ]
{ "id": 0, "code_window": [ " let {parentPath} = path;\n", " let grandparentPath = parentPath.parentPath;\n", "\n", " // ex: args[0]\n", " if (\n", " parentPath.isMemberExpression({ computed: true, object: node }) &&\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " // ex: [rest[0]] = [rest[1]]\n", " if (grandparentPath.isLVal()) {\n", " state.deopted = true;\n", " return;\n", " }\n", "\n" ], "file_path": "packages/babel-plugin-transform-es2015-parameters/src/rest.js", "type": "add", "edit_start_line_idx": 62 }
var a: ?{numVal: number};
packages/babylon/test/fixtures/flow/type-annotations/35/actual.js
0
https://github.com/babel/babel/commit/183fbab967cce7d6fc7ad61c26673928caef9322
[ 0.0001742287422530353, 0.0001742287422530353, 0.0001742287422530353, 0.0001742287422530353, 0 ]
{ "id": 0, "code_window": [ " let {parentPath} = path;\n", " let grandparentPath = parentPath.parentPath;\n", "\n", " // ex: args[0]\n", " if (\n", " parentPath.isMemberExpression({ computed: true, object: node }) &&\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " // ex: [rest[0]] = [rest[1]]\n", " if (grandparentPath.isLVal()) {\n", " state.deopted = true;\n", " return;\n", " }\n", "\n" ], "file_path": "packages/babel-plugin-transform-es2015-parameters/src/rest.js", "type": "add", "edit_start_line_idx": 62 }
var a: { (): number }; var a: { (): number; }; var a: { (): number; y: string; (x: string): string }; var a: { <T>(x: T): number; }; interface A { (): number; };
packages/babel-generator/test/fixtures/flow/call-properties/actual.js
0
https://github.com/babel/babel/commit/183fbab967cce7d6fc7ad61c26673928caef9322
[ 0.00017623489839024842, 0.00017623489839024842, 0.00017623489839024842, 0.00017623489839024842, 0 ]
{ "id": 1, "code_window": [ " // ex: `args[0] = \"whatever\"`\n", " !(\n", " grandparentPath.isAssignmentExpression() &&\n", " parentPath.node === grandparentPath.node.left\n", " )\n", " ) {\n", " // if we know that this member expression is referencing a number then\n", " // we can safely optimise it\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " ) &&\n", " !grandparentPath.isForInStatement()\n" ], "file_path": "packages/babel-plugin-transform-es2015-parameters/src/rest.js", "type": "replace", "edit_start_line_idx": 70 }
var x = function (foo) { for (var _len = arguments.length, bar = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { bar[_key - 1] = arguments[_key]; } console.log(bar); }; var y = function (foo) { for (var _len2 = arguments.length, bar = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { bar[_key2 - 1] = arguments[_key2]; } var x = function z(bar) { bar[1] = 5; }; }; var b = function (x, y) { for (var _len3 = arguments.length, args = Array(_len3 > 2 ? _len3 - 2 : 0), _key3 = 2; _key3 < _len3; _key3++) { args[_key3 - 2] = arguments[_key3]; } console.log(args[0]); args.pop(); console.log(args[1]); }; var z = function (foo) { for (var _len4 = arguments.length, bar = Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) { bar[_key4 - 1] = arguments[_key4]; } var x = function () { bar[1] = 5; }; }; var a = function (foo) { for (var _len5 = arguments.length, bar = Array(_len5 > 1 ? _len5 - 1 : 0), _key5 = 1; _key5 < _len5; _key5++) { bar[_key5 - 1] = arguments[_key5]; } return bar.join(","); }; var b = function (foo) { var join = "join"; for (var _len6 = arguments.length, bar = Array(_len6 > 1 ? _len6 - 1 : 0), _key6 = 1; _key6 < _len6; _key6++) { bar[_key6 - 1] = arguments[_key6]; } return bar[join]; }; var b = function () { for (var _len7 = arguments.length, bar = Array(_len7), _key7 = 0; _key7 < _len7; _key7++) { bar[_key7] = arguments[_key7]; } return bar.len; }; var b = function (foo) { return (arguments.length - 1) * 2; }; var b = function (foo, baz) { return arguments.length - 2; }; function x() { for (var _len8 = arguments.length, rest = Array(_len8), _key8 = 0; _key8 < _len8; _key8++) { rest[_key8] = arguments[_key8]; } rest[0] = 0; } function swap() { for (var _len9 = arguments.length, rest = Array(_len9), _key9 = 0; _key9 < _len9; _key9++) { rest[_key9] = arguments[_key9]; } [rest[0], rest[1]] = [rest[1], rest[0]]; } function x() { for (var _len10 = arguments.length, rest = Array(_len10), _key10 = 0; _key10 < _len10; _key10++) { rest[_key10] = arguments[_key10]; } for (rest[0] in this) { foo(rest[0]); } } function inc() { for (var _len11 = arguments.length, rest = Array(_len11), _key11 = 0; _key11 < _len11; _key11++) { rest[_key11] = arguments[_key11]; } ++rest[0]; } function dec() { for (var _len12 = arguments.length, rest = Array(_len12), _key12 = 0; _key12 < _len12; _key12++) { rest[_key12] = arguments[_key12]; } --rest[0]; } function del() { for (var _len13 = arguments.length, rest = Array(_len13), _key13 = 0; _key13 < _len13; _key13++) { rest[_key13] = arguments[_key13]; } delete rest[0]; } function method() { for (var _len14 = arguments.length, rest = Array(_len14), _key14 = 0; _key14 < _len14; _key14++) { rest[_key14] = arguments[_key14]; } rest[0](); } function newExp() { for (var _len15 = arguments.length, rest = Array(_len15), _key15 = 0; _key15 < _len15; _key15++) { rest[_key15] = arguments[_key15]; } new rest[0](); } // In addition to swap() above because at some point someone tried checking // grandparent path for isArrayExpression() to deopt. function arrayDestructure() { for (var _len16 = arguments.length, rest = Array(_len16), _key16 = 0; _key16 < _len16; _key16++) { rest[_key16] = arguments[_key16]; } var _x = babelHelpers.slicedToArray(x, 1); rest[0] = _x[0]; }
packages/babel-plugin-transform-es2015-parameters/test/fixtures/parameters/rest-member-expression-deoptimisation/expected.js
1
https://github.com/babel/babel/commit/183fbab967cce7d6fc7ad61c26673928caef9322
[ 0.0015806268202140927, 0.0002842307440005243, 0.00016548259009141475, 0.00017183332238346338, 0.00035364629002287984 ]
{ "id": 1, "code_window": [ " // ex: `args[0] = \"whatever\"`\n", " !(\n", " grandparentPath.isAssignmentExpression() &&\n", " parentPath.node === grandparentPath.node.left\n", " )\n", " ) {\n", " // if we know that this member expression is referencing a number then\n", " // we can safely optimise it\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " ) &&\n", " !grandparentPath.isForInStatement()\n" ], "file_path": "packages/babel-plugin-transform-es2015-parameters/src/rest.js", "type": "replace", "edit_start_line_idx": 70 }
/** * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * https://raw.github.com/facebook/regenerator/master/LICENSE file. An * additional grant of patent rights can be found in the PATENTS file in * the same directory. */ import assert from "assert"; import * as t from "babel-types"; import * as leap from "./leap"; import * as meta from "./meta"; import * as util from "./util"; let hasOwn = Object.prototype.hasOwnProperty; function Emitter(contextId) { assert.ok(this instanceof Emitter); t.assertIdentifier(contextId); // Used to generate unique temporary names. this.nextTempId = 0; // In order to make sure the context object does not collide with // anything in the local scope, we might have to rename it, so we // refer to it symbolically instead of just assuming that it will be // called "context". this.contextId = contextId; // An append-only list of Statements that grows each time this.emit is // called. this.listing = []; // A sparse array whose keys correspond to locations in this.listing // that have been marked as branch/jump targets. this.marked = [true]; // The last location will be marked when this.getDispatchLoop is // called. this.finalLoc = loc(); // A list of all leap.TryEntry statements emitted. this.tryEntries = []; // Each time we evaluate the body of a loop, we tell this.leapManager // to enter a nested loop context that determines the meaning of break // and continue statements therein. this.leapManager = new leap.LeapManager(this); } let Ep = Emitter.prototype; exports.Emitter = Emitter; // Offsets into this.listing that could be used as targets for branches or // jumps are represented as numeric Literal nodes. This representation has // the amazingly convenient benefit of allowing the exact value of the // location to be determined at any time, even after generating code that // refers to the location. function loc() { return t.numericLiteral(-1); } // Sets the exact value of the given location to the offset of the next // Statement emitted. Ep.mark = function(loc) { t.assertLiteral(loc); let index = this.listing.length; if (loc.value === -1) { loc.value = index; } else { // Locations can be marked redundantly, but their values cannot change // once set the first time. assert.strictEqual(loc.value, index); } this.marked[index] = true; return loc; }; Ep.emit = function(node) { if (t.isExpression(node)) { node = t.expressionStatement(node); } t.assertStatement(node); this.listing.push(node); }; // Shorthand for emitting assignment statements. This will come in handy // for assignments to temporary variables. Ep.emitAssign = function(lhs, rhs) { this.emit(this.assign(lhs, rhs)); return lhs; }; // Shorthand for an assignment statement. Ep.assign = function(lhs, rhs) { return t.expressionStatement( t.assignmentExpression("=", lhs, rhs)); }; // Convenience function for generating expressions like context.next, // context.sent, and context.rval. Ep.contextProperty = function(name, computed) { return t.memberExpression( this.contextId, computed ? t.stringLiteral(name) : t.identifier(name), !!computed ); }; // Shorthand for setting context.rval and jumping to `context.stop()`. Ep.stop = function(rval) { if (rval) { this.setReturnValue(rval); } this.jump(this.finalLoc); }; Ep.setReturnValue = function(valuePath) { t.assertExpression(valuePath.value); this.emitAssign( this.contextProperty("rval"), this.explodeExpression(valuePath) ); }; Ep.clearPendingException = function(tryLoc, assignee) { t.assertLiteral(tryLoc); let catchCall = t.callExpression( this.contextProperty("catch", true), [tryLoc] ); if (assignee) { this.emitAssign(assignee, catchCall); } else { this.emit(catchCall); } }; // Emits code for an unconditional jump to the given location, even if the // exact value of the location is not yet known. Ep.jump = function(toLoc) { this.emitAssign(this.contextProperty("next"), toLoc); this.emit(t.breakStatement()); }; // Conditional jump. Ep.jumpIf = function(test, toLoc) { t.assertExpression(test); t.assertLiteral(toLoc); this.emit(t.ifStatement( test, t.blockStatement([ this.assign(this.contextProperty("next"), toLoc), t.breakStatement() ]) )); }; // Conditional jump, with the condition negated. Ep.jumpIfNot = function(test, toLoc) { t.assertExpression(test); t.assertLiteral(toLoc); let negatedTest; if (t.isUnaryExpression(test) && test.operator === "!") { // Avoid double negation. negatedTest = test.argument; } else { negatedTest = t.unaryExpression("!", test); } this.emit(t.ifStatement( negatedTest, t.blockStatement([ this.assign(this.contextProperty("next"), toLoc), t.breakStatement() ]) )); }; // Returns a unique MemberExpression that can be used to store and // retrieve temporary values. Since the object of the member expression is // the context object, which is presumed to coexist peacefully with all // other local variables, and since we just increment `nextTempId` // monotonically, uniqueness is assured. Ep.makeTempVar = function() { return this.contextProperty("t" + this.nextTempId++); }; Ep.getContextFunction = function(id) { return t.functionExpression( id || null/*Anonymous*/, [this.contextId], t.blockStatement([this.getDispatchLoop()]), false, // Not a generator anymore! false // Nor an expression. ); }; // Turns this.listing into a loop of the form // // while (1) switch (context.next) { // case 0: // ... // case n: // return context.stop(); // } // // Each marked location in this.listing will correspond to one generated // case statement. Ep.getDispatchLoop = function() { let self = this; let cases = []; let current; // If we encounter a break, continue, or return statement in a switch // case, we can skip the rest of the statements until the next case. let alreadyEnded = false; self.listing.forEach(function(stmt, i) { if (self.marked.hasOwnProperty(i)) { cases.push(t.switchCase( t.numericLiteral(i), current = [])); alreadyEnded = false; } if (!alreadyEnded) { current.push(stmt); if (t.isCompletionStatement(stmt)) alreadyEnded = true; } }); // Now that we know how many statements there will be in this.listing, // we can finally resolve this.finalLoc.value. this.finalLoc.value = this.listing.length; cases.push( t.switchCase(this.finalLoc, [ // Intentionally fall through to the "end" case... ]), // So that the runtime can jump to the final location without having // to know its offset, we provide the "end" case as a synonym. t.switchCase(t.stringLiteral("end"), [ // This will check/clear both context.thrown and context.rval. t.returnStatement( t.callExpression(this.contextProperty("stop"), []) ) ]) ); return t.whileStatement( t.numericLiteral(1), t.switchStatement( t.assignmentExpression( "=", this.contextProperty("prev"), this.contextProperty("next") ), cases ) ); }; Ep.getTryLocsList = function() { if (this.tryEntries.length === 0) { // To avoid adding a needless [] to the majority of runtime.wrap // argument lists, force the caller to handle this case specially. return null; } let lastLocValue = 0; return t.arrayExpression( this.tryEntries.map(function(tryEntry) { let thisLocValue = tryEntry.firstLoc.value; assert.ok(thisLocValue >= lastLocValue, "try entries out of order"); lastLocValue = thisLocValue; let ce = tryEntry.catchEntry; let fe = tryEntry.finallyEntry; let locs = [ tryEntry.firstLoc, // The null here makes a hole in the array. ce ? ce.firstLoc : null ]; if (fe) { locs[2] = fe.firstLoc; locs[3] = fe.afterLoc; } return t.arrayExpression(locs); }) ); }; // All side effects must be realized in order. // If any subexpression harbors a leap, all subexpressions must be // neutered of side effects. // No destructive modification of AST nodes. Ep.explode = function(path, ignoreResult) { let node = path.node; let self = this; t.assertNode(node); if (t.isDeclaration(node)) throw getDeclError(node); if (t.isStatement(node)) return self.explodeStatement(path); if (t.isExpression(node)) return self.explodeExpression(path, ignoreResult); switch (node.type) { case "Program": return path.get("body").map( self.explodeStatement, self ); case "VariableDeclarator": throw getDeclError(node); // These node types should be handled by their parent nodes // (ObjectExpression, SwitchStatement, and TryStatement, respectively). case "Property": case "SwitchCase": case "CatchClause": throw new Error( node.type + " nodes should be handled by their parents"); default: throw new Error( "unknown Node of type " + JSON.stringify(node.type)); } }; function getDeclError(node) { return new Error( "all declarations should have been transformed into " + "assignments before the Exploder began its work: " + JSON.stringify(node)); } Ep.explodeStatement = function(path, labelId) { let stmt = path.node; let self = this; let before, after, head; t.assertStatement(stmt); if (labelId) { t.assertIdentifier(labelId); } else { labelId = null; } // Explode BlockStatement nodes even if they do not contain a yield, // because we don't want or need the curly braces. if (t.isBlockStatement(stmt)) { path.get("body").forEach(function (path) { self.explodeStatement(path); }); return; } if (!meta.containsLeap(stmt)) { // Technically we should be able to avoid emitting the statement // altogether if !meta.hasSideEffects(stmt), but that leads to // confusing generated code (for instance, `while (true) {}` just // disappears) and is probably a more appropriate job for a dedicated // dead code elimination pass. self.emit(stmt); return; } switch (stmt.type) { case "ExpressionStatement": self.explodeExpression(path.get("expression"), true); break; case "LabeledStatement": after = loc(); // Did you know you can break from any labeled block statement or // control structure? Well, you can! Note: when a labeled loop is // encountered, the leap.LabeledEntry created here will immediately // enclose a leap.LoopEntry on the leap manager's stack, and both // entries will have the same label. Though this works just fine, it // may seem a bit redundant. In theory, we could check here to // determine if stmt knows how to handle its own label; for example, // stmt happens to be a WhileStatement and so we know it's going to // establish its own LoopEntry when we explode it (below). Then this // LabeledEntry would be unnecessary. Alternatively, we might be // tempted not to pass stmt.label down into self.explodeStatement, // because we've handled the label here, but that's a mistake because // labeled loops may contain labeled continue statements, which is not // something we can handle in this generic case. All in all, I think a // little redundancy greatly simplifies the logic of this case, since // it's clear that we handle all possible LabeledStatements correctly // here, regardless of whether they interact with the leap manager // themselves. Also remember that labels and break/continue-to-label // statements are rare, and all of this logic happens at transform // time, so it has no additional runtime cost. self.leapManager.withEntry( new leap.LabeledEntry(after, stmt.label), function() { self.explodeStatement(path.get("body"), stmt.label); } ); self.mark(after); break; case "WhileStatement": before = loc(); after = loc(); self.mark(before); self.jumpIfNot(self.explodeExpression(path.get("test")), after); self.leapManager.withEntry( new leap.LoopEntry(after, before, labelId), function() { self.explodeStatement(path.get("body")); } ); self.jump(before); self.mark(after); break; case "DoWhileStatement": let first = loc(); let test = loc(); after = loc(); self.mark(first); self.leapManager.withEntry( new leap.LoopEntry(after, test, labelId), function() { self.explode(path.get("body")); } ); self.mark(test); self.jumpIf(self.explodeExpression(path.get("test")), first); self.mark(after); break; case "ForStatement": head = loc(); let update = loc(); after = loc(); if (stmt.init) { // We pass true here to indicate that if stmt.init is an expression // then we do not care about its result. self.explode(path.get("init"), true); } self.mark(head); if (stmt.test) { self.jumpIfNot(self.explodeExpression(path.get("test")), after); } else { // No test means continue unconditionally. } self.leapManager.withEntry( new leap.LoopEntry(after, update, labelId), function() { self.explodeStatement(path.get("body")); } ); self.mark(update); if (stmt.update) { // We pass true here to indicate that if stmt.update is an // expression then we do not care about its result. self.explode(path.get("update"), true); } self.jump(head); self.mark(after); break; case "TypeCastExpression": return self.explodeExpression(path.get("expression")); case "ForInStatement": head = loc(); after = loc(); let keyIterNextFn = self.makeTempVar(); self.emitAssign( keyIterNextFn, t.callExpression( util.runtimeProperty("keys"), [self.explodeExpression(path.get("right"))] ) ); self.mark(head); let keyInfoTmpVar = self.makeTempVar(); self.jumpIf( t.memberExpression( t.assignmentExpression( "=", keyInfoTmpVar, t.callExpression(keyIterNextFn, []) ), t.identifier("done"), false ), after ); self.emitAssign( stmt.left, t.memberExpression( keyInfoTmpVar, t.identifier("value"), false ) ); self.leapManager.withEntry( new leap.LoopEntry(after, head, labelId), function() { self.explodeStatement(path.get("body")); } ); self.jump(head); self.mark(after); break; case "BreakStatement": self.emitAbruptCompletion({ type: "break", target: self.leapManager.getBreakLoc(stmt.label) }); break; case "ContinueStatement": self.emitAbruptCompletion({ type: "continue", target: self.leapManager.getContinueLoc(stmt.label) }); break; case "SwitchStatement": // Always save the discriminant into a temporary variable in case the // test expressions overwrite values like context.sent. let disc = self.emitAssign( self.makeTempVar(), self.explodeExpression(path.get("discriminant")) ); after = loc(); let defaultLoc = loc(); let condition = defaultLoc; let caseLocs = []; // If there are no cases, .cases might be undefined. let cases = stmt.cases || []; for (let i = cases.length - 1; i >= 0; --i) { let c = cases[i]; t.assertSwitchCase(c); if (c.test) { condition = t.conditionalExpression( t.binaryExpression("===", disc, c.test), caseLocs[i] = loc(), condition ); } else { caseLocs[i] = defaultLoc; } } let discriminant = path.get("discriminant"); discriminant.replaceWith(condition); self.jump(self.explodeExpression(discriminant)); self.leapManager.withEntry( new leap.SwitchEntry(after), function() { path.get("cases").forEach(function(casePath) { let i = casePath.key; self.mark(caseLocs[i]); casePath.get("consequent").forEach(function (path) { self.explodeStatement(path); }); }); } ); self.mark(after); if (defaultLoc.value === -1) { self.mark(defaultLoc); assert.strictEqual(after.value, defaultLoc.value); } break; case "IfStatement": let elseLoc = stmt.alternate && loc(); after = loc(); self.jumpIfNot( self.explodeExpression(path.get("test")), elseLoc || after ); self.explodeStatement(path.get("consequent")); if (elseLoc) { self.jump(after); self.mark(elseLoc); self.explodeStatement(path.get("alternate")); } self.mark(after); break; case "ReturnStatement": self.emitAbruptCompletion({ type: "return", value: self.explodeExpression(path.get("argument")) }); break; case "WithStatement": throw new Error("WithStatement not supported in generator functions."); case "TryStatement": after = loc(); let handler = stmt.handler; let catchLoc = handler && loc(); let catchEntry = catchLoc && new leap.CatchEntry( catchLoc, handler.param ); let finallyLoc = stmt.finalizer && loc(); let finallyEntry = finallyLoc && new leap.FinallyEntry(finallyLoc, after); let tryEntry = new leap.TryEntry( self.getUnmarkedCurrentLoc(), catchEntry, finallyEntry ); self.tryEntries.push(tryEntry); self.updateContextPrevLoc(tryEntry.firstLoc); self.leapManager.withEntry(tryEntry, function() { self.explodeStatement(path.get("block")); if (catchLoc) { if (finallyLoc) { // If we have both a catch block and a finally block, then // because we emit the catch block first, we need to jump over // it to the finally block. self.jump(finallyLoc); } else { // If there is no finally block, then we need to jump over the // catch block to the fall-through location. self.jump(after); } self.updateContextPrevLoc(self.mark(catchLoc)); let bodyPath = path.get("handler.body"); let safeParam = self.makeTempVar(); self.clearPendingException(tryEntry.firstLoc, safeParam); bodyPath.traverse(catchParamVisitor, { safeParam: safeParam, catchParamName: handler.param.name }); self.leapManager.withEntry(catchEntry, function() { self.explodeStatement(bodyPath); }); } if (finallyLoc) { self.updateContextPrevLoc(self.mark(finallyLoc)); self.leapManager.withEntry(finallyEntry, function() { self.explodeStatement(path.get("finalizer")); }); self.emit(t.returnStatement(t.callExpression( self.contextProperty("finish"), [finallyEntry.firstLoc] ))); } }); self.mark(after); break; case "ThrowStatement": self.emit(t.throwStatement( self.explodeExpression(path.get("argument")) )); break; default: throw new Error( "unknown Statement of type " + JSON.stringify(stmt.type)); } }; let catchParamVisitor = { Identifier: function(path, state) { if (path.node.name === state.catchParamName && util.isReference(path)) { path.replaceWith(state.safeParam); } }, Scope: function(path, state) { if (path.scope.hasOwnBinding(state.catchParamName)) { // Don't descend into nested scopes that shadow the catch // parameter with their own declarations. path.skip(); } } }; Ep.emitAbruptCompletion = function(record) { if (!isValidCompletion(record)) { assert.ok( false, "invalid completion record: " + JSON.stringify(record) ); } assert.notStrictEqual( record.type, "normal", "normal completions are not abrupt" ); let abruptArgs = [t.stringLiteral(record.type)]; if (record.type === "break" || record.type === "continue") { t.assertLiteral(record.target); abruptArgs[1] = record.target; } else if (record.type === "return" || record.type === "throw") { if (record.value) { t.assertExpression(record.value); abruptArgs[1] = record.value; } } this.emit( t.returnStatement( t.callExpression( this.contextProperty("abrupt"), abruptArgs ) ) ); }; function isValidCompletion(record) { let type = record.type; if (type === "normal") { return !hasOwn.call(record, "target"); } if (type === "break" || type === "continue") { return !hasOwn.call(record, "value") && t.isLiteral(record.target); } if (type === "return" || type === "throw") { return hasOwn.call(record, "value") && !hasOwn.call(record, "target"); } return false; } // Not all offsets into emitter.listing are potential jump targets. For // example, execution typically falls into the beginning of a try block // without jumping directly there. This method returns the current offset // without marking it, so that a switch case will not necessarily be // generated for this offset (I say "not necessarily" because the same // location might end up being marked in the process of emitting other // statements). There's no logical harm in marking such locations as jump // targets, but minimizing the number of switch cases keeps the generated // code shorter. Ep.getUnmarkedCurrentLoc = function() { return t.numericLiteral(this.listing.length); }; // The context.prev property takes the value of context.next whenever we // evaluate the switch statement discriminant, which is generally good // enough for tracking the last location we jumped to, but sometimes // context.prev needs to be more precise, such as when we fall // successfully out of a try block and into a finally block without // jumping. This method exists to update context.prev to the freshest // available location. If we were implementing a full interpreter, we // would know the location of the current instruction with complete // precision at all times, but we don't have that luxury here, as it would // be costly and verbose to set context.prev before every statement. Ep.updateContextPrevLoc = function(loc) { if (loc) { t.assertLiteral(loc); if (loc.value === -1) { // If an uninitialized location literal was passed in, set its value // to the current this.listing.length. loc.value = this.listing.length; } else { // Otherwise assert that the location matches the current offset. assert.strictEqual(loc.value, this.listing.length); } } else { loc = this.getUnmarkedCurrentLoc(); } // Make sure context.prev is up to date in case we fell into this try // statement without jumping to it. TODO Consider avoiding this // assignment when we know control must have jumped here. this.emitAssign(this.contextProperty("prev"), loc); }; Ep.explodeExpression = function(path, ignoreResult) { let expr = path.node; if (expr) { t.assertExpression(expr); } else { return expr; } let self = this; let result; // Used optionally by several cases below. let after; function finish(expr) { t.assertExpression(expr); if (ignoreResult) { self.emit(expr); } else { return expr; } } // If the expression does not contain a leap, then we either emit the // expression as a standalone statement or return it whole. if (!meta.containsLeap(expr)) { return finish(expr); } // If any child contains a leap (such as a yield or labeled continue or // break statement), then any sibling subexpressions will almost // certainly have to be exploded in order to maintain the order of their // side effects relative to the leaping child(ren). let hasLeapingChildren = meta.containsLeap.onlyChildren(expr); // In order to save the rest of explodeExpression from a combinatorial // trainwreck of special cases, explodeViaTempVar is responsible for // deciding when a subexpression needs to be "exploded," which is my // very technical term for emitting the subexpression as an assignment // to a temporary variable and the substituting the temporary variable // for the original subexpression. Think of exploded view diagrams, not // Michael Bay movies. The point of exploding subexpressions is to // control the precise order in which the generated code realizes the // side effects of those subexpressions. function explodeViaTempVar(tempVar, childPath, ignoreChildResult) { assert.ok( !ignoreChildResult || !tempVar, "Ignoring the result of a child expression but forcing it to " + "be assigned to a temporary variable?" ); let result = self.explodeExpression(childPath, ignoreChildResult); if (ignoreChildResult) { // Side effects already emitted above. } else if (tempVar || (hasLeapingChildren && !t.isLiteral(result))) { // If tempVar was provided, then the result will always be assigned // to it, even if the result does not otherwise need to be assigned // to a temporary variable. When no tempVar is provided, we have // the flexibility to decide whether a temporary variable is really // necessary. Unfortunately, in general, a temporary variable is // required whenever any child contains a yield expression, since it // is difficult to prove (at all, let alone efficiently) whether // this result would evaluate to the same value before and after the // yield (see #206). One narrow case where we can prove it doesn't // matter (and thus we do not need a temporary variable) is when the // result in question is a Literal value. result = self.emitAssign( tempVar || self.makeTempVar(), result ); } return result; } // If ignoreResult is true, then we must take full responsibility for // emitting the expression with all its side effects, and we should not // return a result. switch (expr.type) { case "MemberExpression": return finish(t.memberExpression( self.explodeExpression(path.get("object")), expr.computed ? explodeViaTempVar(null, path.get("property")) : expr.property, expr.computed )); case "CallExpression": let calleePath = path.get("callee"); let argsPath = path.get("arguments"); let newCallee; let newArgs = []; let hasLeapingArgs = false; argsPath.forEach(function(argPath) { hasLeapingArgs = hasLeapingArgs || meta.containsLeap(argPath.node); }); if (t.isMemberExpression(calleePath.node)) { if (hasLeapingArgs) { // If the arguments of the CallExpression contained any yield // expressions, then we need to be sure to evaluate the callee // before evaluating the arguments, but if the callee was a member // expression, then we must be careful that the object of the // member expression still gets bound to `this` for the call. let newObject = explodeViaTempVar( // Assign the exploded callee.object expression to a temporary // variable so that we can use it twice without reevaluating it. self.makeTempVar(), calleePath.get("object") ); let newProperty = calleePath.node.computed ? explodeViaTempVar(null, calleePath.get("property")) : calleePath.node.property; newArgs.unshift(newObject); newCallee = t.memberExpression( t.memberExpression( newObject, newProperty, calleePath.node.computed ), t.identifier("call"), false ); } else { newCallee = self.explodeExpression(calleePath); } } else { newCallee = self.explodeExpression(calleePath); if (t.isMemberExpression(newCallee)) { // If the callee was not previously a MemberExpression, then the // CallExpression was "unqualified," meaning its `this` object // should be the global object. If the exploded expression has // become a MemberExpression (e.g. a context property, probably a // temporary variable), then we need to force it to be unqualified // by using the (0, object.property)(...) trick; otherwise, it // will receive the object of the MemberExpression as its `this` // object. newCallee = t.sequenceExpression([ t.numericLiteral(0), newCallee ]); } } argsPath.forEach(function(argPath) { newArgs.push(explodeViaTempVar(null, argPath)); }); return finish(t.callExpression( newCallee, newArgs )); case "NewExpression": return finish(t.newExpression( explodeViaTempVar(null, path.get("callee")), path.get("arguments").map(function(argPath) { return explodeViaTempVar(null, argPath); }) )); case "ObjectExpression": return finish(t.objectExpression( path.get("properties").map(function(propPath) { if (propPath.isObjectProperty()) { return t.objectProperty( propPath.node.key, explodeViaTempVar(null, propPath.get("value")), propPath.node.computed ); } else { return propPath.node; } }) )); case "ArrayExpression": return finish(t.arrayExpression( path.get("elements").map(function(elemPath) { return explodeViaTempVar(null, elemPath); }) )); case "SequenceExpression": let lastIndex = expr.expressions.length - 1; path.get("expressions").forEach(function(exprPath) { if (exprPath.key === lastIndex) { result = self.explodeExpression(exprPath, ignoreResult); } else { self.explodeExpression(exprPath, true); } }); return result; case "LogicalExpression": after = loc(); if (!ignoreResult) { result = self.makeTempVar(); } let left = explodeViaTempVar(result, path.get("left")); if (expr.operator === "&&") { self.jumpIfNot(left, after); } else { assert.strictEqual(expr.operator, "||"); self.jumpIf(left, after); } explodeViaTempVar(result, path.get("right"), ignoreResult); self.mark(after); return result; case "ConditionalExpression": let elseLoc = loc(); after = loc(); let test = self.explodeExpression(path.get("test")); self.jumpIfNot(test, elseLoc); if (!ignoreResult) { result = self.makeTempVar(); } explodeViaTempVar(result, path.get("consequent"), ignoreResult); self.jump(after); self.mark(elseLoc); explodeViaTempVar(result, path.get("alternate"), ignoreResult); self.mark(after); return result; case "UnaryExpression": return finish(t.unaryExpression( expr.operator, // Can't (and don't need to) break up the syntax of the argument. // Think about delete a[b]. self.explodeExpression(path.get("argument")), !!expr.prefix )); case "BinaryExpression": return finish(t.binaryExpression( expr.operator, explodeViaTempVar(null, path.get("left")), explodeViaTempVar(null, path.get("right")) )); case "AssignmentExpression": return finish(t.assignmentExpression( expr.operator, self.explodeExpression(path.get("left")), self.explodeExpression(path.get("right")) )); case "UpdateExpression": return finish(t.updateExpression( expr.operator, self.explodeExpression(path.get("argument")), expr.prefix )); case "YieldExpression": after = loc(); let arg = expr.argument && self.explodeExpression(path.get("argument")); if (arg && expr.delegate) { let result = self.makeTempVar(); self.emit(t.returnStatement(t.callExpression( self.contextProperty("delegateYield"), [ arg, t.stringLiteral(result.property.name), after ] ))); self.mark(after); return result; } self.emitAssign(self.contextProperty("next"), after); self.emit(t.returnStatement(arg || null)); self.mark(after); return self.contextProperty("sent"); default: throw new Error( "unknown Expression of type " + JSON.stringify(expr.type)); } };
packages/babel-plugin-transform-regenerator/src/emit.js
0
https://github.com/babel/babel/commit/183fbab967cce7d6fc7ad61c26673928caef9322
[ 0.0022847598884254694, 0.00019484173390083015, 0.00016204288112930954, 0.0001714024692773819, 0.00019468448590487242 ]
{ "id": 1, "code_window": [ " // ex: `args[0] = \"whatever\"`\n", " !(\n", " grandparentPath.isAssignmentExpression() &&\n", " parentPath.node === grandparentPath.node.left\n", " )\n", " ) {\n", " // if we know that this member expression is referencing a number then\n", " // we can safely optimise it\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " ) &&\n", " !grandparentPath.isForInStatement()\n" ], "file_path": "packages/babel-plugin-transform-es2015-parameters/src/rest.js", "type": "replace", "edit_start_line_idx": 70 }
var a: typeof A[]
packages/babylon/test/fixtures/flow/array-types/6/actual.js
0
https://github.com/babel/babel/commit/183fbab967cce7d6fc7ad61c26673928caef9322
[ 0.00016661464178469032, 0.00016661464178469032, 0.00016661464178469032, 0.00016661464178469032, 0 ]
{ "id": 1, "code_window": [ " // ex: `args[0] = \"whatever\"`\n", " !(\n", " grandparentPath.isAssignmentExpression() &&\n", " parentPath.node === grandparentPath.node.left\n", " )\n", " ) {\n", " // if we know that this member expression is referencing a number then\n", " // we can safely optimise it\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " ) &&\n", " !grandparentPath.isForInStatement()\n" ], "file_path": "packages/babel-plugin-transform-es2015-parameters/src/rest.js", "type": "replace", "edit_start_line_idx": 70 }
node_modules *.log src test
packages/babel-plugin-transform-es5-property-mutators/.npmignore
0
https://github.com/babel/babel/commit/183fbab967cce7d6fc7ad61c26673928caef9322
[ 0.00016773267998360097, 0.00016773267998360097, 0.00016773267998360097, 0.00016773267998360097, 0 ]
{ "id": 2, "code_window": [ " for (var _len9 = arguments.length, rest = Array(_len9), _key9 = 0; _key9 < _len9; _key9++) {\n", " rest[_key9] = arguments[_key9];\n", " }\n", "\n", " [rest[0], rest[1]] = [rest[1], rest[0]];\n", "}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ " var _ref = [rest[1], rest[0]];\n", " rest[0] = _ref[0];\n", " rest[1] = _ref[1];\n" ], "file_path": "packages/babel-plugin-transform-es2015-parameters/test/fixtures/parameters/rest-member-expression-deoptimisation/expected.js", "type": "replace", "edit_start_line_idx": 85 }
/* eslint indent: 0 */ import template from "babel-template"; import * as t from "babel-types"; let buildRest = template(` for (var LEN = ARGUMENTS.length, ARRAY = Array(ARRAY_LEN), KEY = START; KEY < LEN; KEY++) { ARRAY[ARRAY_KEY] = ARGUMENTS[KEY]; } `); let loadRest = template(` ARGUMENTS.length <= INDEX ? undefined : ARGUMENTS[INDEX] `); let memberExpressionOptimisationVisitor = { Scope(path, state) { // check if this scope has a local binding that will shadow the rest parameter if (!path.scope.bindingIdentifierEquals(state.name, state.outerBinding)) { path.skip(); } }, Flow(path) { // don't touch reference in type annotations path.skip(); }, Function(path, state) { // Detect whether any reference to rest is contained in nested functions to // determine if deopt is necessary. let oldNoOptimise = state.noOptimise; state.noOptimise = true; path.traverse(memberExpressionOptimisationVisitor, state); state.noOptimise = oldNoOptimise; // Skip because optimizing references to rest would refer to the `arguments` // of the nested function. path.skip(); }, ReferencedIdentifier(path, state) { let { node } = path; // we can't guarantee the purity of arguments if (node.name === "arguments") { state.deopted = true; } // is this a referenced identifier and is it referencing the rest parameter? if (node.name !== state.name) return; if (state.noOptimise) { state.deopted = true; } else { let {parentPath} = path; let grandparentPath = parentPath.parentPath; // ex: args[0] if ( parentPath.isMemberExpression({ computed: true, object: node }) && // ex: `args[0] = "whatever"` !( grandparentPath.isAssignmentExpression() && parentPath.node === grandparentPath.node.left ) ) { // if we know that this member expression is referencing a number then // we can safely optimise it let prop = parentPath.get("property"); if (prop.isBaseType("number")) { state.candidates.push({cause: "indexGetter", path}); return; } } // ex: args.length if (parentPath.isMemberExpression({ computed: false, object: node })) { let prop = parentPath.get("property"); if (prop.node.name === "length") { state.candidates.push({cause: "lengthGetter", path}); return; } } // we can only do these optimizations if the rest variable would match // the arguments exactly // optimise single spread args in calls // ex: fn(...args) if (state.offset === 0 && parentPath.isSpreadElement()) { let call = parentPath.parentPath; if (call.isCallExpression() && call.node.arguments.length === 1) { state.candidates.push({cause: "argSpread", path}); return; } } state.references.push(path); } }, /** * Deopt on use of a binding identifier with the same name as our rest param. * * See https://github.com/babel/babel/issues/2091 */ BindingIdentifier({ node }, state) { if (node.name === state.name) { state.deopted = true; } } }; function hasRest(node) { return t.isRestElement(node.params[node.params.length - 1]); } function optimiseIndexGetter(path, argsId, offset) { let index; if (t.isNumericLiteral(path.parent.property)) { index = t.numericLiteral(path.parent.property.value + offset); } else { index = t.binaryExpression("+", path.parent.property, t.numericLiteral(offset)); } path.parentPath.replaceWith(loadRest({ ARGUMENTS: argsId, INDEX: index, })); } function optimiseLengthGetter(path, argsLengthExpression, argsId, offset) { if (offset) { path.parentPath.replaceWith( t.binaryExpression( "-", argsLengthExpression, t.numericLiteral(offset), ) ); } else { path.replaceWith(argsId); } } export let visitor = { Function(path) { let { node, scope } = path; if (!hasRest(node)) return; let rest = node.params.pop().argument; let argsId = t.identifier("arguments"); let argsLengthExpression = t.memberExpression( argsId, t.identifier("length"), ); // otherwise `arguments` will be remapped in arrow functions argsId._shadowedFunctionLiteral = path; // check and optimise for extremely common cases let state = { references: [], offset: node.params.length, argumentsNode: argsId, outerBinding: scope.getBindingIdentifier(rest.name), // candidate member expressions we could optimise if there are no other references candidates: [], // local rest binding name name: rest.name, /* It may be possible to optimize the output code in certain ways, such as not generating code to initialize an array (perhaps substituting direct references to arguments[i] or arguments.length for reads of the corresponding rest parameter property) or positioning the initialization code so that it may not have to execute depending on runtime conditions. This property tracks eligibility for optimization. "deopted" means give up and don't perform optimization. For example, when any of rest's elements / properties is assigned to at the top level, or referenced at all in a nested function. */ deopted: false, }; path.traverse(memberExpressionOptimisationVisitor, state); // There are only "shorthand" references if (!state.deopted && !state.references.length) { for (let {path, cause} of (state.candidates: Array)) { switch (cause) { case "indexGetter": optimiseIndexGetter(path, argsId, state.offset); break; case "lengthGetter": optimiseLengthGetter(path, argsLengthExpression, argsId, state.offset); break; default: path.replaceWith(argsId); } } return; } state.references = state.references.concat( state.candidates.map(({ path }) => path) ); // deopt shadowed functions as transforms like regenerator may try touch the allocation loop state.deopted = state.deopted || !!node.shadow; let start = t.numericLiteral(node.params.length); let key = scope.generateUidIdentifier("key"); let len = scope.generateUidIdentifier("len"); let arrKey = key; let arrLen = len; if (node.params.length) { // this method has additional params, so we need to subtract // the index of the current argument position from the // position in the array that we want to populate arrKey = t.binaryExpression("-", key, start); // we need to work out the size of the array that we're // going to store all the rest parameters // // we need to add a check to avoid constructing the array // with <0 if there are less arguments than params as it'll // cause an error arrLen = t.conditionalExpression( t.binaryExpression(">", len, start), t.binaryExpression("-", len, start), t.numericLiteral(0) ); } let loop = buildRest({ ARGUMENTS: argsId, ARRAY_KEY: arrKey, ARRAY_LEN: arrLen, START: start, ARRAY: rest, KEY: key, LEN: len, }); if (state.deopted) { loop._blockHoist = node.params.length + 1; node.body.body.unshift(loop); } else { // perform allocation at the lowest common ancestor of all references loop._blockHoist = 1; let target = path.getEarliestCommonAncestorFrom(state.references).getStatementParent(); // don't perform the allocation inside a loop target.findParent((path) => { if (path.isLoop()) { target = path; } else { // Stop crawling up if this is a function. return path.isFunction(); } }); target.insertBefore(loop); } } };
packages/babel-plugin-transform-es2015-parameters/src/rest.js
1
https://github.com/babel/babel/commit/183fbab967cce7d6fc7ad61c26673928caef9322
[ 0.9808185696601868, 0.06319043040275574, 0.00015912250091787428, 0.00017267887596972287, 0.23127295076847076 ]
{ "id": 2, "code_window": [ " for (var _len9 = arguments.length, rest = Array(_len9), _key9 = 0; _key9 < _len9; _key9++) {\n", " rest[_key9] = arguments[_key9];\n", " }\n", "\n", " [rest[0], rest[1]] = [rest[1], rest[0]];\n", "}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ " var _ref = [rest[1], rest[0]];\n", " rest[0] = _ref[0];\n", " rest[1] = _ref[1];\n" ], "file_path": "packages/babel-plugin-transform-es2015-parameters/test/fixtures/parameters/rest-member-expression-deoptimisation/expected.js", "type": "replace", "edit_start_line_idx": 85 }
{ "type": "File", "start": 0, "end": 17, "loc": { "start": { "line": 1, "column": 0 }, "end": { "line": 1, "column": 17 } }, "program": { "type": "Program", "start": 0, "end": 17, "loc": { "start": { "line": 1, "column": 0 }, "end": { "line": 1, "column": 17 } }, "sourceType": "script", "body": [ { "type": "VariableDeclaration", "start": 0, "end": 17, "loc": { "start": { "line": 1, "column": 0 }, "end": { "line": 1, "column": 17 } }, "declarations": [ { "type": "VariableDeclarator", "start": 4, "end": 17, "loc": { "start": { "line": 1, "column": 4 }, "end": { "line": 1, "column": 17 } }, "id": { "type": "ObjectPattern", "start": 4, "end": 13, "loc": { "start": { "line": 1, "column": 4 }, "end": { "line": 1, "column": 13 } }, "properties": [ { "type": "ObjectProperty", "start": 5, "end": 6, "loc": { "start": { "line": 1, "column": 5 }, "end": { "line": 1, "column": 6 } }, "method": false, "shorthand": true, "computed": false, "key": { "type": "Identifier", "start": 5, "end": 6, "loc": { "start": { "line": 1, "column": 5 }, "end": { "line": 1, "column": 6 } }, "name": "x" }, "value": { "type": "Identifier", "start": 5, "end": 6, "loc": { "start": { "line": 1, "column": 5 }, "end": { "line": 1, "column": 6 } }, "name": "x" } }, { "type": "RestProperty", "start": 8, "end": 12, "loc": { "start": { "line": 1, "column": 8 }, "end": { "line": 1, "column": 12 } }, "argument": { "type": "Identifier", "start": 11, "end": 12, "loc": { "start": { "line": 1, "column": 11 }, "end": { "line": 1, "column": 12 } }, "name": "y" } } ] }, "init": { "type": "Identifier", "start": 16, "end": 17, "loc": { "start": { "line": 1, "column": 16 }, "end": { "line": 1, "column": 17 } }, "name": "z" } } ], "kind": "let" } ], "directives": [] } }
packages/babylon/test/fixtures/experimental/uncategorised/10/expected.json
0
https://github.com/babel/babel/commit/183fbab967cce7d6fc7ad61c26673928caef9322
[ 0.0001752262032823637, 0.00017235982522834092, 0.00016732965013943613, 0.0001730116200633347, 0.0000021813293642480858 ]
{ "id": 2, "code_window": [ " for (var _len9 = arguments.length, rest = Array(_len9), _key9 = 0; _key9 < _len9; _key9++) {\n", " rest[_key9] = arguments[_key9];\n", " }\n", "\n", " [rest[0], rest[1]] = [rest[1], rest[0]];\n", "}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ " var _ref = [rest[1], rest[0]];\n", " rest[0] = _ref[0];\n", " rest[1] = _ref[1];\n" ], "file_path": "packages/babel-plugin-transform-es2015-parameters/test/fixtures/parameters/rest-member-expression-deoptimisation/expected.js", "type": "replace", "edit_start_line_idx": 85 }
new X;new Y()();new F().z;new new x();new new x()(a);new new x(a);new new x(a)(a);
packages/babel-generator/test/fixtures/minified/new-expression/expected.js
0
https://github.com/babel/babel/commit/183fbab967cce7d6fc7ad61c26673928caef9322
[ 0.00017550760821904987, 0.00017550760821904987, 0.00017550760821904987, 0.00017550760821904987, 0 ]
{ "id": 2, "code_window": [ " for (var _len9 = arguments.length, rest = Array(_len9), _key9 = 0; _key9 < _len9; _key9++) {\n", " rest[_key9] = arguments[_key9];\n", " }\n", "\n", " [rest[0], rest[1]] = [rest[1], rest[0]];\n", "}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ " var _ref = [rest[1], rest[0]];\n", " rest[0] = _ref[0];\n", " rest[1] = _ref[1];\n" ], "file_path": "packages/babel-plugin-transform-es2015-parameters/test/fixtures/parameters/rest-member-expression-deoptimisation/expected.js", "type": "replace", "edit_start_line_idx": 85 }
function* wrap(generator) { return yield *generator; } class BadIterable { constructor() { this.closed = false; } [Symbol.iterator]() { return { iterable: this, next(v) { return {value: 42, done: false}; }, // throw method missing return(v) { this.iterable.closed = true; return {value: undefined, done: true}; } }; } } var i1 = new BadIterable(); var g1 = wrap(i1); assert.deepEqual(g1.next(), {value: 42, done: false}); assert.throws(() => g1.throw('ex1'), TypeError); assert.isTrue(i1.closed); function* f2() { try { yield 1; } finally { f2.closed = true; } } f2.closed = false; var g2 = wrap(f2()); assert.deepEqual(g2.next(), {value: 1, done: false}); assert.throws(() => g2.throw('ex2'), 'ex2'); assert.isTrue(f2.closed);
packages/babel-preset-es2015/test/fixtures/traceur/Yield/BadIterable.js
0
https://github.com/babel/babel/commit/183fbab967cce7d6fc7ad61c26673928caef9322
[ 0.000240445660892874, 0.0001891043211799115, 0.00017363070219289511, 0.00017788652621675283, 0.00002576424776634667 ]
{ "id": 3, "code_window": [ "}\n", "\n", "function x() {\n", " for (var _len10 = arguments.length, rest = Array(_len10), _key10 = 0; _key10 < _len10; _key10++) {\n", " rest[_key10] = arguments[_key10];\n", " }\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "function forIn() {\n" ], "file_path": "packages/babel-plugin-transform-es2015-parameters/test/fixtures/parameters/rest-member-expression-deoptimisation/expected.js", "type": "replace", "edit_start_line_idx": 88 }
var x = function (foo) { for (var _len = arguments.length, bar = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { bar[_key - 1] = arguments[_key]; } console.log(bar); }; var y = function (foo) { for (var _len2 = arguments.length, bar = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { bar[_key2 - 1] = arguments[_key2]; } var x = function z(bar) { bar[1] = 5; }; }; var b = function (x, y) { for (var _len3 = arguments.length, args = Array(_len3 > 2 ? _len3 - 2 : 0), _key3 = 2; _key3 < _len3; _key3++) { args[_key3 - 2] = arguments[_key3]; } console.log(args[0]); args.pop(); console.log(args[1]); }; var z = function (foo) { for (var _len4 = arguments.length, bar = Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) { bar[_key4 - 1] = arguments[_key4]; } var x = function () { bar[1] = 5; }; }; var a = function (foo) { for (var _len5 = arguments.length, bar = Array(_len5 > 1 ? _len5 - 1 : 0), _key5 = 1; _key5 < _len5; _key5++) { bar[_key5 - 1] = arguments[_key5]; } return bar.join(","); }; var b = function (foo) { var join = "join"; for (var _len6 = arguments.length, bar = Array(_len6 > 1 ? _len6 - 1 : 0), _key6 = 1; _key6 < _len6; _key6++) { bar[_key6 - 1] = arguments[_key6]; } return bar[join]; }; var b = function () { for (var _len7 = arguments.length, bar = Array(_len7), _key7 = 0; _key7 < _len7; _key7++) { bar[_key7] = arguments[_key7]; } return bar.len; }; var b = function (foo) { return (arguments.length - 1) * 2; }; var b = function (foo, baz) { return arguments.length - 2; }; function x() { for (var _len8 = arguments.length, rest = Array(_len8), _key8 = 0; _key8 < _len8; _key8++) { rest[_key8] = arguments[_key8]; } rest[0] = 0; } function swap() { for (var _len9 = arguments.length, rest = Array(_len9), _key9 = 0; _key9 < _len9; _key9++) { rest[_key9] = arguments[_key9]; } [rest[0], rest[1]] = [rest[1], rest[0]]; } function x() { for (var _len10 = arguments.length, rest = Array(_len10), _key10 = 0; _key10 < _len10; _key10++) { rest[_key10] = arguments[_key10]; } for (rest[0] in this) { foo(rest[0]); } } function inc() { for (var _len11 = arguments.length, rest = Array(_len11), _key11 = 0; _key11 < _len11; _key11++) { rest[_key11] = arguments[_key11]; } ++rest[0]; } function dec() { for (var _len12 = arguments.length, rest = Array(_len12), _key12 = 0; _key12 < _len12; _key12++) { rest[_key12] = arguments[_key12]; } --rest[0]; } function del() { for (var _len13 = arguments.length, rest = Array(_len13), _key13 = 0; _key13 < _len13; _key13++) { rest[_key13] = arguments[_key13]; } delete rest[0]; } function method() { for (var _len14 = arguments.length, rest = Array(_len14), _key14 = 0; _key14 < _len14; _key14++) { rest[_key14] = arguments[_key14]; } rest[0](); } function newExp() { for (var _len15 = arguments.length, rest = Array(_len15), _key15 = 0; _key15 < _len15; _key15++) { rest[_key15] = arguments[_key15]; } new rest[0](); } // In addition to swap() above because at some point someone tried checking // grandparent path for isArrayExpression() to deopt. function arrayDestructure() { for (var _len16 = arguments.length, rest = Array(_len16), _key16 = 0; _key16 < _len16; _key16++) { rest[_key16] = arguments[_key16]; } var _x = babelHelpers.slicedToArray(x, 1); rest[0] = _x[0]; }
packages/babel-plugin-transform-es2015-parameters/test/fixtures/parameters/rest-member-expression-deoptimisation/expected.js
1
https://github.com/babel/babel/commit/183fbab967cce7d6fc7ad61c26673928caef9322
[ 0.9977329969406128, 0.48021963238716125, 0.00027494467212818563, 0.17559775710105896, 0.4561748802661896 ]
{ "id": 3, "code_window": [ "}\n", "\n", "function x() {\n", " for (var _len10 = arguments.length, rest = Array(_len10), _key10 = 0; _key10 < _len10; _key10++) {\n", " rest[_key10] = arguments[_key10];\n", " }\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "function forIn() {\n" ], "file_path": "packages/babel-plugin-transform-es2015-parameters/test/fixtures/parameters/rest-member-expression-deoptimisation/expected.js", "type": "replace", "edit_start_line_idx": 88 }
var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; try { b: for (var _iterator = d()[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { let c = _step.value; var _iteratorNormalCompletion2 = true; var _didIteratorError2 = false; var _iteratorError2 = undefined; try { for (var _iterator2 = f()[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { let e = _step2.value; continue b; } } catch (err) { _didIteratorError2 = true; _iteratorError2 = err; } finally { try { if (!_iteratorNormalCompletion2 && _iterator2.return) { _iterator2.return(); } } finally { if (_didIteratorError2) { throw _iteratorError2; } } } } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator.return) { _iterator.return(); } } finally { if (_didIteratorError) { throw _iteratorError; } } }
packages/babel-plugin-transform-es2015-for-of/test/fixtures/spec/nested-label-for-of/expected.js
0
https://github.com/babel/babel/commit/183fbab967cce7d6fc7ad61c26673928caef9322
[ 0.00018166024528909475, 0.00017222834867425263, 0.00016692902136128396, 0.00016795514966361225, 0.000006207445039763115 ]
{ "id": 3, "code_window": [ "}\n", "\n", "function x() {\n", " for (var _len10 = arguments.length, rest = Array(_len10), _key10 = 0; _key10 < _len10; _key10++) {\n", " rest[_key10] = arguments[_key10];\n", " }\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "function forIn() {\n" ], "file_path": "packages/babel-plugin-transform-es2015-parameters/test/fixtures/parameters/rest-member-expression-deoptimisation/expected.js", "type": "replace", "edit_start_line_idx": 88 }
{ "type": "File", "start": 0, "end": 3, "loc": { "start": { "line": 1, "column": 0 }, "end": { "line": 1, "column": 3 } }, "program": { "type": "Program", "start": 0, "end": 3, "loc": { "start": { "line": 1, "column": 0 }, "end": { "line": 1, "column": 3 } }, "sourceType": "script", "body": [ { "type": "ExpressionStatement", "start": 0, "end": 3, "loc": { "start": { "line": 1, "column": 0 }, "end": { "line": 1, "column": 3 } }, "expression": { "type": "UpdateExpression", "start": 0, "end": 3, "loc": { "start": { "line": 1, "column": 0 }, "end": { "line": 1, "column": 3 } }, "operator": "++", "prefix": true, "argument": { "type": "Identifier", "start": 2, "end": 3, "loc": { "start": { "line": 1, "column": 2 }, "end": { "line": 1, "column": 3 } }, "name": "x" } } } ] } }
packages/babylon/test/fixtures/esprima/expression-unary/migrated_0000/expected.json
0
https://github.com/babel/babel/commit/183fbab967cce7d6fc7ad61c26673928caef9322
[ 0.0012948655057698488, 0.0002951080386992544, 0.00016844752826727927, 0.00017018594371620566, 0.00035346992081031203 ]
{ "id": 3, "code_window": [ "}\n", "\n", "function x() {\n", " for (var _len10 = arguments.length, rest = Array(_len10), _key10 = 0; _key10 < _len10; _key10++) {\n", " rest[_key10] = arguments[_key10];\n", " }\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "function forIn() {\n" ], "file_path": "packages/babel-plugin-transform-es2015-parameters/test/fixtures/parameters/rest-member-expression-deoptimisation/expected.js", "type": "replace", "edit_start_line_idx": 88 }
{ "throws": "Identifier directly after number (1:1)" }
packages/babylon/test/fixtures/core/uncategorised/358/options.json
0
https://github.com/babel/babel/commit/183fbab967cce7d6fc7ad61c26673928caef9322
[ 0.00016847111692186445, 0.00016847111692186445, 0.00016847111692186445, 0.00016847111692186445, 0 ]
{ "id": 0, "code_window": [ "/*---------------------------------------------------------------------------------------------\n", " * Copyright (c) Microsoft Corporation. All rights reserved.\n", " * Licensed under the MIT License. See License.txt in the project root for license information.\n", " *--------------------------------------------------------------------------------------------*/\n", "\n", "import { INotebookEditor, NOTEBOOK_EDITOR_FOCUSED, NOTEBOOK_IS_ACTIVE_EDITOR, NOTEBOOK_HAS_MULTIPLE_KERNELS } from 'vs/workbench/contrib/notebook/browser/notebookBrowser';\n", "import { IEditorService } from 'vs/workbench/services/editor/common/editorService';\n", "import { IQuickInputService, QuickPickInput, IQuickPickItem } from 'vs/platform/quickinput/common/quickInput';\n", "import { INotebookService } from 'vs/workbench/contrib/notebook/common/notebookService';\n", "import * as nls from 'vs/nls';\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/contrib/notebook/browser/contrib/status/editorStatus.ts", "type": "replace", "edit_start_line_idx": 5 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { INotebookEditor, NOTEBOOK_EDITOR_FOCUSED, NOTEBOOK_IS_ACTIVE_EDITOR, NOTEBOOK_HAS_MULTIPLE_KERNELS } from 'vs/workbench/contrib/notebook/browser/notebookBrowser'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; import { IQuickInputService, QuickPickInput, IQuickPickItem } from 'vs/platform/quickinput/common/quickInput'; import { INotebookService } from 'vs/workbench/contrib/notebook/common/notebookService'; import * as nls from 'vs/nls'; import { registerAction2, Action2, MenuId } from 'vs/platform/actions/common/actions'; import { NOTEBOOK_ACTIONS_CATEGORY, INotebookCellActionContext } from 'vs/workbench/contrib/notebook/browser/contrib/coreActions'; import { ContextKeyExpr } from 'vs/platform/contextkey/common/contextkey'; import { ServicesAccessor } from 'vs/platform/instantiation/common/instantiation'; registerAction2(class extends Action2 { constructor() { super({ id: 'notebook.selectKernel', category: NOTEBOOK_ACTIONS_CATEGORY, title: nls.localize('notebookActions.selectKernel', "Select Notebook Kernel"), precondition: ContextKeyExpr.and(NOTEBOOK_IS_ACTIVE_EDITOR, NOTEBOOK_EDITOR_FOCUSED), icon: { id: 'codicon/server-environment' }, menu: { id: MenuId.EditorTitle, when: ContextKeyExpr.and(NOTEBOOK_IS_ACTIVE_EDITOR, NOTEBOOK_HAS_MULTIPLE_KERNELS), group: 'navigation', order: -2, }, f1: true }); } async run(accessor: ServicesAccessor, context?: INotebookCellActionContext): Promise<void> { const editorService = accessor.get<IEditorService>(IEditorService); const notebookService = accessor.get<INotebookService>(INotebookService); const quickInputService = accessor.get<IQuickInputService>(IQuickInputService); const activeEditorPane = editorService.activeEditorPane as unknown as { isNotebookEditor?: boolean } | undefined; if (!activeEditorPane?.isNotebookEditor) { return; } const editor = editorService.activeEditorPane?.getControl() as INotebookEditor; const activeKernel = editor.activeKernel; const availableKernels = notebookService.getContributedNotebookKernels(editor.viewModel!.viewType, editor.viewModel!.uri); const picks: QuickPickInput<IQuickPickItem & { run(): void; }>[] = availableKernels.map((a) => { return { id: a.id, label: a.label, picked: a.id === activeKernel?.id, description: a.extension.value + (a.id === activeKernel?.id ? nls.localize('currentActiveKernel', " (Currently Active)") : ''), run: () => { editor.activeKernel = a; } }; }); const provider = notebookService.getContributedNotebookProviders(editor.viewModel!.uri)[0]; if (provider.kernel) { picks.unshift({ id: provider.id, label: provider.displayName, picked: !activeKernel, // no active kernel, the builtin kernel of the provider is used description: activeKernel === undefined ? nls.localize('currentActiveBuiltinKernel', " (Currently Active)") : '', run: () => { editor.activeKernel = undefined; } }); } const action = await quickInputService.pick(picks, { placeHolder: nls.localize('pickAction', "Select Action"), matchOnDetail: true }); return action?.run(); } });
src/vs/workbench/contrib/notebook/browser/contrib/status/editorStatus.ts
1
https://github.com/microsoft/vscode/commit/9504dda6a717a0a0d45d992e21f2565f8a23f390
[ 0.09910012036561966, 0.011302676051855087, 0.0001644132426008582, 0.00017439411021769047, 0.031042946502566338 ]
{ "id": 0, "code_window": [ "/*---------------------------------------------------------------------------------------------\n", " * Copyright (c) Microsoft Corporation. All rights reserved.\n", " * Licensed under the MIT License. See License.txt in the project root for license information.\n", " *--------------------------------------------------------------------------------------------*/\n", "\n", "import { INotebookEditor, NOTEBOOK_EDITOR_FOCUSED, NOTEBOOK_IS_ACTIVE_EDITOR, NOTEBOOK_HAS_MULTIPLE_KERNELS } from 'vs/workbench/contrib/notebook/browser/notebookBrowser';\n", "import { IEditorService } from 'vs/workbench/services/editor/common/editorService';\n", "import { IQuickInputService, QuickPickInput, IQuickPickItem } from 'vs/platform/quickinput/common/quickInput';\n", "import { INotebookService } from 'vs/workbench/contrib/notebook/common/notebookService';\n", "import * as nls from 'vs/nls';\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/contrib/notebook/browser/contrib/status/editorStatus.ts", "type": "replace", "edit_start_line_idx": 5 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Color } from 'vs/base/common/color'; import { Event } from 'vs/base/common/event'; import { IDisposable, Disposable } from 'vs/base/common/lifecycle'; import * as strings from 'vs/base/common/strings'; import { ConfigurationChangedEvent, EDITOR_FONT_DEFAULTS, EditorOption, filterValidationDecorations } from 'vs/editor/common/config/editorOptions'; import { IPosition, Position } from 'vs/editor/common/core/position'; import { ISelection, Selection } from 'vs/editor/common/core/selection'; import { IRange, Range } from 'vs/editor/common/core/range'; import { IConfiguration, IViewState, ScrollType, ICursorState, ICommand, INewScrollPosition } from 'vs/editor/common/editorCommon'; import { EndOfLinePreference, IActiveIndentGuideInfo, ITextModel, TrackedRangeStickiness, TextModelResolvedOptions, IIdentifiedSingleEditOperation, ICursorStateComputer } from 'vs/editor/common/model'; import { ModelDecorationOverviewRulerOptions, ModelDecorationMinimapOptions } from 'vs/editor/common/model/textModel'; import * as textModelEvents from 'vs/editor/common/model/textModelEvents'; import { ColorId, LanguageId, TokenizationRegistry } from 'vs/editor/common/modes'; import { tokenizeLineToHTML } from 'vs/editor/common/modes/textToHtmlTokenizer'; import { MinimapTokensColorTracker } from 'vs/editor/common/viewModel/minimapTokensColorTracker'; import * as viewEvents from 'vs/editor/common/view/viewEvents'; import { ViewLayout } from 'vs/editor/common/viewLayout/viewLayout'; import { IViewModelLinesCollection, IdentityLinesCollection, SplitLinesCollection, ILineBreaksComputerFactory } from 'vs/editor/common/viewModel/splitLinesCollection'; import { ICoordinatesConverter, IOverviewRulerDecorations, IViewModel, MinimapLinesRenderingData, ViewLineData, ViewLineRenderingData, ViewModelDecoration } from 'vs/editor/common/viewModel/viewModel'; import { ViewModelDecorations } from 'vs/editor/common/viewModel/viewModelDecorations'; import { RunOnceScheduler } from 'vs/base/common/async'; import * as platform from 'vs/base/common/platform'; import { EditorTheme } from 'vs/editor/common/view/viewContext'; import { Cursor } from 'vs/editor/common/controller/cursor'; import { PartialCursorState, CursorState, IColumnSelectData, EditOperationType, CursorConfiguration } from 'vs/editor/common/controller/cursorCommon'; import { CursorChangeReason } from 'vs/editor/common/controller/cursorEvents'; import { IWhitespaceChangeAccessor } from 'vs/editor/common/viewLayout/linesLayout'; import { ViewModelEventDispatcher, OutgoingViewModelEvent, FocusChangedEvent, ScrollChangedEvent, ViewZonesChangedEvent, ViewModelEventsCollector, ReadOnlyEditAttemptEvent } from 'vs/editor/common/viewModel/viewModelEventDispatcher'; import { ViewEventHandler } from 'vs/editor/common/viewModel/viewEventHandler'; const USE_IDENTITY_LINES_COLLECTION = true; export class ViewModel extends Disposable implements IViewModel { private readonly _editorId: number; private readonly _configuration: IConfiguration; public readonly model: ITextModel; private readonly _eventDispatcher: ViewModelEventDispatcher; public readonly onEvent: Event<OutgoingViewModelEvent>; public cursorConfig: CursorConfiguration; private readonly _tokenizeViewportSoon: RunOnceScheduler; private readonly _updateConfigurationViewLineCount: RunOnceScheduler; private _hasFocus: boolean; private _viewportStartLine: number; private _viewportStartLineTrackedRange: string | null; private _viewportStartLineDelta: number; private readonly _lines: IViewModelLinesCollection; public readonly coordinatesConverter: ICoordinatesConverter; public readonly viewLayout: ViewLayout; private readonly _cursor: Cursor; private readonly _decorations: ViewModelDecorations; constructor( editorId: number, configuration: IConfiguration, model: ITextModel, domLineBreaksComputerFactory: ILineBreaksComputerFactory, monospaceLineBreaksComputerFactory: ILineBreaksComputerFactory, scheduleAtNextAnimationFrame: (callback: () => void) => IDisposable ) { super(); this._editorId = editorId; this._configuration = configuration; this.model = model; this._eventDispatcher = new ViewModelEventDispatcher(); this.onEvent = this._eventDispatcher.onEvent; this.cursorConfig = new CursorConfiguration(this.model.getLanguageIdentifier(), this.model.getOptions(), this._configuration); this._tokenizeViewportSoon = this._register(new RunOnceScheduler(() => this.tokenizeViewport(), 50)); this._updateConfigurationViewLineCount = this._register(new RunOnceScheduler(() => this._updateConfigurationViewLineCountNow(), 0)); this._hasFocus = false; this._viewportStartLine = -1; this._viewportStartLineTrackedRange = null; this._viewportStartLineDelta = 0; if (USE_IDENTITY_LINES_COLLECTION && this.model.isTooLargeForTokenization()) { this._lines = new IdentityLinesCollection(this.model); } else { const options = this._configuration.options; const fontInfo = options.get(EditorOption.fontInfo); const wrappingStrategy = options.get(EditorOption.wrappingStrategy); const wrappingInfo = options.get(EditorOption.wrappingInfo); const wrappingIndent = options.get(EditorOption.wrappingIndent); this._lines = new SplitLinesCollection( this.model, domLineBreaksComputerFactory, monospaceLineBreaksComputerFactory, fontInfo, this.model.getOptions().tabSize, wrappingStrategy, wrappingInfo.wrappingColumn, wrappingIndent ); } this.coordinatesConverter = this._lines.createCoordinatesConverter(); this._cursor = this._register(new Cursor(model, this, this.coordinatesConverter, this.cursorConfig)); this.viewLayout = this._register(new ViewLayout(this._configuration, this.getLineCount(), scheduleAtNextAnimationFrame)); this._register(this.viewLayout.onDidScroll((e) => { if (e.scrollTopChanged) { this._tokenizeViewportSoon.schedule(); } this._eventDispatcher.emitSingleViewEvent(new viewEvents.ViewScrollChangedEvent(e)); this._eventDispatcher.emitOutgoingEvent(new ScrollChangedEvent( e.oldScrollWidth, e.oldScrollLeft, e.oldScrollHeight, e.oldScrollTop, e.scrollWidth, e.scrollLeft, e.scrollHeight, e.scrollTop )); })); this._register(this.viewLayout.onDidContentSizeChange((e) => { this._eventDispatcher.emitOutgoingEvent(e); })); this._decorations = new ViewModelDecorations(this._editorId, this.model, this._configuration, this._lines, this.coordinatesConverter); this._registerModelEvents(); this._register(this._configuration.onDidChangeFast((e) => { try { const eventsCollector = this._eventDispatcher.beginEmitViewEvents(); this._onConfigurationChanged(eventsCollector, e); } finally { this._eventDispatcher.endEmitViewEvents(); } })); this._register(MinimapTokensColorTracker.getInstance().onDidChange(() => { this._eventDispatcher.emitSingleViewEvent(new viewEvents.ViewTokensColorsChangedEvent()); })); this._updateConfigurationViewLineCountNow(); } public dispose(): void { // First remove listeners, as disposing the lines might end up sending // model decoration changed events ... and we no longer care about them ... super.dispose(); this._decorations.dispose(); this._lines.dispose(); this.invalidateMinimapColorCache(); this._viewportStartLineTrackedRange = this.model._setTrackedRange(this._viewportStartLineTrackedRange, null, TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges); this._eventDispatcher.dispose(); } public addViewEventHandler(eventHandler: ViewEventHandler): void { this._eventDispatcher.addViewEventHandler(eventHandler); } public removeViewEventHandler(eventHandler: ViewEventHandler): void { this._eventDispatcher.removeViewEventHandler(eventHandler); } private _updateConfigurationViewLineCountNow(): void { this._configuration.setViewLineCount(this._lines.getViewLineCount()); } public tokenizeViewport(): void { const linesViewportData = this.viewLayout.getLinesViewportData(); const startPosition = this.coordinatesConverter.convertViewPositionToModelPosition(new Position(linesViewportData.startLineNumber, 1)); const endPosition = this.coordinatesConverter.convertViewPositionToModelPosition(new Position(linesViewportData.endLineNumber, 1)); this.model.tokenizeViewport(startPosition.lineNumber, endPosition.lineNumber); } public setHasFocus(hasFocus: boolean): void { this._hasFocus = hasFocus; this._cursor.setHasFocus(hasFocus); this._eventDispatcher.emitSingleViewEvent(new viewEvents.ViewFocusChangedEvent(hasFocus)); this._eventDispatcher.emitOutgoingEvent(new FocusChangedEvent(!hasFocus, hasFocus)); } public onDidColorThemeChange(): void { this._eventDispatcher.emitSingleViewEvent(new viewEvents.ViewThemeChangedEvent()); } private _onConfigurationChanged(eventsCollector: ViewModelEventsCollector, e: ConfigurationChangedEvent): void { // We might need to restore the current centered view range, so save it (if available) let previousViewportStartModelPosition: Position | null = null; if (this._viewportStartLine !== -1) { let previousViewportStartViewPosition = new Position(this._viewportStartLine, this.getLineMinColumn(this._viewportStartLine)); previousViewportStartModelPosition = this.coordinatesConverter.convertViewPositionToModelPosition(previousViewportStartViewPosition); } let restorePreviousViewportStart = false; const options = this._configuration.options; const fontInfo = options.get(EditorOption.fontInfo); const wrappingStrategy = options.get(EditorOption.wrappingStrategy); const wrappingInfo = options.get(EditorOption.wrappingInfo); const wrappingIndent = options.get(EditorOption.wrappingIndent); if (this._lines.setWrappingSettings(fontInfo, wrappingStrategy, wrappingInfo.wrappingColumn, wrappingIndent)) { eventsCollector.emitViewEvent(new viewEvents.ViewFlushedEvent()); eventsCollector.emitViewEvent(new viewEvents.ViewLineMappingChangedEvent()); eventsCollector.emitViewEvent(new viewEvents.ViewDecorationsChangedEvent(null)); this._cursor.onLineMappingChanged(eventsCollector); this._decorations.onLineMappingChanged(); this.viewLayout.onFlushed(this.getLineCount()); if (this.viewLayout.getCurrentScrollTop() !== 0) { // Never change the scroll position from 0 to something else... restorePreviousViewportStart = true; } this._updateConfigurationViewLineCount.schedule(); } if (e.hasChanged(EditorOption.readOnly)) { // Must read again all decorations due to readOnly filtering this._decorations.reset(); eventsCollector.emitViewEvent(new viewEvents.ViewDecorationsChangedEvent(null)); } eventsCollector.emitViewEvent(new viewEvents.ViewConfigurationChangedEvent(e)); this.viewLayout.onConfigurationChanged(e); if (restorePreviousViewportStart && previousViewportStartModelPosition) { const viewPosition = this.coordinatesConverter.convertModelPositionToViewPosition(previousViewportStartModelPosition); const viewPositionTop = this.viewLayout.getVerticalOffsetForLineNumber(viewPosition.lineNumber); this.viewLayout.setScrollPosition({ scrollTop: viewPositionTop + this._viewportStartLineDelta }, ScrollType.Immediate); } if (CursorConfiguration.shouldRecreate(e)) { this.cursorConfig = new CursorConfiguration(this.model.getLanguageIdentifier(), this.model.getOptions(), this._configuration); this._cursor.updateConfiguration(this.cursorConfig); } } private _registerModelEvents(): void { this._register(this.model.onDidChangeRawContentFast((e) => { try { const eventsCollector = this._eventDispatcher.beginEmitViewEvents(); let hadOtherModelChange = false; let hadModelLineChangeThatChangedLineMapping = false; const changes = e.changes; const versionId = e.versionId; // Do a first pass to compute line mappings, and a second pass to actually interpret them const lineBreaksComputer = this._lines.createLineBreaksComputer(); for (const change of changes) { switch (change.changeType) { case textModelEvents.RawContentChangedType.LinesInserted: { for (const line of change.detail) { lineBreaksComputer.addRequest(line, null); } break; } case textModelEvents.RawContentChangedType.LineChanged: { lineBreaksComputer.addRequest(change.detail, null); break; } } } const lineBreaks = lineBreaksComputer.finalize(); let lineBreaksOffset = 0; for (const change of changes) { switch (change.changeType) { case textModelEvents.RawContentChangedType.Flush: { this._lines.onModelFlushed(); eventsCollector.emitViewEvent(new viewEvents.ViewFlushedEvent()); this._decorations.reset(); this.viewLayout.onFlushed(this.getLineCount()); hadOtherModelChange = true; break; } case textModelEvents.RawContentChangedType.LinesDeleted: { const linesDeletedEvent = this._lines.onModelLinesDeleted(versionId, change.fromLineNumber, change.toLineNumber); if (linesDeletedEvent !== null) { eventsCollector.emitViewEvent(linesDeletedEvent); this.viewLayout.onLinesDeleted(linesDeletedEvent.fromLineNumber, linesDeletedEvent.toLineNumber); } hadOtherModelChange = true; break; } case textModelEvents.RawContentChangedType.LinesInserted: { const insertedLineBreaks = lineBreaks.slice(lineBreaksOffset, lineBreaksOffset + change.detail.length); lineBreaksOffset += change.detail.length; const linesInsertedEvent = this._lines.onModelLinesInserted(versionId, change.fromLineNumber, change.toLineNumber, insertedLineBreaks); if (linesInsertedEvent !== null) { eventsCollector.emitViewEvent(linesInsertedEvent); this.viewLayout.onLinesInserted(linesInsertedEvent.fromLineNumber, linesInsertedEvent.toLineNumber); } hadOtherModelChange = true; break; } case textModelEvents.RawContentChangedType.LineChanged: { const changedLineBreakData = lineBreaks[lineBreaksOffset]; lineBreaksOffset++; const [lineMappingChanged, linesChangedEvent, linesInsertedEvent, linesDeletedEvent] = this._lines.onModelLineChanged(versionId, change.lineNumber, changedLineBreakData); hadModelLineChangeThatChangedLineMapping = lineMappingChanged; if (linesChangedEvent) { eventsCollector.emitViewEvent(linesChangedEvent); } if (linesInsertedEvent) { eventsCollector.emitViewEvent(linesInsertedEvent); this.viewLayout.onLinesInserted(linesInsertedEvent.fromLineNumber, linesInsertedEvent.toLineNumber); } if (linesDeletedEvent) { eventsCollector.emitViewEvent(linesDeletedEvent); this.viewLayout.onLinesDeleted(linesDeletedEvent.fromLineNumber, linesDeletedEvent.toLineNumber); } break; } case textModelEvents.RawContentChangedType.EOLChanged: { // Nothing to do. The new version will be accepted below break; } } } this._lines.acceptVersionId(versionId); this.viewLayout.onHeightMaybeChanged(); if (!hadOtherModelChange && hadModelLineChangeThatChangedLineMapping) { eventsCollector.emitViewEvent(new viewEvents.ViewLineMappingChangedEvent()); eventsCollector.emitViewEvent(new viewEvents.ViewDecorationsChangedEvent(null)); this._cursor.onLineMappingChanged(eventsCollector); this._decorations.onLineMappingChanged(); } } finally { this._eventDispatcher.endEmitViewEvents(); } // Update the configuration and reset the centered view line this._viewportStartLine = -1; this._configuration.setMaxLineNumber(this.model.getLineCount()); this._updateConfigurationViewLineCountNow(); // Recover viewport if (!this._hasFocus && this.model.getAttachedEditorCount() >= 2 && this._viewportStartLineTrackedRange) { const modelRange = this.model._getTrackedRange(this._viewportStartLineTrackedRange); if (modelRange) { const viewPosition = this.coordinatesConverter.convertModelPositionToViewPosition(modelRange.getStartPosition()); const viewPositionTop = this.viewLayout.getVerticalOffsetForLineNumber(viewPosition.lineNumber); this.viewLayout.setScrollPosition({ scrollTop: viewPositionTop + this._viewportStartLineDelta }, ScrollType.Immediate); } } try { const eventsCollector = this._eventDispatcher.beginEmitViewEvents(); this._cursor.onModelContentChanged(eventsCollector, e); } finally { this._eventDispatcher.endEmitViewEvents(); } })); this._register(this.model.onDidChangeTokens((e) => { let viewRanges: { fromLineNumber: number; toLineNumber: number; }[] = []; for (let j = 0, lenJ = e.ranges.length; j < lenJ; j++) { const modelRange = e.ranges[j]; const viewStartLineNumber = this.coordinatesConverter.convertModelPositionToViewPosition(new Position(modelRange.fromLineNumber, 1)).lineNumber; const viewEndLineNumber = this.coordinatesConverter.convertModelPositionToViewPosition(new Position(modelRange.toLineNumber, this.model.getLineMaxColumn(modelRange.toLineNumber))).lineNumber; viewRanges[j] = { fromLineNumber: viewStartLineNumber, toLineNumber: viewEndLineNumber }; } this._eventDispatcher.emitSingleViewEvent(new viewEvents.ViewTokensChangedEvent(viewRanges)); if (e.tokenizationSupportChanged) { this._tokenizeViewportSoon.schedule(); } })); this._register(this.model.onDidChangeLanguageConfiguration((e) => { this._eventDispatcher.emitSingleViewEvent(new viewEvents.ViewLanguageConfigurationEvent()); this.cursorConfig = new CursorConfiguration(this.model.getLanguageIdentifier(), this.model.getOptions(), this._configuration); this._cursor.updateConfiguration(this.cursorConfig); })); this._register(this.model.onDidChangeLanguage((e) => { this.cursorConfig = new CursorConfiguration(this.model.getLanguageIdentifier(), this.model.getOptions(), this._configuration); this._cursor.updateConfiguration(this.cursorConfig); })); this._register(this.model.onDidChangeOptions((e) => { // A tab size change causes a line mapping changed event => all view parts will repaint OK, no further event needed here if (this._lines.setTabSize(this.model.getOptions().tabSize)) { try { const eventsCollector = this._eventDispatcher.beginEmitViewEvents(); eventsCollector.emitViewEvent(new viewEvents.ViewFlushedEvent()); eventsCollector.emitViewEvent(new viewEvents.ViewLineMappingChangedEvent()); eventsCollector.emitViewEvent(new viewEvents.ViewDecorationsChangedEvent(null)); this._cursor.onLineMappingChanged(eventsCollector); this._decorations.onLineMappingChanged(); this.viewLayout.onFlushed(this.getLineCount()); } finally { this._eventDispatcher.endEmitViewEvents(); } this._updateConfigurationViewLineCount.schedule(); } this.cursorConfig = new CursorConfiguration(this.model.getLanguageIdentifier(), this.model.getOptions(), this._configuration); this._cursor.updateConfiguration(this.cursorConfig); })); this._register(this.model.onDidChangeDecorations((e) => { this._decorations.onModelDecorationsChanged(); this._eventDispatcher.emitSingleViewEvent(new viewEvents.ViewDecorationsChangedEvent(e)); })); } public setHiddenAreas(ranges: Range[]): void { try { const eventsCollector = this._eventDispatcher.beginEmitViewEvents(); let lineMappingChanged = this._lines.setHiddenAreas(ranges); if (lineMappingChanged) { eventsCollector.emitViewEvent(new viewEvents.ViewFlushedEvent()); eventsCollector.emitViewEvent(new viewEvents.ViewLineMappingChangedEvent()); eventsCollector.emitViewEvent(new viewEvents.ViewDecorationsChangedEvent(null)); this._cursor.onLineMappingChanged(eventsCollector); this._decorations.onLineMappingChanged(); this.viewLayout.onFlushed(this.getLineCount()); this.viewLayout.onHeightMaybeChanged(); } } finally { this._eventDispatcher.endEmitViewEvents(); } this._updateConfigurationViewLineCount.schedule(); } public getVisibleRangesPlusViewportAboveBelow(): Range[] { const layoutInfo = this._configuration.options.get(EditorOption.layoutInfo); const lineHeight = this._configuration.options.get(EditorOption.lineHeight); const linesAround = Math.max(20, Math.round(layoutInfo.height / lineHeight)); const partialData = this.viewLayout.getLinesViewportData(); const startViewLineNumber = Math.max(1, partialData.completelyVisibleStartLineNumber - linesAround); const endViewLineNumber = Math.min(this.getLineCount(), partialData.completelyVisibleEndLineNumber + linesAround); return this._toModelVisibleRanges(new Range( startViewLineNumber, this.getLineMinColumn(startViewLineNumber), endViewLineNumber, this.getLineMaxColumn(endViewLineNumber) )); } public getVisibleRanges(): Range[] { const visibleViewRange = this.getCompletelyVisibleViewRange(); return this._toModelVisibleRanges(visibleViewRange); } private _toModelVisibleRanges(visibleViewRange: Range): Range[] { const visibleRange = this.coordinatesConverter.convertViewRangeToModelRange(visibleViewRange); const hiddenAreas = this._lines.getHiddenAreas(); if (hiddenAreas.length === 0) { return [visibleRange]; } let result: Range[] = [], resultLen = 0; let startLineNumber = visibleRange.startLineNumber; let startColumn = visibleRange.startColumn; let endLineNumber = visibleRange.endLineNumber; let endColumn = visibleRange.endColumn; for (let i = 0, len = hiddenAreas.length; i < len; i++) { const hiddenStartLineNumber = hiddenAreas[i].startLineNumber; const hiddenEndLineNumber = hiddenAreas[i].endLineNumber; if (hiddenEndLineNumber < startLineNumber) { continue; } if (hiddenStartLineNumber > endLineNumber) { continue; } if (startLineNumber < hiddenStartLineNumber) { result[resultLen++] = new Range( startLineNumber, startColumn, hiddenStartLineNumber - 1, this.model.getLineMaxColumn(hiddenStartLineNumber - 1) ); } startLineNumber = hiddenEndLineNumber + 1; startColumn = 1; } if (startLineNumber < endLineNumber || (startLineNumber === endLineNumber && startColumn < endColumn)) { result[resultLen++] = new Range( startLineNumber, startColumn, endLineNumber, endColumn ); } return result; } public getCompletelyVisibleViewRange(): Range { const partialData = this.viewLayout.getLinesViewportData(); const startViewLineNumber = partialData.completelyVisibleStartLineNumber; const endViewLineNumber = partialData.completelyVisibleEndLineNumber; return new Range( startViewLineNumber, this.getLineMinColumn(startViewLineNumber), endViewLineNumber, this.getLineMaxColumn(endViewLineNumber) ); } public getCompletelyVisibleViewRangeAtScrollTop(scrollTop: number): Range { const partialData = this.viewLayout.getLinesViewportDataAtScrollTop(scrollTop); const startViewLineNumber = partialData.completelyVisibleStartLineNumber; const endViewLineNumber = partialData.completelyVisibleEndLineNumber; return new Range( startViewLineNumber, this.getLineMinColumn(startViewLineNumber), endViewLineNumber, this.getLineMaxColumn(endViewLineNumber) ); } public saveState(): IViewState { const compatViewState = this.viewLayout.saveState(); const scrollTop = compatViewState.scrollTop; const firstViewLineNumber = this.viewLayout.getLineNumberAtVerticalOffset(scrollTop); const firstPosition = this.coordinatesConverter.convertViewPositionToModelPosition(new Position(firstViewLineNumber, this.getLineMinColumn(firstViewLineNumber))); const firstPositionDeltaTop = this.viewLayout.getVerticalOffsetForLineNumber(firstViewLineNumber) - scrollTop; return { scrollLeft: compatViewState.scrollLeft, firstPosition: firstPosition, firstPositionDeltaTop: firstPositionDeltaTop }; } public reduceRestoreState(state: IViewState): { scrollLeft: number; scrollTop: number; } { if (typeof state.firstPosition === 'undefined') { // This is a view state serialized by an older version return this._reduceRestoreStateCompatibility(state); } const modelPosition = this.model.validatePosition(state.firstPosition); const viewPosition = this.coordinatesConverter.convertModelPositionToViewPosition(modelPosition); const scrollTop = this.viewLayout.getVerticalOffsetForLineNumber(viewPosition.lineNumber) - state.firstPositionDeltaTop; return { scrollLeft: state.scrollLeft, scrollTop: scrollTop }; } private _reduceRestoreStateCompatibility(state: IViewState): { scrollLeft: number; scrollTop: number; } { return { scrollLeft: state.scrollLeft, scrollTop: state.scrollTopWithoutViewZones! }; } private getTabSize(): number { return this.model.getOptions().tabSize; } public getTextModelOptions(): TextModelResolvedOptions { return this.model.getOptions(); } public getLineCount(): number { return this._lines.getViewLineCount(); } /** * Gives a hint that a lot of requests are about to come in for these line numbers. */ public setViewport(startLineNumber: number, endLineNumber: number, centeredLineNumber: number): void { this._viewportStartLine = startLineNumber; let position = this.coordinatesConverter.convertViewPositionToModelPosition(new Position(startLineNumber, this.getLineMinColumn(startLineNumber))); this._viewportStartLineTrackedRange = this.model._setTrackedRange(this._viewportStartLineTrackedRange, new Range(position.lineNumber, position.column, position.lineNumber, position.column), TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges); const viewportStartLineTop = this.viewLayout.getVerticalOffsetForLineNumber(startLineNumber); const scrollTop = this.viewLayout.getCurrentScrollTop(); this._viewportStartLineDelta = scrollTop - viewportStartLineTop; } public getActiveIndentGuide(lineNumber: number, minLineNumber: number, maxLineNumber: number): IActiveIndentGuideInfo { return this._lines.getActiveIndentGuide(lineNumber, minLineNumber, maxLineNumber); } public getLinesIndentGuides(startLineNumber: number, endLineNumber: number): number[] { return this._lines.getViewLinesIndentGuides(startLineNumber, endLineNumber); } public getLineContent(lineNumber: number): string { return this._lines.getViewLineContent(lineNumber); } public getLineLength(lineNumber: number): number { return this._lines.getViewLineLength(lineNumber); } public getLineMinColumn(lineNumber: number): number { return this._lines.getViewLineMinColumn(lineNumber); } public getLineMaxColumn(lineNumber: number): number { return this._lines.getViewLineMaxColumn(lineNumber); } public getLineFirstNonWhitespaceColumn(lineNumber: number): number { const result = strings.firstNonWhitespaceIndex(this.getLineContent(lineNumber)); if (result === -1) { return 0; } return result + 1; } public getLineLastNonWhitespaceColumn(lineNumber: number): number { const result = strings.lastNonWhitespaceIndex(this.getLineContent(lineNumber)); if (result === -1) { return 0; } return result + 2; } public getDecorationsInViewport(visibleRange: Range): ViewModelDecoration[] { return this._decorations.getDecorationsViewportData(visibleRange).decorations; } public getViewLineRenderingData(visibleRange: Range, lineNumber: number): ViewLineRenderingData { let mightContainRTL = this.model.mightContainRTL(); let mightContainNonBasicASCII = this.model.mightContainNonBasicASCII(); let tabSize = this.getTabSize(); let lineData = this._lines.getViewLineData(lineNumber); let allInlineDecorations = this._decorations.getDecorationsViewportData(visibleRange).inlineDecorations; let inlineDecorations = allInlineDecorations[lineNumber - visibleRange.startLineNumber]; return new ViewLineRenderingData( lineData.minColumn, lineData.maxColumn, lineData.content, lineData.continuesWithWrappedLine, mightContainRTL, mightContainNonBasicASCII, lineData.tokens, inlineDecorations, tabSize, lineData.startVisibleColumn ); } public getViewLineData(lineNumber: number): ViewLineData { return this._lines.getViewLineData(lineNumber); } public getMinimapLinesRenderingData(startLineNumber: number, endLineNumber: number, needed: boolean[]): MinimapLinesRenderingData { let result = this._lines.getViewLinesData(startLineNumber, endLineNumber, needed); return new MinimapLinesRenderingData( this.getTabSize(), result ); } public getAllOverviewRulerDecorations(theme: EditorTheme): IOverviewRulerDecorations { return this._lines.getAllOverviewRulerDecorations(this._editorId, filterValidationDecorations(this._configuration.options), theme); } public invalidateOverviewRulerColorCache(): void { const decorations = this.model.getOverviewRulerDecorations(); for (const decoration of decorations) { const opts = <ModelDecorationOverviewRulerOptions>decoration.options.overviewRuler; if (opts) { opts.invalidateCachedColor(); } } } public invalidateMinimapColorCache(): void { const decorations = this.model.getAllDecorations(); for (const decoration of decorations) { const opts = <ModelDecorationMinimapOptions>decoration.options.minimap; if (opts) { opts.invalidateCachedColor(); } } } public getValueInRange(range: Range, eol: EndOfLinePreference): string { const modelRange = this.coordinatesConverter.convertViewRangeToModelRange(range); return this.model.getValueInRange(modelRange, eol); } public getModelLineMaxColumn(modelLineNumber: number): number { return this.model.getLineMaxColumn(modelLineNumber); } public validateModelPosition(position: IPosition): Position { return this.model.validatePosition(position); } public validateModelRange(range: IRange): Range { return this.model.validateRange(range); } public deduceModelPositionRelativeToViewPosition(viewAnchorPosition: Position, deltaOffset: number, lineFeedCnt: number): Position { const modelAnchor = this.coordinatesConverter.convertViewPositionToModelPosition(viewAnchorPosition); if (this.model.getEOL().length === 2) { // This model uses CRLF, so the delta must take that into account if (deltaOffset < 0) { deltaOffset -= lineFeedCnt; } else { deltaOffset += lineFeedCnt; } } const modelAnchorOffset = this.model.getOffsetAt(modelAnchor); const resultOffset = modelAnchorOffset + deltaOffset; return this.model.getPositionAt(resultOffset); } public getEOL(): string { return this.model.getEOL(); } public getPlainTextToCopy(modelRanges: Range[], emptySelectionClipboard: boolean, forceCRLF: boolean): string | string[] { const newLineCharacter = forceCRLF ? '\r\n' : this.model.getEOL(); modelRanges = modelRanges.slice(0); modelRanges.sort(Range.compareRangesUsingStarts); let hasEmptyRange = false; let hasNonEmptyRange = false; for (const range of modelRanges) { if (range.isEmpty()) { hasEmptyRange = true; } else { hasNonEmptyRange = true; } } if (!hasNonEmptyRange) { // all ranges are empty if (!emptySelectionClipboard) { return ''; } const modelLineNumbers = modelRanges.map((r) => r.startLineNumber); let result = ''; for (let i = 0; i < modelLineNumbers.length; i++) { if (i > 0 && modelLineNumbers[i - 1] === modelLineNumbers[i]) { continue; } result += this.model.getLineContent(modelLineNumbers[i]) + newLineCharacter; } return result; } if (hasEmptyRange && emptySelectionClipboard) { // mixed empty selections and non-empty selections let result: string[] = []; let prevModelLineNumber = 0; for (const modelRange of modelRanges) { const modelLineNumber = modelRange.startLineNumber; if (modelRange.isEmpty()) { if (modelLineNumber !== prevModelLineNumber) { result.push(this.model.getLineContent(modelLineNumber)); } } else { result.push(this.model.getValueInRange(modelRange, forceCRLF ? EndOfLinePreference.CRLF : EndOfLinePreference.TextDefined)); } prevModelLineNumber = modelLineNumber; } return result.length === 1 ? result[0] : result; } let result: string[] = []; for (const modelRange of modelRanges) { if (!modelRange.isEmpty()) { result.push(this.model.getValueInRange(modelRange, forceCRLF ? EndOfLinePreference.CRLF : EndOfLinePreference.TextDefined)); } } return result.length === 1 ? result[0] : result; } public getRichTextToCopy(modelRanges: Range[], emptySelectionClipboard: boolean): { html: string, mode: string } | null { const languageId = this.model.getLanguageIdentifier(); if (languageId.id === LanguageId.PlainText) { return null; } if (modelRanges.length !== 1) { // no multiple selection support at this time return null; } let range = modelRanges[0]; if (range.isEmpty()) { if (!emptySelectionClipboard) { // nothing to copy return null; } const lineNumber = range.startLineNumber; range = new Range(lineNumber, this.model.getLineMinColumn(lineNumber), lineNumber, this.model.getLineMaxColumn(lineNumber)); } const fontInfo = this._configuration.options.get(EditorOption.fontInfo); const colorMap = this._getColorMap(); const fontFamily = fontInfo.fontFamily === EDITOR_FONT_DEFAULTS.fontFamily ? fontInfo.fontFamily : `'${fontInfo.fontFamily}', ${EDITOR_FONT_DEFAULTS.fontFamily}`; return { mode: languageId.language, html: ( `<div style="` + `color: ${colorMap[ColorId.DefaultForeground]};` + `background-color: ${colorMap[ColorId.DefaultBackground]};` + `font-family: ${fontFamily};` + `font-weight: ${fontInfo.fontWeight};` + `font-size: ${fontInfo.fontSize}px;` + `line-height: ${fontInfo.lineHeight}px;` + `white-space: pre;` + `">` + this._getHTMLToCopy(range, colorMap) + '</div>' ) }; } private _getHTMLToCopy(modelRange: Range, colorMap: string[]): string { const startLineNumber = modelRange.startLineNumber; const startColumn = modelRange.startColumn; const endLineNumber = modelRange.endLineNumber; const endColumn = modelRange.endColumn; const tabSize = this.getTabSize(); let result = ''; for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) { const lineTokens = this.model.getLineTokens(lineNumber); const lineContent = lineTokens.getLineContent(); const startOffset = (lineNumber === startLineNumber ? startColumn - 1 : 0); const endOffset = (lineNumber === endLineNumber ? endColumn - 1 : lineContent.length); if (lineContent === '') { result += '<br>'; } else { result += tokenizeLineToHTML(lineContent, lineTokens.inflate(), colorMap, startOffset, endOffset, tabSize, platform.isWindows); } } return result; } private _getColorMap(): string[] { let colorMap = TokenizationRegistry.getColorMap(); let result: string[] = ['#000000']; if (colorMap) { for (let i = 1, len = colorMap.length; i < len; i++) { result[i] = Color.Format.CSS.formatHex(colorMap[i]); } } return result; } //#region model public pushStackElement(): void { this.model.pushStackElement(); } //#endregion //#region cursor operations public getPrimaryCursorState(): CursorState { return this._cursor.getPrimaryCursorState(); } public getLastAddedCursorIndex(): number { return this._cursor.getLastAddedCursorIndex(); } public getCursorStates(): CursorState[] { return this._cursor.getCursorStates(); } public setCursorStates(source: string | null | undefined, reason: CursorChangeReason, states: PartialCursorState[] | null): void { this._withViewEventsCollector(eventsCollector => this._cursor.setStates(eventsCollector, source, reason, states)); } public getCursorColumnSelectData(): IColumnSelectData { return this._cursor.getCursorColumnSelectData(); } public setCursorColumnSelectData(columnSelectData: IColumnSelectData): void { this._cursor.setCursorColumnSelectData(columnSelectData); } public getPrevEditOperationType(): EditOperationType { return this._cursor.getPrevEditOperationType(); } public setPrevEditOperationType(type: EditOperationType): void { this._cursor.setPrevEditOperationType(type); } public getSelection(): Selection { return this._cursor.getSelection(); } public getSelections(): Selection[] { return this._cursor.getSelections(); } public getPosition(): Position { return this._cursor.getPrimaryCursorState().modelState.position; } public setSelections(source: string | null | undefined, selections: readonly ISelection[]): void { this._withViewEventsCollector(eventsCollector => this._cursor.setSelections(eventsCollector, source, selections)); } public saveCursorState(): ICursorState[] { return this._cursor.saveState(); } public restoreCursorState(states: ICursorState[]): void { this._withViewEventsCollector(eventsCollector => this._cursor.restoreState(eventsCollector, states)); } private _executeCursorEdit(callback: (eventsCollector: ViewModelEventsCollector) => void): void { if (this._cursor.context.cursorConfig.readOnly) { // we cannot edit when read only... this._eventDispatcher.emitOutgoingEvent(new ReadOnlyEditAttemptEvent()); return; } this._withViewEventsCollector(callback); } public executeEdits(source: string | null | undefined, edits: IIdentifiedSingleEditOperation[], cursorStateComputer: ICursorStateComputer): void { this._executeCursorEdit(eventsCollector => this._cursor.executeEdits(eventsCollector, source, edits, cursorStateComputer)); } public startComposition(): void { this._cursor.setIsDoingComposition(true); this._executeCursorEdit(eventsCollector => this._cursor.startComposition(eventsCollector)); } public endComposition(source?: string | null | undefined): void { this._cursor.setIsDoingComposition(false); this._executeCursorEdit(eventsCollector => this._cursor.endComposition(eventsCollector, source)); } public type(text: string, source?: string | null | undefined): void { this._executeCursorEdit(eventsCollector => this._cursor.type(eventsCollector, text, source)); } public replacePreviousChar(text: string, replaceCharCnt: number, source?: string | null | undefined): void { this._executeCursorEdit(eventsCollector => this._cursor.replacePreviousChar(eventsCollector, text, replaceCharCnt, source)); } public paste(text: string, pasteOnNewLine: boolean, multicursorText?: string[] | null | undefined, source?: string | null | undefined): void { this._executeCursorEdit(eventsCollector => this._cursor.paste(eventsCollector, text, pasteOnNewLine, multicursorText, source)); } public cut(source?: string | null | undefined): void { this._executeCursorEdit(eventsCollector => this._cursor.cut(eventsCollector, source)); } public executeCommand(command: ICommand, source?: string | null | undefined): void { this._executeCursorEdit(eventsCollector => this._cursor.executeCommand(eventsCollector, command, source)); } public executeCommands(commands: ICommand[], source?: string | null | undefined): void { this._executeCursorEdit(eventsCollector => this._cursor.executeCommands(eventsCollector, commands, source)); } public revealPrimaryCursor(source: string | null | undefined, revealHorizontal: boolean): void { this._withViewEventsCollector(eventsCollector => this._cursor.revealPrimary(eventsCollector, source, revealHorizontal, ScrollType.Smooth)); } public revealTopMostCursor(source: string | null | undefined): void { const viewPosition = this._cursor.getTopMostViewPosition(); const viewRange = new Range(viewPosition.lineNumber, viewPosition.column, viewPosition.lineNumber, viewPosition.column); this._withViewEventsCollector(eventsCollector => eventsCollector.emitViewEvent(new viewEvents.ViewRevealRangeRequestEvent(source, viewRange, null, viewEvents.VerticalRevealType.Simple, true, ScrollType.Smooth))); } public revealBottomMostCursor(source: string | null | undefined): void { const viewPosition = this._cursor.getBottomMostViewPosition(); const viewRange = new Range(viewPosition.lineNumber, viewPosition.column, viewPosition.lineNumber, viewPosition.column); this._withViewEventsCollector(eventsCollector => eventsCollector.emitViewEvent(new viewEvents.ViewRevealRangeRequestEvent(source, viewRange, null, viewEvents.VerticalRevealType.Simple, true, ScrollType.Smooth))); } public revealRange(source: string | null | undefined, revealHorizontal: boolean, viewRange: Range, verticalType: viewEvents.VerticalRevealType, scrollType: ScrollType): void { this._withViewEventsCollector(eventsCollector => eventsCollector.emitViewEvent(new viewEvents.ViewRevealRangeRequestEvent(source, viewRange, null, verticalType, revealHorizontal, scrollType))); } //#endregion //#region viewLayout public getVerticalOffsetForLineNumber(viewLineNumber: number): number { return this.viewLayout.getVerticalOffsetForLineNumber(viewLineNumber); } public getScrollTop(): number { return this.viewLayout.getCurrentScrollTop(); } public setScrollTop(newScrollTop: number, scrollType: ScrollType): void { this.viewLayout.setScrollPosition({ scrollTop: newScrollTop }, scrollType); } public setScrollPosition(position: INewScrollPosition, type: ScrollType): void { this.viewLayout.setScrollPosition(position, type); } public deltaScrollNow(deltaScrollLeft: number, deltaScrollTop: number): void { this.viewLayout.deltaScrollNow(deltaScrollLeft, deltaScrollTop); } public changeWhitespace(callback: (accessor: IWhitespaceChangeAccessor) => void): void { const hadAChange = this.viewLayout.changeWhitespace(callback); if (hadAChange) { this._eventDispatcher.emitSingleViewEvent(new viewEvents.ViewZonesChangedEvent()); this._eventDispatcher.emitOutgoingEvent(new ViewZonesChangedEvent()); } } public setMaxLineWidth(maxLineWidth: number): void { this.viewLayout.setMaxLineWidth(maxLineWidth); } //#endregion private _withViewEventsCollector(callback: (eventsCollector: ViewModelEventsCollector) => void): void { try { const eventsCollector = this._eventDispatcher.beginEmitViewEvents(); callback(eventsCollector); } finally { this._eventDispatcher.endEmitViewEvents(); } } }
src/vs/editor/common/viewModel/viewModelImpl.ts
0
https://github.com/microsoft/vscode/commit/9504dda6a717a0a0d45d992e21f2565f8a23f390
[ 0.00017856918566394597, 0.00017354216834064573, 0.00016264084842987359, 0.00017405254766345024, 0.000002581527951406315 ]
{ "id": 0, "code_window": [ "/*---------------------------------------------------------------------------------------------\n", " * Copyright (c) Microsoft Corporation. All rights reserved.\n", " * Licensed under the MIT License. See License.txt in the project root for license information.\n", " *--------------------------------------------------------------------------------------------*/\n", "\n", "import { INotebookEditor, NOTEBOOK_EDITOR_FOCUSED, NOTEBOOK_IS_ACTIVE_EDITOR, NOTEBOOK_HAS_MULTIPLE_KERNELS } from 'vs/workbench/contrib/notebook/browser/notebookBrowser';\n", "import { IEditorService } from 'vs/workbench/services/editor/common/editorService';\n", "import { IQuickInputService, QuickPickInput, IQuickPickItem } from 'vs/platform/quickinput/common/quickInput';\n", "import { INotebookService } from 'vs/workbench/contrib/notebook/common/notebookService';\n", "import * as nls from 'vs/nls';\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/contrib/notebook/browser/contrib/status/editorStatus.ts", "type": "replace", "edit_start_line_idx": 5 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ //@ts-check 'use strict'; const withDefaults = require('../shared.webpack.config'); module.exports = withDefaults({ context: __dirname, entry: { main: './src/main.ts', }, resolve: { mainFields: ['module', 'main'] } });
extensions/jake/extension.webpack.config.js
0
https://github.com/microsoft/vscode/commit/9504dda6a717a0a0d45d992e21f2565f8a23f390
[ 0.00017015542834997177, 0.0001676814426900819, 0.00016447219240944833, 0.00016841669275891036, 0.0000023777079150022473 ]
{ "id": 0, "code_window": [ "/*---------------------------------------------------------------------------------------------\n", " * Copyright (c) Microsoft Corporation. All rights reserved.\n", " * Licensed under the MIT License. See License.txt in the project root for license information.\n", " *--------------------------------------------------------------------------------------------*/\n", "\n", "import { INotebookEditor, NOTEBOOK_EDITOR_FOCUSED, NOTEBOOK_IS_ACTIVE_EDITOR, NOTEBOOK_HAS_MULTIPLE_KERNELS } from 'vs/workbench/contrib/notebook/browser/notebookBrowser';\n", "import { IEditorService } from 'vs/workbench/services/editor/common/editorService';\n", "import { IQuickInputService, QuickPickInput, IQuickPickItem } from 'vs/platform/quickinput/common/quickInput';\n", "import { INotebookService } from 'vs/workbench/contrib/notebook/common/notebookService';\n", "import * as nls from 'vs/nls';\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/contrib/notebook/browser/contrib/status/editorStatus.ts", "type": "replace", "edit_start_line_idx": 5 }
{ "name": "ini", "displayName": "%displayName%", "description": "%description%", "version": "1.0.0", "publisher": "vscode", "license": "MIT", "engines": { "vscode": "*" }, "scripts": { "update-grammar": "node ../../build/npm/update-grammar.js textmate/ini.tmbundle Syntaxes/Ini.plist ./syntaxes/ini.tmLanguage.json" }, "contributes": { "languages": [{ "id": "ini", "extensions": [ ".ini"], "aliases": [ "Ini", "ini" ], "configuration": "./ini.language-configuration.json" }, { "id": "properties", "extensions": [ ".properties", ".cfg", ".conf", ".directory" ], "filenames": [ ".gitattributes", ".gitconfig", "gitconfig", ".gitmodules", ".editorconfig" ], "filenamePatterns": [ "**/.config/git/config", "**/.git/config" ], "aliases": [ "Properties", "properties" ], "configuration": "./properties.language-configuration.json" }], "grammars": [{ "language": "ini", "scopeName": "source.ini", "path": "./syntaxes/ini.tmLanguage.json" },{ "language": "properties", "scopeName": "source.ini", "path": "./syntaxes/ini.tmLanguage.json" }] } }
extensions/ini/package.json
0
https://github.com/microsoft/vscode/commit/9504dda6a717a0a0d45d992e21f2565f8a23f390
[ 0.00017621490405872464, 0.00017320884217042476, 0.00017147194012068212, 0.00017257426225114614, 0.000001835247303461074 ]
{ "id": 1, "code_window": [ "import * as nls from 'vs/nls';\n", "import { registerAction2, Action2, MenuId } from 'vs/platform/actions/common/actions';\n", "import { NOTEBOOK_ACTIONS_CATEGORY, INotebookCellActionContext } from 'vs/workbench/contrib/notebook/browser/contrib/coreActions';\n", "import { ContextKeyExpr } from 'vs/platform/contextkey/common/contextkey';\n", "import { ServicesAccessor } from 'vs/platform/instantiation/common/instantiation';\n" ], "labels": [ "keep", "replace", "replace", "replace", "keep" ], "after_edit": [ "import { Action2, MenuId, registerAction2 } from 'vs/platform/actions/common/actions';\n" ], "file_path": "src/vs/workbench/contrib/notebook/browser/contrib/status/editorStatus.ts", "type": "replace", "edit_start_line_idx": 10 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { getZoomLevel } from 'vs/base/browser/browser'; import * as DOM from 'vs/base/browser/dom'; import { IMouseWheelEvent, StandardMouseEvent } from 'vs/base/browser/mouseEvent'; import { CancellationTokenSource } from 'vs/base/common/cancellation'; import { Color, RGBA } from 'vs/base/common/color'; import { onUnexpectedError } from 'vs/base/common/errors'; import { Emitter, Event } from 'vs/base/common/event'; import { combinedDisposable, DisposableStore, Disposable, IDisposable, toDisposable } from 'vs/base/common/lifecycle'; import 'vs/css!./media/notebook'; import { ICodeEditor } from 'vs/editor/browser/editorBrowser'; import { IEditorOptions } from 'vs/editor/common/config/editorOptions'; import { BareFontInfo } from 'vs/editor/common/config/fontInfo'; import { Range } from 'vs/editor/common/core/range'; import { IEditor } from 'vs/editor/common/editorCommon'; import * as nls from 'vs/nls'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IContextKey, IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { IResourceEditorInput } from 'vs/platform/editor/common/editor'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage'; import { contrastBorder, editorBackground, focusBorder, foreground, registerColor, textBlockQuoteBackground, textBlockQuoteBorder, textLinkActiveForeground, textLinkForeground, textPreformatForeground, errorForeground, transparent, widgetShadow, listFocusBackground, listInactiveSelectionBackground, scrollbarSliderBackground, scrollbarSliderHoverBackground, scrollbarSliderActiveBackground } from 'vs/platform/theme/common/colorRegistry'; import { registerThemingParticipant } from 'vs/platform/theme/common/themeService'; import { EditorMemento } from 'vs/workbench/browser/parts/editor/baseEditor'; import { EditorOptions, IEditorMemento } from 'vs/workbench/common/editor'; import { CELL_MARGIN, CELL_RUN_GUTTER, EDITOR_BOTTOM_PADDING, EDITOR_TOP_MARGIN, EDITOR_TOP_PADDING, SCROLLABLE_ELEMENT_PADDING_TOP, BOTTOM_CELL_TOOLBAR_HEIGHT, CELL_BOTTOM_MARGIN, CODE_CELL_LEFT_MARGIN } from 'vs/workbench/contrib/notebook/browser/constants'; import { CellEditState, CellFocusMode, ICellRange, ICellViewModel, INotebookCellList, INotebookEditor, INotebookEditorContribution, INotebookEditorMouseEvent, NotebookLayoutInfo, NOTEBOOK_EDITOR_EDITABLE, NOTEBOOK_EDITOR_EXECUTING_NOTEBOOK, NOTEBOOK_EDITOR_FOCUSED, NOTEBOOK_EDITOR_RUNNABLE, NOTEBOOK_HAS_MULTIPLE_KERNELS, NOTEBOOK_OUTPUT_FOCUSED } from 'vs/workbench/contrib/notebook/browser/notebookBrowser'; import { NotebookEditorExtensionsRegistry } from 'vs/workbench/contrib/notebook/browser/notebookEditorExtensions'; import { NotebookCellList } from 'vs/workbench/contrib/notebook/browser/view/notebookCellList'; import { OutputRenderer } from 'vs/workbench/contrib/notebook/browser/view/output/outputRenderer'; import { BackLayerWebView } from 'vs/workbench/contrib/notebook/browser/view/renderers/backLayerWebView'; import { CellDragAndDropController, CodeCellRenderer, MarkdownCellRenderer, NotebookCellListDelegate } from 'vs/workbench/contrib/notebook/browser/view/renderers/cellRenderer'; import { CodeCellViewModel } from 'vs/workbench/contrib/notebook/browser/viewModel/codeCellViewModel'; import { NotebookEventDispatcher, NotebookLayoutChangedEvent } from 'vs/workbench/contrib/notebook/browser/viewModel/eventDispatcher'; import { CellViewModel, IModelDecorationsChangeAccessor, INotebookEditorViewState, NotebookViewModel } from 'vs/workbench/contrib/notebook/browser/viewModel/notebookViewModel'; import { CellKind, IProcessedOutput, INotebookKernelInfo, INotebookKernelInfoDto } from 'vs/workbench/contrib/notebook/common/notebookCommon'; import { INotebookService } from 'vs/workbench/contrib/notebook/common/notebookService'; import { Webview } from 'vs/workbench/contrib/webview/browser/webview'; import { IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService'; import { ILayoutService } from 'vs/platform/layout/browser/layoutService'; import { generateUuid } from 'vs/base/common/uuid'; import { Memento, MementoObject } from 'vs/workbench/common/memento'; import { NotebookTextModel } from 'vs/workbench/contrib/notebook/common/model/notebookTextModel'; import { URI } from 'vs/base/common/uri'; import { PANEL_BORDER } from 'vs/workbench/common/theme'; import { debugIconStartForeground } from 'vs/workbench/contrib/debug/browser/debugToolBar'; import { CellContextKeyManager } from 'vs/workbench/contrib/notebook/browser/view/renderers/cellContextKeys'; const $ = DOM.$; export class NotebookEditorOptions extends EditorOptions { readonly cellOptions?: IResourceEditorInput; constructor(options: Partial<NotebookEditorOptions>) { super(); this.overwrite(options); this.cellOptions = options.cellOptions; } with(options: Partial<NotebookEditorOptions>): NotebookEditorOptions { return new NotebookEditorOptions({ ...this, ...options }); } } export class NotebookEditorWidget extends Disposable implements INotebookEditor { static readonly ID: string = 'workbench.editor.notebook'; private static readonly EDITOR_MEMENTOS = new Map<string, EditorMemento<unknown>>(); private _overlayContainer!: HTMLElement; private _body!: HTMLElement; private _webview: BackLayerWebView | null = null; private _webviewTransparentCover: HTMLElement | null = null; private _list: INotebookCellList | undefined; private _dndController: CellDragAndDropController | null = null; private _renderedEditors: Map<ICellViewModel, ICodeEditor | undefined> = new Map(); private _eventDispatcher: NotebookEventDispatcher | undefined; private _notebookViewModel: NotebookViewModel | undefined; private _localStore: DisposableStore = this._register(new DisposableStore()); private _fontInfo: BareFontInfo | undefined; private _dimension: DOM.Dimension | null = null; private _shadowElementViewInfo: { height: number, width: number, top: number; left: number; } | null = null; private _editorFocus: IContextKey<boolean> | null = null; private _outputFocus: IContextKey<boolean> | null = null; private _editorEditable: IContextKey<boolean> | null = null; private _editorRunnable: IContextKey<boolean> | null = null; private _editorExecutingNotebook: IContextKey<boolean> | null = null; private _notebookHasMultipleKernels: IContextKey<boolean> | null = null; private _outputRenderer: OutputRenderer; protected readonly _contributions: { [key: string]: INotebookEditorContribution; }; private _scrollBeyondLastLine: boolean; private readonly _memento: Memento; private readonly _onDidFocusEmitter = this._register(new Emitter<void>()); public readonly onDidFocus = this._onDidFocusEmitter.event; private _cellContextKeyManager: CellContextKeyManager | null = null; private _isVisible = false; private readonly _uuid = generateUuid(); private _webiewFocused: boolean = false; private _isDisposed: boolean = false; get isDisposed() { return this._isDisposed; } private readonly _onDidChangeModel = this._register(new Emitter<NotebookTextModel | undefined>()); readonly onDidChangeModel: Event<NotebookTextModel | undefined> = this._onDidChangeModel.event; private readonly _onDidFocusEditorWidget = this._register(new Emitter<void>()); readonly onDidFocusEditorWidget = this._onDidFocusEditorWidget.event; set viewModel(newModel: NotebookViewModel | undefined) { this._notebookViewModel = newModel; this._onDidChangeModel.fire(newModel?.notebookDocument); } get viewModel() { return this._notebookViewModel; } get uri() { return this._notebookViewModel?.uri; } get textModel() { return this._notebookViewModel?.notebookDocument; } private _activeKernel: INotebookKernelInfo | undefined = undefined; private readonly _onDidChangeKernel = this._register(new Emitter<void>()); readonly onDidChangeKernel: Event<void> = this._onDidChangeKernel.event; get activeKernel() { return this._activeKernel; } set activeKernel(kernel: INotebookKernelInfo | undefined) { if (this._isDisposed) { return; } this._activeKernel = kernel; this._onDidChangeKernel.fire(); } private readonly _onDidChangeActiveEditor = this._register(new Emitter<this>()); readonly onDidChangeActiveEditor: Event<this> = this._onDidChangeActiveEditor.event; get activeCodeEditor(): IEditor | undefined { if (this._isDisposed) { return; } const [focused] = this._list!.getFocusedElements(); return this._renderedEditors.get(focused); } constructor( @IInstantiationService private readonly instantiationService: IInstantiationService, @IStorageService storageService: IStorageService, @INotebookService private notebookService: INotebookService, @IConfigurationService private readonly configurationService: IConfigurationService, @IContextKeyService readonly contextKeyService: IContextKeyService, @ILayoutService private readonly layoutService: ILayoutService ) { super(); this._memento = new Memento(NotebookEditorWidget.ID, storageService); this._outputRenderer = new OutputRenderer(this, this.instantiationService); this._contributions = {}; this._scrollBeyondLastLine = this.configurationService.getValue<boolean>('editor.scrollBeyondLastLine'); this.configurationService.onDidChangeConfiguration(e => { if (e.affectsConfiguration('editor.scrollBeyondLastLine')) { this._scrollBeyondLastLine = this.configurationService.getValue<boolean>('editor.scrollBeyondLastLine'); if (this._dimension && this._isVisible) { this.layout(this._dimension); } } }); this.notebookService.addNotebookEditor(this); } public getId(): string { return this._uuid; } hasModel() { return !!this._notebookViewModel; } //#region Editor Core protected getEditorMemento<T>(editorGroupService: IEditorGroupsService, key: string, limit: number = 10): IEditorMemento<T> { const mementoKey = `${NotebookEditorWidget.ID}${key}`; let editorMemento = NotebookEditorWidget.EDITOR_MEMENTOS.get(mementoKey); if (!editorMemento) { editorMemento = new EditorMemento(NotebookEditorWidget.ID, key, this.getMemento(StorageScope.WORKSPACE), limit, editorGroupService); NotebookEditorWidget.EDITOR_MEMENTOS.set(mementoKey, editorMemento); } return editorMemento as IEditorMemento<T>; } protected getMemento(scope: StorageScope): MementoObject { return this._memento.getMemento(scope); } public get isNotebookEditor() { return true; } updateEditorFocus() { // Note - focus going to the webview will fire 'blur', but the webview element will be // a descendent of the notebook editor root. const focused = DOM.isAncestor(document.activeElement, this._overlayContainer); this._editorFocus?.set(focused); this._notebookViewModel?.setFocus(focused); } hasFocus() { return this._editorFocus?.get() || false; } createEditor(): void { this._overlayContainer = document.createElement('div'); const id = generateUuid(); this._overlayContainer.id = `notebook-${id}`; this._overlayContainer.className = 'notebookOverlay'; DOM.addClass(this._overlayContainer, 'notebook-editor'); this._overlayContainer.style.visibility = 'hidden'; this.layoutService.container.appendChild(this._overlayContainer); this._createBody(this._overlayContainer); this._generateFontInfo(); this._editorFocus = NOTEBOOK_EDITOR_FOCUSED.bindTo(this.contextKeyService); this._editorFocus.set(true); this._isVisible = true; this._outputFocus = NOTEBOOK_OUTPUT_FOCUSED.bindTo(this.contextKeyService); this._editorEditable = NOTEBOOK_EDITOR_EDITABLE.bindTo(this.contextKeyService); this._editorEditable.set(true); this._editorRunnable = NOTEBOOK_EDITOR_RUNNABLE.bindTo(this.contextKeyService); this._editorRunnable.set(true); this._editorExecutingNotebook = NOTEBOOK_EDITOR_EXECUTING_NOTEBOOK.bindTo(this.contextKeyService); this._notebookHasMultipleKernels = NOTEBOOK_HAS_MULTIPLE_KERNELS.bindTo(this.contextKeyService); this._notebookHasMultipleKernels.set(false); const contributions = NotebookEditorExtensionsRegistry.getEditorContributions(); for (const desc of contributions) { try { const contribution = this.instantiationService.createInstance(desc.ctor, this); this._contributions[desc.id] = contribution; } catch (err) { onUnexpectedError(err); } } } private _generateFontInfo(): void { const editorOptions = this.configurationService.getValue<IEditorOptions>('editor'); this._fontInfo = BareFontInfo.createFromRawSettings(editorOptions, getZoomLevel()); } private _createBody(parent: HTMLElement): void { this._body = document.createElement('div'); DOM.addClass(this._body, 'cell-list-container'); this._createCellList(); DOM.append(parent, this._body); } private _createCellList(): void { DOM.addClass(this._body, 'cell-list-container'); this._dndController = this._register(new CellDragAndDropController(this, this._body)); const getScopedContextKeyService = (container?: HTMLElement) => this._list!.contextKeyService.createScoped(container); const renderers = [ this.instantiationService.createInstance(CodeCellRenderer, this, this._renderedEditors, this._dndController, getScopedContextKeyService), this.instantiationService.createInstance(MarkdownCellRenderer, this, this._dndController, this._renderedEditors, getScopedContextKeyService), ]; this._list = this.instantiationService.createInstance( NotebookCellList, 'NotebookCellList', this._body, this.instantiationService.createInstance(NotebookCellListDelegate), renderers, this.contextKeyService, { setRowLineHeight: false, setRowHeight: false, supportDynamicHeights: true, horizontalScrolling: false, keyboardSupport: false, mouseSupport: true, multipleSelectionSupport: false, enableKeyboardNavigation: true, additionalScrollHeight: 0, transformOptimization: false, styleController: (_suffix: string) => { return this._list!; }, overrideStyles: { listBackground: editorBackground, listActiveSelectionBackground: editorBackground, listActiveSelectionForeground: foreground, listFocusAndSelectionBackground: editorBackground, listFocusAndSelectionForeground: foreground, listFocusBackground: editorBackground, listFocusForeground: foreground, listHoverForeground: foreground, listHoverBackground: editorBackground, listHoverOutline: focusBorder, listFocusOutline: focusBorder, listInactiveSelectionBackground: editorBackground, listInactiveSelectionForeground: foreground, listInactiveFocusBackground: editorBackground, listInactiveFocusOutline: editorBackground, }, accessibilityProvider: { getAriaLabel() { return null; }, getWidgetAriaLabel() { return nls.localize('notebookTreeAriaLabel', "Notebook"); } } }, ); this._dndController.setList(this._list); // create Webview this._register(this._list); this._register(combinedDisposable(...renderers)); // transparent cover this._webviewTransparentCover = DOM.append(this._list.rowsContainer, $('.webview-cover')); this._webviewTransparentCover.style.display = 'none'; this._register(DOM.addStandardDisposableGenericMouseDownListner(this._overlayContainer, (e: StandardMouseEvent) => { if (DOM.hasClass(e.target, 'slider') && this._webviewTransparentCover) { this._webviewTransparentCover.style.display = 'block'; } })); this._register(DOM.addStandardDisposableGenericMouseUpListner(this._overlayContainer, () => { if (this._webviewTransparentCover) { // no matter when this._webviewTransparentCover.style.display = 'none'; } })); this._register(this._list.onMouseDown(e => { if (e.element) { this._onMouseDown.fire({ event: e.browserEvent, target: e.element }); } })); this._register(this._list.onMouseUp(e => { if (e.element) { this._onMouseUp.fire({ event: e.browserEvent, target: e.element }); } })); this._register(this._list.onDidChangeFocus(_e => this._onDidChangeActiveEditor.fire(this))); const widgetFocusTracker = DOM.trackFocus(this.getDomNode()); this._register(widgetFocusTracker); this._register(widgetFocusTracker.onDidFocus(() => this._onDidFocusEmitter.fire())); } getDomNode() { return this._overlayContainer; } onWillHide() { this._isVisible = false; this._editorFocus?.set(false); this._overlayContainer.style.visibility = 'hidden'; this._overlayContainer.style.left = '-50000px'; } getInnerWebview(): Webview | undefined { return this._webview?.webview; } focus() { this._isVisible = true; this._editorFocus?.set(true); if (this._webiewFocused) { this._webview?.focusWebview(); } else { const focus = this._list?.getFocus()[0]; if (typeof focus === 'number') { const element = this._notebookViewModel!.viewCells[focus]; if (element.focusMode === CellFocusMode.Editor) { element.editState = CellEditState.Editing; element.focusMode = CellFocusMode.Editor; this._onDidFocusEditorWidget.fire(); return; } } this._list?.domFocus(); } this._onDidFocusEditorWidget.fire(); } async setModel(textModel: NotebookTextModel, viewState: INotebookEditorViewState | undefined): Promise<void> { if (this._notebookViewModel === undefined || !this._notebookViewModel.equal(textModel)) { this._detachModel(); await this._attachModel(textModel, viewState); } else { this.restoreListViewState(viewState); } // clear state this._dndController?.clearGlobalDragState(); this._setKernels(textModel); this._localStore.add(this.notebookService.onDidChangeKernels(() => { if (this.activeKernel === undefined) { this._setKernels(textModel); } })); this._localStore.add(this._list!.onDidChangeFocus(() => { const focused = this._list!.getFocusedElements()[0]; if (focused) { if (!this._cellContextKeyManager) { this._cellContextKeyManager = this._localStore.add(new CellContextKeyManager(this.contextKeyService, textModel, focused as CellViewModel)); } this._cellContextKeyManager.updateForElement(focused as CellViewModel); } })); } async setOptions(options: NotebookEditorOptions | undefined) { // reveal cell if editor options tell to do so if (options?.cellOptions) { const cellOptions = options.cellOptions; const cell = this._notebookViewModel!.viewCells.find(cell => cell.uri.toString() === cellOptions.resource.toString()); if (cell) { this.selectElement(cell); this.revealInCenterIfOutsideViewport(cell); const editor = this._renderedEditors.get(cell)!; if (editor) { if (cellOptions.options?.selection) { const { selection } = cellOptions.options; editor.setSelection({ ...selection, endLineNumber: selection.endLineNumber || selection.startLineNumber, endColumn: selection.endColumn || selection.startColumn }); editor.revealPositionInCenterIfOutsideViewport({ lineNumber: selection.startLineNumber, column: selection.startColumn }); } if (!cellOptions.options?.preserveFocus) { editor.focus(); } } } } else if (this._notebookViewModel && this._notebookViewModel.viewCells.length === 1 && this._notebookViewModel.viewCells[0].cellKind === CellKind.Code) { // there is only one code cell in the document const cell = this._notebookViewModel!.viewCells[0]; if (cell.getTextLength() === 0) { // the cell is empty, very likely a template cell, focus it this.selectElement(cell); await this.revealLineInCenterAsync(cell, 1); const editor = this._renderedEditors.get(cell)!; if (editor) { editor.focus(); } } } } private _detachModel() { this._localStore.clear(); this._list?.detachViewModel(); this.viewModel?.dispose(); // avoid event this._notebookViewModel = undefined; // this.webview?.clearInsets(); // this.webview?.clearPreloadsCache(); this._webview?.dispose(); this._webview?.element.remove(); this._webview = null; this._list?.clear(); } private _setKernels(textModel: NotebookTextModel) { const provider = this.notebookService.getContributedNotebookProviders(this.viewModel!.uri)[0]; const availableKernels = this.notebookService.getContributedNotebookKernels(textModel.viewType, textModel.uri); if (provider.kernel && availableKernels.length > 0) { this._notebookHasMultipleKernels!.set(true); } else if (availableKernels.length > 1) { this._notebookHasMultipleKernels!.set(true); } else { this._notebookHasMultipleKernels!.set(false); } if (provider && provider.kernel) { // it has a builtin kernel, don't automatically choose a kernel this._loadKernelPreloads(provider.providerExtensionLocation, provider.kernel); return; } // the provider doesn't have a builtin kernel, choose a kernel this.activeKernel = availableKernels[0]; if (this.activeKernel) { this._loadKernelPreloads(this.activeKernel.extensionLocation, this.activeKernel); } } private _loadKernelPreloads(extensionLocation: URI, kernel: INotebookKernelInfoDto) { if (kernel.preloads) { this._webview?.updateKernelPreloads([extensionLocation], kernel.preloads.map(preload => URI.revive(preload))); } } private _updateForMetadata(): void { this._editorEditable?.set(!!this.viewModel!.metadata?.editable); this._editorRunnable?.set(!!this.viewModel!.metadata?.runnable); DOM.toggleClass(this._overlayContainer, 'notebook-editor-editable', !!this.viewModel!.metadata?.editable); DOM.toggleClass(this.getDomNode(), 'notebook-editor-editable', !!this.viewModel!.metadata?.editable); } private async _createWebview(id: string, resource: URI): Promise<void> { this._webview = this.instantiationService.createInstance(BackLayerWebView, this, id, resource); // attach the webview container to the DOM tree first this._list?.rowsContainer.insertAdjacentElement('afterbegin', this._webview.element); await this._webview.createWebview(); this._webview.webview.onDidBlur(() => { this._outputFocus?.set(false); this.updateEditorFocus(); if (this._overlayContainer.contains(document.activeElement)) { this._webiewFocused = false; } }); this._webview.webview.onDidFocus(() => { this._outputFocus?.set(true); this.updateEditorFocus(); this._onDidFocusEmitter.fire(); if (this._overlayContainer.contains(document.activeElement)) { this._webiewFocused = true; } }); this._localStore.add(this._webview.onMessage(({ message, forRenderer }) => { if (this.viewModel) { this.notebookService.onDidReceiveMessage(this.viewModel.viewType, this.getId(), forRenderer, message); } })); } private async _attachModel(textModel: NotebookTextModel, viewState: INotebookEditorViewState | undefined) { await this._createWebview(this.getId(), textModel.uri); this._eventDispatcher = new NotebookEventDispatcher(); this.viewModel = this.instantiationService.createInstance(NotebookViewModel, textModel.viewType, textModel, this._eventDispatcher, this.getLayoutInfo()); this._eventDispatcher.emit([new NotebookLayoutChangedEvent({ width: true, fontInfo: true }, this.getLayoutInfo())]); this._updateForMetadata(); this._localStore.add(this._eventDispatcher.onDidChangeMetadata(() => { this._updateForMetadata(); })); // restore view states, including contributions { // restore view state this.viewModel.restoreEditorViewState(viewState); // contribution state restore const contributionsState = viewState?.contributionsState || {}; const keys = Object.keys(this._contributions); for (let i = 0, len = keys.length; i < len; i++) { const id = keys[i]; const contribution = this._contributions[id]; if (typeof contribution.restoreViewState === 'function') { contribution.restoreViewState(contributionsState[id]); } } } this._webview?.updateRendererPreloads(this.viewModel.renderers); this._localStore.add(this._list!.onWillScroll(e => { this._webview!.updateViewScrollTop(-e.scrollTop, []); this._webviewTransparentCover!.style.top = `${e.scrollTop}px`; })); this._localStore.add(this._list!.onDidChangeContentHeight(() => { DOM.scheduleAtNextAnimationFrame(() => { if (this._isDisposed) { return; } const scrollTop = this._list?.scrollTop || 0; const scrollHeight = this._list?.scrollHeight || 0; this._webview!.element.style.height = `${scrollHeight}px`; if (this._webview?.insetMapping) { let updateItems: { cell: CodeCellViewModel, output: IProcessedOutput, cellTop: number }[] = []; let removedItems: IProcessedOutput[] = []; this._webview?.insetMapping.forEach((value, key) => { const cell = value.cell; const viewIndex = this._list?.getViewIndex(cell); if (viewIndex === undefined) { return; } if (cell.outputs.indexOf(key) < 0) { // output is already gone removedItems.push(key); } const cellTop = this._list?.getAbsoluteTopOfElement(cell) || 0; if (this._webview!.shouldUpdateInset(cell, key, cellTop)) { updateItems.push({ cell: cell, output: key, cellTop: cellTop }); } }); removedItems.forEach(output => this._webview?.removeInset(output)); if (updateItems.length) { this._webview?.updateViewScrollTop(-scrollTop, updateItems); } } }); })); this._list!.attachViewModel(this.viewModel); this._localStore.add(this._list!.onDidRemoveOutput(output => { this.removeInset(output); })); this._localStore.add(this._list!.onDidHideOutput(output => { this.hideInset(output); })); this._list!.layout(); this._dndController?.clearGlobalDragState(); // restore list state at last, it must be after list layout this.restoreListViewState(viewState); } restoreListViewState(viewState: INotebookEditorViewState | undefined): void { if (viewState?.scrollPosition !== undefined) { this._list!.scrollTop = viewState!.scrollPosition.top; this._list!.scrollLeft = viewState!.scrollPosition.left; } else { this._list!.scrollTop = 0; this._list!.scrollLeft = 0; } const focusIdx = typeof viewState?.focus === 'number' ? viewState.focus : 0; if (focusIdx < this._list!.length) { this._list!.setFocus([focusIdx]); this._list!.setSelection([focusIdx]); } else if (this._list!.length > 0) { this._list!.setFocus([0]); } if (viewState?.editorFocused) { this._list?.focusView(); const cell = this._notebookViewModel?.viewCells[focusIdx]; if (cell) { cell.focusMode = CellFocusMode.Editor; } } } getEditorViewState(): INotebookEditorViewState { const state = this._notebookViewModel?.getEditorViewState(); if (!state) { return { editingCells: {}, editorViewStates: {} }; } if (this._list) { state.scrollPosition = { left: this._list.scrollLeft, top: this._list.scrollTop }; let cellHeights: { [key: number]: number } = {}; for (let i = 0; i < this.viewModel!.length; i++) { const elm = this.viewModel!.viewCells[i] as CellViewModel; if (elm.cellKind === CellKind.Code) { cellHeights[i] = elm.layoutInfo.totalHeight; } else { cellHeights[i] = 0; } } state.cellTotalHeights = cellHeights; const focus = this._list.getFocus()[0]; if (typeof focus === 'number') { const element = this._notebookViewModel!.viewCells[focus]; if (element) { const itemDOM = this._list?.domElementOfElement(element); let editorFocused = !!(document.activeElement && itemDOM && itemDOM.contains(document.activeElement)); state.editorFocused = editorFocused; state.focus = focus; } } } // Save contribution view states const contributionsState: { [key: string]: unknown } = {}; const keys = Object.keys(this._contributions); for (const id of keys) { const contribution = this._contributions[id]; if (typeof contribution.saveViewState === 'function') { contributionsState[id] = contribution.saveViewState(); } } state.contributionsState = contributionsState; return state; } // private saveEditorViewState(input: NotebookEditorInput): void { // if (this.group && this.notebookViewModel) { // } // } // private loadTextEditorViewState(): INotebookEditorViewState | undefined { // return this.editorMemento.loadEditorState(this.group, input.resource); // } layout(dimension: DOM.Dimension, shadowElement?: HTMLElement): void { if (!shadowElement && this._shadowElementViewInfo === null) { this._dimension = dimension; return; } if (shadowElement) { const containerRect = shadowElement.getBoundingClientRect(); this._shadowElementViewInfo = { height: containerRect.height, width: containerRect.width, top: containerRect.top, left: containerRect.left }; } this._dimension = new DOM.Dimension(dimension.width, dimension.height); DOM.size(this._body, dimension.width, dimension.height); this._list?.updateOptions({ additionalScrollHeight: this._scrollBeyondLastLine ? dimension.height - SCROLLABLE_ELEMENT_PADDING_TOP : 0 }); this._list?.layout(dimension.height - SCROLLABLE_ELEMENT_PADDING_TOP, dimension.width); this._overlayContainer.style.visibility = 'visible'; this._overlayContainer.style.display = 'block'; this._overlayContainer.style.position = 'absolute'; this._overlayContainer.style.top = `${this._shadowElementViewInfo!.top}px`; this._overlayContainer.style.left = `${this._shadowElementViewInfo!.left}px`; this._overlayContainer.style.width = `${dimension ? dimension.width : this._shadowElementViewInfo!.width}px`; this._overlayContainer.style.height = `${dimension ? dimension.height : this._shadowElementViewInfo!.height}px`; if (this._webviewTransparentCover) { this._webviewTransparentCover.style.height = `${dimension.height}px`; this._webviewTransparentCover.style.width = `${dimension.width}px`; } this._eventDispatcher?.emit([new NotebookLayoutChangedEvent({ width: true, fontInfo: true }, this.getLayoutInfo())]); } // protected saveState(): void { // if (this.input instanceof NotebookEditorInput) { // this.saveEditorViewState(this.input); // } // super.saveState(); // } //#endregion //#region Editor Features selectElement(cell: ICellViewModel) { this._list?.selectElement(cell); // this.viewModel!.selectionHandles = [cell.handle]; } revealInView(cell: ICellViewModel) { this._list?.revealElementInView(cell); } revealInCenterIfOutsideViewport(cell: ICellViewModel) { this._list?.revealElementInCenterIfOutsideViewport(cell); } revealInCenter(cell: ICellViewModel) { this._list?.revealElementInCenter(cell); } async revealLineInViewAsync(cell: ICellViewModel, line: number): Promise<void> { return this._list?.revealElementLineInViewAsync(cell, line); } async revealLineInCenterAsync(cell: ICellViewModel, line: number): Promise<void> { return this._list?.revealElementLineInCenterAsync(cell, line); } async revealLineInCenterIfOutsideViewportAsync(cell: ICellViewModel, line: number): Promise<void> { return this._list?.revealElementLineInCenterIfOutsideViewportAsync(cell, line); } async revealRangeInViewAsync(cell: ICellViewModel, range: Range): Promise<void> { return this._list?.revealElementRangeInViewAsync(cell, range); } async revealRangeInCenterAsync(cell: ICellViewModel, range: Range): Promise<void> { return this._list?.revealElementRangeInCenterAsync(cell, range); } async revealRangeInCenterIfOutsideViewportAsync(cell: ICellViewModel, range: Range): Promise<void> { return this._list?.revealElementRangeInCenterIfOutsideViewportAsync(cell, range); } setCellSelection(cell: ICellViewModel, range: Range): void { this._list?.setCellSelection(cell, range); } changeDecorations<T>(callback: (changeAccessor: IModelDecorationsChangeAccessor) => T): T | null { return this._notebookViewModel?.changeDecorations<T>(callback) || null; } setHiddenAreas(_ranges: ICellRange[]): boolean { return this._list!.setHiddenAreas(_ranges, true); } //#endregion //#region Mouse Events private readonly _onMouseUp: Emitter<INotebookEditorMouseEvent> = this._register(new Emitter<INotebookEditorMouseEvent>()); public readonly onMouseUp: Event<INotebookEditorMouseEvent> = this._onMouseUp.event; private readonly _onMouseDown: Emitter<INotebookEditorMouseEvent> = this._register(new Emitter<INotebookEditorMouseEvent>()); public readonly onMouseDown: Event<INotebookEditorMouseEvent> = this._onMouseDown.event; private pendingLayouts = new WeakMap<ICellViewModel, IDisposable>(); //#endregion //#region Cell operations async layoutNotebookCell(cell: ICellViewModel, height: number): Promise<void> { const viewIndex = this._list!.getViewIndex(cell); if (viewIndex === undefined) { // the cell is hidden return; } let relayout = (cell: ICellViewModel, height: number) => { if (this._isDisposed) { return; } this._list?.updateElementHeight2(cell, height); }; if (this.pendingLayouts.has(cell)) { this.pendingLayouts.get(cell)!.dispose(); } let r: () => void; const layoutDisposable = DOM.scheduleAtNextAnimationFrame(() => { if (this._isDisposed) { return; } this.pendingLayouts.delete(cell); relayout(cell, height); r(); }); this.pendingLayouts.set(cell, toDisposable(() => { layoutDisposable.dispose(); r(); })); return new Promise(resolve => { r = resolve; }); } insertNotebookCell(cell: ICellViewModel | undefined, type: CellKind, direction: 'above' | 'below' = 'above', initialText: string = '', ui: boolean = false): CellViewModel | null { if (!this._notebookViewModel!.metadata.editable) { return null; } const index = cell ? this._notebookViewModel!.getCellIndex(cell) : 0; const nextIndex = ui ? this._notebookViewModel!.getNextVisibleCellIndex(index) : index + 1; const newLanguages = this._notebookViewModel!.languages; const language = (cell?.cellKind === CellKind.Code && type === CellKind.Code) ? cell.language : ((type === CellKind.Code && newLanguages && newLanguages.length) ? newLanguages[0] : 'markdown'); const insertIndex = cell ? (direction === 'above' ? index : nextIndex) : index; const newCell = this._notebookViewModel!.createCell(insertIndex, initialText.split(/\r?\n/g), language, type, undefined, true); return newCell as CellViewModel; } async splitNotebookCell(cell: ICellViewModel): Promise<CellViewModel[] | null> { const index = this._notebookViewModel!.getCellIndex(cell); return this._notebookViewModel!.splitNotebookCell(index); } async joinNotebookCells(cell: ICellViewModel, direction: 'above' | 'below', constraint?: CellKind): Promise<ICellViewModel | null> { const index = this._notebookViewModel!.getCellIndex(cell); const ret = await this._notebookViewModel!.joinNotebookCells(index, direction, constraint); if (ret) { ret.deletedCells.forEach(cell => { if (this.pendingLayouts.has(cell)) { this.pendingLayouts.get(cell)!.dispose(); } }); return ret.cell; } else { return null; } } async deleteNotebookCell(cell: ICellViewModel): Promise<boolean> { if (!this._notebookViewModel!.metadata.editable) { return false; } if (this.pendingLayouts.has(cell)) { this.pendingLayouts.get(cell)!.dispose(); } const index = this._notebookViewModel!.getCellIndex(cell); this._notebookViewModel!.deleteCell(index, true); return true; } async moveCellDown(cell: ICellViewModel): Promise<ICellViewModel | null> { if (!this._notebookViewModel!.metadata.editable) { return null; } const index = this._notebookViewModel!.getCellIndex(cell); if (index === this._notebookViewModel!.length - 1) { return null; } const newIdx = index + 1; return this._moveCellToIndex(index, newIdx); } async moveCellUp(cell: ICellViewModel): Promise<ICellViewModel | null> { if (!this._notebookViewModel!.metadata.editable) { return null; } const index = this._notebookViewModel!.getCellIndex(cell); if (index === 0) { return null; } const newIdx = index - 1; return this._moveCellToIndex(index, newIdx); } async moveCell(cell: ICellViewModel, relativeToCell: ICellViewModel, direction: 'above' | 'below'): Promise<ICellViewModel | null> { if (!this._notebookViewModel!.metadata.editable) { return null; } if (cell === relativeToCell) { return null; } const originalIdx = this._notebookViewModel!.getCellIndex(cell); const relativeToIndex = this._notebookViewModel!.getCellIndex(relativeToCell); let newIdx = direction === 'above' ? relativeToIndex : relativeToIndex + 1; if (originalIdx < newIdx) { newIdx--; } return this._moveCellToIndex(originalIdx, newIdx); } private async _moveCellToIndex(index: number, newIdx: number): Promise<ICellViewModel | null> { if (index === newIdx) { return null; } if (!this._notebookViewModel!.moveCellToIdx(index, newIdx, true)) { throw new Error('Notebook Editor move cell, index out of range'); } let r: (val: ICellViewModel | null) => void; DOM.scheduleAtNextAnimationFrame(() => { if (this._isDisposed) { r(null); } const viewCell = this._notebookViewModel!.viewCells[newIdx]; this._list?.revealElementInView(viewCell); r(viewCell); }); return new Promise(resolve => { r = resolve; }); } editNotebookCell(cell: CellViewModel): void { if (!cell.getEvaluatedMetadata(this._notebookViewModel!.metadata).editable) { return; } cell.editState = CellEditState.Editing; this._renderedEditors.get(cell)?.focus(); } getActiveCell() { let elements = this._list?.getFocusedElements(); if (elements && elements.length) { return elements[0]; } return undefined; } cancelNotebookExecution(): void { if (!this._notebookViewModel!.currentTokenSource) { throw new Error('Notebook is not executing'); } this._notebookViewModel!.currentTokenSource.cancel(); this._notebookViewModel!.currentTokenSource = undefined; } async executeNotebook(): Promise<void> { if (!this._notebookViewModel!.metadata.runnable) { return; } return this._executeNotebook(); } async _executeNotebook(): Promise<void> { if (this._notebookViewModel!.currentTokenSource) { return; } const tokenSource = new CancellationTokenSource(); try { this._editorExecutingNotebook!.set(true); this._notebookViewModel!.currentTokenSource = tokenSource; const provider = this.notebookService.getContributedNotebookProviders(this.viewModel!.uri)[0]; if (provider) { const viewType = provider.id; const notebookUri = this._notebookViewModel!.uri; if (this._activeKernel) { await this.notebookService.executeNotebook2(this._notebookViewModel!.viewType, this._notebookViewModel!.uri, this._activeKernel.id, tokenSource.token); } else if (provider.kernel) { return await this.notebookService.executeNotebook(viewType, notebookUri, true, tokenSource.token); } else { return await this.notebookService.executeNotebook(viewType, notebookUri, false, tokenSource.token); } } } finally { this._editorExecutingNotebook!.set(false); this._notebookViewModel!.currentTokenSource = undefined; tokenSource.dispose(); } } cancelNotebookCellExecution(cell: ICellViewModel): void { if (!cell.currentTokenSource) { throw new Error('Cell is not executing'); } cell.currentTokenSource.cancel(); cell.currentTokenSource = undefined; } async executeNotebookCell(cell: ICellViewModel): Promise<void> { if (cell.cellKind === CellKind.Markdown) { this.focusNotebookCell(cell, 'container'); return; } if (!cell.getEvaluatedMetadata(this._notebookViewModel!.metadata).runnable) { return; } const tokenSource = new CancellationTokenSource(); try { await this._executeNotebookCell(cell, tokenSource); } finally { tokenSource.dispose(); } } private async _executeNotebookCell(cell: ICellViewModel, tokenSource: CancellationTokenSource): Promise<void> { try { cell.currentTokenSource = tokenSource; const provider = this.notebookService.getContributedNotebookProviders(this.viewModel!.uri)[0]; if (provider) { const viewType = provider.id; const notebookUri = this._notebookViewModel!.uri; if (this._activeKernel) { return await this.notebookService.executeNotebookCell2(viewType, notebookUri, cell.handle, this._activeKernel.id, tokenSource.token); } else if (provider.kernel) { return await this.notebookService.executeNotebookCell(viewType, notebookUri, cell.handle, true, tokenSource.token); } else { return await this.notebookService.executeNotebookCell(viewType, notebookUri, cell.handle, false, tokenSource.token); } } } finally { cell.currentTokenSource = undefined; } } focusNotebookCell(cell: ICellViewModel, focusItem: 'editor' | 'container' | 'output') { if (this._isDisposed) { return; } if (focusItem === 'editor') { this.selectElement(cell); this._list?.focusView(); cell.editState = CellEditState.Editing; cell.focusMode = CellFocusMode.Editor; this.revealInCenterIfOutsideViewport(cell); } else if (focusItem === 'output') { this.selectElement(cell); this._list?.focusView(); if (!this._webview) { return; } this._webview.focusOutput(cell.id); cell.editState = CellEditState.Preview; cell.focusMode = CellFocusMode.Container; this.revealInCenterIfOutsideViewport(cell); } else { let itemDOM = this._list?.domElementOfElement(cell); if (document.activeElement && itemDOM && itemDOM.contains(document.activeElement)) { (document.activeElement as HTMLElement).blur(); } cell.editState = CellEditState.Preview; cell.focusMode = CellFocusMode.Container; this.selectElement(cell); this.revealInCenterIfOutsideViewport(cell); this._list?.focusView(); } } //#endregion //#region MISC getLayoutInfo(): NotebookLayoutInfo { if (!this._list) { throw new Error('Editor is not initalized successfully'); } return { width: this._dimension!.width, height: this._dimension!.height, fontInfo: this._fontInfo! }; } triggerScroll(event: IMouseWheelEvent) { this._list?.triggerScrollFromMouseWheelEvent(event); } async createInset(cell: CodeCellViewModel, output: IProcessedOutput, shadowContent: string, offset: number) { if (!this._webview) { return; } let preloads = this._notebookViewModel!.renderers; if (!this._webview!.insetMapping.has(output)) { let cellTop = this._list?.getAbsoluteTopOfElement(cell) || 0; await this._webview!.createInset(cell, output, cellTop, offset, shadowContent, preloads); } else { let cellTop = this._list?.getAbsoluteTopOfElement(cell) || 0; let scrollTop = this._list?.scrollTop || 0; this._webview!.updateViewScrollTop(-scrollTop, [{ cell: cell, output: output, cellTop: cellTop }]); } } removeInset(output: IProcessedOutput) { if (!this._webview) { return; } this._webview!.removeInset(output); } hideInset(output: IProcessedOutput) { if (!this._webview) { return; } this._webview!.hideInset(output); } getOutputRenderer(): OutputRenderer { return this._outputRenderer; } postMessage(forRendererId: string | undefined, message: any) { if (forRendererId === undefined) { this._webview?.webview.postMessage(message); } else { this._webview?.postRendererMessage(forRendererId, message); } } toggleClassName(className: string) { DOM.toggleClass(this._overlayContainer, className); } addClassName(className: string) { DOM.addClass(this._overlayContainer, className); } removeClassName(className: string) { DOM.removeClass(this._overlayContainer, className); } //#endregion //#region Editor Contributions public getContribution<T extends INotebookEditorContribution>(id: string): T { return <T>(this._contributions[id] || null); } //#endregion dispose() { this._isDisposed = true; // dispose webview first this._webview?.dispose(); this.notebookService.removeNotebookEditor(this); const keys = Object.keys(this._contributions); for (let i = 0, len = keys.length; i < len; i++) { const contributionId = keys[i]; this._contributions[contributionId].dispose(); } this._localStore.clear(); this._list?.dispose(); this._overlayContainer.remove(); this.viewModel?.dispose(); // this._layoutService.container.removeChild(this.overlayContainer); super.dispose(); } toJSON(): object { return { notebookHandle: this.viewModel?.handle }; } } export const notebookCellBorder = registerColor('notebook.cellBorderColor', { dark: transparent(PANEL_BORDER, .4), light: transparent(listInactiveSelectionBackground, 1), hc: PANEL_BORDER }, nls.localize('notebook.cellBorderColor', "The border color for notebook cells.")); export const focusedEditorBorderColor = registerColor('notebook.focusedEditorBorder', { light: focusBorder, dark: focusBorder, hc: focusBorder }, nls.localize('notebook.focusedEditorBorder', "The color of the notebook cell editor border.")); export const cellStatusIconSuccess = registerColor('notebookStatusSuccessIcon.foreground', { light: debugIconStartForeground, dark: debugIconStartForeground, hc: debugIconStartForeground }, nls.localize('notebookStatusSuccessIcon.foreground', "The error icon color of notebook cells in the cell status bar.")); export const cellStatusIconError = registerColor('notebookStatusErrorIcon.foreground', { light: errorForeground, dark: errorForeground, hc: errorForeground }, nls.localize('notebookStatusErrorIcon.foreground', "The error icon color of notebook cells in the cell status bar.")); export const cellStatusIconRunning = registerColor('notebookStatusRunningIcon.foreground', { light: foreground, dark: foreground, hc: foreground }, nls.localize('notebookStatusRunningIcon.foreground', "The running icon color of notebook cells in the cell status bar.")); export const notebookOutputContainerColor = registerColor('notebook.outputContainerBackgroundColor', { dark: notebookCellBorder, light: transparent(listFocusBackground, .4), hc: null }, nls.localize('notebook.outputContainerBackgroundColor', "The Color of the notebook output container background.")); // TODO currently also used for toolbar border, if we keep all of this, pick a generic name export const CELL_TOOLBAR_SEPERATOR = registerColor('notebook.cellToolbarSeperator', { dark: Color.fromHex('#808080').transparent(0.35), light: Color.fromHex('#808080').transparent(0.35), hc: contrastBorder }, nls.localize('notebook.cellToolbarSeperator', "The color of the seperator in the cell bottom toolbar")); export const focusedCellBackground = registerColor('notebook.focusedCellBackground', { dark: transparent(PANEL_BORDER, .4), light: transparent(listFocusBackground, .4), hc: null }, nls.localize('focusedCellBackground', "The background color of a cell when the cell is focused.")); export const cellHoverBackground = registerColor('notebook.cellHoverBackground', { dark: transparent(focusedCellBackground, .5), light: transparent(focusedCellBackground, .7), hc: null }, nls.localize('notebook.cellHoverBackground', "The background color of a cell when the cell is hovered.")); export const focusedCellBorder = registerColor('notebook.focusedCellBorder', { dark: Color.white.transparent(0.12), light: Color.black.transparent(0.12), hc: focusBorder }, nls.localize('notebook.focusedCellBorder', "The color of the cell's top and bottom border when the cell is focused.")); export const focusedCellShadow = registerColor('notebook.focusedCellShadow', { dark: transparent(widgetShadow, 0.6), light: transparent(widgetShadow, 0.4), hc: Color.transparent }, nls.localize('notebook.focusedCellShadow', "The color of the cell shadow when cells are focused.")); export const cellStatusBarItemHover = registerColor('notebook.cellStatusBarItemHoverBackground', { light: new Color(new RGBA(0, 0, 0, 0.08)), dark: new Color(new RGBA(255, 255, 255, 0.15)), hc: new Color(new RGBA(255, 255, 255, 0.15)), }, nls.localize('notebook.cellStatusBarItemHoverBackground', "The background color of notebook cell status bar items.")); export const cellInsertionIndicator = registerColor('notebook.cellInsertionIndicator', { light: focusBorder, dark: focusBorder, hc: focusBorder }, nls.localize('notebook.cellInsertionIndicator', "The color of the notebook cell insertion indicator.")); export const listScrollbarSliderBackground = registerColor('notebookScrollbarSlider.background', { dark: scrollbarSliderBackground, light: scrollbarSliderBackground, hc: scrollbarSliderBackground }, nls.localize('notebookScrollbarSliderBackground', "Notebook scrollbar slider background color.")); export const listScrollbarSliderHoverBackground = registerColor('notebookScrollbarSlider.hoverBackground', { dark: scrollbarSliderHoverBackground, light: scrollbarSliderHoverBackground, hc: scrollbarSliderHoverBackground }, nls.localize('notebookScrollbarSliderHoverBackground', "Notebook scrollbar slider background color when hovering.")); export const listScrollbarSliderActiveBackground = registerColor('notebookScrollbarSlider.activeBackground', { dark: scrollbarSliderActiveBackground, light: scrollbarSliderActiveBackground, hc: scrollbarSliderActiveBackground }, nls.localize('notebookScrollbarSliderActiveBackground', "Notebook scrollbar slider background color when clicked on.")); registerThemingParticipant((theme, collector) => { collector.addRule(`.notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element { padding-top: ${SCROLLABLE_ELEMENT_PADDING_TOP}px; box-sizing: border-box; }`); // const color = getExtraColor(theme, embeddedEditorBackground, { dark: 'rgba(0, 0, 0, .4)', extra_dark: 'rgba(200, 235, 255, .064)', light: '#f4f4f4', hc: null }); const color = theme.getColor(editorBackground); if (color) { collector.addRule(`.notebookOverlay .cell .monaco-editor-background, .notebookOverlay .cell .margin-view-overlays, .notebookOverlay .cell .cell-statusbar-container { background: ${color}; }`); collector.addRule(`.notebookOverlay .cell-drag-image .cell-editor-container > div { background: ${color} !important; }`); } const link = theme.getColor(textLinkForeground); if (link) { collector.addRule(`.notebookOverlay .output a, .notebookOverlay .cell.markdown a { color: ${link};} `); } const activeLink = theme.getColor(textLinkActiveForeground); if (activeLink) { collector.addRule(`.notebookOverlay .output a:hover, .notebookOverlay .cell .output a:active { color: ${activeLink}; }`); } const shortcut = theme.getColor(textPreformatForeground); if (shortcut) { collector.addRule(`.notebookOverlay code, .notebookOverlay .shortcut { color: ${shortcut}; }`); } const border = theme.getColor(contrastBorder); if (border) { collector.addRule(`.notebookOverlay .monaco-editor { border-color: ${border}; }`); } const quoteBackground = theme.getColor(textBlockQuoteBackground); if (quoteBackground) { collector.addRule(`.notebookOverlay blockquote { background: ${quoteBackground}; }`); } const quoteBorder = theme.getColor(textBlockQuoteBorder); if (quoteBorder) { collector.addRule(`.notebookOverlay blockquote { border-color: ${quoteBorder}; }`); } const containerBackground = theme.getColor(notebookOutputContainerColor); if (containerBackground) { collector.addRule(`.notebookOverlay .output { background-color: ${containerBackground}; }`); collector.addRule(`.notebookOverlay .output-element { background-color: ${containerBackground}; }`); } const editorBackgroundColor = theme.getColor(editorBackground); if (editorBackgroundColor) { collector.addRule(`.notebookOverlay .cell-statusbar-container { border-top: solid 1px ${editorBackgroundColor}; }`); collector.addRule(`.notebookOverlay .monaco-list-row > .monaco-toolbar { background-color: ${editorBackgroundColor}; }`); collector.addRule(`.notebookOverlay .monaco-list-row.cell-drag-image { background-color: ${editorBackgroundColor}; }`); } const cellToolbarSeperator = theme.getColor(CELL_TOOLBAR_SEPERATOR); if (cellToolbarSeperator) { collector.addRule(`.notebookOverlay .cell-bottom-toolbar-container .separator { background-color: ${cellToolbarSeperator} }`); collector.addRule(`.notebookOverlay .cell-bottom-toolbar-container .action-item:first-child::after { background-color: ${cellToolbarSeperator} }`); collector.addRule(`.notebookOverlay .monaco-list-row > .monaco-toolbar { border: solid 1px ${cellToolbarSeperator}; }`); } const focusedCellBackgroundColor = theme.getColor(focusedCellBackground); if (focusedCellBackgroundColor) { collector.addRule(`.notebookOverlay .code-cell-row.focused .cell-focus-indicator, .notebookOverlay .markdown-cell-row.focused { background-color: ${focusedCellBackgroundColor} !important; }`); } const cellHoverBackgroundColor = theme.getColor(cellHoverBackground); if (cellHoverBackgroundColor) { collector.addRule(`.notebookOverlay .code-cell-row:not(.focused):hover .cell-focus-indicator, .notebookOverlay .code-cell-row:not(.focused).cell-output-hover .cell-focus-indicator, .notebookOverlay .markdown-cell-row:not(.focused):hover { background-color: ${cellHoverBackgroundColor} !important; }`); } const focusedCellBorderColor = theme.getColor(focusedCellBorder); collector.addRule(`.monaco-workbench .notebookOverlay .monaco-list .monaco-list-row.focused .cell-focus-indicator-top:before, .monaco-workbench .notebookOverlay .monaco-list .monaco-list-row.focused .cell-focus-indicator-bottom:before, .monaco-workbench .notebookOverlay .monaco-list .markdown-cell-row.focused:before, .monaco-workbench .notebookOverlay .monaco-list .markdown-cell-row.focused:after { border-color: ${focusedCellBorderColor} !important; }`); const focusedEditorBorderColorColor = theme.getColor(focusedEditorBorderColor); if (focusedEditorBorderColorColor) { collector.addRule(`.notebookOverlay .monaco-list-row.cell-editor-focus .cell-editor-part:before { outline: solid 1px ${focusedEditorBorderColorColor}; }`); } const editorBorderColor = theme.getColor(notebookCellBorder); if (editorBorderColor) { collector.addRule(`.notebookOverlay .monaco-list-row .cell-editor-part:before { outline: solid 1px ${editorBorderColor}; }`); } const headingBorderColor = theme.getColor(notebookCellBorder); if (headingBorderColor) { collector.addRule(`.notebookOverlay .cell.markdown h1 { border-color: ${headingBorderColor}; }`); } const cellStatusSuccessIcon = theme.getColor(cellStatusIconSuccess); if (cellStatusSuccessIcon) { collector.addRule(`.monaco-workbench .notebookOverlay .cell-statusbar-container .cell-run-status .codicon-check { color: ${cellStatusSuccessIcon} }`); } const cellStatusErrorIcon = theme.getColor(cellStatusIconError); if (cellStatusErrorIcon) { collector.addRule(`.monaco-workbench .notebookOverlay .cell-statusbar-container .cell-run-status .codicon-error { color: ${cellStatusErrorIcon} }`); } const cellStatusRunningIcon = theme.getColor(cellStatusIconRunning); if (cellStatusRunningIcon) { collector.addRule(`.monaco-workbench .notebookOverlay .cell-statusbar-container .cell-run-status .codicon-sync { color: ${cellStatusRunningIcon} }`); } const cellStatusBarHoverBg = theme.getColor(cellStatusBarItemHover); if (cellStatusBarHoverBg) { collector.addRule(`.monaco-workbench .notebookOverlay .cell-statusbar-container .cell-language-picker:hover { background-color: ${cellStatusBarHoverBg}; }`); } const cellShadowColor = theme.getColor(focusedCellShadow); if (cellShadowColor) { // Code cells collector.addRule(`.monaco-workbench .notebookOverlay .monaco-list .monaco-list-row.focused .cell-shadow { box-shadow: 0px 0px 4px 2px ${cellShadowColor} }`); // Markdown cells collector.addRule(`.monaco-workbench .notebookOverlay .monaco-list .markdown-cell-row.focused { box-shadow: 0px 0px 4px 2px ${cellShadowColor} }`); } const cellInsertionIndicatorColor = theme.getColor(cellInsertionIndicator); if (cellInsertionIndicatorColor) { collector.addRule(`.notebookOverlay > .cell-list-container > .cell-list-insertion-indicator { background-color: ${cellInsertionIndicatorColor}; }`); } const scrollbarSliderBackgroundColor = theme.getColor(listScrollbarSliderBackground); if (scrollbarSliderBackgroundColor) { collector.addRule(` .notebookOverlay .cell-list-container > .monaco-list > .monaco-scrollable-element > .scrollbar > .slider { background: ${editorBackgroundColor}; } `); collector.addRule(` .notebookOverlay .cell-list-container > .monaco-list > .monaco-scrollable-element > .scrollbar > .slider:before { content: ""; width: 100%; height: 100%; position: absolute; background: ${scrollbarSliderBackgroundColor}; } `); /* hack to not have cells see through scroller */ } const scrollbarSliderHoverBackgroundColor = theme.getColor(listScrollbarSliderHoverBackground); if (scrollbarSliderHoverBackgroundColor) { collector.addRule(` .notebookOverlay .cell-list-container > .monaco-list > .monaco-scrollable-element > .scrollbar > .slider:hover { background: ${editorBackgroundColor}; } `); collector.addRule(` .notebookOverlay .cell-list-container > .monaco-list > .monaco-scrollable-element > .scrollbar > .slider:hover:before { content: ""; width: 100%; height: 100%; position: absolute; background: ${scrollbarSliderHoverBackgroundColor}; } `); /* hack to not have cells see through scroller */ } const scrollbarSliderActiveBackgroundColor = theme.getColor(listScrollbarSliderActiveBackground); if (scrollbarSliderActiveBackgroundColor) { collector.addRule(` .notebookOverlay .cell-list-container > .monaco-list > .monaco-scrollable-element > .scrollbar > .slider.active { background: ${editorBackgroundColor}; } `); collector.addRule(` .notebookOverlay .cell-list-container > .monaco-list > .monaco-scrollable-element > .scrollbar > .slider.active:before { content: ""; width: 100%; height: 100%; position: absolute; background: ${scrollbarSliderActiveBackgroundColor}; } `); /* hack to not have cells see through scroller */ } // Cell Margin collector.addRule(`.notebookOverlay .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row > div.cell { margin: 0px ${CELL_MARGIN * 2}px 0px ${CELL_MARGIN}px; }`); collector.addRule(`.notebookOverlay .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row > div.cell.code { margin-left: ${CODE_CELL_LEFT_MARGIN}px; }`); collector.addRule(`.notebookOverlay .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row { padding-top: ${EDITOR_TOP_MARGIN}px; }`); collector.addRule(`.notebookOverlay .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .markdown-cell-row { padding-bottom: ${CELL_BOTTOM_MARGIN}px; }`); collector.addRule(`.notebookOverlay .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .markdown-cell-row .cell-bottom-toolbar-container { margin-top: ${CELL_BOTTOM_MARGIN}px; }`); collector.addRule(`.notebookOverlay .output { margin: 0px ${CELL_MARGIN}px 0px ${CODE_CELL_LEFT_MARGIN + CELL_RUN_GUTTER}px; }`); collector.addRule(`.notebookOverlay .output { width: calc(100% - ${CODE_CELL_LEFT_MARGIN + CELL_RUN_GUTTER + (CELL_MARGIN * 2)}px); }`); collector.addRule(`.notebookOverlay .cell-bottom-toolbar-container { width: calc(100% - ${CELL_MARGIN * 2 + CELL_RUN_GUTTER}px); margin: 0px ${CELL_MARGIN * 2}px 0px ${CELL_MARGIN + CELL_RUN_GUTTER}px; }`); collector.addRule(`.notebookOverlay .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row > div.cell.markdown { padding-left: ${CELL_RUN_GUTTER}px; }`); collector.addRule(`.notebookOverlay .cell .run-button-container { width: ${CELL_RUN_GUTTER}px; }`); collector.addRule(`.notebookOverlay .cell-drag-image .cell-editor-container > div { padding: ${EDITOR_TOP_PADDING}px 16px ${EDITOR_BOTTOM_PADDING}px 16px; }`); collector.addRule(`.notebookOverlay .monaco-list .monaco-list-row .cell-focus-indicator-top { height: ${EDITOR_TOP_MARGIN}px; }`); collector.addRule(`.notebookOverlay .monaco-list .monaco-list-row .cell-focus-indicator-side { bottom: ${BOTTOM_CELL_TOOLBAR_HEIGHT}px; }`); collector.addRule(`.notebookOverlay .monaco-list .monaco-list-row.code-cell-row .cell-focus-indicator-left { width: ${CODE_CELL_LEFT_MARGIN + CELL_RUN_GUTTER}px; }`); collector.addRule(`.notebookOverlay .monaco-list .monaco-list-row.markdown-cell-row .cell-focus-indicator-left { width: ${CODE_CELL_LEFT_MARGIN}px; }`); collector.addRule(`.notebookOverlay .monaco-list .monaco-list-row .cell-focus-indicator.cell-focus-indicator-right { width: ${CELL_MARGIN * 2}px; }`); collector.addRule(`.notebookOverlay .monaco-list .monaco-list-row .cell-focus-indicator-bottom { height: ${CELL_BOTTOM_MARGIN}px; }`); collector.addRule(`.notebookOverlay .monaco-list .monaco-list-row .cell-shadow-container-bottom { top: ${CELL_BOTTOM_MARGIN}px; }`); });
src/vs/workbench/contrib/notebook/browser/notebookEditorWidget.ts
1
https://github.com/microsoft/vscode/commit/9504dda6a717a0a0d45d992e21f2565f8a23f390
[ 0.0010534232715144753, 0.00019030073599424213, 0.00016251046326942742, 0.00017077807569876313, 0.00009719374793348834 ]
{ "id": 1, "code_window": [ "import * as nls from 'vs/nls';\n", "import { registerAction2, Action2, MenuId } from 'vs/platform/actions/common/actions';\n", "import { NOTEBOOK_ACTIONS_CATEGORY, INotebookCellActionContext } from 'vs/workbench/contrib/notebook/browser/contrib/coreActions';\n", "import { ContextKeyExpr } from 'vs/platform/contextkey/common/contextkey';\n", "import { ServicesAccessor } from 'vs/platform/instantiation/common/instantiation';\n" ], "labels": [ "keep", "replace", "replace", "replace", "keep" ], "after_edit": [ "import { Action2, MenuId, registerAction2 } from 'vs/platform/actions/common/actions';\n" ], "file_path": "src/vs/workbench/contrib/notebook/browser/contrib/status/editorStatus.ts", "type": "replace", "edit_start_line_idx": 10 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IExtensionManifest, ExtensionKind, ExtensionIdentifier } from 'vs/platform/extensions/common/extensions'; import { ExtensionsRegistry } from 'vs/workbench/services/extensions/common/extensionsRegistry'; import { getGalleryExtensionId } from 'vs/platform/extensionManagement/common/extensionManagementUtil'; import { isNonEmptyArray } from 'vs/base/common/arrays'; import { IProductService } from 'vs/platform/product/common/productService'; export function prefersExecuteOnUI(manifest: IExtensionManifest, productService: IProductService, configurationService: IConfigurationService): boolean { const extensionKind = getExtensionKind(manifest, productService, configurationService); return (extensionKind.length > 0 && extensionKind[0] === 'ui'); } export function prefersExecuteOnWorkspace(manifest: IExtensionManifest, productService: IProductService, configurationService: IConfigurationService): boolean { const extensionKind = getExtensionKind(manifest, productService, configurationService); return (extensionKind.length > 0 && extensionKind[0] === 'workspace'); } export function prefersExecuteOnWeb(manifest: IExtensionManifest, productService: IProductService, configurationService: IConfigurationService): boolean { const extensionKind = getExtensionKind(manifest, productService, configurationService); return (extensionKind.length > 0 && extensionKind[0] === 'web'); } export function canExecuteOnUI(manifest: IExtensionManifest, productService: IProductService, configurationService: IConfigurationService): boolean { const extensionKind = getExtensionKind(manifest, productService, configurationService); return extensionKind.some(kind => kind === 'ui'); } export function canExecuteOnWorkspace(manifest: IExtensionManifest, productService: IProductService, configurationService: IConfigurationService): boolean { const extensionKind = getExtensionKind(manifest, productService, configurationService); return extensionKind.some(kind => kind === 'workspace'); } export function canExecuteOnWeb(manifest: IExtensionManifest, productService: IProductService, configurationService: IConfigurationService): boolean { const extensionKind = getExtensionKind(manifest, productService, configurationService); return extensionKind.some(kind => kind === 'web'); } export function getExtensionKind(manifest: IExtensionManifest, productService: IProductService, configurationService: IConfigurationService): ExtensionKind[] { // check in config let result = getConfiguredExtensionKind(manifest, configurationService); if (typeof result !== 'undefined') { return toArray(result); } // check product.json result = getProductExtensionKind(manifest, productService); if (typeof result !== 'undefined') { return result; } // check the manifest itself result = manifest.extensionKind; if (typeof result !== 'undefined') { return toArray(result); } // Not an UI extension if it has main if (manifest.main) { return ['workspace']; } // Not an UI extension if it has dependencies or an extension pack if (isNonEmptyArray(manifest.extensionDependencies) || isNonEmptyArray(manifest.extensionPack)) { return ['workspace']; } if (manifest.contributes) { // Not an UI extension if it has no ui contributions for (const contribution of Object.keys(manifest.contributes)) { if (!isUIExtensionPoint(contribution)) { return ['workspace']; } } } return ['ui', 'workspace']; } let _uiExtensionPoints: Set<string> | null = null; function isUIExtensionPoint(extensionPoint: string): boolean { if (_uiExtensionPoints === null) { const uiExtensionPoints = new Set<string>(); ExtensionsRegistry.getExtensionPoints().filter(e => e.defaultExtensionKind !== 'workspace').forEach(e => { uiExtensionPoints.add(e.name); }); _uiExtensionPoints = uiExtensionPoints; } return _uiExtensionPoints.has(extensionPoint); } let _productExtensionKindsMap: Map<string, ExtensionKind[]> | null = null; function getProductExtensionKind(manifest: IExtensionManifest, productService: IProductService): ExtensionKind[] | undefined { if (_productExtensionKindsMap === null) { const productExtensionKindsMap = new Map<string, ExtensionKind[]>(); if (productService.extensionKind) { for (const id of Object.keys(productService.extensionKind)) { productExtensionKindsMap.set(ExtensionIdentifier.toKey(id), productService.extensionKind[id]); } } _productExtensionKindsMap = productExtensionKindsMap; } const extensionId = getGalleryExtensionId(manifest.publisher, manifest.name); return _productExtensionKindsMap.get(ExtensionIdentifier.toKey(extensionId)); } let _configuredExtensionKindsMap: Map<string, ExtensionKind | ExtensionKind[]> | null = null; function getConfiguredExtensionKind(manifest: IExtensionManifest, configurationService: IConfigurationService): ExtensionKind | ExtensionKind[] | undefined { if (_configuredExtensionKindsMap === null) { const configuredExtensionKindsMap = new Map<string, ExtensionKind | ExtensionKind[]>(); const configuredExtensionKinds = configurationService.getValue<{ [key: string]: ExtensionKind | ExtensionKind[] }>('remote.extensionKind') || {}; for (const id of Object.keys(configuredExtensionKinds)) { configuredExtensionKindsMap.set(ExtensionIdentifier.toKey(id), configuredExtensionKinds[id]); } _configuredExtensionKindsMap = configuredExtensionKindsMap; } const extensionId = getGalleryExtensionId(manifest.publisher, manifest.name); return _configuredExtensionKindsMap.get(ExtensionIdentifier.toKey(extensionId)); } function toArray(extensionKind: ExtensionKind | ExtensionKind[]): ExtensionKind[] { if (Array.isArray(extensionKind)) { return extensionKind; } return extensionKind === 'ui' ? ['ui', 'workspace'] : [extensionKind]; }
src/vs/workbench/services/extensions/common/extensionsUtil.ts
0
https://github.com/microsoft/vscode/commit/9504dda6a717a0a0d45d992e21f2565f8a23f390
[ 0.00017656911222729832, 0.0001717639242997393, 0.00016566381964366883, 0.0001718941202852875, 0.0000029420150440273574 ]
{ "id": 1, "code_window": [ "import * as nls from 'vs/nls';\n", "import { registerAction2, Action2, MenuId } from 'vs/platform/actions/common/actions';\n", "import { NOTEBOOK_ACTIONS_CATEGORY, INotebookCellActionContext } from 'vs/workbench/contrib/notebook/browser/contrib/coreActions';\n", "import { ContextKeyExpr } from 'vs/platform/contextkey/common/contextkey';\n", "import { ServicesAccessor } from 'vs/platform/instantiation/common/instantiation';\n" ], "labels": [ "keep", "replace", "replace", "replace", "keep" ], "after_edit": [ "import { Action2, MenuId, registerAction2 } from 'vs/platform/actions/common/actions';\n" ], "file_path": "src/vs/workbench/contrib/notebook/browser/contrib/status/editorStatus.ts", "type": "replace", "edit_start_line_idx": 10 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import 'vs/css!./folding'; import * as nls from 'vs/nls'; import * as types from 'vs/base/common/types'; import { escapeRegExpCharacters } from 'vs/base/common/strings'; import { RunOnceScheduler, Delayer, CancelablePromise, createCancelablePromise } from 'vs/base/common/async'; import { KeyCode, KeyMod, KeyChord } from 'vs/base/common/keyCodes'; import { Disposable, DisposableStore } from 'vs/base/common/lifecycle'; import { ScrollType, IEditorContribution } from 'vs/editor/common/editorCommon'; import { ITextModel } from 'vs/editor/common/model'; import { registerEditorAction, registerEditorContribution, ServicesAccessor, EditorAction, registerInstantiatedEditorAction } from 'vs/editor/browser/editorExtensions'; import { ICodeEditor, IEditorMouseEvent, MouseTargetType } from 'vs/editor/browser/editorBrowser'; import { FoldingModel, setCollapseStateAtLevel, CollapseMemento, setCollapseStateLevelsDown, setCollapseStateLevelsUp, setCollapseStateForMatchingLines, setCollapseStateForType, toggleCollapseState, setCollapseStateUp } from 'vs/editor/contrib/folding/foldingModel'; import { FoldingDecorationProvider, foldingCollapsedIcon, foldingExpandedIcon } from './foldingDecorations'; import { FoldingRegions, FoldingRegion } from './foldingRanges'; import { EditorContextKeys } from 'vs/editor/common/editorContextKeys'; import { ConfigurationChangedEvent, EditorOption } from 'vs/editor/common/config/editorOptions'; import { IMarginData, IEmptyContentData } from 'vs/editor/browser/controller/mouseTarget'; import { HiddenRangeModel } from 'vs/editor/contrib/folding/hiddenRangeModel'; import { IRange } from 'vs/editor/common/core/range'; import { LanguageConfigurationRegistry } from 'vs/editor/common/modes/languageConfigurationRegistry'; import { IndentRangeProvider } from 'vs/editor/contrib/folding/indentRangeProvider'; import { IPosition } from 'vs/editor/common/core/position'; import { FoldingRangeProviderRegistry, FoldingRangeKind } from 'vs/editor/common/modes'; import { SyntaxRangeProvider, ID_SYNTAX_PROVIDER } from './syntaxRangeProvider'; import { CancellationToken } from 'vs/base/common/cancellation'; import { InitializingRangeProvider, ID_INIT_PROVIDER } from 'vs/editor/contrib/folding/intializingRangeProvider'; import { KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry'; import { onUnexpectedError } from 'vs/base/common/errors'; import { RawContextKey, IContextKey, IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { registerThemingParticipant } from 'vs/platform/theme/common/themeService'; import { registerColor, editorSelectionBackground, transparent, iconForeground } from 'vs/platform/theme/common/colorRegistry'; const CONTEXT_FOLDING_ENABLED = new RawContextKey<boolean>('foldingEnabled', false); export interface RangeProvider { readonly id: string; compute(cancelationToken: CancellationToken): Promise<FoldingRegions | null>; dispose(): void; } interface FoldingStateMemento { collapsedRegions?: CollapseMemento; lineCount?: number; provider?: string; } export class FoldingController extends Disposable implements IEditorContribution { public static ID = 'editor.contrib.folding'; static readonly MAX_FOLDING_REGIONS = 5000; public static get(editor: ICodeEditor): FoldingController { return editor.getContribution<FoldingController>(FoldingController.ID); } private readonly editor: ICodeEditor; private _isEnabled: boolean; private _useFoldingProviders: boolean; private _unfoldOnClickAfterEndOfLine: boolean; private readonly foldingDecorationProvider: FoldingDecorationProvider; private foldingModel: FoldingModel | null; private hiddenRangeModel: HiddenRangeModel | null; private rangeProvider: RangeProvider | null; private foldingRegionPromise: CancelablePromise<FoldingRegions | null> | null; private foldingStateMemento: FoldingStateMemento | null; private foldingModelPromise: Promise<FoldingModel | null> | null; private updateScheduler: Delayer<FoldingModel | null> | null; private foldingEnabled: IContextKey<boolean>; private cursorChangedScheduler: RunOnceScheduler | null; private readonly localToDispose = this._register(new DisposableStore()); private mouseDownInfo: { lineNumber: number, iconClicked: boolean } | null; constructor( editor: ICodeEditor, @IContextKeyService private readonly contextKeyService: IContextKeyService ) { super(); this.editor = editor; const options = this.editor.getOptions(); this._isEnabled = options.get(EditorOption.folding); this._useFoldingProviders = options.get(EditorOption.foldingStrategy) !== 'indentation'; this._unfoldOnClickAfterEndOfLine = options.get(EditorOption.unfoldOnClickAfterEndOfLine); this.foldingModel = null; this.hiddenRangeModel = null; this.rangeProvider = null; this.foldingRegionPromise = null; this.foldingStateMemento = null; this.foldingModelPromise = null; this.updateScheduler = null; this.cursorChangedScheduler = null; this.mouseDownInfo = null; this.foldingDecorationProvider = new FoldingDecorationProvider(editor); this.foldingDecorationProvider.autoHideFoldingControls = options.get(EditorOption.showFoldingControls) === 'mouseover'; this.foldingDecorationProvider.showFoldingHighlights = options.get(EditorOption.foldingHighlight); this.foldingEnabled = CONTEXT_FOLDING_ENABLED.bindTo(this.contextKeyService); this.foldingEnabled.set(this._isEnabled); this._register(this.editor.onDidChangeModel(() => this.onModelChanged())); this._register(this.editor.onDidChangeConfiguration((e: ConfigurationChangedEvent) => { if (e.hasChanged(EditorOption.folding)) { this._isEnabled = this.editor.getOptions().get(EditorOption.folding); this.foldingEnabled.set(this._isEnabled); this.onModelChanged(); } if (e.hasChanged(EditorOption.showFoldingControls) || e.hasChanged(EditorOption.foldingHighlight)) { const options = this.editor.getOptions(); this.foldingDecorationProvider.autoHideFoldingControls = options.get(EditorOption.showFoldingControls) === 'mouseover'; this.foldingDecorationProvider.showFoldingHighlights = options.get(EditorOption.foldingHighlight); this.onModelContentChanged(); } if (e.hasChanged(EditorOption.foldingStrategy)) { this._useFoldingProviders = this.editor.getOptions().get(EditorOption.foldingStrategy) !== 'indentation'; this.onFoldingStrategyChanged(); } if (e.hasChanged(EditorOption.unfoldOnClickAfterEndOfLine)) { this._unfoldOnClickAfterEndOfLine = this.editor.getOptions().get(EditorOption.unfoldOnClickAfterEndOfLine); } })); this.onModelChanged(); } /** * Store view state. */ public saveViewState(): FoldingStateMemento | undefined { let model = this.editor.getModel(); if (!model || !this._isEnabled || model.isTooLargeForTokenization()) { return {}; } if (this.foldingModel) { // disposed ? let collapsedRegions = this.foldingModel.isInitialized ? this.foldingModel.getMemento() : this.hiddenRangeModel!.getMemento(); let provider = this.rangeProvider ? this.rangeProvider.id : undefined; return { collapsedRegions, lineCount: model.getLineCount(), provider }; } return undefined; } /** * Restore view state. */ public restoreViewState(state: FoldingStateMemento): void { let model = this.editor.getModel(); if (!model || !this._isEnabled || model.isTooLargeForTokenization() || !this.hiddenRangeModel) { return; } if (!state || !state.collapsedRegions || state.lineCount !== model.getLineCount()) { return; } if (state.provider === ID_SYNTAX_PROVIDER || state.provider === ID_INIT_PROVIDER) { this.foldingStateMemento = state; } const collapsedRegions = state.collapsedRegions; // set the hidden ranges right away, before waiting for the folding model. if (this.hiddenRangeModel.applyMemento(collapsedRegions)) { const foldingModel = this.getFoldingModel(); if (foldingModel) { foldingModel.then(foldingModel => { if (foldingModel) { foldingModel.applyMemento(collapsedRegions); } }).then(undefined, onUnexpectedError); } } } private onModelChanged(): void { this.localToDispose.clear(); let model = this.editor.getModel(); if (!this._isEnabled || !model || model.isTooLargeForTokenization()) { // huge files get no view model, so they cannot support hidden areas return; } this.foldingModel = new FoldingModel(model, this.foldingDecorationProvider); this.localToDispose.add(this.foldingModel); this.hiddenRangeModel = new HiddenRangeModel(this.foldingModel); this.localToDispose.add(this.hiddenRangeModel); this.localToDispose.add(this.hiddenRangeModel.onDidChange(hr => this.onHiddenRangesChanges(hr))); this.updateScheduler = new Delayer<FoldingModel>(200); this.cursorChangedScheduler = new RunOnceScheduler(() => this.revealCursor(), 200); this.localToDispose.add(this.cursorChangedScheduler); this.localToDispose.add(FoldingRangeProviderRegistry.onDidChange(() => this.onFoldingStrategyChanged())); this.localToDispose.add(this.editor.onDidChangeModelLanguageConfiguration(() => this.onFoldingStrategyChanged())); // covers model language changes as well this.localToDispose.add(this.editor.onDidChangeModelContent(() => this.onModelContentChanged())); this.localToDispose.add(this.editor.onDidChangeCursorPosition(() => this.onCursorPositionChanged())); this.localToDispose.add(this.editor.onMouseDown(e => this.onEditorMouseDown(e))); this.localToDispose.add(this.editor.onMouseUp(e => this.onEditorMouseUp(e))); this.localToDispose.add({ dispose: () => { if (this.foldingRegionPromise) { this.foldingRegionPromise.cancel(); this.foldingRegionPromise = null; } if (this.updateScheduler) { this.updateScheduler.cancel(); } this.updateScheduler = null; this.foldingModel = null; this.foldingModelPromise = null; this.hiddenRangeModel = null; this.cursorChangedScheduler = null; this.foldingStateMemento = null; if (this.rangeProvider) { this.rangeProvider.dispose(); } this.rangeProvider = null; } }); this.onModelContentChanged(); } private onFoldingStrategyChanged() { if (this.rangeProvider) { this.rangeProvider.dispose(); } this.rangeProvider = null; this.onModelContentChanged(); } private getRangeProvider(editorModel: ITextModel): RangeProvider { if (this.rangeProvider) { return this.rangeProvider; } this.rangeProvider = new IndentRangeProvider(editorModel); // fallback if (this._useFoldingProviders && this.foldingModel) { let foldingProviders = FoldingRangeProviderRegistry.ordered(this.foldingModel.textModel); if (foldingProviders.length === 0 && this.foldingStateMemento && this.foldingStateMemento.collapsedRegions) { const rangeProvider = this.rangeProvider = new InitializingRangeProvider(editorModel, this.foldingStateMemento.collapsedRegions, () => { // if after 30 the InitializingRangeProvider is still not replaced, force a refresh this.foldingStateMemento = null; this.onFoldingStrategyChanged(); }, 30000); return rangeProvider; // keep memento in case there are still no foldingProviders on the next request. } else if (foldingProviders.length > 0) { this.rangeProvider = new SyntaxRangeProvider(editorModel, foldingProviders); } } this.foldingStateMemento = null; return this.rangeProvider; } public getFoldingModel() { return this.foldingModelPromise; } private onModelContentChanged() { if (this.updateScheduler) { if (this.foldingRegionPromise) { this.foldingRegionPromise.cancel(); this.foldingRegionPromise = null; } this.foldingModelPromise = this.updateScheduler.trigger(() => { const foldingModel = this.foldingModel; if (!foldingModel) { // null if editor has been disposed, or folding turned off return null; } let foldingRegionPromise = this.foldingRegionPromise = createCancelablePromise(token => this.getRangeProvider(foldingModel.textModel).compute(token)); return foldingRegionPromise.then(foldingRanges => { if (foldingRanges && foldingRegionPromise === this.foldingRegionPromise) { // new request or cancelled in the meantime? // some cursors might have moved into hidden regions, make sure they are in expanded regions let selections = this.editor.getSelections(); let selectionLineNumbers = selections ? selections.map(s => s.startLineNumber) : []; foldingModel.update(foldingRanges, selectionLineNumbers); } return foldingModel; }); }).then(undefined, (err) => { onUnexpectedError(err); return null; }); } } private onHiddenRangesChanges(hiddenRanges: IRange[]) { if (this.hiddenRangeModel && hiddenRanges.length) { let selections = this.editor.getSelections(); if (selections) { if (this.hiddenRangeModel.adjustSelections(selections)) { this.editor.setSelections(selections); } } } this.editor.setHiddenAreas(hiddenRanges); } private onCursorPositionChanged() { if (this.hiddenRangeModel && this.hiddenRangeModel.hasRanges()) { this.cursorChangedScheduler!.schedule(); } } private revealCursor() { const foldingModel = this.getFoldingModel(); if (!foldingModel) { return; } foldingModel.then(foldingModel => { // null is returned if folding got disabled in the meantime if (foldingModel) { let selections = this.editor.getSelections(); if (selections && selections.length > 0) { let toToggle: FoldingRegion[] = []; for (let selection of selections) { let lineNumber = selection.selectionStartLineNumber; if (this.hiddenRangeModel && this.hiddenRangeModel.isHidden(lineNumber)) { toToggle.push(...foldingModel.getAllRegionsAtLine(lineNumber, r => r.isCollapsed && lineNumber > r.startLineNumber)); } } if (toToggle.length) { foldingModel.toggleCollapseState(toToggle); this.reveal(selections[0].getPosition()); } } } }).then(undefined, onUnexpectedError); } private onEditorMouseDown(e: IEditorMouseEvent): void { this.mouseDownInfo = null; if (!this.hiddenRangeModel || !e.target || !e.target.range) { return; } if (!e.event.leftButton && !e.event.middleButton) { return; } const range = e.target.range; let iconClicked = false; switch (e.target.type) { case MouseTargetType.GUTTER_LINE_DECORATIONS: const data = e.target.detail as IMarginData; const offsetLeftInGutter = (e.target.element as HTMLElement).offsetLeft; const gutterOffsetX = data.offsetX - offsetLeftInGutter; // const gutterOffsetX = data.offsetX - data.glyphMarginWidth - data.lineNumbersWidth - data.glyphMarginLeft; // TODO@joao TODO@alex TODO@martin this is such that we don't collide with dirty diff if (gutterOffsetX < 5) { // the whitespace between the border and the real folding icon border is 5px return; } iconClicked = true; break; case MouseTargetType.CONTENT_EMPTY: { if (this._unfoldOnClickAfterEndOfLine && this.hiddenRangeModel.hasRanges()) { const data = e.target.detail as IEmptyContentData; if (!data.isAfterLines) { break; } } return; } case MouseTargetType.CONTENT_TEXT: { if (this.hiddenRangeModel.hasRanges()) { let model = this.editor.getModel(); if (model && range.startColumn === model.getLineMaxColumn(range.startLineNumber)) { break; } } return; } default: return; } this.mouseDownInfo = { lineNumber: range.startLineNumber, iconClicked }; } private onEditorMouseUp(e: IEditorMouseEvent): void { const foldingModel = this.getFoldingModel(); if (!foldingModel || !this.mouseDownInfo || !e.target) { return; } let lineNumber = this.mouseDownInfo.lineNumber; let iconClicked = this.mouseDownInfo.iconClicked; let range = e.target.range; if (!range || range.startLineNumber !== lineNumber) { return; } if (iconClicked) { if (e.target.type !== MouseTargetType.GUTTER_LINE_DECORATIONS) { return; } } else { let model = this.editor.getModel(); if (!model || range.startColumn !== model.getLineMaxColumn(lineNumber)) { return; } } foldingModel.then(foldingModel => { if (foldingModel) { let region = foldingModel.getRegionAtLine(lineNumber); if (region && region.startLineNumber === lineNumber) { let isCollapsed = region.isCollapsed; if (iconClicked || isCollapsed) { let toToggle = []; let recursive = e.event.middleButton || e.event.shiftKey; if (recursive) { for (const r of foldingModel.getRegionsInside(region)) { if (r.isCollapsed === isCollapsed) { toToggle.push(r); } } } // when recursive, first only collapse all children. If all are already folded or there are no children, also fold parent. if (isCollapsed || !recursive || toToggle.length === 0) { toToggle.push(region); } foldingModel.toggleCollapseState(toToggle); this.reveal({ lineNumber, column: 1 }); } } } }).then(undefined, onUnexpectedError); } public reveal(position: IPosition): void { this.editor.revealPositionInCenterIfOutsideViewport(position, ScrollType.Smooth); } } abstract class FoldingAction<T> extends EditorAction { abstract invoke(foldingController: FoldingController, foldingModel: FoldingModel, editor: ICodeEditor, args: T): void; public runEditorCommand(accessor: ServicesAccessor, editor: ICodeEditor, args: T): void | Promise<void> { let foldingController = FoldingController.get(editor); if (!foldingController) { return; } let foldingModelPromise = foldingController.getFoldingModel(); if (foldingModelPromise) { this.reportTelemetry(accessor, editor); return foldingModelPromise.then(foldingModel => { if (foldingModel) { this.invoke(foldingController, foldingModel, editor, args); const selection = editor.getSelection(); if (selection) { foldingController.reveal(selection.getStartPosition()); } } }); } } protected getSelectedLines(editor: ICodeEditor) { let selections = editor.getSelections(); return selections ? selections.map(s => s.startLineNumber) : []; } protected getLineNumbers(args: FoldingArguments, editor: ICodeEditor) { if (args && args.selectionLines) { return args.selectionLines.map(l => l + 1); // to 0-bases line numbers } return this.getSelectedLines(editor); } public run(_accessor: ServicesAccessor, _editor: ICodeEditor): void { } } interface FoldingArguments { levels?: number; direction?: 'up' | 'down'; selectionLines?: number[]; } function foldingArgumentsConstraint(args: any) { if (!types.isUndefined(args)) { if (!types.isObject(args)) { return false; } const foldingArgs: FoldingArguments = args; if (!types.isUndefined(foldingArgs.levels) && !types.isNumber(foldingArgs.levels)) { return false; } if (!types.isUndefined(foldingArgs.direction) && !types.isString(foldingArgs.direction)) { return false; } if (!types.isUndefined(foldingArgs.selectionLines) && (!types.isArray(foldingArgs.selectionLines) || !foldingArgs.selectionLines.every(types.isNumber))) { return false; } } return true; } class UnfoldAction extends FoldingAction<FoldingArguments> { constructor() { super({ id: 'editor.unfold', label: nls.localize('unfoldAction.label', "Unfold"), alias: 'Unfold', precondition: CONTEXT_FOLDING_ENABLED, kbOpts: { kbExpr: EditorContextKeys.editorTextFocus, primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.US_CLOSE_SQUARE_BRACKET, mac: { primary: KeyMod.CtrlCmd | KeyMod.Alt | KeyCode.US_CLOSE_SQUARE_BRACKET }, weight: KeybindingWeight.EditorContrib }, description: { description: 'Unfold the content in the editor', args: [ { name: 'Unfold editor argument', description: `Property-value pairs that can be passed through this argument: * 'levels': Number of levels to unfold. If not set, defaults to 1. * 'direction': If 'up', unfold given number of levels up otherwise unfolds down. * 'selectionLines': The start lines (0-based) of the editor selections to apply the unfold action to. If not set, the active selection(s) will be used. `, constraint: foldingArgumentsConstraint, schema: { 'type': 'object', 'properties': { 'levels': { 'type': 'number', 'default': 1 }, 'direction': { 'type': 'string', 'enum': ['up', 'down'], 'default': 'down' }, 'selectionLines': { 'type': 'array', 'items': { 'type': 'number' } } } } } ] } }); } invoke(_foldingController: FoldingController, foldingModel: FoldingModel, editor: ICodeEditor, args: FoldingArguments): void { let levels = args && args.levels || 1; let lineNumbers = this.getLineNumbers(args, editor); if (args && args.direction === 'up') { setCollapseStateLevelsUp(foldingModel, false, levels, lineNumbers); } else { setCollapseStateLevelsDown(foldingModel, false, levels, lineNumbers); } } } class UnFoldRecursivelyAction extends FoldingAction<void> { constructor() { super({ id: 'editor.unfoldRecursively', label: nls.localize('unFoldRecursivelyAction.label', "Unfold Recursively"), alias: 'Unfold Recursively', precondition: CONTEXT_FOLDING_ENABLED, kbOpts: { kbExpr: EditorContextKeys.editorTextFocus, primary: KeyChord(KeyMod.CtrlCmd | KeyCode.KEY_K, KeyMod.CtrlCmd | KeyCode.US_CLOSE_SQUARE_BRACKET), weight: KeybindingWeight.EditorContrib } }); } invoke(_foldingController: FoldingController, foldingModel: FoldingModel, editor: ICodeEditor, _args: any): void { setCollapseStateLevelsDown(foldingModel, false, Number.MAX_VALUE, this.getSelectedLines(editor)); } } class FoldAction extends FoldingAction<FoldingArguments> { constructor() { super({ id: 'editor.fold', label: nls.localize('foldAction.label', "Fold"), alias: 'Fold', precondition: CONTEXT_FOLDING_ENABLED, kbOpts: { kbExpr: EditorContextKeys.editorTextFocus, primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.US_OPEN_SQUARE_BRACKET, mac: { primary: KeyMod.CtrlCmd | KeyMod.Alt | KeyCode.US_OPEN_SQUARE_BRACKET }, weight: KeybindingWeight.EditorContrib }, description: { description: 'Fold the content in the editor', args: [ { name: 'Fold editor argument', description: `Property-value pairs that can be passed through this argument: * 'levels': Number of levels to fold. * 'direction': If 'up', folds given number of levels up otherwise folds down. * 'selectionLines': The start lines (0-based) of the editor selections to apply the fold action to. If not set, the active selection(s) will be used. If no levels or direction is set, folds the region at the locations or if already collapsed, the first uncollapsed parent instead. `, constraint: foldingArgumentsConstraint, schema: { 'type': 'object', 'properties': { 'levels': { 'type': 'number', }, 'direction': { 'type': 'string', 'enum': ['up', 'down'], }, 'selectionLines': { 'type': 'array', 'items': { 'type': 'number' } } } } } ] } }); } invoke(_foldingController: FoldingController, foldingModel: FoldingModel, editor: ICodeEditor, args: FoldingArguments): void { let lineNumbers = this.getLineNumbers(args, editor); const levels = args && args.levels; const direction = args && args.direction; if (typeof levels !== 'number' && typeof direction !== 'string') { // fold the region at the location or if already collapsed, the first uncollapsed parent instead. setCollapseStateUp(foldingModel, true, lineNumbers); } else { if (direction === 'up') { setCollapseStateLevelsUp(foldingModel, true, levels || 1, lineNumbers); } else { setCollapseStateLevelsDown(foldingModel, true, levels || 1, lineNumbers); } } } } class ToggleFoldAction extends FoldingAction<void> { constructor() { super({ id: 'editor.toggleFold', label: nls.localize('toggleFoldAction.label', "Toggle Fold"), alias: 'Toggle Fold', precondition: CONTEXT_FOLDING_ENABLED, kbOpts: { kbExpr: EditorContextKeys.editorTextFocus, primary: KeyChord(KeyMod.CtrlCmd | KeyCode.KEY_K, KeyMod.CtrlCmd | KeyCode.KEY_L), weight: KeybindingWeight.EditorContrib } }); } invoke(_foldingController: FoldingController, foldingModel: FoldingModel, editor: ICodeEditor): void { let selectedLines = this.getSelectedLines(editor); toggleCollapseState(foldingModel, 1, selectedLines); } } class FoldRecursivelyAction extends FoldingAction<void> { constructor() { super({ id: 'editor.foldRecursively', label: nls.localize('foldRecursivelyAction.label', "Fold Recursively"), alias: 'Fold Recursively', precondition: CONTEXT_FOLDING_ENABLED, kbOpts: { kbExpr: EditorContextKeys.editorTextFocus, primary: KeyChord(KeyMod.CtrlCmd | KeyCode.KEY_K, KeyMod.CtrlCmd | KeyCode.US_OPEN_SQUARE_BRACKET), weight: KeybindingWeight.EditorContrib } }); } invoke(_foldingController: FoldingController, foldingModel: FoldingModel, editor: ICodeEditor): void { let selectedLines = this.getSelectedLines(editor); setCollapseStateLevelsDown(foldingModel, true, Number.MAX_VALUE, selectedLines); } } class FoldAllBlockCommentsAction extends FoldingAction<void> { constructor() { super({ id: 'editor.foldAllBlockComments', label: nls.localize('foldAllBlockComments.label', "Fold All Block Comments"), alias: 'Fold All Block Comments', precondition: CONTEXT_FOLDING_ENABLED, kbOpts: { kbExpr: EditorContextKeys.editorTextFocus, primary: KeyChord(KeyMod.CtrlCmd | KeyCode.KEY_K, KeyMod.CtrlCmd | KeyCode.US_SLASH), weight: KeybindingWeight.EditorContrib } }); } invoke(_foldingController: FoldingController, foldingModel: FoldingModel, editor: ICodeEditor): void { if (foldingModel.regions.hasTypes()) { setCollapseStateForType(foldingModel, FoldingRangeKind.Comment.value, true); } else { const editorModel = editor.getModel(); if (!editorModel) { return; } let comments = LanguageConfigurationRegistry.getComments(editorModel.getLanguageIdentifier().id); if (comments && comments.blockCommentStartToken) { let regExp = new RegExp('^\\s*' + escapeRegExpCharacters(comments.blockCommentStartToken)); setCollapseStateForMatchingLines(foldingModel, regExp, true); } } } } class FoldAllRegionsAction extends FoldingAction<void> { constructor() { super({ id: 'editor.foldAllMarkerRegions', label: nls.localize('foldAllMarkerRegions.label', "Fold All Regions"), alias: 'Fold All Regions', precondition: CONTEXT_FOLDING_ENABLED, kbOpts: { kbExpr: EditorContextKeys.editorTextFocus, primary: KeyChord(KeyMod.CtrlCmd | KeyCode.KEY_K, KeyMod.CtrlCmd | KeyCode.KEY_8), weight: KeybindingWeight.EditorContrib } }); } invoke(_foldingController: FoldingController, foldingModel: FoldingModel, editor: ICodeEditor): void { if (foldingModel.regions.hasTypes()) { setCollapseStateForType(foldingModel, FoldingRangeKind.Region.value, true); } else { const editorModel = editor.getModel(); if (!editorModel) { return; } let foldingRules = LanguageConfigurationRegistry.getFoldingRules(editorModel.getLanguageIdentifier().id); if (foldingRules && foldingRules.markers && foldingRules.markers.start) { let regExp = new RegExp(foldingRules.markers.start); setCollapseStateForMatchingLines(foldingModel, regExp, true); } } } } class UnfoldAllRegionsAction extends FoldingAction<void> { constructor() { super({ id: 'editor.unfoldAllMarkerRegions', label: nls.localize('unfoldAllMarkerRegions.label', "Unfold All Regions"), alias: 'Unfold All Regions', precondition: CONTEXT_FOLDING_ENABLED, kbOpts: { kbExpr: EditorContextKeys.editorTextFocus, primary: KeyChord(KeyMod.CtrlCmd | KeyCode.KEY_K, KeyMod.CtrlCmd | KeyCode.KEY_9), weight: KeybindingWeight.EditorContrib } }); } invoke(_foldingController: FoldingController, foldingModel: FoldingModel, editor: ICodeEditor): void { if (foldingModel.regions.hasTypes()) { setCollapseStateForType(foldingModel, FoldingRangeKind.Region.value, false); } else { const editorModel = editor.getModel(); if (!editorModel) { return; } let foldingRules = LanguageConfigurationRegistry.getFoldingRules(editorModel.getLanguageIdentifier().id); if (foldingRules && foldingRules.markers && foldingRules.markers.start) { let regExp = new RegExp(foldingRules.markers.start); setCollapseStateForMatchingLines(foldingModel, regExp, false); } } } } class FoldAllAction extends FoldingAction<void> { constructor() { super({ id: 'editor.foldAll', label: nls.localize('foldAllAction.label', "Fold All"), alias: 'Fold All', precondition: CONTEXT_FOLDING_ENABLED, kbOpts: { kbExpr: EditorContextKeys.editorTextFocus, primary: KeyChord(KeyMod.CtrlCmd | KeyCode.KEY_K, KeyMod.CtrlCmd | KeyCode.KEY_0), weight: KeybindingWeight.EditorContrib } }); } invoke(_foldingController: FoldingController, foldingModel: FoldingModel, _editor: ICodeEditor): void { setCollapseStateLevelsDown(foldingModel, true); } } class UnfoldAllAction extends FoldingAction<void> { constructor() { super({ id: 'editor.unfoldAll', label: nls.localize('unfoldAllAction.label', "Unfold All"), alias: 'Unfold All', precondition: CONTEXT_FOLDING_ENABLED, kbOpts: { kbExpr: EditorContextKeys.editorTextFocus, primary: KeyChord(KeyMod.CtrlCmd | KeyCode.KEY_K, KeyMod.CtrlCmd | KeyCode.KEY_J), weight: KeybindingWeight.EditorContrib } }); } invoke(_foldingController: FoldingController, foldingModel: FoldingModel, _editor: ICodeEditor): void { setCollapseStateLevelsDown(foldingModel, false); } } class FoldLevelAction extends FoldingAction<void> { private static readonly ID_PREFIX = 'editor.foldLevel'; public static readonly ID = (level: number) => FoldLevelAction.ID_PREFIX + level; private getFoldingLevel() { return parseInt(this.id.substr(FoldLevelAction.ID_PREFIX.length)); } invoke(_foldingController: FoldingController, foldingModel: FoldingModel, editor: ICodeEditor): void { setCollapseStateAtLevel(foldingModel, this.getFoldingLevel(), true, this.getSelectedLines(editor)); } } registerEditorContribution(FoldingController.ID, FoldingController); registerEditorAction(UnfoldAction); registerEditorAction(UnFoldRecursivelyAction); registerEditorAction(FoldAction); registerEditorAction(FoldRecursivelyAction); registerEditorAction(FoldAllAction); registerEditorAction(UnfoldAllAction); registerEditorAction(FoldAllBlockCommentsAction); registerEditorAction(FoldAllRegionsAction); registerEditorAction(UnfoldAllRegionsAction); registerEditorAction(ToggleFoldAction); for (let i = 1; i <= 7; i++) { registerInstantiatedEditorAction( new FoldLevelAction({ id: FoldLevelAction.ID(i), label: nls.localize('foldLevelAction.label', "Fold Level {0}", i), alias: `Fold Level ${i}`, precondition: CONTEXT_FOLDING_ENABLED, kbOpts: { kbExpr: EditorContextKeys.editorTextFocus, primary: KeyChord(KeyMod.CtrlCmd | KeyCode.KEY_K, KeyMod.CtrlCmd | (KeyCode.KEY_0 + i)), weight: KeybindingWeight.EditorContrib } }) ); } export const foldBackgroundBackground = registerColor('editor.foldBackground', { light: transparent(editorSelectionBackground, 0.3), dark: transparent(editorSelectionBackground, 0.3), hc: null }, nls.localize('foldBackgroundBackground', "Background color behind folded ranges. The color must not be opaque so as not to hide underlying decorations."), true); export const editorFoldForeground = registerColor('editorGutter.foldingControlForeground', { dark: iconForeground, light: iconForeground, hc: iconForeground }, nls.localize('editorGutter.foldingControlForeground', 'Color of the folding control in the editor gutter.')); registerThemingParticipant((theme, collector) => { const foldBackground = theme.getColor(foldBackgroundBackground); if (foldBackground) { collector.addRule(`.monaco-editor .folded-background { background-color: ${foldBackground}; }`); } const editorFoldColor = theme.getColor(editorFoldForeground); if (editorFoldColor) { collector.addRule(` .monaco-editor .cldr${foldingExpandedIcon.cssSelector}, .monaco-editor .cldr${foldingCollapsedIcon.cssSelector} { color: ${editorFoldColor} !important; } `); } });
src/vs/editor/contrib/folding/folding.ts
0
https://github.com/microsoft/vscode/commit/9504dda6a717a0a0d45d992e21f2565f8a23f390
[ 0.0007181509281508625, 0.000180988252395764, 0.00016333117673639208, 0.00017178224516101182, 0.00005865527054993436 ]
{ "id": 1, "code_window": [ "import * as nls from 'vs/nls';\n", "import { registerAction2, Action2, MenuId } from 'vs/platform/actions/common/actions';\n", "import { NOTEBOOK_ACTIONS_CATEGORY, INotebookCellActionContext } from 'vs/workbench/contrib/notebook/browser/contrib/coreActions';\n", "import { ContextKeyExpr } from 'vs/platform/contextkey/common/contextkey';\n", "import { ServicesAccessor } from 'vs/platform/instantiation/common/instantiation';\n" ], "labels": [ "keep", "replace", "replace", "replace", "keep" ], "after_edit": [ "import { Action2, MenuId, registerAction2 } from 'vs/platform/actions/common/actions';\n" ], "file_path": "src/vs/workbench/contrib/notebook/browser/contrib/status/editorStatus.ts", "type": "replace", "edit_start_line_idx": 10 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as vscode from 'vscode'; export function disposeAll(disposables: vscode.Disposable[]) { while (disposables.length) { const item = disposables.pop(); if (item) { item.dispose(); } } } export abstract class Disposable { private _isDisposed = false; protected _disposables: vscode.Disposable[] = []; public dispose(): any { if (this._isDisposed) { return; } this._isDisposed = true; disposeAll(this._disposables); } protected _register<T extends vscode.Disposable>(value: T): T { if (this._isDisposed) { value.dispose(); } else { this._disposables.push(value); } return value; } protected get isDisposed() { return this._isDisposed; } }
extensions/markdown-language-features/src/util/dispose.ts
0
https://github.com/microsoft/vscode/commit/9504dda6a717a0a0d45d992e21f2565f8a23f390
[ 0.0001751934614730999, 0.00017076253425329924, 0.00016365871124435216, 0.00017080859106499702, 0.0000040004056245379616 ]
{ "id": 2, "code_window": [ "import { ServicesAccessor } from 'vs/platform/instantiation/common/instantiation';\n", "\n", "\n", "registerAction2(class extends Action2 {\n" ], "labels": [ "add", "keep", "keep", "keep" ], "after_edit": [ "import { IQuickInputService, IQuickPickItem, QuickPickInput } from 'vs/platform/quickinput/common/quickInput';\n", "import { INotebookCellActionContext, NOTEBOOK_ACTIONS_CATEGORY } from 'vs/workbench/contrib/notebook/browser/contrib/coreActions';\n", "import { INotebookEditor, NOTEBOOK_HAS_MULTIPLE_KERNELS, NOTEBOOK_IS_ACTIVE_EDITOR } from 'vs/workbench/contrib/notebook/browser/notebookBrowser';\n", "import { INotebookService } from 'vs/workbench/contrib/notebook/common/notebookService';\n", "import { IEditorService } from 'vs/workbench/services/editor/common/editorService';\n" ], "file_path": "src/vs/workbench/contrib/notebook/browser/contrib/status/editorStatus.ts", "type": "add", "edit_start_line_idx": 14 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { getZoomLevel } from 'vs/base/browser/browser'; import * as DOM from 'vs/base/browser/dom'; import { IMouseWheelEvent, StandardMouseEvent } from 'vs/base/browser/mouseEvent'; import { CancellationTokenSource } from 'vs/base/common/cancellation'; import { Color, RGBA } from 'vs/base/common/color'; import { onUnexpectedError } from 'vs/base/common/errors'; import { Emitter, Event } from 'vs/base/common/event'; import { combinedDisposable, DisposableStore, Disposable, IDisposable, toDisposable } from 'vs/base/common/lifecycle'; import 'vs/css!./media/notebook'; import { ICodeEditor } from 'vs/editor/browser/editorBrowser'; import { IEditorOptions } from 'vs/editor/common/config/editorOptions'; import { BareFontInfo } from 'vs/editor/common/config/fontInfo'; import { Range } from 'vs/editor/common/core/range'; import { IEditor } from 'vs/editor/common/editorCommon'; import * as nls from 'vs/nls'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IContextKey, IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { IResourceEditorInput } from 'vs/platform/editor/common/editor'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage'; import { contrastBorder, editorBackground, focusBorder, foreground, registerColor, textBlockQuoteBackground, textBlockQuoteBorder, textLinkActiveForeground, textLinkForeground, textPreformatForeground, errorForeground, transparent, widgetShadow, listFocusBackground, listInactiveSelectionBackground, scrollbarSliderBackground, scrollbarSliderHoverBackground, scrollbarSliderActiveBackground } from 'vs/platform/theme/common/colorRegistry'; import { registerThemingParticipant } from 'vs/platform/theme/common/themeService'; import { EditorMemento } from 'vs/workbench/browser/parts/editor/baseEditor'; import { EditorOptions, IEditorMemento } from 'vs/workbench/common/editor'; import { CELL_MARGIN, CELL_RUN_GUTTER, EDITOR_BOTTOM_PADDING, EDITOR_TOP_MARGIN, EDITOR_TOP_PADDING, SCROLLABLE_ELEMENT_PADDING_TOP, BOTTOM_CELL_TOOLBAR_HEIGHT, CELL_BOTTOM_MARGIN, CODE_CELL_LEFT_MARGIN } from 'vs/workbench/contrib/notebook/browser/constants'; import { CellEditState, CellFocusMode, ICellRange, ICellViewModel, INotebookCellList, INotebookEditor, INotebookEditorContribution, INotebookEditorMouseEvent, NotebookLayoutInfo, NOTEBOOK_EDITOR_EDITABLE, NOTEBOOK_EDITOR_EXECUTING_NOTEBOOK, NOTEBOOK_EDITOR_FOCUSED, NOTEBOOK_EDITOR_RUNNABLE, NOTEBOOK_HAS_MULTIPLE_KERNELS, NOTEBOOK_OUTPUT_FOCUSED } from 'vs/workbench/contrib/notebook/browser/notebookBrowser'; import { NotebookEditorExtensionsRegistry } from 'vs/workbench/contrib/notebook/browser/notebookEditorExtensions'; import { NotebookCellList } from 'vs/workbench/contrib/notebook/browser/view/notebookCellList'; import { OutputRenderer } from 'vs/workbench/contrib/notebook/browser/view/output/outputRenderer'; import { BackLayerWebView } from 'vs/workbench/contrib/notebook/browser/view/renderers/backLayerWebView'; import { CellDragAndDropController, CodeCellRenderer, MarkdownCellRenderer, NotebookCellListDelegate } from 'vs/workbench/contrib/notebook/browser/view/renderers/cellRenderer'; import { CodeCellViewModel } from 'vs/workbench/contrib/notebook/browser/viewModel/codeCellViewModel'; import { NotebookEventDispatcher, NotebookLayoutChangedEvent } from 'vs/workbench/contrib/notebook/browser/viewModel/eventDispatcher'; import { CellViewModel, IModelDecorationsChangeAccessor, INotebookEditorViewState, NotebookViewModel } from 'vs/workbench/contrib/notebook/browser/viewModel/notebookViewModel'; import { CellKind, IProcessedOutput, INotebookKernelInfo, INotebookKernelInfoDto } from 'vs/workbench/contrib/notebook/common/notebookCommon'; import { INotebookService } from 'vs/workbench/contrib/notebook/common/notebookService'; import { Webview } from 'vs/workbench/contrib/webview/browser/webview'; import { IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService'; import { ILayoutService } from 'vs/platform/layout/browser/layoutService'; import { generateUuid } from 'vs/base/common/uuid'; import { Memento, MementoObject } from 'vs/workbench/common/memento'; import { NotebookTextModel } from 'vs/workbench/contrib/notebook/common/model/notebookTextModel'; import { URI } from 'vs/base/common/uri'; import { PANEL_BORDER } from 'vs/workbench/common/theme'; import { debugIconStartForeground } from 'vs/workbench/contrib/debug/browser/debugToolBar'; import { CellContextKeyManager } from 'vs/workbench/contrib/notebook/browser/view/renderers/cellContextKeys'; const $ = DOM.$; export class NotebookEditorOptions extends EditorOptions { readonly cellOptions?: IResourceEditorInput; constructor(options: Partial<NotebookEditorOptions>) { super(); this.overwrite(options); this.cellOptions = options.cellOptions; } with(options: Partial<NotebookEditorOptions>): NotebookEditorOptions { return new NotebookEditorOptions({ ...this, ...options }); } } export class NotebookEditorWidget extends Disposable implements INotebookEditor { static readonly ID: string = 'workbench.editor.notebook'; private static readonly EDITOR_MEMENTOS = new Map<string, EditorMemento<unknown>>(); private _overlayContainer!: HTMLElement; private _body!: HTMLElement; private _webview: BackLayerWebView | null = null; private _webviewTransparentCover: HTMLElement | null = null; private _list: INotebookCellList | undefined; private _dndController: CellDragAndDropController | null = null; private _renderedEditors: Map<ICellViewModel, ICodeEditor | undefined> = new Map(); private _eventDispatcher: NotebookEventDispatcher | undefined; private _notebookViewModel: NotebookViewModel | undefined; private _localStore: DisposableStore = this._register(new DisposableStore()); private _fontInfo: BareFontInfo | undefined; private _dimension: DOM.Dimension | null = null; private _shadowElementViewInfo: { height: number, width: number, top: number; left: number; } | null = null; private _editorFocus: IContextKey<boolean> | null = null; private _outputFocus: IContextKey<boolean> | null = null; private _editorEditable: IContextKey<boolean> | null = null; private _editorRunnable: IContextKey<boolean> | null = null; private _editorExecutingNotebook: IContextKey<boolean> | null = null; private _notebookHasMultipleKernels: IContextKey<boolean> | null = null; private _outputRenderer: OutputRenderer; protected readonly _contributions: { [key: string]: INotebookEditorContribution; }; private _scrollBeyondLastLine: boolean; private readonly _memento: Memento; private readonly _onDidFocusEmitter = this._register(new Emitter<void>()); public readonly onDidFocus = this._onDidFocusEmitter.event; private _cellContextKeyManager: CellContextKeyManager | null = null; private _isVisible = false; private readonly _uuid = generateUuid(); private _webiewFocused: boolean = false; private _isDisposed: boolean = false; get isDisposed() { return this._isDisposed; } private readonly _onDidChangeModel = this._register(new Emitter<NotebookTextModel | undefined>()); readonly onDidChangeModel: Event<NotebookTextModel | undefined> = this._onDidChangeModel.event; private readonly _onDidFocusEditorWidget = this._register(new Emitter<void>()); readonly onDidFocusEditorWidget = this._onDidFocusEditorWidget.event; set viewModel(newModel: NotebookViewModel | undefined) { this._notebookViewModel = newModel; this._onDidChangeModel.fire(newModel?.notebookDocument); } get viewModel() { return this._notebookViewModel; } get uri() { return this._notebookViewModel?.uri; } get textModel() { return this._notebookViewModel?.notebookDocument; } private _activeKernel: INotebookKernelInfo | undefined = undefined; private readonly _onDidChangeKernel = this._register(new Emitter<void>()); readonly onDidChangeKernel: Event<void> = this._onDidChangeKernel.event; get activeKernel() { return this._activeKernel; } set activeKernel(kernel: INotebookKernelInfo | undefined) { if (this._isDisposed) { return; } this._activeKernel = kernel; this._onDidChangeKernel.fire(); } private readonly _onDidChangeActiveEditor = this._register(new Emitter<this>()); readonly onDidChangeActiveEditor: Event<this> = this._onDidChangeActiveEditor.event; get activeCodeEditor(): IEditor | undefined { if (this._isDisposed) { return; } const [focused] = this._list!.getFocusedElements(); return this._renderedEditors.get(focused); } constructor( @IInstantiationService private readonly instantiationService: IInstantiationService, @IStorageService storageService: IStorageService, @INotebookService private notebookService: INotebookService, @IConfigurationService private readonly configurationService: IConfigurationService, @IContextKeyService readonly contextKeyService: IContextKeyService, @ILayoutService private readonly layoutService: ILayoutService ) { super(); this._memento = new Memento(NotebookEditorWidget.ID, storageService); this._outputRenderer = new OutputRenderer(this, this.instantiationService); this._contributions = {}; this._scrollBeyondLastLine = this.configurationService.getValue<boolean>('editor.scrollBeyondLastLine'); this.configurationService.onDidChangeConfiguration(e => { if (e.affectsConfiguration('editor.scrollBeyondLastLine')) { this._scrollBeyondLastLine = this.configurationService.getValue<boolean>('editor.scrollBeyondLastLine'); if (this._dimension && this._isVisible) { this.layout(this._dimension); } } }); this.notebookService.addNotebookEditor(this); } public getId(): string { return this._uuid; } hasModel() { return !!this._notebookViewModel; } //#region Editor Core protected getEditorMemento<T>(editorGroupService: IEditorGroupsService, key: string, limit: number = 10): IEditorMemento<T> { const mementoKey = `${NotebookEditorWidget.ID}${key}`; let editorMemento = NotebookEditorWidget.EDITOR_MEMENTOS.get(mementoKey); if (!editorMemento) { editorMemento = new EditorMemento(NotebookEditorWidget.ID, key, this.getMemento(StorageScope.WORKSPACE), limit, editorGroupService); NotebookEditorWidget.EDITOR_MEMENTOS.set(mementoKey, editorMemento); } return editorMemento as IEditorMemento<T>; } protected getMemento(scope: StorageScope): MementoObject { return this._memento.getMemento(scope); } public get isNotebookEditor() { return true; } updateEditorFocus() { // Note - focus going to the webview will fire 'blur', but the webview element will be // a descendent of the notebook editor root. const focused = DOM.isAncestor(document.activeElement, this._overlayContainer); this._editorFocus?.set(focused); this._notebookViewModel?.setFocus(focused); } hasFocus() { return this._editorFocus?.get() || false; } createEditor(): void { this._overlayContainer = document.createElement('div'); const id = generateUuid(); this._overlayContainer.id = `notebook-${id}`; this._overlayContainer.className = 'notebookOverlay'; DOM.addClass(this._overlayContainer, 'notebook-editor'); this._overlayContainer.style.visibility = 'hidden'; this.layoutService.container.appendChild(this._overlayContainer); this._createBody(this._overlayContainer); this._generateFontInfo(); this._editorFocus = NOTEBOOK_EDITOR_FOCUSED.bindTo(this.contextKeyService); this._editorFocus.set(true); this._isVisible = true; this._outputFocus = NOTEBOOK_OUTPUT_FOCUSED.bindTo(this.contextKeyService); this._editorEditable = NOTEBOOK_EDITOR_EDITABLE.bindTo(this.contextKeyService); this._editorEditable.set(true); this._editorRunnable = NOTEBOOK_EDITOR_RUNNABLE.bindTo(this.contextKeyService); this._editorRunnable.set(true); this._editorExecutingNotebook = NOTEBOOK_EDITOR_EXECUTING_NOTEBOOK.bindTo(this.contextKeyService); this._notebookHasMultipleKernels = NOTEBOOK_HAS_MULTIPLE_KERNELS.bindTo(this.contextKeyService); this._notebookHasMultipleKernels.set(false); const contributions = NotebookEditorExtensionsRegistry.getEditorContributions(); for (const desc of contributions) { try { const contribution = this.instantiationService.createInstance(desc.ctor, this); this._contributions[desc.id] = contribution; } catch (err) { onUnexpectedError(err); } } } private _generateFontInfo(): void { const editorOptions = this.configurationService.getValue<IEditorOptions>('editor'); this._fontInfo = BareFontInfo.createFromRawSettings(editorOptions, getZoomLevel()); } private _createBody(parent: HTMLElement): void { this._body = document.createElement('div'); DOM.addClass(this._body, 'cell-list-container'); this._createCellList(); DOM.append(parent, this._body); } private _createCellList(): void { DOM.addClass(this._body, 'cell-list-container'); this._dndController = this._register(new CellDragAndDropController(this, this._body)); const getScopedContextKeyService = (container?: HTMLElement) => this._list!.contextKeyService.createScoped(container); const renderers = [ this.instantiationService.createInstance(CodeCellRenderer, this, this._renderedEditors, this._dndController, getScopedContextKeyService), this.instantiationService.createInstance(MarkdownCellRenderer, this, this._dndController, this._renderedEditors, getScopedContextKeyService), ]; this._list = this.instantiationService.createInstance( NotebookCellList, 'NotebookCellList', this._body, this.instantiationService.createInstance(NotebookCellListDelegate), renderers, this.contextKeyService, { setRowLineHeight: false, setRowHeight: false, supportDynamicHeights: true, horizontalScrolling: false, keyboardSupport: false, mouseSupport: true, multipleSelectionSupport: false, enableKeyboardNavigation: true, additionalScrollHeight: 0, transformOptimization: false, styleController: (_suffix: string) => { return this._list!; }, overrideStyles: { listBackground: editorBackground, listActiveSelectionBackground: editorBackground, listActiveSelectionForeground: foreground, listFocusAndSelectionBackground: editorBackground, listFocusAndSelectionForeground: foreground, listFocusBackground: editorBackground, listFocusForeground: foreground, listHoverForeground: foreground, listHoverBackground: editorBackground, listHoverOutline: focusBorder, listFocusOutline: focusBorder, listInactiveSelectionBackground: editorBackground, listInactiveSelectionForeground: foreground, listInactiveFocusBackground: editorBackground, listInactiveFocusOutline: editorBackground, }, accessibilityProvider: { getAriaLabel() { return null; }, getWidgetAriaLabel() { return nls.localize('notebookTreeAriaLabel', "Notebook"); } } }, ); this._dndController.setList(this._list); // create Webview this._register(this._list); this._register(combinedDisposable(...renderers)); // transparent cover this._webviewTransparentCover = DOM.append(this._list.rowsContainer, $('.webview-cover')); this._webviewTransparentCover.style.display = 'none'; this._register(DOM.addStandardDisposableGenericMouseDownListner(this._overlayContainer, (e: StandardMouseEvent) => { if (DOM.hasClass(e.target, 'slider') && this._webviewTransparentCover) { this._webviewTransparentCover.style.display = 'block'; } })); this._register(DOM.addStandardDisposableGenericMouseUpListner(this._overlayContainer, () => { if (this._webviewTransparentCover) { // no matter when this._webviewTransparentCover.style.display = 'none'; } })); this._register(this._list.onMouseDown(e => { if (e.element) { this._onMouseDown.fire({ event: e.browserEvent, target: e.element }); } })); this._register(this._list.onMouseUp(e => { if (e.element) { this._onMouseUp.fire({ event: e.browserEvent, target: e.element }); } })); this._register(this._list.onDidChangeFocus(_e => this._onDidChangeActiveEditor.fire(this))); const widgetFocusTracker = DOM.trackFocus(this.getDomNode()); this._register(widgetFocusTracker); this._register(widgetFocusTracker.onDidFocus(() => this._onDidFocusEmitter.fire())); } getDomNode() { return this._overlayContainer; } onWillHide() { this._isVisible = false; this._editorFocus?.set(false); this._overlayContainer.style.visibility = 'hidden'; this._overlayContainer.style.left = '-50000px'; } getInnerWebview(): Webview | undefined { return this._webview?.webview; } focus() { this._isVisible = true; this._editorFocus?.set(true); if (this._webiewFocused) { this._webview?.focusWebview(); } else { const focus = this._list?.getFocus()[0]; if (typeof focus === 'number') { const element = this._notebookViewModel!.viewCells[focus]; if (element.focusMode === CellFocusMode.Editor) { element.editState = CellEditState.Editing; element.focusMode = CellFocusMode.Editor; this._onDidFocusEditorWidget.fire(); return; } } this._list?.domFocus(); } this._onDidFocusEditorWidget.fire(); } async setModel(textModel: NotebookTextModel, viewState: INotebookEditorViewState | undefined): Promise<void> { if (this._notebookViewModel === undefined || !this._notebookViewModel.equal(textModel)) { this._detachModel(); await this._attachModel(textModel, viewState); } else { this.restoreListViewState(viewState); } // clear state this._dndController?.clearGlobalDragState(); this._setKernels(textModel); this._localStore.add(this.notebookService.onDidChangeKernels(() => { if (this.activeKernel === undefined) { this._setKernels(textModel); } })); this._localStore.add(this._list!.onDidChangeFocus(() => { const focused = this._list!.getFocusedElements()[0]; if (focused) { if (!this._cellContextKeyManager) { this._cellContextKeyManager = this._localStore.add(new CellContextKeyManager(this.contextKeyService, textModel, focused as CellViewModel)); } this._cellContextKeyManager.updateForElement(focused as CellViewModel); } })); } async setOptions(options: NotebookEditorOptions | undefined) { // reveal cell if editor options tell to do so if (options?.cellOptions) { const cellOptions = options.cellOptions; const cell = this._notebookViewModel!.viewCells.find(cell => cell.uri.toString() === cellOptions.resource.toString()); if (cell) { this.selectElement(cell); this.revealInCenterIfOutsideViewport(cell); const editor = this._renderedEditors.get(cell)!; if (editor) { if (cellOptions.options?.selection) { const { selection } = cellOptions.options; editor.setSelection({ ...selection, endLineNumber: selection.endLineNumber || selection.startLineNumber, endColumn: selection.endColumn || selection.startColumn }); editor.revealPositionInCenterIfOutsideViewport({ lineNumber: selection.startLineNumber, column: selection.startColumn }); } if (!cellOptions.options?.preserveFocus) { editor.focus(); } } } } else if (this._notebookViewModel && this._notebookViewModel.viewCells.length === 1 && this._notebookViewModel.viewCells[0].cellKind === CellKind.Code) { // there is only one code cell in the document const cell = this._notebookViewModel!.viewCells[0]; if (cell.getTextLength() === 0) { // the cell is empty, very likely a template cell, focus it this.selectElement(cell); await this.revealLineInCenterAsync(cell, 1); const editor = this._renderedEditors.get(cell)!; if (editor) { editor.focus(); } } } } private _detachModel() { this._localStore.clear(); this._list?.detachViewModel(); this.viewModel?.dispose(); // avoid event this._notebookViewModel = undefined; // this.webview?.clearInsets(); // this.webview?.clearPreloadsCache(); this._webview?.dispose(); this._webview?.element.remove(); this._webview = null; this._list?.clear(); } private _setKernels(textModel: NotebookTextModel) { const provider = this.notebookService.getContributedNotebookProviders(this.viewModel!.uri)[0]; const availableKernels = this.notebookService.getContributedNotebookKernels(textModel.viewType, textModel.uri); if (provider.kernel && availableKernels.length > 0) { this._notebookHasMultipleKernels!.set(true); } else if (availableKernels.length > 1) { this._notebookHasMultipleKernels!.set(true); } else { this._notebookHasMultipleKernels!.set(false); } if (provider && provider.kernel) { // it has a builtin kernel, don't automatically choose a kernel this._loadKernelPreloads(provider.providerExtensionLocation, provider.kernel); return; } // the provider doesn't have a builtin kernel, choose a kernel this.activeKernel = availableKernels[0]; if (this.activeKernel) { this._loadKernelPreloads(this.activeKernel.extensionLocation, this.activeKernel); } } private _loadKernelPreloads(extensionLocation: URI, kernel: INotebookKernelInfoDto) { if (kernel.preloads) { this._webview?.updateKernelPreloads([extensionLocation], kernel.preloads.map(preload => URI.revive(preload))); } } private _updateForMetadata(): void { this._editorEditable?.set(!!this.viewModel!.metadata?.editable); this._editorRunnable?.set(!!this.viewModel!.metadata?.runnable); DOM.toggleClass(this._overlayContainer, 'notebook-editor-editable', !!this.viewModel!.metadata?.editable); DOM.toggleClass(this.getDomNode(), 'notebook-editor-editable', !!this.viewModel!.metadata?.editable); } private async _createWebview(id: string, resource: URI): Promise<void> { this._webview = this.instantiationService.createInstance(BackLayerWebView, this, id, resource); // attach the webview container to the DOM tree first this._list?.rowsContainer.insertAdjacentElement('afterbegin', this._webview.element); await this._webview.createWebview(); this._webview.webview.onDidBlur(() => { this._outputFocus?.set(false); this.updateEditorFocus(); if (this._overlayContainer.contains(document.activeElement)) { this._webiewFocused = false; } }); this._webview.webview.onDidFocus(() => { this._outputFocus?.set(true); this.updateEditorFocus(); this._onDidFocusEmitter.fire(); if (this._overlayContainer.contains(document.activeElement)) { this._webiewFocused = true; } }); this._localStore.add(this._webview.onMessage(({ message, forRenderer }) => { if (this.viewModel) { this.notebookService.onDidReceiveMessage(this.viewModel.viewType, this.getId(), forRenderer, message); } })); } private async _attachModel(textModel: NotebookTextModel, viewState: INotebookEditorViewState | undefined) { await this._createWebview(this.getId(), textModel.uri); this._eventDispatcher = new NotebookEventDispatcher(); this.viewModel = this.instantiationService.createInstance(NotebookViewModel, textModel.viewType, textModel, this._eventDispatcher, this.getLayoutInfo()); this._eventDispatcher.emit([new NotebookLayoutChangedEvent({ width: true, fontInfo: true }, this.getLayoutInfo())]); this._updateForMetadata(); this._localStore.add(this._eventDispatcher.onDidChangeMetadata(() => { this._updateForMetadata(); })); // restore view states, including contributions { // restore view state this.viewModel.restoreEditorViewState(viewState); // contribution state restore const contributionsState = viewState?.contributionsState || {}; const keys = Object.keys(this._contributions); for (let i = 0, len = keys.length; i < len; i++) { const id = keys[i]; const contribution = this._contributions[id]; if (typeof contribution.restoreViewState === 'function') { contribution.restoreViewState(contributionsState[id]); } } } this._webview?.updateRendererPreloads(this.viewModel.renderers); this._localStore.add(this._list!.onWillScroll(e => { this._webview!.updateViewScrollTop(-e.scrollTop, []); this._webviewTransparentCover!.style.top = `${e.scrollTop}px`; })); this._localStore.add(this._list!.onDidChangeContentHeight(() => { DOM.scheduleAtNextAnimationFrame(() => { if (this._isDisposed) { return; } const scrollTop = this._list?.scrollTop || 0; const scrollHeight = this._list?.scrollHeight || 0; this._webview!.element.style.height = `${scrollHeight}px`; if (this._webview?.insetMapping) { let updateItems: { cell: CodeCellViewModel, output: IProcessedOutput, cellTop: number }[] = []; let removedItems: IProcessedOutput[] = []; this._webview?.insetMapping.forEach((value, key) => { const cell = value.cell; const viewIndex = this._list?.getViewIndex(cell); if (viewIndex === undefined) { return; } if (cell.outputs.indexOf(key) < 0) { // output is already gone removedItems.push(key); } const cellTop = this._list?.getAbsoluteTopOfElement(cell) || 0; if (this._webview!.shouldUpdateInset(cell, key, cellTop)) { updateItems.push({ cell: cell, output: key, cellTop: cellTop }); } }); removedItems.forEach(output => this._webview?.removeInset(output)); if (updateItems.length) { this._webview?.updateViewScrollTop(-scrollTop, updateItems); } } }); })); this._list!.attachViewModel(this.viewModel); this._localStore.add(this._list!.onDidRemoveOutput(output => { this.removeInset(output); })); this._localStore.add(this._list!.onDidHideOutput(output => { this.hideInset(output); })); this._list!.layout(); this._dndController?.clearGlobalDragState(); // restore list state at last, it must be after list layout this.restoreListViewState(viewState); } restoreListViewState(viewState: INotebookEditorViewState | undefined): void { if (viewState?.scrollPosition !== undefined) { this._list!.scrollTop = viewState!.scrollPosition.top; this._list!.scrollLeft = viewState!.scrollPosition.left; } else { this._list!.scrollTop = 0; this._list!.scrollLeft = 0; } const focusIdx = typeof viewState?.focus === 'number' ? viewState.focus : 0; if (focusIdx < this._list!.length) { this._list!.setFocus([focusIdx]); this._list!.setSelection([focusIdx]); } else if (this._list!.length > 0) { this._list!.setFocus([0]); } if (viewState?.editorFocused) { this._list?.focusView(); const cell = this._notebookViewModel?.viewCells[focusIdx]; if (cell) { cell.focusMode = CellFocusMode.Editor; } } } getEditorViewState(): INotebookEditorViewState { const state = this._notebookViewModel?.getEditorViewState(); if (!state) { return { editingCells: {}, editorViewStates: {} }; } if (this._list) { state.scrollPosition = { left: this._list.scrollLeft, top: this._list.scrollTop }; let cellHeights: { [key: number]: number } = {}; for (let i = 0; i < this.viewModel!.length; i++) { const elm = this.viewModel!.viewCells[i] as CellViewModel; if (elm.cellKind === CellKind.Code) { cellHeights[i] = elm.layoutInfo.totalHeight; } else { cellHeights[i] = 0; } } state.cellTotalHeights = cellHeights; const focus = this._list.getFocus()[0]; if (typeof focus === 'number') { const element = this._notebookViewModel!.viewCells[focus]; if (element) { const itemDOM = this._list?.domElementOfElement(element); let editorFocused = !!(document.activeElement && itemDOM && itemDOM.contains(document.activeElement)); state.editorFocused = editorFocused; state.focus = focus; } } } // Save contribution view states const contributionsState: { [key: string]: unknown } = {}; const keys = Object.keys(this._contributions); for (const id of keys) { const contribution = this._contributions[id]; if (typeof contribution.saveViewState === 'function') { contributionsState[id] = contribution.saveViewState(); } } state.contributionsState = contributionsState; return state; } // private saveEditorViewState(input: NotebookEditorInput): void { // if (this.group && this.notebookViewModel) { // } // } // private loadTextEditorViewState(): INotebookEditorViewState | undefined { // return this.editorMemento.loadEditorState(this.group, input.resource); // } layout(dimension: DOM.Dimension, shadowElement?: HTMLElement): void { if (!shadowElement && this._shadowElementViewInfo === null) { this._dimension = dimension; return; } if (shadowElement) { const containerRect = shadowElement.getBoundingClientRect(); this._shadowElementViewInfo = { height: containerRect.height, width: containerRect.width, top: containerRect.top, left: containerRect.left }; } this._dimension = new DOM.Dimension(dimension.width, dimension.height); DOM.size(this._body, dimension.width, dimension.height); this._list?.updateOptions({ additionalScrollHeight: this._scrollBeyondLastLine ? dimension.height - SCROLLABLE_ELEMENT_PADDING_TOP : 0 }); this._list?.layout(dimension.height - SCROLLABLE_ELEMENT_PADDING_TOP, dimension.width); this._overlayContainer.style.visibility = 'visible'; this._overlayContainer.style.display = 'block'; this._overlayContainer.style.position = 'absolute'; this._overlayContainer.style.top = `${this._shadowElementViewInfo!.top}px`; this._overlayContainer.style.left = `${this._shadowElementViewInfo!.left}px`; this._overlayContainer.style.width = `${dimension ? dimension.width : this._shadowElementViewInfo!.width}px`; this._overlayContainer.style.height = `${dimension ? dimension.height : this._shadowElementViewInfo!.height}px`; if (this._webviewTransparentCover) { this._webviewTransparentCover.style.height = `${dimension.height}px`; this._webviewTransparentCover.style.width = `${dimension.width}px`; } this._eventDispatcher?.emit([new NotebookLayoutChangedEvent({ width: true, fontInfo: true }, this.getLayoutInfo())]); } // protected saveState(): void { // if (this.input instanceof NotebookEditorInput) { // this.saveEditorViewState(this.input); // } // super.saveState(); // } //#endregion //#region Editor Features selectElement(cell: ICellViewModel) { this._list?.selectElement(cell); // this.viewModel!.selectionHandles = [cell.handle]; } revealInView(cell: ICellViewModel) { this._list?.revealElementInView(cell); } revealInCenterIfOutsideViewport(cell: ICellViewModel) { this._list?.revealElementInCenterIfOutsideViewport(cell); } revealInCenter(cell: ICellViewModel) { this._list?.revealElementInCenter(cell); } async revealLineInViewAsync(cell: ICellViewModel, line: number): Promise<void> { return this._list?.revealElementLineInViewAsync(cell, line); } async revealLineInCenterAsync(cell: ICellViewModel, line: number): Promise<void> { return this._list?.revealElementLineInCenterAsync(cell, line); } async revealLineInCenterIfOutsideViewportAsync(cell: ICellViewModel, line: number): Promise<void> { return this._list?.revealElementLineInCenterIfOutsideViewportAsync(cell, line); } async revealRangeInViewAsync(cell: ICellViewModel, range: Range): Promise<void> { return this._list?.revealElementRangeInViewAsync(cell, range); } async revealRangeInCenterAsync(cell: ICellViewModel, range: Range): Promise<void> { return this._list?.revealElementRangeInCenterAsync(cell, range); } async revealRangeInCenterIfOutsideViewportAsync(cell: ICellViewModel, range: Range): Promise<void> { return this._list?.revealElementRangeInCenterIfOutsideViewportAsync(cell, range); } setCellSelection(cell: ICellViewModel, range: Range): void { this._list?.setCellSelection(cell, range); } changeDecorations<T>(callback: (changeAccessor: IModelDecorationsChangeAccessor) => T): T | null { return this._notebookViewModel?.changeDecorations<T>(callback) || null; } setHiddenAreas(_ranges: ICellRange[]): boolean { return this._list!.setHiddenAreas(_ranges, true); } //#endregion //#region Mouse Events private readonly _onMouseUp: Emitter<INotebookEditorMouseEvent> = this._register(new Emitter<INotebookEditorMouseEvent>()); public readonly onMouseUp: Event<INotebookEditorMouseEvent> = this._onMouseUp.event; private readonly _onMouseDown: Emitter<INotebookEditorMouseEvent> = this._register(new Emitter<INotebookEditorMouseEvent>()); public readonly onMouseDown: Event<INotebookEditorMouseEvent> = this._onMouseDown.event; private pendingLayouts = new WeakMap<ICellViewModel, IDisposable>(); //#endregion //#region Cell operations async layoutNotebookCell(cell: ICellViewModel, height: number): Promise<void> { const viewIndex = this._list!.getViewIndex(cell); if (viewIndex === undefined) { // the cell is hidden return; } let relayout = (cell: ICellViewModel, height: number) => { if (this._isDisposed) { return; } this._list?.updateElementHeight2(cell, height); }; if (this.pendingLayouts.has(cell)) { this.pendingLayouts.get(cell)!.dispose(); } let r: () => void; const layoutDisposable = DOM.scheduleAtNextAnimationFrame(() => { if (this._isDisposed) { return; } this.pendingLayouts.delete(cell); relayout(cell, height); r(); }); this.pendingLayouts.set(cell, toDisposable(() => { layoutDisposable.dispose(); r(); })); return new Promise(resolve => { r = resolve; }); } insertNotebookCell(cell: ICellViewModel | undefined, type: CellKind, direction: 'above' | 'below' = 'above', initialText: string = '', ui: boolean = false): CellViewModel | null { if (!this._notebookViewModel!.metadata.editable) { return null; } const index = cell ? this._notebookViewModel!.getCellIndex(cell) : 0; const nextIndex = ui ? this._notebookViewModel!.getNextVisibleCellIndex(index) : index + 1; const newLanguages = this._notebookViewModel!.languages; const language = (cell?.cellKind === CellKind.Code && type === CellKind.Code) ? cell.language : ((type === CellKind.Code && newLanguages && newLanguages.length) ? newLanguages[0] : 'markdown'); const insertIndex = cell ? (direction === 'above' ? index : nextIndex) : index; const newCell = this._notebookViewModel!.createCell(insertIndex, initialText.split(/\r?\n/g), language, type, undefined, true); return newCell as CellViewModel; } async splitNotebookCell(cell: ICellViewModel): Promise<CellViewModel[] | null> { const index = this._notebookViewModel!.getCellIndex(cell); return this._notebookViewModel!.splitNotebookCell(index); } async joinNotebookCells(cell: ICellViewModel, direction: 'above' | 'below', constraint?: CellKind): Promise<ICellViewModel | null> { const index = this._notebookViewModel!.getCellIndex(cell); const ret = await this._notebookViewModel!.joinNotebookCells(index, direction, constraint); if (ret) { ret.deletedCells.forEach(cell => { if (this.pendingLayouts.has(cell)) { this.pendingLayouts.get(cell)!.dispose(); } }); return ret.cell; } else { return null; } } async deleteNotebookCell(cell: ICellViewModel): Promise<boolean> { if (!this._notebookViewModel!.metadata.editable) { return false; } if (this.pendingLayouts.has(cell)) { this.pendingLayouts.get(cell)!.dispose(); } const index = this._notebookViewModel!.getCellIndex(cell); this._notebookViewModel!.deleteCell(index, true); return true; } async moveCellDown(cell: ICellViewModel): Promise<ICellViewModel | null> { if (!this._notebookViewModel!.metadata.editable) { return null; } const index = this._notebookViewModel!.getCellIndex(cell); if (index === this._notebookViewModel!.length - 1) { return null; } const newIdx = index + 1; return this._moveCellToIndex(index, newIdx); } async moveCellUp(cell: ICellViewModel): Promise<ICellViewModel | null> { if (!this._notebookViewModel!.metadata.editable) { return null; } const index = this._notebookViewModel!.getCellIndex(cell); if (index === 0) { return null; } const newIdx = index - 1; return this._moveCellToIndex(index, newIdx); } async moveCell(cell: ICellViewModel, relativeToCell: ICellViewModel, direction: 'above' | 'below'): Promise<ICellViewModel | null> { if (!this._notebookViewModel!.metadata.editable) { return null; } if (cell === relativeToCell) { return null; } const originalIdx = this._notebookViewModel!.getCellIndex(cell); const relativeToIndex = this._notebookViewModel!.getCellIndex(relativeToCell); let newIdx = direction === 'above' ? relativeToIndex : relativeToIndex + 1; if (originalIdx < newIdx) { newIdx--; } return this._moveCellToIndex(originalIdx, newIdx); } private async _moveCellToIndex(index: number, newIdx: number): Promise<ICellViewModel | null> { if (index === newIdx) { return null; } if (!this._notebookViewModel!.moveCellToIdx(index, newIdx, true)) { throw new Error('Notebook Editor move cell, index out of range'); } let r: (val: ICellViewModel | null) => void; DOM.scheduleAtNextAnimationFrame(() => { if (this._isDisposed) { r(null); } const viewCell = this._notebookViewModel!.viewCells[newIdx]; this._list?.revealElementInView(viewCell); r(viewCell); }); return new Promise(resolve => { r = resolve; }); } editNotebookCell(cell: CellViewModel): void { if (!cell.getEvaluatedMetadata(this._notebookViewModel!.metadata).editable) { return; } cell.editState = CellEditState.Editing; this._renderedEditors.get(cell)?.focus(); } getActiveCell() { let elements = this._list?.getFocusedElements(); if (elements && elements.length) { return elements[0]; } return undefined; } cancelNotebookExecution(): void { if (!this._notebookViewModel!.currentTokenSource) { throw new Error('Notebook is not executing'); } this._notebookViewModel!.currentTokenSource.cancel(); this._notebookViewModel!.currentTokenSource = undefined; } async executeNotebook(): Promise<void> { if (!this._notebookViewModel!.metadata.runnable) { return; } return this._executeNotebook(); } async _executeNotebook(): Promise<void> { if (this._notebookViewModel!.currentTokenSource) { return; } const tokenSource = new CancellationTokenSource(); try { this._editorExecutingNotebook!.set(true); this._notebookViewModel!.currentTokenSource = tokenSource; const provider = this.notebookService.getContributedNotebookProviders(this.viewModel!.uri)[0]; if (provider) { const viewType = provider.id; const notebookUri = this._notebookViewModel!.uri; if (this._activeKernel) { await this.notebookService.executeNotebook2(this._notebookViewModel!.viewType, this._notebookViewModel!.uri, this._activeKernel.id, tokenSource.token); } else if (provider.kernel) { return await this.notebookService.executeNotebook(viewType, notebookUri, true, tokenSource.token); } else { return await this.notebookService.executeNotebook(viewType, notebookUri, false, tokenSource.token); } } } finally { this._editorExecutingNotebook!.set(false); this._notebookViewModel!.currentTokenSource = undefined; tokenSource.dispose(); } } cancelNotebookCellExecution(cell: ICellViewModel): void { if (!cell.currentTokenSource) { throw new Error('Cell is not executing'); } cell.currentTokenSource.cancel(); cell.currentTokenSource = undefined; } async executeNotebookCell(cell: ICellViewModel): Promise<void> { if (cell.cellKind === CellKind.Markdown) { this.focusNotebookCell(cell, 'container'); return; } if (!cell.getEvaluatedMetadata(this._notebookViewModel!.metadata).runnable) { return; } const tokenSource = new CancellationTokenSource(); try { await this._executeNotebookCell(cell, tokenSource); } finally { tokenSource.dispose(); } } private async _executeNotebookCell(cell: ICellViewModel, tokenSource: CancellationTokenSource): Promise<void> { try { cell.currentTokenSource = tokenSource; const provider = this.notebookService.getContributedNotebookProviders(this.viewModel!.uri)[0]; if (provider) { const viewType = provider.id; const notebookUri = this._notebookViewModel!.uri; if (this._activeKernel) { return await this.notebookService.executeNotebookCell2(viewType, notebookUri, cell.handle, this._activeKernel.id, tokenSource.token); } else if (provider.kernel) { return await this.notebookService.executeNotebookCell(viewType, notebookUri, cell.handle, true, tokenSource.token); } else { return await this.notebookService.executeNotebookCell(viewType, notebookUri, cell.handle, false, tokenSource.token); } } } finally { cell.currentTokenSource = undefined; } } focusNotebookCell(cell: ICellViewModel, focusItem: 'editor' | 'container' | 'output') { if (this._isDisposed) { return; } if (focusItem === 'editor') { this.selectElement(cell); this._list?.focusView(); cell.editState = CellEditState.Editing; cell.focusMode = CellFocusMode.Editor; this.revealInCenterIfOutsideViewport(cell); } else if (focusItem === 'output') { this.selectElement(cell); this._list?.focusView(); if (!this._webview) { return; } this._webview.focusOutput(cell.id); cell.editState = CellEditState.Preview; cell.focusMode = CellFocusMode.Container; this.revealInCenterIfOutsideViewport(cell); } else { let itemDOM = this._list?.domElementOfElement(cell); if (document.activeElement && itemDOM && itemDOM.contains(document.activeElement)) { (document.activeElement as HTMLElement).blur(); } cell.editState = CellEditState.Preview; cell.focusMode = CellFocusMode.Container; this.selectElement(cell); this.revealInCenterIfOutsideViewport(cell); this._list?.focusView(); } } //#endregion //#region MISC getLayoutInfo(): NotebookLayoutInfo { if (!this._list) { throw new Error('Editor is not initalized successfully'); } return { width: this._dimension!.width, height: this._dimension!.height, fontInfo: this._fontInfo! }; } triggerScroll(event: IMouseWheelEvent) { this._list?.triggerScrollFromMouseWheelEvent(event); } async createInset(cell: CodeCellViewModel, output: IProcessedOutput, shadowContent: string, offset: number) { if (!this._webview) { return; } let preloads = this._notebookViewModel!.renderers; if (!this._webview!.insetMapping.has(output)) { let cellTop = this._list?.getAbsoluteTopOfElement(cell) || 0; await this._webview!.createInset(cell, output, cellTop, offset, shadowContent, preloads); } else { let cellTop = this._list?.getAbsoluteTopOfElement(cell) || 0; let scrollTop = this._list?.scrollTop || 0; this._webview!.updateViewScrollTop(-scrollTop, [{ cell: cell, output: output, cellTop: cellTop }]); } } removeInset(output: IProcessedOutput) { if (!this._webview) { return; } this._webview!.removeInset(output); } hideInset(output: IProcessedOutput) { if (!this._webview) { return; } this._webview!.hideInset(output); } getOutputRenderer(): OutputRenderer { return this._outputRenderer; } postMessage(forRendererId: string | undefined, message: any) { if (forRendererId === undefined) { this._webview?.webview.postMessage(message); } else { this._webview?.postRendererMessage(forRendererId, message); } } toggleClassName(className: string) { DOM.toggleClass(this._overlayContainer, className); } addClassName(className: string) { DOM.addClass(this._overlayContainer, className); } removeClassName(className: string) { DOM.removeClass(this._overlayContainer, className); } //#endregion //#region Editor Contributions public getContribution<T extends INotebookEditorContribution>(id: string): T { return <T>(this._contributions[id] || null); } //#endregion dispose() { this._isDisposed = true; // dispose webview first this._webview?.dispose(); this.notebookService.removeNotebookEditor(this); const keys = Object.keys(this._contributions); for (let i = 0, len = keys.length; i < len; i++) { const contributionId = keys[i]; this._contributions[contributionId].dispose(); } this._localStore.clear(); this._list?.dispose(); this._overlayContainer.remove(); this.viewModel?.dispose(); // this._layoutService.container.removeChild(this.overlayContainer); super.dispose(); } toJSON(): object { return { notebookHandle: this.viewModel?.handle }; } } export const notebookCellBorder = registerColor('notebook.cellBorderColor', { dark: transparent(PANEL_BORDER, .4), light: transparent(listInactiveSelectionBackground, 1), hc: PANEL_BORDER }, nls.localize('notebook.cellBorderColor', "The border color for notebook cells.")); export const focusedEditorBorderColor = registerColor('notebook.focusedEditorBorder', { light: focusBorder, dark: focusBorder, hc: focusBorder }, nls.localize('notebook.focusedEditorBorder', "The color of the notebook cell editor border.")); export const cellStatusIconSuccess = registerColor('notebookStatusSuccessIcon.foreground', { light: debugIconStartForeground, dark: debugIconStartForeground, hc: debugIconStartForeground }, nls.localize('notebookStatusSuccessIcon.foreground', "The error icon color of notebook cells in the cell status bar.")); export const cellStatusIconError = registerColor('notebookStatusErrorIcon.foreground', { light: errorForeground, dark: errorForeground, hc: errorForeground }, nls.localize('notebookStatusErrorIcon.foreground', "The error icon color of notebook cells in the cell status bar.")); export const cellStatusIconRunning = registerColor('notebookStatusRunningIcon.foreground', { light: foreground, dark: foreground, hc: foreground }, nls.localize('notebookStatusRunningIcon.foreground', "The running icon color of notebook cells in the cell status bar.")); export const notebookOutputContainerColor = registerColor('notebook.outputContainerBackgroundColor', { dark: notebookCellBorder, light: transparent(listFocusBackground, .4), hc: null }, nls.localize('notebook.outputContainerBackgroundColor', "The Color of the notebook output container background.")); // TODO currently also used for toolbar border, if we keep all of this, pick a generic name export const CELL_TOOLBAR_SEPERATOR = registerColor('notebook.cellToolbarSeperator', { dark: Color.fromHex('#808080').transparent(0.35), light: Color.fromHex('#808080').transparent(0.35), hc: contrastBorder }, nls.localize('notebook.cellToolbarSeperator', "The color of the seperator in the cell bottom toolbar")); export const focusedCellBackground = registerColor('notebook.focusedCellBackground', { dark: transparent(PANEL_BORDER, .4), light: transparent(listFocusBackground, .4), hc: null }, nls.localize('focusedCellBackground', "The background color of a cell when the cell is focused.")); export const cellHoverBackground = registerColor('notebook.cellHoverBackground', { dark: transparent(focusedCellBackground, .5), light: transparent(focusedCellBackground, .7), hc: null }, nls.localize('notebook.cellHoverBackground', "The background color of a cell when the cell is hovered.")); export const focusedCellBorder = registerColor('notebook.focusedCellBorder', { dark: Color.white.transparent(0.12), light: Color.black.transparent(0.12), hc: focusBorder }, nls.localize('notebook.focusedCellBorder', "The color of the cell's top and bottom border when the cell is focused.")); export const focusedCellShadow = registerColor('notebook.focusedCellShadow', { dark: transparent(widgetShadow, 0.6), light: transparent(widgetShadow, 0.4), hc: Color.transparent }, nls.localize('notebook.focusedCellShadow', "The color of the cell shadow when cells are focused.")); export const cellStatusBarItemHover = registerColor('notebook.cellStatusBarItemHoverBackground', { light: new Color(new RGBA(0, 0, 0, 0.08)), dark: new Color(new RGBA(255, 255, 255, 0.15)), hc: new Color(new RGBA(255, 255, 255, 0.15)), }, nls.localize('notebook.cellStatusBarItemHoverBackground', "The background color of notebook cell status bar items.")); export const cellInsertionIndicator = registerColor('notebook.cellInsertionIndicator', { light: focusBorder, dark: focusBorder, hc: focusBorder }, nls.localize('notebook.cellInsertionIndicator', "The color of the notebook cell insertion indicator.")); export const listScrollbarSliderBackground = registerColor('notebookScrollbarSlider.background', { dark: scrollbarSliderBackground, light: scrollbarSliderBackground, hc: scrollbarSliderBackground }, nls.localize('notebookScrollbarSliderBackground', "Notebook scrollbar slider background color.")); export const listScrollbarSliderHoverBackground = registerColor('notebookScrollbarSlider.hoverBackground', { dark: scrollbarSliderHoverBackground, light: scrollbarSliderHoverBackground, hc: scrollbarSliderHoverBackground }, nls.localize('notebookScrollbarSliderHoverBackground', "Notebook scrollbar slider background color when hovering.")); export const listScrollbarSliderActiveBackground = registerColor('notebookScrollbarSlider.activeBackground', { dark: scrollbarSliderActiveBackground, light: scrollbarSliderActiveBackground, hc: scrollbarSliderActiveBackground }, nls.localize('notebookScrollbarSliderActiveBackground', "Notebook scrollbar slider background color when clicked on.")); registerThemingParticipant((theme, collector) => { collector.addRule(`.notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element { padding-top: ${SCROLLABLE_ELEMENT_PADDING_TOP}px; box-sizing: border-box; }`); // const color = getExtraColor(theme, embeddedEditorBackground, { dark: 'rgba(0, 0, 0, .4)', extra_dark: 'rgba(200, 235, 255, .064)', light: '#f4f4f4', hc: null }); const color = theme.getColor(editorBackground); if (color) { collector.addRule(`.notebookOverlay .cell .monaco-editor-background, .notebookOverlay .cell .margin-view-overlays, .notebookOverlay .cell .cell-statusbar-container { background: ${color}; }`); collector.addRule(`.notebookOverlay .cell-drag-image .cell-editor-container > div { background: ${color} !important; }`); } const link = theme.getColor(textLinkForeground); if (link) { collector.addRule(`.notebookOverlay .output a, .notebookOverlay .cell.markdown a { color: ${link};} `); } const activeLink = theme.getColor(textLinkActiveForeground); if (activeLink) { collector.addRule(`.notebookOverlay .output a:hover, .notebookOverlay .cell .output a:active { color: ${activeLink}; }`); } const shortcut = theme.getColor(textPreformatForeground); if (shortcut) { collector.addRule(`.notebookOverlay code, .notebookOverlay .shortcut { color: ${shortcut}; }`); } const border = theme.getColor(contrastBorder); if (border) { collector.addRule(`.notebookOverlay .monaco-editor { border-color: ${border}; }`); } const quoteBackground = theme.getColor(textBlockQuoteBackground); if (quoteBackground) { collector.addRule(`.notebookOverlay blockquote { background: ${quoteBackground}; }`); } const quoteBorder = theme.getColor(textBlockQuoteBorder); if (quoteBorder) { collector.addRule(`.notebookOverlay blockquote { border-color: ${quoteBorder}; }`); } const containerBackground = theme.getColor(notebookOutputContainerColor); if (containerBackground) { collector.addRule(`.notebookOverlay .output { background-color: ${containerBackground}; }`); collector.addRule(`.notebookOverlay .output-element { background-color: ${containerBackground}; }`); } const editorBackgroundColor = theme.getColor(editorBackground); if (editorBackgroundColor) { collector.addRule(`.notebookOverlay .cell-statusbar-container { border-top: solid 1px ${editorBackgroundColor}; }`); collector.addRule(`.notebookOverlay .monaco-list-row > .monaco-toolbar { background-color: ${editorBackgroundColor}; }`); collector.addRule(`.notebookOverlay .monaco-list-row.cell-drag-image { background-color: ${editorBackgroundColor}; }`); } const cellToolbarSeperator = theme.getColor(CELL_TOOLBAR_SEPERATOR); if (cellToolbarSeperator) { collector.addRule(`.notebookOverlay .cell-bottom-toolbar-container .separator { background-color: ${cellToolbarSeperator} }`); collector.addRule(`.notebookOverlay .cell-bottom-toolbar-container .action-item:first-child::after { background-color: ${cellToolbarSeperator} }`); collector.addRule(`.notebookOverlay .monaco-list-row > .monaco-toolbar { border: solid 1px ${cellToolbarSeperator}; }`); } const focusedCellBackgroundColor = theme.getColor(focusedCellBackground); if (focusedCellBackgroundColor) { collector.addRule(`.notebookOverlay .code-cell-row.focused .cell-focus-indicator, .notebookOverlay .markdown-cell-row.focused { background-color: ${focusedCellBackgroundColor} !important; }`); } const cellHoverBackgroundColor = theme.getColor(cellHoverBackground); if (cellHoverBackgroundColor) { collector.addRule(`.notebookOverlay .code-cell-row:not(.focused):hover .cell-focus-indicator, .notebookOverlay .code-cell-row:not(.focused).cell-output-hover .cell-focus-indicator, .notebookOverlay .markdown-cell-row:not(.focused):hover { background-color: ${cellHoverBackgroundColor} !important; }`); } const focusedCellBorderColor = theme.getColor(focusedCellBorder); collector.addRule(`.monaco-workbench .notebookOverlay .monaco-list .monaco-list-row.focused .cell-focus-indicator-top:before, .monaco-workbench .notebookOverlay .monaco-list .monaco-list-row.focused .cell-focus-indicator-bottom:before, .monaco-workbench .notebookOverlay .monaco-list .markdown-cell-row.focused:before, .monaco-workbench .notebookOverlay .monaco-list .markdown-cell-row.focused:after { border-color: ${focusedCellBorderColor} !important; }`); const focusedEditorBorderColorColor = theme.getColor(focusedEditorBorderColor); if (focusedEditorBorderColorColor) { collector.addRule(`.notebookOverlay .monaco-list-row.cell-editor-focus .cell-editor-part:before { outline: solid 1px ${focusedEditorBorderColorColor}; }`); } const editorBorderColor = theme.getColor(notebookCellBorder); if (editorBorderColor) { collector.addRule(`.notebookOverlay .monaco-list-row .cell-editor-part:before { outline: solid 1px ${editorBorderColor}; }`); } const headingBorderColor = theme.getColor(notebookCellBorder); if (headingBorderColor) { collector.addRule(`.notebookOverlay .cell.markdown h1 { border-color: ${headingBorderColor}; }`); } const cellStatusSuccessIcon = theme.getColor(cellStatusIconSuccess); if (cellStatusSuccessIcon) { collector.addRule(`.monaco-workbench .notebookOverlay .cell-statusbar-container .cell-run-status .codicon-check { color: ${cellStatusSuccessIcon} }`); } const cellStatusErrorIcon = theme.getColor(cellStatusIconError); if (cellStatusErrorIcon) { collector.addRule(`.monaco-workbench .notebookOverlay .cell-statusbar-container .cell-run-status .codicon-error { color: ${cellStatusErrorIcon} }`); } const cellStatusRunningIcon = theme.getColor(cellStatusIconRunning); if (cellStatusRunningIcon) { collector.addRule(`.monaco-workbench .notebookOverlay .cell-statusbar-container .cell-run-status .codicon-sync { color: ${cellStatusRunningIcon} }`); } const cellStatusBarHoverBg = theme.getColor(cellStatusBarItemHover); if (cellStatusBarHoverBg) { collector.addRule(`.monaco-workbench .notebookOverlay .cell-statusbar-container .cell-language-picker:hover { background-color: ${cellStatusBarHoverBg}; }`); } const cellShadowColor = theme.getColor(focusedCellShadow); if (cellShadowColor) { // Code cells collector.addRule(`.monaco-workbench .notebookOverlay .monaco-list .monaco-list-row.focused .cell-shadow { box-shadow: 0px 0px 4px 2px ${cellShadowColor} }`); // Markdown cells collector.addRule(`.monaco-workbench .notebookOverlay .monaco-list .markdown-cell-row.focused { box-shadow: 0px 0px 4px 2px ${cellShadowColor} }`); } const cellInsertionIndicatorColor = theme.getColor(cellInsertionIndicator); if (cellInsertionIndicatorColor) { collector.addRule(`.notebookOverlay > .cell-list-container > .cell-list-insertion-indicator { background-color: ${cellInsertionIndicatorColor}; }`); } const scrollbarSliderBackgroundColor = theme.getColor(listScrollbarSliderBackground); if (scrollbarSliderBackgroundColor) { collector.addRule(` .notebookOverlay .cell-list-container > .monaco-list > .monaco-scrollable-element > .scrollbar > .slider { background: ${editorBackgroundColor}; } `); collector.addRule(` .notebookOverlay .cell-list-container > .monaco-list > .monaco-scrollable-element > .scrollbar > .slider:before { content: ""; width: 100%; height: 100%; position: absolute; background: ${scrollbarSliderBackgroundColor}; } `); /* hack to not have cells see through scroller */ } const scrollbarSliderHoverBackgroundColor = theme.getColor(listScrollbarSliderHoverBackground); if (scrollbarSliderHoverBackgroundColor) { collector.addRule(` .notebookOverlay .cell-list-container > .monaco-list > .monaco-scrollable-element > .scrollbar > .slider:hover { background: ${editorBackgroundColor}; } `); collector.addRule(` .notebookOverlay .cell-list-container > .monaco-list > .monaco-scrollable-element > .scrollbar > .slider:hover:before { content: ""; width: 100%; height: 100%; position: absolute; background: ${scrollbarSliderHoverBackgroundColor}; } `); /* hack to not have cells see through scroller */ } const scrollbarSliderActiveBackgroundColor = theme.getColor(listScrollbarSliderActiveBackground); if (scrollbarSliderActiveBackgroundColor) { collector.addRule(` .notebookOverlay .cell-list-container > .monaco-list > .monaco-scrollable-element > .scrollbar > .slider.active { background: ${editorBackgroundColor}; } `); collector.addRule(` .notebookOverlay .cell-list-container > .monaco-list > .monaco-scrollable-element > .scrollbar > .slider.active:before { content: ""; width: 100%; height: 100%; position: absolute; background: ${scrollbarSliderActiveBackgroundColor}; } `); /* hack to not have cells see through scroller */ } // Cell Margin collector.addRule(`.notebookOverlay .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row > div.cell { margin: 0px ${CELL_MARGIN * 2}px 0px ${CELL_MARGIN}px; }`); collector.addRule(`.notebookOverlay .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row > div.cell.code { margin-left: ${CODE_CELL_LEFT_MARGIN}px; }`); collector.addRule(`.notebookOverlay .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row { padding-top: ${EDITOR_TOP_MARGIN}px; }`); collector.addRule(`.notebookOverlay .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .markdown-cell-row { padding-bottom: ${CELL_BOTTOM_MARGIN}px; }`); collector.addRule(`.notebookOverlay .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .markdown-cell-row .cell-bottom-toolbar-container { margin-top: ${CELL_BOTTOM_MARGIN}px; }`); collector.addRule(`.notebookOverlay .output { margin: 0px ${CELL_MARGIN}px 0px ${CODE_CELL_LEFT_MARGIN + CELL_RUN_GUTTER}px; }`); collector.addRule(`.notebookOverlay .output { width: calc(100% - ${CODE_CELL_LEFT_MARGIN + CELL_RUN_GUTTER + (CELL_MARGIN * 2)}px); }`); collector.addRule(`.notebookOverlay .cell-bottom-toolbar-container { width: calc(100% - ${CELL_MARGIN * 2 + CELL_RUN_GUTTER}px); margin: 0px ${CELL_MARGIN * 2}px 0px ${CELL_MARGIN + CELL_RUN_GUTTER}px; }`); collector.addRule(`.notebookOverlay .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row > div.cell.markdown { padding-left: ${CELL_RUN_GUTTER}px; }`); collector.addRule(`.notebookOverlay .cell .run-button-container { width: ${CELL_RUN_GUTTER}px; }`); collector.addRule(`.notebookOverlay .cell-drag-image .cell-editor-container > div { padding: ${EDITOR_TOP_PADDING}px 16px ${EDITOR_BOTTOM_PADDING}px 16px; }`); collector.addRule(`.notebookOverlay .monaco-list .monaco-list-row .cell-focus-indicator-top { height: ${EDITOR_TOP_MARGIN}px; }`); collector.addRule(`.notebookOverlay .monaco-list .monaco-list-row .cell-focus-indicator-side { bottom: ${BOTTOM_CELL_TOOLBAR_HEIGHT}px; }`); collector.addRule(`.notebookOverlay .monaco-list .monaco-list-row.code-cell-row .cell-focus-indicator-left { width: ${CODE_CELL_LEFT_MARGIN + CELL_RUN_GUTTER}px; }`); collector.addRule(`.notebookOverlay .monaco-list .monaco-list-row.markdown-cell-row .cell-focus-indicator-left { width: ${CODE_CELL_LEFT_MARGIN}px; }`); collector.addRule(`.notebookOverlay .monaco-list .monaco-list-row .cell-focus-indicator.cell-focus-indicator-right { width: ${CELL_MARGIN * 2}px; }`); collector.addRule(`.notebookOverlay .monaco-list .monaco-list-row .cell-focus-indicator-bottom { height: ${CELL_BOTTOM_MARGIN}px; }`); collector.addRule(`.notebookOverlay .monaco-list .monaco-list-row .cell-shadow-container-bottom { top: ${CELL_BOTTOM_MARGIN}px; }`); });
src/vs/workbench/contrib/notebook/browser/notebookEditorWidget.ts
1
https://github.com/microsoft/vscode/commit/9504dda6a717a0a0d45d992e21f2565f8a23f390
[ 0.00020170646894257516, 0.0001716587576083839, 0.0001630308834137395, 0.00017176117398776114, 0.000003807341045103385 ]
{ "id": 2, "code_window": [ "import { ServicesAccessor } from 'vs/platform/instantiation/common/instantiation';\n", "\n", "\n", "registerAction2(class extends Action2 {\n" ], "labels": [ "add", "keep", "keep", "keep" ], "after_edit": [ "import { IQuickInputService, IQuickPickItem, QuickPickInput } from 'vs/platform/quickinput/common/quickInput';\n", "import { INotebookCellActionContext, NOTEBOOK_ACTIONS_CATEGORY } from 'vs/workbench/contrib/notebook/browser/contrib/coreActions';\n", "import { INotebookEditor, NOTEBOOK_HAS_MULTIPLE_KERNELS, NOTEBOOK_IS_ACTIVE_EDITOR } from 'vs/workbench/contrib/notebook/browser/notebookBrowser';\n", "import { INotebookService } from 'vs/workbench/contrib/notebook/common/notebookService';\n", "import { IEditorService } from 'vs/workbench/services/editor/common/editorService';\n" ], "file_path": "src/vs/workbench/contrib/notebook/browser/contrib/status/editorStatus.ts", "type": "add", "edit_start_line_idx": 14 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as assert from 'assert'; import { parseLinkedText } from 'vs/base/common/linkedText'; suite('LinkedText', () => { test('parses correctly', () => { assert.deepEqual(parseLinkedText('').nodes, []); assert.deepEqual(parseLinkedText('hello').nodes, ['hello']); assert.deepEqual(parseLinkedText('hello there').nodes, ['hello there']); assert.deepEqual(parseLinkedText('Some message with [link text](http://link.href).').nodes, [ 'Some message with ', { label: 'link text', href: 'http://link.href' }, '.' ]); assert.deepEqual(parseLinkedText('Some message with [link text](http://link.href "and a title").').nodes, [ 'Some message with ', { label: 'link text', href: 'http://link.href', title: 'and a title' }, '.' ]); assert.deepEqual(parseLinkedText('Some message with [link text](http://link.href \'and a title\').').nodes, [ 'Some message with ', { label: 'link text', href: 'http://link.href', title: 'and a title' }, '.' ]); assert.deepEqual(parseLinkedText('Some message with [link text](http://link.href "and a \'title\'").').nodes, [ 'Some message with ', { label: 'link text', href: 'http://link.href', title: 'and a \'title\'' }, '.' ]); assert.deepEqual(parseLinkedText('Some message with [link text](http://link.href \'and a "title"\').').nodes, [ 'Some message with ', { label: 'link text', href: 'http://link.href', title: 'and a "title"' }, '.' ]); assert.deepEqual(parseLinkedText('Some message with [link text](random stuff).').nodes, [ 'Some message with [link text](random stuff).' ]); assert.deepEqual(parseLinkedText('Some message with [https link](https://link.href).').nodes, [ 'Some message with ', { label: 'https link', href: 'https://link.href' }, '.' ]); assert.deepEqual(parseLinkedText('Some message with [https link](https:).').nodes, [ 'Some message with [https link](https:).' ]); assert.deepEqual(parseLinkedText('Some message with [a command](command:foobar).').nodes, [ 'Some message with ', { label: 'a command', href: 'command:foobar' }, '.' ]); assert.deepEqual(parseLinkedText('Some message with [a command](command:).').nodes, [ 'Some message with [a command](command:).' ]); assert.deepEqual(parseLinkedText('link [one](command:foo "nice") and link [two](http://foo)...').nodes, [ 'link ', { label: 'one', href: 'command:foo', title: 'nice' }, ' and link ', { label: 'two', href: 'http://foo' }, '...' ]); assert.deepEqual(parseLinkedText('link\n[one](command:foo "nice")\nand link [two](http://foo)...').nodes, [ 'link\n', { label: 'one', href: 'command:foo', title: 'nice' }, '\nand link ', { label: 'two', href: 'http://foo' }, '...' ]); }); });
src/vs/base/test/common/linkedText.test.ts
0
https://github.com/microsoft/vscode/commit/9504dda6a717a0a0d45d992e21f2565f8a23f390
[ 0.00017753815336618572, 0.00017047075380105525, 0.00016564993711654097, 0.0001702010486042127, 0.00000357025487573992 ]
{ "id": 2, "code_window": [ "import { ServicesAccessor } from 'vs/platform/instantiation/common/instantiation';\n", "\n", "\n", "registerAction2(class extends Action2 {\n" ], "labels": [ "add", "keep", "keep", "keep" ], "after_edit": [ "import { IQuickInputService, IQuickPickItem, QuickPickInput } from 'vs/platform/quickinput/common/quickInput';\n", "import { INotebookCellActionContext, NOTEBOOK_ACTIONS_CATEGORY } from 'vs/workbench/contrib/notebook/browser/contrib/coreActions';\n", "import { INotebookEditor, NOTEBOOK_HAS_MULTIPLE_KERNELS, NOTEBOOK_IS_ACTIVE_EDITOR } from 'vs/workbench/contrib/notebook/browser/notebookBrowser';\n", "import { INotebookService } from 'vs/workbench/contrib/notebook/common/notebookService';\n", "import { IEditorService } from 'vs/workbench/services/editor/common/editorService';\n" ], "file_path": "src/vs/workbench/contrib/notebook/browser/contrib/status/editorStatus.ts", "type": "add", "edit_start_line_idx": 14 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { IAction } from 'vs/base/common/actions'; import { Disposable, MutableDisposable, toDisposable } from 'vs/base/common/lifecycle'; import { Emitter, Event } from 'vs/base/common/event'; import { MenuId, IMenuService } from 'vs/platform/actions/common/actions'; import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { createAndFillInActionBarActions } from 'vs/platform/actions/browser/menuEntryActionViewItem'; export class ViewMenuActions extends Disposable { private primaryActions: IAction[] = []; private readonly titleActionsDisposable = this._register(new MutableDisposable()); private secondaryActions: IAction[] = []; private contextMenuActions: IAction[] = []; private _onDidChangeTitle = this._register(new Emitter<void>()); readonly onDidChangeTitle: Event<void> = this._onDidChangeTitle.event; constructor( viewId: string, menuId: MenuId, contextMenuId: MenuId, @IContextKeyService private readonly contextKeyService: IContextKeyService, @IMenuService private readonly menuService: IMenuService, ) { super(); const scopedContextKeyService = this._register(this.contextKeyService.createScoped()); scopedContextKeyService.createKey('view', viewId); const menu = this._register(this.menuService.createMenu(menuId, scopedContextKeyService)); const updateActions = () => { this.primaryActions = []; this.secondaryActions = []; this.titleActionsDisposable.value = createAndFillInActionBarActions(menu, { shouldForwardArgs: true }, { primary: this.primaryActions, secondary: this.secondaryActions }); this._onDidChangeTitle.fire(); }; this._register(menu.onDidChange(updateActions)); updateActions(); const contextMenu = this._register(this.menuService.createMenu(contextMenuId, scopedContextKeyService)); const updateContextMenuActions = () => { this.contextMenuActions = []; this.titleActionsDisposable.value = createAndFillInActionBarActions(contextMenu, { shouldForwardArgs: true }, { primary: [], secondary: this.contextMenuActions }); }; this._register(contextMenu.onDidChange(updateContextMenuActions)); updateContextMenuActions(); this._register(toDisposable(() => { this.primaryActions = []; this.secondaryActions = []; this.contextMenuActions = []; })); } getPrimaryActions(): IAction[] { return this.primaryActions; } getSecondaryActions(): IAction[] { return this.secondaryActions; } getContextMenuActions(): IAction[] { return this.contextMenuActions; } } export class ViewContainerMenuActions extends Disposable { private readonly titleActionsDisposable = this._register(new MutableDisposable()); private contextMenuActions: IAction[] = []; constructor( containerId: string, contextMenuId: MenuId, @IContextKeyService private readonly contextKeyService: IContextKeyService, @IMenuService private readonly menuService: IMenuService, ) { super(); const scopedContextKeyService = this._register(this.contextKeyService.createScoped()); scopedContextKeyService.createKey('container', containerId); const contextMenu = this._register(this.menuService.createMenu(contextMenuId, scopedContextKeyService)); const updateContextMenuActions = () => { this.contextMenuActions = []; this.titleActionsDisposable.value = createAndFillInActionBarActions(contextMenu, { shouldForwardArgs: true }, { primary: [], secondary: this.contextMenuActions }); }; this._register(contextMenu.onDidChange(updateContextMenuActions)); updateContextMenuActions(); this._register(toDisposable(() => { this.contextMenuActions = []; })); } getContextMenuActions(): IAction[] { return this.contextMenuActions; } }
src/vs/workbench/browser/parts/views/viewMenuActions.ts
0
https://github.com/microsoft/vscode/commit/9504dda6a717a0a0d45d992e21f2565f8a23f390
[ 0.0002988771302625537, 0.00018602996715344489, 0.00016627134755253792, 0.0001697372063063085, 0.00003743891647900455 ]
{ "id": 2, "code_window": [ "import { ServicesAccessor } from 'vs/platform/instantiation/common/instantiation';\n", "\n", "\n", "registerAction2(class extends Action2 {\n" ], "labels": [ "add", "keep", "keep", "keep" ], "after_edit": [ "import { IQuickInputService, IQuickPickItem, QuickPickInput } from 'vs/platform/quickinput/common/quickInput';\n", "import { INotebookCellActionContext, NOTEBOOK_ACTIONS_CATEGORY } from 'vs/workbench/contrib/notebook/browser/contrib/coreActions';\n", "import { INotebookEditor, NOTEBOOK_HAS_MULTIPLE_KERNELS, NOTEBOOK_IS_ACTIVE_EDITOR } from 'vs/workbench/contrib/notebook/browser/notebookBrowser';\n", "import { INotebookService } from 'vs/workbench/contrib/notebook/common/notebookService';\n", "import { IEditorService } from 'vs/workbench/services/editor/common/editorService';\n" ], "file_path": "src/vs/workbench/contrib/notebook/browser/contrib/status/editorStatus.ts", "type": "add", "edit_start_line_idx": 14 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { LinkDetector } from 'vs/workbench/contrib/debug/browser/linkDetector'; import { RGBA, Color } from 'vs/base/common/color'; import { IThemeService } from 'vs/platform/theme/common/themeService'; import { ansiColorIdentifiers } from 'vs/workbench/contrib/terminal/common/terminalColorRegistry'; import { IDebugSession } from 'vs/workbench/contrib/debug/common/debug'; /** * @param text The content to stylize. * @returns An {@link HTMLSpanElement} that contains the potentially stylized text. */ export function handleANSIOutput(text: string, linkDetector: LinkDetector, themeService: IThemeService, debugSession: IDebugSession): HTMLSpanElement { const root: HTMLSpanElement = document.createElement('span'); const textLength: number = text.length; let styleNames: string[] = []; let customFgColor: RGBA | undefined; let customBgColor: RGBA | undefined; let currentPos: number = 0; let buffer: string = ''; while (currentPos < textLength) { let sequenceFound: boolean = false; // Potentially an ANSI escape sequence. // See http://ascii-table.com/ansi-escape-sequences.php & https://en.wikipedia.org/wiki/ANSI_escape_code if (text.charCodeAt(currentPos) === 27 && text.charAt(currentPos + 1) === '[') { const startPos: number = currentPos; currentPos += 2; // Ignore 'Esc[' as it's in every sequence. let ansiSequence: string = ''; while (currentPos < textLength) { const char: string = text.charAt(currentPos); ansiSequence += char; currentPos++; // Look for a known sequence terminating character. if (char.match(/^[ABCDHIJKfhmpsu]$/)) { sequenceFound = true; break; } } if (sequenceFound) { // Flush buffer with previous styles. appendStylizedStringToContainer(root, buffer, styleNames, linkDetector, debugSession, customFgColor, customBgColor); buffer = ''; /* * Certain ranges that are matched here do not contain real graphics rendition sequences. For * the sake of having a simpler expression, they have been included anyway. */ if (ansiSequence.match(/^(?:[34][0-8]|9[0-7]|10[0-7]|[013]|4|[34]9)(?:;[349][0-7]|10[0-7]|[013]|[245]|[34]9)?(?:;[012]?[0-9]?[0-9])*;?m$/)) { const styleCodes: number[] = ansiSequence.slice(0, -1) // Remove final 'm' character. .split(';') // Separate style codes. .filter(elem => elem !== '') // Filter empty elems as '34;m' -> ['34', '']. .map(elem => parseInt(elem, 10)); // Convert to numbers. if (styleCodes[0] === 38 || styleCodes[0] === 48) { // Advanced color code - can't be combined with formatting codes like simple colors can // Ignores invalid colors and additional info beyond what is necessary const colorType = (styleCodes[0] === 38) ? 'foreground' : 'background'; if (styleCodes[1] === 5) { set8BitColor(styleCodes, colorType); } else if (styleCodes[1] === 2) { set24BitColor(styleCodes, colorType); } } else { setBasicFormatters(styleCodes); } } else { // Unsupported sequence so simply hide it. } } else { currentPos = startPos; } } if (sequenceFound === false) { buffer += text.charAt(currentPos); currentPos++; } } // Flush remaining text buffer if not empty. if (buffer) { appendStylizedStringToContainer(root, buffer, styleNames, linkDetector, debugSession, customFgColor, customBgColor); } return root; /** * Change the foreground or background color by clearing the current color * and adding the new one. * @param colorType If `'foreground'`, will change the foreground color, if * `'background'`, will change the background color. * @param color Color to change to. If `undefined` or not provided, * will clear current color without adding a new one. */ function changeColor(colorType: 'foreground' | 'background', color?: RGBA | undefined): void { if (colorType === 'foreground') { customFgColor = color; } else if (colorType === 'background') { customBgColor = color; } styleNames = styleNames.filter(style => style !== `code-${colorType}-colored`); if (color !== undefined) { styleNames.push(`code-${colorType}-colored`); } } /** * Calculate and set basic ANSI formatting. Supports bold, italic, underline, * normal foreground and background colors, and bright foreground and * background colors. Not to be used for codes containing advanced colors. * Will ignore invalid codes. * @param styleCodes Array of ANSI basic styling numbers, which will be * applied in order. New colors and backgrounds clear old ones; new formatting * does not. * @see {@link https://en.wikipedia.org/wiki/ANSI_escape_code } */ function setBasicFormatters(styleCodes: number[]): void { for (let code of styleCodes) { switch (code) { case 0: { styleNames = []; customFgColor = undefined; customBgColor = undefined; break; } case 1: { styleNames.push('code-bold'); break; } case 3: { styleNames.push('code-italic'); break; } case 4: { styleNames.push('code-underline'); break; } case 39: { changeColor('foreground', undefined); break; } case 49: { changeColor('background', undefined); break; } default: { setBasicColor(code); break; } } } } /** * Calculate and set styling for complicated 24-bit ANSI color codes. * @param styleCodes Full list of integer codes that make up the full ANSI * sequence, including the two defining codes and the three RGB codes. * @param colorType If `'foreground'`, will set foreground color, if * `'background'`, will set background color. * @see {@link https://en.wikipedia.org/wiki/ANSI_escape_code#24-bit } */ function set24BitColor(styleCodes: number[], colorType: 'foreground' | 'background'): void { if (styleCodes.length >= 5 && styleCodes[2] >= 0 && styleCodes[2] <= 255 && styleCodes[3] >= 0 && styleCodes[3] <= 255 && styleCodes[4] >= 0 && styleCodes[4] <= 255) { const customColor = new RGBA(styleCodes[2], styleCodes[3], styleCodes[4]); changeColor(colorType, customColor); } } /** * Calculate and set styling for advanced 8-bit ANSI color codes. * @param styleCodes Full list of integer codes that make up the ANSI * sequence, including the two defining codes and the one color code. * @param colorType If `'foreground'`, will set foreground color, if * `'background'`, will set background color. * @see {@link https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit } */ function set8BitColor(styleCodes: number[], colorType: 'foreground' | 'background'): void { let colorNumber = styleCodes[2]; const color = calcANSI8bitColor(colorNumber); if (color) { changeColor(colorType, color); } else if (colorNumber >= 0 && colorNumber <= 15) { // Need to map to one of the four basic color ranges (30-37, 90-97, 40-47, 100-107) colorNumber += 30; if (colorNumber >= 38) { // Bright colors colorNumber += 52; } if (colorType === 'background') { colorNumber += 10; } setBasicColor(colorNumber); } } /** * Calculate and set styling for basic bright and dark ANSI color codes. Uses * theme colors if available. Automatically distinguishes between foreground * and background colors; does not support color-clearing codes 39 and 49. * @param styleCode Integer color code on one of the following ranges: * [30-37, 90-97, 40-47, 100-107]. If not on one of these ranges, will do * nothing. */ function setBasicColor(styleCode: number): void { const theme = themeService.getColorTheme(); let colorType: 'foreground' | 'background' | undefined; let colorIndex: number | undefined; if (styleCode >= 30 && styleCode <= 37) { colorIndex = styleCode - 30; colorType = 'foreground'; } else if (styleCode >= 90 && styleCode <= 97) { colorIndex = (styleCode - 90) + 8; // High-intensity (bright) colorType = 'foreground'; } else if (styleCode >= 40 && styleCode <= 47) { colorIndex = styleCode - 40; colorType = 'background'; } else if (styleCode >= 100 && styleCode <= 107) { colorIndex = (styleCode - 100) + 8; // High-intensity (bright) colorType = 'background'; } if (colorIndex !== undefined && colorType) { const colorName = ansiColorIdentifiers[colorIndex]; const color = theme.getColor(colorName); if (color) { changeColor(colorType, color.rgba); } } } } /** * @param root The {@link HTMLElement} to append the content to. * @param stringContent The text content to be appended. * @param cssClasses The list of CSS styles to apply to the text content. * @param linkDetector The {@link LinkDetector} responsible for generating links from {@param stringContent}. * @param customTextColor If provided, will apply custom color with inline style. * @param customBackgroundColor If provided, will apply custom color with inline style. */ export function appendStylizedStringToContainer( root: HTMLElement, stringContent: string, cssClasses: string[], linkDetector: LinkDetector, debugSession: IDebugSession, customTextColor?: RGBA, customBackgroundColor?: RGBA ): void { if (!root || !stringContent) { return; } const container = linkDetector.linkify(stringContent, true, debugSession.root); container.className = cssClasses.join(' '); if (customTextColor) { container.style.color = Color.Format.CSS.formatRGB(new Color(customTextColor)); } if (customBackgroundColor) { container.style.backgroundColor = Color.Format.CSS.formatRGB(new Color(customBackgroundColor)); } root.appendChild(container); } /** * Calculate the color from the color set defined in the ANSI 8-bit standard. * Standard and high intensity colors are not defined in the standard as specific * colors, so these and invalid colors return `undefined`. * @see {@link https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit } for info. * @param colorNumber The number (ranging from 16 to 255) referring to the color * desired. */ export function calcANSI8bitColor(colorNumber: number): RGBA | undefined { if (colorNumber % 1 !== 0) { // Should be integer return; } if (colorNumber >= 16 && colorNumber <= 231) { // Converts to one of 216 RGB colors colorNumber -= 16; let blue: number = colorNumber % 6; colorNumber = (colorNumber - blue) / 6; let green: number = colorNumber % 6; colorNumber = (colorNumber - green) / 6; let red: number = colorNumber; // red, green, blue now range on [0, 5], need to map to [0,255] const convFactor: number = 255 / 5; blue = Math.round(blue * convFactor); green = Math.round(green * convFactor); red = Math.round(red * convFactor); return new RGBA(red, green, blue); } else if (colorNumber >= 232 && colorNumber <= 255) { // Converts to a grayscale value colorNumber -= 232; const colorLevel: number = Math.round(colorNumber / 23 * 255); return new RGBA(colorLevel, colorLevel, colorLevel); } else { return; } }
src/vs/workbench/contrib/debug/browser/debugANSIHandling.ts
0
https://github.com/microsoft/vscode/commit/9504dda6a717a0a0d45d992e21f2565f8a23f390
[ 0.00018046471814159304, 0.00017169890634249896, 0.0001640502450754866, 0.00017255009151995182, 0.0000037255197185004363 ]
{ "id": 3, "code_window": [ "\t\tsuper({\n", "\t\t\tid: 'notebook.selectKernel',\n", "\t\t\tcategory: NOTEBOOK_ACTIONS_CATEGORY,\n", "\t\t\ttitle: nls.localize('notebookActions.selectKernel', \"Select Notebook Kernel\"),\n", "\t\t\tprecondition: ContextKeyExpr.and(NOTEBOOK_IS_ACTIVE_EDITOR, NOTEBOOK_EDITOR_FOCUSED),\n", "\t\t\ticon: { id: 'codicon/server-environment' },\n", "\t\t\tmenu: {\n", "\t\t\t\tid: MenuId.EditorTitle,\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tprecondition: NOTEBOOK_IS_ACTIVE_EDITOR,\n" ], "file_path": "src/vs/workbench/contrib/notebook/browser/contrib/status/editorStatus.ts", "type": "replace", "edit_start_line_idx": 22 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as DOM from 'vs/base/browser/dom'; import { raceCancellation } from 'vs/base/common/async'; import { CancellationTokenSource } from 'vs/base/common/cancellation'; import { Disposable, DisposableStore } from 'vs/base/common/lifecycle'; import { IModeService } from 'vs/editor/common/services/modeService'; import * as nls from 'vs/nls'; import { IQuickInputService, IQuickPickItem } from 'vs/platform/quickinput/common/quickInput'; import { EDITOR_BOTTOM_PADDING, EDITOR_TOP_PADDING } from 'vs/workbench/contrib/notebook/browser/constants'; import { CellFocusMode, CodeCellRenderTemplate, INotebookEditor } from 'vs/workbench/contrib/notebook/browser/notebookBrowser'; import { INotebookService } from 'vs/workbench/contrib/notebook/common/notebookService'; import { getResizesObserver } from 'vs/workbench/contrib/notebook/browser/view/renderers/sizeObserver'; import { CodeCellViewModel } from 'vs/workbench/contrib/notebook/browser/viewModel/codeCellViewModel'; import { CellOutputKind, IProcessedOutput, IRenderOutput, ITransformedDisplayOutputDto, BUILTIN_RENDERER_ID } from 'vs/workbench/contrib/notebook/common/notebookCommon'; import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent'; import { KeyCode } from 'vs/base/common/keyCodes'; import { IDimension } from 'vs/editor/common/editorCommon'; interface IMimeTypeRenderer extends IQuickPickItem { index: number; } export class CodeCell extends Disposable { private outputResizeListeners = new Map<IProcessedOutput, DisposableStore>(); private outputElements = new Map<IProcessedOutput, HTMLElement>(); constructor( private notebookEditor: INotebookEditor, private viewCell: CodeCellViewModel, private templateData: CodeCellRenderTemplate, @INotebookService private notebookService: INotebookService, @IQuickInputService private readonly quickInputService: IQuickInputService, @IModeService private readonly _modeService: IModeService ) { super(); const width = this.viewCell.layoutInfo.editorWidth; const lineNum = this.viewCell.lineCount; const lineHeight = this.viewCell.layoutInfo.fontInfo?.lineHeight || 17; const totalHeight = this.viewCell.layoutInfo.editorHeight === 0 ? lineNum * lineHeight + EDITOR_TOP_PADDING + EDITOR_BOTTOM_PADDING : this.viewCell.layoutInfo.editorHeight; this.layoutEditor( { width: width, height: totalHeight } ); const cts = new CancellationTokenSource(); this._register({ dispose() { cts.dispose(true); } }); raceCancellation(viewCell.resolveTextModel(), cts.token).then(model => { if (model && templateData.editor) { templateData.editor.setModel(model); viewCell.attachTextEditor(templateData.editor); if (notebookEditor.getActiveCell() === viewCell && viewCell.focusMode === CellFocusMode.Editor) { templateData.editor?.focus(); } const realContentHeight = templateData.editor?.getContentHeight(); if (realContentHeight !== undefined && realContentHeight !== totalHeight) { this.onCellHeightChange(realContentHeight); } if (this.notebookEditor.getActiveCell() === this.viewCell && viewCell.focusMode === CellFocusMode.Editor) { templateData.editor?.focus(); } } }); const updateForFocusMode = () => { if (viewCell.focusMode === CellFocusMode.Editor) { templateData.editor?.focus(); } DOM.toggleClass(templateData.container, 'cell-editor-focus', viewCell.focusMode === CellFocusMode.Editor); }; this._register(viewCell.onDidChangeState((e) => { if (!e.focusModeChanged) { return; } updateForFocusMode(); })); updateForFocusMode(); templateData.editor?.updateOptions({ readOnly: !(viewCell.getEvaluatedMetadata(notebookEditor.viewModel!.metadata).editable) }); this._register(viewCell.onDidChangeState((e) => { if (e.metadataChanged) { templateData.editor?.updateOptions({ readOnly: !(viewCell.getEvaluatedMetadata(notebookEditor.viewModel!.metadata).editable) }); } })); this._register(viewCell.onDidChangeState((e) => { if (!e.languageChanged) { return; } const mode = this._modeService.create(viewCell.language); templateData.editor?.getModel()?.setMode(mode.languageIdentifier); })); this._register(viewCell.onDidChangeLayout((e) => { if (e.outerWidth === undefined) { return; } const layoutInfo = templateData.editor!.getLayoutInfo(); if (layoutInfo.width !== viewCell.layoutInfo.editorWidth) { this.onCellWidthChange(); } })); this._register(templateData.editor!.onDidContentSizeChange((e) => { if (e.contentHeightChanged) { if (this.viewCell.layoutInfo.editorHeight !== e.contentHeight) { this.onCellHeightChange(e.contentHeight); } } })); this._register(templateData.editor!.onDidChangeCursorSelection((e) => { if (e.source === 'restoreState') { // do not reveal the cell into view if this selection change was caused by restoring editors... return; } const primarySelection = templateData.editor!.getSelection(); if (primarySelection) { this.notebookEditor.revealLineInViewAsync(viewCell, primarySelection!.positionLineNumber); } })); this._register(viewCell.onDidChangeOutputs((splices) => { if (!splices.length) { return; } const previousOutputHeight = this.viewCell.layoutInfo.outputTotalHeight; if (this.viewCell.outputs.length) { this.templateData.outputContainer!.style.display = 'block'; } else { this.templateData.outputContainer!.style.display = 'none'; } let reversedSplices = splices.reverse(); reversedSplices.forEach(splice => { viewCell.spliceOutputHeights(splice[0], splice[1], splice[2].map(_ => 0)); }); let removedKeys: IProcessedOutput[] = []; this.outputElements.forEach((value, key) => { if (viewCell.outputs.indexOf(key) < 0) { // already removed removedKeys.push(key); // remove element from DOM this.templateData?.outputContainer?.removeChild(value); this.notebookEditor.removeInset(key); } }); removedKeys.forEach(key => { // remove element cache this.outputElements.delete(key); // remove elment resize listener if there is one this.outputResizeListeners.delete(key); }); let prevElement: HTMLElement | undefined = undefined; [...this.viewCell.outputs].reverse().forEach(output => { if (this.outputElements.has(output)) { // already exist prevElement = this.outputElements.get(output); return; } // newly added element let currIndex = this.viewCell.outputs.indexOf(output); this.renderOutput(output, currIndex, prevElement); prevElement = this.outputElements.get(output); }); let editorHeight = templateData.editor!.getContentHeight(); viewCell.editorHeight = editorHeight; if (previousOutputHeight === 0 || this.viewCell.outputs.length === 0) { // first execution or removing all outputs this.relayoutCell(); } else { this.relayoutCellDebounced(); } })); this._register(viewCell.onDidChangeLayout(() => { this.outputElements.forEach((value, key) => { const index = viewCell.outputs.indexOf(key); if (index >= 0) { const top = this.viewCell.getOutputOffsetInContainer(index); value.style.top = `${top}px`; } }); })); const updateFocusMode = () => viewCell.focusMode = templateData.editor!.hasWidgetFocus() ? CellFocusMode.Editor : CellFocusMode.Container; this._register(templateData.editor!.onDidFocusEditorWidget(() => { updateFocusMode(); })); this._register(templateData.editor!.onDidBlurEditorWidget(() => { updateFocusMode(); })); updateFocusMode(); if (viewCell.outputs.length > 0) { let layoutCache = false; if (this.viewCell.layoutInfo.totalHeight !== 0 && this.viewCell.layoutInfo.totalHeight > totalHeight) { layoutCache = true; this.relayoutCell(); } this.templateData.outputContainer!.style.display = 'block'; // there are outputs, we need to calcualte their sizes and trigger relayout // @TODO@rebornix, if there is no resizable output, we should not check their height individually, which hurts the performance for (let index = 0; index < this.viewCell.outputs.length; index++) { const currOutput = this.viewCell.outputs[index]; // always add to the end this.renderOutput(currOutput, index, undefined); } viewCell.editorHeight = totalHeight; if (layoutCache) { this.relayoutCellDebounced(); } else { this.relayoutCell(); } } else { // noop viewCell.editorHeight = totalHeight; this.relayoutCell(); this.templateData.outputContainer!.style.display = 'none'; } } private layoutEditor(dimension: IDimension): void { this.templateData.editor?.layout(dimension); this.templateData.statusBarContainer.style.width = `${dimension.width}px`; } private onCellWidthChange(): void { const realContentHeight = this.templateData.editor!.getContentHeight(); this.layoutEditor( { width: this.viewCell.layoutInfo.editorWidth, height: realContentHeight } ); this.viewCell.editorHeight = realContentHeight; this.relayoutCell(); } private onCellHeightChange(newHeight: number): void { const viewLayout = this.templateData.editor!.getLayoutInfo(); this.layoutEditor( { width: viewLayout.width, height: newHeight } ); this.viewCell.editorHeight = newHeight; this.relayoutCell(); } renderOutput(currOutput: IProcessedOutput, index: number, beforeElement?: HTMLElement) { if (!this.outputResizeListeners.has(currOutput)) { this.outputResizeListeners.set(currOutput, new DisposableStore()); } let outputItemDiv = document.createElement('div'); let result: IRenderOutput | undefined = undefined; if (currOutput.outputKind === CellOutputKind.Rich) { let transformedDisplayOutput = currOutput as ITransformedDisplayOutputDto; if (transformedDisplayOutput.orderedMimeTypes!.length > 1) { outputItemDiv.style.position = 'relative'; const mimeTypePicker = DOM.$('.multi-mimetype-output'); DOM.addClasses(mimeTypePicker, 'codicon', 'codicon-code'); mimeTypePicker.tabIndex = 0; mimeTypePicker.title = nls.localize('mimeTypePicker', "Choose a different output mimetype, available mimetypes: {0}", transformedDisplayOutput.orderedMimeTypes!.map(mimeType => mimeType.mimeType).join(', ')); outputItemDiv.appendChild(mimeTypePicker); this.outputResizeListeners.get(currOutput)!.add(DOM.addStandardDisposableListener(mimeTypePicker, 'mousedown', async e => { if (e.leftButton) { e.preventDefault(); e.stopPropagation(); await this.pickActiveMimeTypeRenderer(transformedDisplayOutput); } })); this.outputResizeListeners.get(currOutput)!.add((DOM.addDisposableListener(mimeTypePicker, DOM.EventType.KEY_DOWN, async e => { const event = new StandardKeyboardEvent(e); if ((event.equals(KeyCode.Enter) || event.equals(KeyCode.Space))) { e.preventDefault(); e.stopPropagation(); await this.pickActiveMimeTypeRenderer(transformedDisplayOutput); } }))); } let pickedMimeTypeRenderer = currOutput.orderedMimeTypes![currOutput.pickedMimeTypeIndex!]; const innerContainer = DOM.$('.output-inner-container'); DOM.append(outputItemDiv, innerContainer); if (pickedMimeTypeRenderer.isResolved) { // html result = this.notebookEditor.getOutputRenderer().render({ outputId: currOutput.outputId, outputKind: CellOutputKind.Rich, data: { 'text/html': pickedMimeTypeRenderer.output! } }, innerContainer, 'text/html'); } else { result = this.notebookEditor.getOutputRenderer().render(currOutput, innerContainer, pickedMimeTypeRenderer.mimeType); } } else { // for text and error, there is no mimetype const innerContainer = DOM.$('.output-inner-container'); DOM.append(outputItemDiv, innerContainer); result = this.notebookEditor.getOutputRenderer().render(currOutput, innerContainer, undefined); } if (!result) { this.viewCell.updateOutputHeight(index, 0); return; } this.outputElements.set(currOutput, outputItemDiv); if (beforeElement) { this.templateData.outputContainer?.insertBefore(outputItemDiv, beforeElement); } else { this.templateData.outputContainer?.appendChild(outputItemDiv); } if (result.shadowContent) { this.viewCell.selfSizeMonitoring = true; this.notebookEditor.createInset(this.viewCell, currOutput, result.shadowContent, this.viewCell.getOutputOffset(index)); } else { DOM.addClass(outputItemDiv, 'foreground'); DOM.addClass(outputItemDiv, 'output-element'); outputItemDiv.style.position = 'absolute'; } let hasDynamicHeight = result.hasDynamicHeight; if (hasDynamicHeight) { this.viewCell.selfSizeMonitoring = true; let clientHeight = outputItemDiv.clientHeight; let dimension = { width: this.viewCell.layoutInfo.editorWidth, height: clientHeight }; const elementSizeObserver = getResizesObserver(outputItemDiv, dimension, () => { if (this.templateData.outputContainer && document.body.contains(this.templateData.outputContainer!)) { let height = Math.ceil(elementSizeObserver.getHeight()); if (clientHeight === height) { return; } const currIndex = this.viewCell.outputs.indexOf(currOutput); if (currIndex < 0) { return; } this.viewCell.updateOutputHeight(currIndex, height); this.relayoutCell(); } }); elementSizeObserver.startObserving(); this.outputResizeListeners.get(currOutput)!.add(elementSizeObserver); this.viewCell.updateOutputHeight(index, clientHeight); } else { if (result.shadowContent) { // webview // noop } else { // static output let clientHeight = Math.ceil(outputItemDiv.clientHeight); this.viewCell.updateOutputHeight(index, clientHeight); const top = this.viewCell.getOutputOffsetInContainer(index); outputItemDiv.style.top = `${top}px`; } } } generateRendererInfo(renderId: string | undefined): string { if (renderId === undefined || renderId === BUILTIN_RENDERER_ID) { return nls.localize('builtinRenderInfo', "built-in"); } let renderInfo = this.notebookService.getRendererInfo(renderId); if (renderInfo) { return `${renderId} (${renderInfo.extensionId.value})`; } return nls.localize('builtinRenderInfo', "built-in"); } async pickActiveMimeTypeRenderer(output: ITransformedDisplayOutputDto) { let currIndex = output.pickedMimeTypeIndex; const items = output.orderedMimeTypes!.map((mimeType, index): IMimeTypeRenderer => ({ label: mimeType.mimeType, id: mimeType.mimeType, index: index, picked: index === currIndex, detail: this.generateRendererInfo(mimeType.rendererId), description: index === currIndex ? nls.localize('curruentActiveMimeType', "Currently Active") : undefined })); const picker = this.quickInputService.createQuickPick(); picker.items = items; picker.activeItems = items.filter(item => !!item.picked); picker.placeholder = nls.localize('promptChooseMimeType.placeHolder', "Select output mimetype to render for current output"); const pick = await new Promise<number | undefined>(resolve => { picker.onDidAccept(() => { resolve(picker.selectedItems.length === 1 ? (picker.selectedItems[0] as IMimeTypeRenderer).index : undefined); picker.dispose(); }); picker.show(); }); if (pick === undefined) { return; } if (pick !== currIndex) { // user chooses another mimetype let index = this.viewCell.outputs.indexOf(output); let nextElement = index + 1 < this.viewCell.outputs.length ? this.outputElements.get(this.viewCell.outputs[index + 1]) : undefined; this.outputResizeListeners.get(output)?.clear(); let element = this.outputElements.get(output); if (element) { this.templateData?.outputContainer?.removeChild(element); this.notebookEditor.removeInset(output); } output.pickedMimeTypeIndex = pick; if (!output.orderedMimeTypes![pick].isResolved && output.orderedMimeTypes![pick].rendererId !== BUILTIN_RENDERER_ID) { // since it's not build in renderer and not resolved yet // let's see if we can activate the extension and then render // await this.notebookService.transformSpliceOutputs(this.notebookEditor.textModel!, [[0, 0, output]]) const outputRet = await this.notebookService.transformSingleOutput(this.notebookEditor.textModel!, output, output.orderedMimeTypes![pick].rendererId!, output.orderedMimeTypes![pick].mimeType); if (outputRet) { output.orderedMimeTypes![pick] = outputRet; } } this.renderOutput(output, index, nextElement); this.relayoutCell(); } } relayoutCell() { if (this._timer !== null) { clearTimeout(this._timer); } this.notebookEditor.layoutNotebookCell(this.viewCell, this.viewCell.layoutInfo.totalHeight); } private _timer: number | null = null; relayoutCellDebounced() { if (this._timer !== null) { clearTimeout(this._timer); } this._timer = setTimeout(() => { this.notebookEditor.layoutNotebookCell(this.viewCell, this.viewCell.layoutInfo.totalHeight); this._timer = null; }, 200) as unknown as number | null; } dispose() { this.viewCell.detachTextEditor(); this.outputResizeListeners.forEach((value) => { value.dispose(); }); this.templateData.focusIndicator!.style.height = 'initial'; super.dispose(); } }
src/vs/workbench/contrib/notebook/browser/view/renderers/codeCell.ts
1
https://github.com/microsoft/vscode/commit/9504dda6a717a0a0d45d992e21f2565f8a23f390
[ 0.0002111429930664599, 0.00017276292783208191, 0.00016199883248191327, 0.0001727440976537764, 0.0000083862605606555 ]
{ "id": 3, "code_window": [ "\t\tsuper({\n", "\t\t\tid: 'notebook.selectKernel',\n", "\t\t\tcategory: NOTEBOOK_ACTIONS_CATEGORY,\n", "\t\t\ttitle: nls.localize('notebookActions.selectKernel', \"Select Notebook Kernel\"),\n", "\t\t\tprecondition: ContextKeyExpr.and(NOTEBOOK_IS_ACTIVE_EDITOR, NOTEBOOK_EDITOR_FOCUSED),\n", "\t\t\ticon: { id: 'codicon/server-environment' },\n", "\t\t\tmenu: {\n", "\t\t\t\tid: MenuId.EditorTitle,\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tprecondition: NOTEBOOK_IS_ACTIVE_EDITOR,\n" ], "file_path": "src/vs/workbench/contrib/notebook/browser/contrib/status/editorStatus.ts", "type": "replace", "edit_start_line_idx": 22 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as vscode from 'vscode'; import type * as Proto from '../protocol'; function replaceLinks(text: string): string { return text // Http(s) links .replace(/\{@(link|linkplain|linkcode) (https?:\/\/[^ |}]+?)(?:[| ]([^{}\n]+?))?\}/gi, (_, tag: string, link: string, text?: string) => { switch (tag) { case 'linkcode': return `[\`${text ? text.trim() : link}\`](${link})`; default: return `[${text ? text.trim() : link}](${link})`; } }); } function processInlineTags(text: string): string { return replaceLinks(text); } function getTagBodyText(tag: Proto.JSDocTagInfo): string | undefined { if (!tag.text) { return undefined; } // Convert to markdown code block if it is not already one function makeCodeblock(text: string): string { if (text.match(/^\s*[~`]{3}/g)) { return text; } return '```\n' + text + '\n```'; } switch (tag.name) { case 'example': // check for caption tags, fix for #79704 const captionTagMatches = tag.text.match(/<caption>(.*?)<\/caption>\s*(\r\n|\n)/); if (captionTagMatches && captionTagMatches.index === 0) { return captionTagMatches[1] + '\n\n' + makeCodeblock(tag.text.substr(captionTagMatches[0].length)); } else { return makeCodeblock(tag.text); } case 'author': // fix obsucated email address, #80898 const emailMatch = tag.text.match(/(.+)\s<([-.\w]+@[-.\w]+)>/); if (emailMatch === null) { return tag.text; } else { return `${emailMatch[1]} ${emailMatch[2]}`; } case 'default': return makeCodeblock(tag.text); } return processInlineTags(tag.text); } function getTagDocumentation(tag: Proto.JSDocTagInfo): string | undefined { switch (tag.name) { case 'augments': case 'extends': case 'param': case 'template': const body = (tag.text || '').split(/^(\S+)\s*-?\s*/); if (body?.length === 3) { const param = body[1]; const doc = body[2]; const label = `*@${tag.name}* \`${param}\``; if (!doc) { return label; } return label + (doc.match(/\r\n|\n/g) ? ' \n' + processInlineTags(doc) : ` — ${processInlineTags(doc)}`); } } // Generic tag const label = `*@${tag.name}*`; const text = getTagBodyText(tag); if (!text) { return label; } return label + (text.match(/\r\n|\n/g) ? ' \n' + text : ` — ${text}`); } export function plain(parts: Proto.SymbolDisplayPart[] | string): string { return processInlineTags( typeof parts === 'string' ? parts : parts.map(part => part.text).join('')); } export function tagsMarkdownPreview(tags: Proto.JSDocTagInfo[]): string { return tags.map(getTagDocumentation).join(' \n\n'); } export function markdownDocumentation( documentation: Proto.SymbolDisplayPart[] | string, tags: Proto.JSDocTagInfo[] ): vscode.MarkdownString { const out = new vscode.MarkdownString(); addMarkdownDocumentation(out, documentation, tags); return out; } export function addMarkdownDocumentation( out: vscode.MarkdownString, documentation: Proto.SymbolDisplayPart[] | string | undefined, tags: Proto.JSDocTagInfo[] | undefined ): vscode.MarkdownString { if (documentation) { out.appendMarkdown(plain(documentation)); } if (tags) { const tagsPreview = tagsMarkdownPreview(tags); if (tagsPreview) { out.appendMarkdown('\n\n' + tagsPreview); } } return out; }
extensions/typescript-language-features/src/utils/previewer.ts
0
https://github.com/microsoft/vscode/commit/9504dda6a717a0a0d45d992e21f2565f8a23f390
[ 0.00017550158372614533, 0.0001717791019473225, 0.0001636226661503315, 0.00017180350550916046, 0.0000028520382784336107 ]
{ "id": 3, "code_window": [ "\t\tsuper({\n", "\t\t\tid: 'notebook.selectKernel',\n", "\t\t\tcategory: NOTEBOOK_ACTIONS_CATEGORY,\n", "\t\t\ttitle: nls.localize('notebookActions.selectKernel', \"Select Notebook Kernel\"),\n", "\t\t\tprecondition: ContextKeyExpr.and(NOTEBOOK_IS_ACTIVE_EDITOR, NOTEBOOK_EDITOR_FOCUSED),\n", "\t\t\ticon: { id: 'codicon/server-environment' },\n", "\t\t\tmenu: {\n", "\t\t\t\tid: MenuId.EditorTitle,\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tprecondition: NOTEBOOK_IS_ACTIVE_EDITOR,\n" ], "file_path": "src/vs/workbench/contrib/notebook/browser/contrib/status/editorStatus.ts", "type": "replace", "edit_start_line_idx": 22 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import 'mocha'; import * as path from 'path'; import * as fs from 'fs'; import * as assert from 'assert'; import { getLanguageModes, TextDocument, Range, FormattingOptions, ClientCapabilities } from '../modes/languageModes'; import { format } from '../modes/formatting'; import { getNodeFSRequestService } from '../node/nodeFs'; suite('HTML Embedded Formatting', () => { async function assertFormat(value: string, expected: string, options?: any, formatOptions?: FormattingOptions, message?: string): Promise<void> { let workspace = { settings: options, folders: [{ name: 'foo', uri: 'test://foo' }] }; const languageModes = getLanguageModes({ css: true, javascript: true }, workspace, ClientCapabilities.LATEST, getNodeFSRequestService()); let rangeStartOffset = value.indexOf('|'); let rangeEndOffset; if (rangeStartOffset !== -1) { value = value.substr(0, rangeStartOffset) + value.substr(rangeStartOffset + 1); rangeEndOffset = value.indexOf('|'); value = value.substr(0, rangeEndOffset) + value.substr(rangeEndOffset + 1); } else { rangeStartOffset = 0; rangeEndOffset = value.length; } let document = TextDocument.create('test://test/test.html', 'html', 0, value); let range = Range.create(document.positionAt(rangeStartOffset), document.positionAt(rangeEndOffset)); if (!formatOptions) { formatOptions = FormattingOptions.create(2, true); } let result = await format(languageModes, document, range, formatOptions, undefined, { css: true, javascript: true }); let actual = TextDocument.applyEdits(document, result); assert.equal(actual, expected, message); } async function assertFormatWithFixture(fixtureName: string, expectedPath: string, options?: any, formatOptions?: FormattingOptions): Promise<void> { let input = fs.readFileSync(path.join(__dirname, '..', '..', 'src', 'test', 'fixtures', 'inputs', fixtureName)).toString().replace(/\r\n/mg, '\n'); let expected = fs.readFileSync(path.join(__dirname, '..', '..', 'src', 'test', 'fixtures', 'expected', expectedPath)).toString().replace(/\r\n/mg, '\n'); await assertFormat(input, expected, options, formatOptions, expectedPath); } test('HTML only', async () => { await assertFormat('<html><body><p>Hello</p></body></html>', '<html>\n\n<body>\n <p>Hello</p>\n</body>\n\n</html>'); await assertFormat('|<html><body><p>Hello</p></body></html>|', '<html>\n\n<body>\n <p>Hello</p>\n</body>\n\n</html>'); await assertFormat('<html>|<body><p>Hello</p></body>|</html>', '<html><body>\n <p>Hello</p>\n</body></html>'); }); test('HTML & Scripts', async () => { await assertFormat('<html><head><script></script></head></html>', '<html>\n\n<head>\n <script></script>\n</head>\n\n</html>'); await assertFormat('<html><head><script>var x=1;</script></head></html>', '<html>\n\n<head>\n <script>var x = 1;</script>\n</head>\n\n</html>'); await assertFormat('<html><head><script>\nvar x=2;\n</script></head></html>', '<html>\n\n<head>\n <script>\n var x = 2;\n </script>\n</head>\n\n</html>'); await assertFormat('<html><head>\n <script>\nvar x=3;\n</script></head></html>', '<html>\n\n<head>\n <script>\n var x = 3;\n </script>\n</head>\n\n</html>'); await assertFormat('<html><head>\n <script>\nvar x=4;\nconsole.log("Hi");\n</script></head></html>', '<html>\n\n<head>\n <script>\n var x = 4;\n console.log("Hi");\n </script>\n</head>\n\n</html>'); await assertFormat('<html><head>\n |<script>\nvar x=5;\n</script>|</head></html>', '<html><head>\n <script>\n var x = 5;\n </script></head></html>'); }); test('HTLM & Scripts - Fixtures', async () => { assertFormatWithFixture('19813.html', '19813.html'); assertFormatWithFixture('19813.html', '19813-4spaces.html', undefined, FormattingOptions.create(4, true)); assertFormatWithFixture('19813.html', '19813-tab.html', undefined, FormattingOptions.create(1, false)); assertFormatWithFixture('21634.html', '21634.html'); }); test('Script end tag', async () => { await assertFormat('<html>\n<head>\n <script>\nvar x = 0;\n</script></head></html>', '<html>\n\n<head>\n <script>\n var x = 0;\n </script>\n</head>\n\n</html>'); }); test('HTML & Multiple Scripts', async () => { await assertFormat('<html><head>\n<script>\nif(x){\nbar(); }\n</script><script>\nfunction(x){ }\n</script></head></html>', '<html>\n\n<head>\n <script>\n if (x) {\n bar();\n }\n </script>\n <script>\n function(x) {}\n </script>\n</head>\n\n</html>'); }); test('HTML & Styles', async () => { await assertFormat('<html><head>\n<style>\n.foo{display:none;}\n</style></head></html>', '<html>\n\n<head>\n <style>\n .foo {\n display: none;\n }\n </style>\n</head>\n\n</html>'); }); test('EndWithNewline', async () => { let options = { html: { format: { endWithNewline: true } } }; await assertFormat('<html><body><p>Hello</p></body></html>', '<html>\n\n<body>\n <p>Hello</p>\n</body>\n\n</html>\n', options); await assertFormat('<html>|<body><p>Hello</p></body>|</html>', '<html><body>\n <p>Hello</p>\n</body></html>', options); await assertFormat('<html><head><script>\nvar x=1;\n</script></head></html>', '<html>\n\n<head>\n <script>\n var x = 1;\n </script>\n</head>\n\n</html>\n', options); }); test('Inside script', async () => { await assertFormat('<html><head>\n <script>\n|var x=6;|\n</script></head></html>', '<html><head>\n <script>\n var x = 6;\n</script></head></html>'); await assertFormat('<html><head>\n <script>\n|var x=6;\nvar y= 9;|\n</script></head></html>', '<html><head>\n <script>\n var x = 6;\n var y = 9;\n</script></head></html>'); }); test('Range after new line', async () => { await assertFormat('<html><head>\n |<script>\nvar x=6;\n</script>\n|</head></html>', '<html><head>\n <script>\n var x = 6;\n </script>\n</head></html>'); }); test('bug 36574', async () => { await assertFormat('<script src="/js/main.js"> </script>', '<script src="/js/main.js"> </script>'); }); test('bug 48049', async () => { await assertFormat( [ '<html>', '<head>', '</head>', '', '<body>', '', ' <script>', ' function f(x) {}', ' f(function () {', ' // ', '', ' console.log(" vsc crashes on formatting")', ' });', ' </script>', '', '', '', ' </body>', '', '</html>' ].join('\n'), [ '<html>', '', '<head>', '</head>', '', '<body>', '', ' <script>', ' function f(x) {}', ' f(function () {', ' // ', '', ' console.log(" vsc crashes on formatting")', ' });', ' </script>', '', '', '', '</body>', '', '</html>' ].join('\n') ); }); test('#58435', async () => { let options = { html: { format: { contentUnformatted: 'textarea' } } }; const content = [ '<html>', '', '<body>', ' <textarea name= "" id ="" cols="30" rows="10">', ' </textarea>', '</body>', '', '</html>', ].join('\n'); const expected = [ '<html>', '', '<body>', ' <textarea name="" id="" cols="30" rows="10">', ' </textarea>', '</body>', '', '</html>', ].join('\n'); await assertFormat(content, expected, options); }); }); /* content_unformatted: Array(4)["pre", "code", "textarea", …] end_with_newline: false eol: "\n" extra_liners: Array(3)["head", "body", "/html"] indent_char: "\t" indent_handlebars: false indent_inner_html: false indent_size: 1 max_preserve_newlines: 32786 preserve_newlines: true unformatted: Array(1)["wbr"] wrap_attributes: "auto" wrap_attributes_indent_size: undefined wrap_line_length: 120*/
extensions/html-language-features/server/src/test/formatting.test.ts
0
https://github.com/microsoft/vscode/commit/9504dda6a717a0a0d45d992e21f2565f8a23f390
[ 0.000176425208337605, 0.00017253246915061027, 0.00016706757014617324, 0.0001726433984003961, 0.00000230773480325297 ]
{ "id": 3, "code_window": [ "\t\tsuper({\n", "\t\t\tid: 'notebook.selectKernel',\n", "\t\t\tcategory: NOTEBOOK_ACTIONS_CATEGORY,\n", "\t\t\ttitle: nls.localize('notebookActions.selectKernel', \"Select Notebook Kernel\"),\n", "\t\t\tprecondition: ContextKeyExpr.and(NOTEBOOK_IS_ACTIVE_EDITOR, NOTEBOOK_EDITOR_FOCUSED),\n", "\t\t\ticon: { id: 'codicon/server-environment' },\n", "\t\t\tmenu: {\n", "\t\t\t\tid: MenuId.EditorTitle,\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tprecondition: NOTEBOOK_IS_ACTIVE_EDITOR,\n" ], "file_path": "src/vs/workbench/contrib/notebook/browser/contrib/status/editorStatus.ts", "type": "replace", "edit_start_line_idx": 22 }
'use strict'; var Conway; (function (Conway) { var Cell = (function () { function Cell() { } return Cell; })(); (function (property, number, property, number, property, boolean) { if (property === undefined) { property = row; } if (property === undefined) { property = col; } if (property === undefined) { property = live; } }); var GameOfLife = (function () { function GameOfLife() { } return GameOfLife; })(); (function () { property; gridSize = 50; property; canvasSize = 600; property; lineColor = '#cdcdcd'; property; liveColor = '#666'; property; deadColor = '#eee'; property; initialLifeProbability = 0.5; property; animationRate = 60; property; cellSize = 0; property; context: ICanvasRenderingContext2D; property; world = createWorld(); circleOfLife(); function createWorld() { return travelWorld(function (cell) { cell.live = Math.random() < initialLifeProbability; return cell; }); } function circleOfLife() { world = travelWorld(function (cell) { cell = world[cell.row][cell.col]; draw(cell); return resolveNextGeneration(cell); }); setTimeout(function () { circleOfLife(); }, animationRate); } function resolveNextGeneration(cell) { var count = countNeighbors(cell); var newCell = new Cell(cell.row, cell.col, cell.live); if (count < 2 || count > 3) newCell.live = false; else if (count == 3) newCell.live = true; return newCell; } function countNeighbors(cell) { var neighbors = 0; for (var row = -1; row <= 1; row++) { for (var col = -1; col <= 1; col++) { if (row == 0 && col == 0) continue; if (isAlive(cell.row + row, cell.col + col)) { neighbors++; } } } return neighbors; } function isAlive(row, col) { // todo - need to guard with worl[row] exists? if (row < 0 || col < 0 || row >= gridSize || col >= gridSize) return false; return world[row][col].live; } function travelWorld(callback) { var result = []; for (var row = 0; row < gridSize; row++) { var rowData = []; for (var col = 0; col < gridSize; col++) { rowData.push(callback(new Cell(row, col, false))); } result.push(rowData); } return result; } function draw(cell) { if (context == null) context = createDrawingContext(); if (cellSize == 0) cellSize = canvasSize / gridSize; context.strokeStyle = lineColor; context.strokeRect(cell.row * cellSize, cell.col * cellSize, cellSize, cellSize); context.fillStyle = cell.live ? liveColor : deadColor; context.fillRect(cell.row * cellSize, cell.col * cellSize, cellSize, cellSize); } function createDrawingContext() { var canvas = document.getElementById('conway-canvas'); if (canvas == null) { canvas = document.createElement('canvas'); canvas.id = "conway-canvas"; canvas.width = canvasSize; canvas.height = canvasSize; document.body.appendChild(canvas); } return canvas.getContext('2d'); } }); })(Conway || (Conway = {})); var game = new Conway.GameOfLife();
src/vs/platform/files/test/electron-browser/fixtures/resolver/examples/conway.js
0
https://github.com/microsoft/vscode/commit/9504dda6a717a0a0d45d992e21f2565f8a23f390
[ 0.00017642354941926897, 0.0001710203941911459, 0.00016500172205269337, 0.00017242647300008684, 0.000004199765953671886 ]
{ "id": 4, "code_window": [ "\t\t\ticon: { id: 'codicon/server-environment' },\n", "\t\t\tmenu: {\n", "\t\t\t\tid: MenuId.EditorTitle,\n", "\t\t\t\twhen: ContextKeyExpr.and(NOTEBOOK_IS_ACTIVE_EDITOR, NOTEBOOK_HAS_MULTIPLE_KERNELS),\n", "\t\t\t\tgroup: 'navigation',\n", "\t\t\t\torder: -2,\n", "\t\t\t},\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\twhen: NOTEBOOK_HAS_MULTIPLE_KERNELS,\n" ], "file_path": "src/vs/workbench/contrib/notebook/browser/contrib/status/editorStatus.ts", "type": "replace", "edit_start_line_idx": 26 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { hide, IDimension, show, toggleClass } from 'vs/base/browser/dom'; import { raceCancellation } from 'vs/base/common/async'; import { CancellationTokenSource } from 'vs/base/common/cancellation'; import { renderCodicons } from 'vs/base/common/codicons'; import { Disposable, DisposableStore, toDisposable } from 'vs/base/common/lifecycle'; import { CodeEditorWidget } from 'vs/editor/browser/widget/codeEditorWidget'; import { IEditorOptions } from 'vs/editor/common/config/editorOptions'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { EDITOR_BOTTOM_PADDING, EDITOR_TOP_PADDING } from 'vs/workbench/contrib/notebook/browser/constants'; import { CellEditState, CellFocusMode, INotebookEditor, MarkdownCellRenderTemplate, ICellViewModel } from 'vs/workbench/contrib/notebook/browser/notebookBrowser'; import { CellFoldingState } from 'vs/workbench/contrib/notebook/browser/contrib/fold/foldingModel'; import { MarkdownCellViewModel } from 'vs/workbench/contrib/notebook/browser/viewModel/markdownCellViewModel'; import { ICodeEditor } from 'vs/editor/browser/editorBrowser'; import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection'; import { EditorContextKeys } from 'vs/editor/common/editorContextKeys'; import { getResizesObserver } from 'vs/workbench/contrib/notebook/browser/view/renderers/sizeObserver'; export class StatefullMarkdownCell extends Disposable { private editor: CodeEditorWidget | null = null; private markdownContainer: HTMLElement; private editorPart: HTMLElement; private localDisposables = new DisposableStore(); private foldingState: CellFoldingState; constructor( private readonly notebookEditor: INotebookEditor, private readonly viewCell: MarkdownCellViewModel, private readonly templateData: MarkdownCellRenderTemplate, private editorOptions: IEditorOptions, private readonly renderedEditors: Map<ICellViewModel, ICodeEditor | undefined>, @IContextKeyService private readonly contextKeyService: IContextKeyService, @IInstantiationService private readonly instantiationService: IInstantiationService, ) { super(); this.markdownContainer = templateData.cellContainer; this.editorPart = templateData.editorPart; this._register(this.localDisposables); this._register(toDisposable(() => renderedEditors.delete(this.viewCell))); this._register(viewCell.onDidChangeState((e) => { if (e.editStateChanged) { this.localDisposables.clear(); this.viewUpdate(); } else if (e.contentChanged) { this.viewUpdate(); } })); this._register(getResizesObserver(this.markdownContainer, undefined, () => { if (viewCell.editState === CellEditState.Preview) { this.viewCell.renderedMarkdownHeight = templateData.container.clientHeight; } })).startObserving(); const updateForFocusMode = () => { if (viewCell.focusMode === CellFocusMode.Editor) { this.focusEditorIfNeeded(); } toggleClass(templateData.container, 'cell-editor-focus', viewCell.focusMode === CellFocusMode.Editor); }; this._register(viewCell.onDidChangeState((e) => { if (!e.focusModeChanged) { return; } updateForFocusMode(); })); updateForFocusMode(); this.foldingState = viewCell.foldingState; this.setFoldingIndicator(); this._register(viewCell.onDidChangeState((e) => { if (!e.foldingStateChanged) { return; } const foldingState = viewCell.foldingState; if (foldingState !== this.foldingState) { this.foldingState = foldingState; this.setFoldingIndicator(); } })); this._register(viewCell.onDidChangeLayout((e) => { const layoutInfo = this.editor?.getLayoutInfo(); if (e.outerWidth && layoutInfo && layoutInfo.width !== viewCell.layoutInfo.editorWidth) { this.onCellEditorWidthChange(); } else if (e.totalHeight || e.outerWidth) { this.relayoutCell(); } })); this.viewUpdate(); } private viewUpdate(): void { if (this.viewCell.editState === CellEditState.Editing) { this.viewUpdateEditing(); } else { this.viewUpdatePreview(); } } private viewUpdateEditing(): void { // switch to editing mode let editorHeight: number; show(this.editorPart); hide(this.markdownContainer); if (this.editor) { editorHeight = this.editor!.getContentHeight(); // not first time, we don't need to create editor or bind listeners this.viewCell.attachTextEditor(this.editor); this.focusEditorIfNeeded(); this.bindEditorListeners(); } else { const width = this.viewCell.layoutInfo.editorWidth; const lineNum = this.viewCell.lineCount; const lineHeight = this.viewCell.layoutInfo.fontInfo?.lineHeight || 17; editorHeight = Math.max(lineNum, 1) * lineHeight + EDITOR_TOP_PADDING + EDITOR_BOTTOM_PADDING; this.templateData.editorContainer.innerHTML = ''; // create a special context key service that set the inCompositeEditor-contextkey const editorContextKeyService = this.contextKeyService.createScoped(); const editorInstaService = this.instantiationService.createChild(new ServiceCollection([IContextKeyService, editorContextKeyService])); EditorContextKeys.inCompositeEditor.bindTo(editorContextKeyService).set(true); this.editor = editorInstaService.createInstance(CodeEditorWidget, this.templateData.editorContainer, { ...this.editorOptions, dimension: { width: width, height: editorHeight } }, {}); this.templateData.currentEditor = this.editor; const cts = new CancellationTokenSource(); this._register({ dispose() { cts.dispose(true); } }); raceCancellation(this.viewCell.resolveTextModel(), cts.token).then(model => { if (!model) { return; } this.editor!.setModel(model); this.focusEditorIfNeeded(); const realContentHeight = this.editor!.getContentHeight(); if (realContentHeight !== editorHeight) { this.editor!.layout( { width: width, height: realContentHeight } ); editorHeight = realContentHeight; } this.viewCell.attachTextEditor(this.editor!); if (this.viewCell.editState === CellEditState.Editing) { this.focusEditorIfNeeded(); } this.bindEditorListeners(); this.viewCell.editorHeight = editorHeight; }); } this.viewCell.editorHeight = editorHeight; this.focusEditorIfNeeded(); this.renderedEditors.set(this.viewCell, this.editor!); } private viewUpdatePreview(): void { this.viewCell.detachTextEditor(); hide(this.editorPart); show(this.markdownContainer); this.renderedEditors.delete(this.viewCell); this.markdownContainer.innerHTML = ''; this.viewCell.clearHTML(); let markdownRenderer = this.viewCell.getMarkdownRenderer(); let renderedHTML = this.viewCell.getHTML(); if (renderedHTML) { this.markdownContainer.appendChild(renderedHTML); } if (this.editor) { // switch from editing mode this.viewCell.renderedMarkdownHeight = this.templateData.container.clientHeight; this.relayoutCell(); } else { // first time, readonly mode this.localDisposables.add(markdownRenderer.onDidUpdateRender(() => { this.viewCell.renderedMarkdownHeight = this.templateData.container.clientHeight; this.relayoutCell(); })); this.localDisposables.add(this.viewCell.textBuffer.onDidChangeContent(() => { this.markdownContainer.innerHTML = ''; this.viewCell.clearHTML(); let renderedHTML = this.viewCell.getHTML(); if (renderedHTML) { this.markdownContainer.appendChild(renderedHTML); } })); this.viewCell.renderedMarkdownHeight = this.templateData.container.clientHeight; this.relayoutCell(); } } private focusEditorIfNeeded() { if (this.viewCell.focusMode === CellFocusMode.Editor) { this.editor?.focus(); } } private layoutEditor(dimension: IDimension): void { this.editor?.layout(dimension); this.templateData.statusBarContainer.style.width = `${dimension.width}px`; } private onCellEditorWidthChange(): void { const realContentHeight = this.editor!.getContentHeight(); this.layoutEditor( { width: this.viewCell.layoutInfo.editorWidth, height: realContentHeight } ); this.viewCell.editorHeight = realContentHeight; this.relayoutCell(); } private relayoutCell(): void { this.notebookEditor.layoutNotebookCell(this.viewCell, this.viewCell.layoutInfo.totalHeight); } updateEditorOptions(newValue: IEditorOptions): void { this.editorOptions = newValue; if (this.editor) { this.editor.updateOptions(this.editorOptions); } } setFoldingIndicator() { switch (this.foldingState) { case CellFoldingState.None: this.templateData.foldingIndicator.innerHTML = ''; break; case CellFoldingState.Collapsed: this.templateData.foldingIndicator.innerHTML = renderCodicons('$(chevron-right)'); break; case CellFoldingState.Expanded: this.templateData.foldingIndicator.innerHTML = renderCodicons('$(chevron-down)'); break; default: break; } } private bindEditorListeners() { this.localDisposables.add(this.editor!.onDidContentSizeChange(e => { let viewLayout = this.editor!.getLayoutInfo(); if (e.contentHeightChanged) { this.editor!.layout( { width: viewLayout.width, height: e.contentHeight } ); this.viewCell.editorHeight = e.contentHeight; } })); this.localDisposables.add(this.editor!.onDidChangeCursorSelection((e) => { if (e.source === 'restoreState') { // do not reveal the cell into view if this selection change was caused by restoring editors... return; } const primarySelection = this.editor!.getSelection(); if (primarySelection) { this.notebookEditor.revealLineInViewAsync(this.viewCell, primarySelection!.positionLineNumber); } })); const updateFocusMode = () => this.viewCell.focusMode = this.editor!.hasWidgetFocus() ? CellFocusMode.Editor : CellFocusMode.Container; this.localDisposables.add(this.editor!.onDidFocusEditorWidget(() => { updateFocusMode(); })); this.localDisposables.add(this.editor!.onDidBlurEditorWidget(() => { updateFocusMode(); })); updateFocusMode(); } dispose() { this.viewCell.detachTextEditor(); super.dispose(); } }
src/vs/workbench/contrib/notebook/browser/view/renderers/markdownCell.ts
1
https://github.com/microsoft/vscode/commit/9504dda6a717a0a0d45d992e21f2565f8a23f390
[ 0.0002297746978001669, 0.00017084252613130957, 0.0001633098436286673, 0.000167073609190993, 0.000012574369975482114 ]
{ "id": 4, "code_window": [ "\t\t\ticon: { id: 'codicon/server-environment' },\n", "\t\t\tmenu: {\n", "\t\t\t\tid: MenuId.EditorTitle,\n", "\t\t\t\twhen: ContextKeyExpr.and(NOTEBOOK_IS_ACTIVE_EDITOR, NOTEBOOK_HAS_MULTIPLE_KERNELS),\n", "\t\t\t\tgroup: 'navigation',\n", "\t\t\t\torder: -2,\n", "\t\t\t},\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\twhen: NOTEBOOK_HAS_MULTIPLE_KERNELS,\n" ], "file_path": "src/vs/workbench/contrib/notebook/browser/contrib/status/editorStatus.ts", "type": "replace", "edit_start_line_idx": 26 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { URI } from 'vs/base/common/uri'; export interface ICommonMenubarService { updateMenubar(windowId: number, menuData: IMenubarData): Promise<void>; } export interface IMenubarData { menus: { [id: string]: IMenubarMenu }; keybindings: { [id: string]: IMenubarKeybinding }; } export interface IMenubarMenu { items: Array<MenubarMenuItem>; } export interface IMenubarKeybinding { label: string; userSettingsLabel?: string; isNative?: boolean; // Assumed true if missing } export interface IMenubarMenuItemAction { id: string; label: string; checked?: boolean; // Assumed false if missing enabled?: boolean; // Assumed true if missing } export interface IMenubarMenuUriItemAction { id: string; label: string; uri: URI; enabled?: boolean; } export interface IMenubarMenuItemSubmenu { id: string; label: string; submenu: IMenubarMenu; } export interface IMenubarMenuItemSeparator { id: 'vscode.menubar.separator'; } export type MenubarMenuItem = IMenubarMenuItemAction | IMenubarMenuItemSubmenu | IMenubarMenuItemSeparator | IMenubarMenuUriItemAction; export function isMenubarMenuItemSubmenu(menuItem: MenubarMenuItem): menuItem is IMenubarMenuItemSubmenu { return (<IMenubarMenuItemSubmenu>menuItem).submenu !== undefined; } export function isMenubarMenuItemSeparator(menuItem: MenubarMenuItem): menuItem is IMenubarMenuItemSeparator { return (<IMenubarMenuItemSeparator>menuItem).id === 'vscode.menubar.separator'; } export function isMenubarMenuItemUriAction(menuItem: MenubarMenuItem): menuItem is IMenubarMenuUriItemAction { return (<IMenubarMenuUriItemAction>menuItem).uri !== undefined; } export function isMenubarMenuItemAction(menuItem: MenubarMenuItem): menuItem is IMenubarMenuItemAction { return !isMenubarMenuItemSubmenu(menuItem) && !isMenubarMenuItemSeparator(menuItem) && !isMenubarMenuItemUriAction(menuItem); }
src/vs/platform/menubar/common/menubar.ts
0
https://github.com/microsoft/vscode/commit/9504dda6a717a0a0d45d992e21f2565f8a23f390
[ 0.0001970299636013806, 0.00017544849833939224, 0.00016649298777338117, 0.00017091221525333822, 0.00001014647841657279 ]
{ "id": 4, "code_window": [ "\t\t\ticon: { id: 'codicon/server-environment' },\n", "\t\t\tmenu: {\n", "\t\t\t\tid: MenuId.EditorTitle,\n", "\t\t\t\twhen: ContextKeyExpr.and(NOTEBOOK_IS_ACTIVE_EDITOR, NOTEBOOK_HAS_MULTIPLE_KERNELS),\n", "\t\t\t\tgroup: 'navigation',\n", "\t\t\t\torder: -2,\n", "\t\t\t},\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\twhen: NOTEBOOK_HAS_MULTIPLE_KERNELS,\n" ], "file_path": "src/vs/workbench/contrib/notebook/browser/contrib/status/editorStatus.ts", "type": "replace", "edit_start_line_idx": 26 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ declare module '@emmetio/html-matcher' { import { BufferStream, HtmlNode } from 'EmmetNode'; function parse(stream: BufferStream): HtmlNode; export default parse; }
extensions/emmet/src/typings/emmetio__html-matcher.d.ts
0
https://github.com/microsoft/vscode/commit/9504dda6a717a0a0d45d992e21f2565f8a23f390
[ 0.00017472368199378252, 0.0001740508887451142, 0.00017337808094453067, 0.0001740508887451142, 6.728005246259272e-7 ]
{ "id": 4, "code_window": [ "\t\t\ticon: { id: 'codicon/server-environment' },\n", "\t\t\tmenu: {\n", "\t\t\t\tid: MenuId.EditorTitle,\n", "\t\t\t\twhen: ContextKeyExpr.and(NOTEBOOK_IS_ACTIVE_EDITOR, NOTEBOOK_HAS_MULTIPLE_KERNELS),\n", "\t\t\t\tgroup: 'navigation',\n", "\t\t\t\torder: -2,\n", "\t\t\t},\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\twhen: NOTEBOOK_HAS_MULTIPLE_KERNELS,\n" ], "file_path": "src/vs/workbench/contrib/notebook/browser/contrib/status/editorStatus.ts", "type": "replace", "edit_start_line_idx": 26 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as assert from 'assert'; import { Lazy } from 'vs/base/common/lazy'; suite('Lazy', () => { test('lazy values should only be resolved once', () => { let counter = 0; const value = new Lazy(() => ++counter); assert.strictEqual(value.hasValue(), false); assert.strictEqual(value.getValue(), 1); assert.strictEqual(value.hasValue(), true); assert.strictEqual(value.getValue(), 1); // make sure we did not evaluate again }); test('lazy values handle error case', () => { let counter = 0; const value = new Lazy(() => { throw new Error(`${++counter}`); }); assert.strictEqual(value.hasValue(), false); assert.throws(() => value.getValue(), /\b1\b/); assert.strictEqual(value.hasValue(), true); assert.throws(() => value.getValue(), /\b1\b/); }); test('map should not cause lazy values to be re-resolved', () => { let outer = 0; let inner = 10; const outerLazy = new Lazy(() => ++outer); const innerLazy = outerLazy.map(x => [x, ++inner]); assert.strictEqual(outerLazy.hasValue(), false); assert.strictEqual(innerLazy.hasValue(), false); assert.deepEqual(innerLazy.getValue(), [1, 11]); assert.strictEqual(outerLazy.hasValue(), true); assert.strictEqual(innerLazy.hasValue(), true); assert.strictEqual(outerLazy.getValue(), 1); // make sure we did not evaluate again assert.strictEqual(outerLazy.getValue(), 1); assert.deepEqual(innerLazy.getValue(), [1, 11]); }); test('map should handle error values', () => { let outer = 0; let inner = 10; const outerLazy = new Lazy(() => { throw new Error(`${++outer}`); }); const innerLazy = outerLazy.map(x => { throw new Error(`${++inner}`); }); assert.strictEqual(outerLazy.hasValue(), false); assert.strictEqual(innerLazy.hasValue(), false); assert.throws(() => innerLazy.getValue(), /\b1\b/); // we should get result from outer assert.strictEqual(outerLazy.hasValue(), true); assert.strictEqual(innerLazy.hasValue(), true); assert.throws(() => outerLazy.getValue(), /\b1\b/); }); });
src/vs/base/test/common/lazy.test.ts
0
https://github.com/microsoft/vscode/commit/9504dda6a717a0a0d45d992e21f2565f8a23f390
[ 0.00017705027130432427, 0.00017490042955614626, 0.00017267739167436957, 0.0001746427151374519, 0.000001445159341528779 ]
{ "id": 5, "code_window": [ "\t\tthis._createBody(this._overlayContainer);\n", "\t\tthis._generateFontInfo();\n", "\t\tthis._editorFocus = NOTEBOOK_EDITOR_FOCUSED.bindTo(this.contextKeyService);\n", "\t\tthis._editorFocus.set(true);\n", "\t\tthis._isVisible = true;\n", "\t\tthis._outputFocus = NOTEBOOK_OUTPUT_FOCUSED.bindTo(this.contextKeyService);\n", "\t\tthis._editorEditable = NOTEBOOK_EDITOR_EDITABLE.bindTo(this.contextKeyService);\n", "\t\tthis._editorEditable.set(true);\n", "\t\tthis._editorRunnable = NOTEBOOK_EDITOR_RUNNABLE.bindTo(this.contextKeyService);\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t// this._editorFocus.set(true);\n" ], "file_path": "src/vs/workbench/contrib/notebook/browser/notebookEditorWidget.ts", "type": "replace", "edit_start_line_idx": 241 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { INotebookEditor, NOTEBOOK_EDITOR_FOCUSED, NOTEBOOK_IS_ACTIVE_EDITOR, NOTEBOOK_HAS_MULTIPLE_KERNELS } from 'vs/workbench/contrib/notebook/browser/notebookBrowser'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; import { IQuickInputService, QuickPickInput, IQuickPickItem } from 'vs/platform/quickinput/common/quickInput'; import { INotebookService } from 'vs/workbench/contrib/notebook/common/notebookService'; import * as nls from 'vs/nls'; import { registerAction2, Action2, MenuId } from 'vs/platform/actions/common/actions'; import { NOTEBOOK_ACTIONS_CATEGORY, INotebookCellActionContext } from 'vs/workbench/contrib/notebook/browser/contrib/coreActions'; import { ContextKeyExpr } from 'vs/platform/contextkey/common/contextkey'; import { ServicesAccessor } from 'vs/platform/instantiation/common/instantiation'; registerAction2(class extends Action2 { constructor() { super({ id: 'notebook.selectKernel', category: NOTEBOOK_ACTIONS_CATEGORY, title: nls.localize('notebookActions.selectKernel', "Select Notebook Kernel"), precondition: ContextKeyExpr.and(NOTEBOOK_IS_ACTIVE_EDITOR, NOTEBOOK_EDITOR_FOCUSED), icon: { id: 'codicon/server-environment' }, menu: { id: MenuId.EditorTitle, when: ContextKeyExpr.and(NOTEBOOK_IS_ACTIVE_EDITOR, NOTEBOOK_HAS_MULTIPLE_KERNELS), group: 'navigation', order: -2, }, f1: true }); } async run(accessor: ServicesAccessor, context?: INotebookCellActionContext): Promise<void> { const editorService = accessor.get<IEditorService>(IEditorService); const notebookService = accessor.get<INotebookService>(INotebookService); const quickInputService = accessor.get<IQuickInputService>(IQuickInputService); const activeEditorPane = editorService.activeEditorPane as unknown as { isNotebookEditor?: boolean } | undefined; if (!activeEditorPane?.isNotebookEditor) { return; } const editor = editorService.activeEditorPane?.getControl() as INotebookEditor; const activeKernel = editor.activeKernel; const availableKernels = notebookService.getContributedNotebookKernels(editor.viewModel!.viewType, editor.viewModel!.uri); const picks: QuickPickInput<IQuickPickItem & { run(): void; }>[] = availableKernels.map((a) => { return { id: a.id, label: a.label, picked: a.id === activeKernel?.id, description: a.extension.value + (a.id === activeKernel?.id ? nls.localize('currentActiveKernel', " (Currently Active)") : ''), run: () => { editor.activeKernel = a; } }; }); const provider = notebookService.getContributedNotebookProviders(editor.viewModel!.uri)[0]; if (provider.kernel) { picks.unshift({ id: provider.id, label: provider.displayName, picked: !activeKernel, // no active kernel, the builtin kernel of the provider is used description: activeKernel === undefined ? nls.localize('currentActiveBuiltinKernel', " (Currently Active)") : '', run: () => { editor.activeKernel = undefined; } }); } const action = await quickInputService.pick(picks, { placeHolder: nls.localize('pickAction', "Select Action"), matchOnDetail: true }); return action?.run(); } });
src/vs/workbench/contrib/notebook/browser/contrib/status/editorStatus.ts
1
https://github.com/microsoft/vscode/commit/9504dda6a717a0a0d45d992e21f2565f8a23f390
[ 0.0009514889097772539, 0.0002693725982680917, 0.00016948135453276336, 0.0001712593511911109, 0.00024277389456983656 ]
{ "id": 5, "code_window": [ "\t\tthis._createBody(this._overlayContainer);\n", "\t\tthis._generateFontInfo();\n", "\t\tthis._editorFocus = NOTEBOOK_EDITOR_FOCUSED.bindTo(this.contextKeyService);\n", "\t\tthis._editorFocus.set(true);\n", "\t\tthis._isVisible = true;\n", "\t\tthis._outputFocus = NOTEBOOK_OUTPUT_FOCUSED.bindTo(this.contextKeyService);\n", "\t\tthis._editorEditable = NOTEBOOK_EDITOR_EDITABLE.bindTo(this.contextKeyService);\n", "\t\tthis._editorEditable.set(true);\n", "\t\tthis._editorRunnable = NOTEBOOK_EDITOR_RUNNABLE.bindTo(this.contextKeyService);\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t// this._editorFocus.set(true);\n" ], "file_path": "src/vs/workbench/contrib/notebook/browser/notebookEditorWidget.ts", "type": "replace", "edit_start_line_idx": 241 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ const vscode = acquireVsCodeApi(); vscode.postMessage({ type: 'custom_renderer_initialize', payload: { firstMessage: true } });
extensions/vscode-notebook-tests/src/customRenderer.js
0
https://github.com/microsoft/vscode/commit/9504dda6a717a0a0d45d992e21f2565f8a23f390
[ 0.00017393160669598728, 0.0001716658443911001, 0.00016940008208621293, 0.0001716658443911001, 0.0000022657623048871756 ]
{ "id": 5, "code_window": [ "\t\tthis._createBody(this._overlayContainer);\n", "\t\tthis._generateFontInfo();\n", "\t\tthis._editorFocus = NOTEBOOK_EDITOR_FOCUSED.bindTo(this.contextKeyService);\n", "\t\tthis._editorFocus.set(true);\n", "\t\tthis._isVisible = true;\n", "\t\tthis._outputFocus = NOTEBOOK_OUTPUT_FOCUSED.bindTo(this.contextKeyService);\n", "\t\tthis._editorEditable = NOTEBOOK_EDITOR_EDITABLE.bindTo(this.contextKeyService);\n", "\t\tthis._editorEditable.set(true);\n", "\t\tthis._editorRunnable = NOTEBOOK_EDITOR_RUNNABLE.bindTo(this.contextKeyService);\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t// this._editorFocus.set(true);\n" ], "file_path": "src/vs/workbench/contrib/notebook/browser/notebookEditorWidget.ts", "type": "replace", "edit_start_line_idx": 241 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Event, Emitter } from 'vs/base/common/event'; import { values } from 'vs/base/common/map'; import { Disposable, toDisposable } from 'vs/base/common/lifecycle'; import { createDecorator } from 'vs/platform/instantiation/common/instantiation'; export interface IStorageKey { readonly key: string; readonly version: number; } export const IStorageKeysSyncRegistryService = createDecorator<IStorageKeysSyncRegistryService>('IStorageKeysSyncRegistryService'); export interface IStorageKeysSyncRegistryService { _serviceBrand: any; /** * All registered storage keys */ readonly storageKeys: ReadonlyArray<IStorageKey>; /** * Event that is triggered when storage keys are changed */ readonly onDidChangeStorageKeys: Event<ReadonlyArray<IStorageKey>>; /** * Register a storage key that has to be synchronized during sync. */ registerStorageKey(key: IStorageKey): void; } export class StorageKeysSyncRegistryService extends Disposable implements IStorageKeysSyncRegistryService { _serviceBrand: any; private readonly _storageKeys = new Map<string, IStorageKey>(); get storageKeys(): ReadonlyArray<IStorageKey> { return values(this._storageKeys); } private readonly _onDidChangeStorageKeys: Emitter<ReadonlyArray<IStorageKey>> = this._register(new Emitter<ReadonlyArray<IStorageKey>>()); readonly onDidChangeStorageKeys = this._onDidChangeStorageKeys.event; constructor() { super(); this._register(toDisposable(() => this._storageKeys.clear())); } registerStorageKey(storageKey: IStorageKey): void { if (!this._storageKeys.has(storageKey.key)) { this._storageKeys.set(storageKey.key, storageKey); this._onDidChangeStorageKeys.fire(this.storageKeys); } } }
src/vs/platform/userDataSync/common/storageKeys.ts
0
https://github.com/microsoft/vscode/commit/9504dda6a717a0a0d45d992e21f2565f8a23f390
[ 0.0001726806949591264, 0.00016767829947639257, 0.00016433425480499864, 0.0001670571946306154, 0.0000032644695693306858 ]
{ "id": 5, "code_window": [ "\t\tthis._createBody(this._overlayContainer);\n", "\t\tthis._generateFontInfo();\n", "\t\tthis._editorFocus = NOTEBOOK_EDITOR_FOCUSED.bindTo(this.contextKeyService);\n", "\t\tthis._editorFocus.set(true);\n", "\t\tthis._isVisible = true;\n", "\t\tthis._outputFocus = NOTEBOOK_OUTPUT_FOCUSED.bindTo(this.contextKeyService);\n", "\t\tthis._editorEditable = NOTEBOOK_EDITOR_EDITABLE.bindTo(this.contextKeyService);\n", "\t\tthis._editorEditable.set(true);\n", "\t\tthis._editorRunnable = NOTEBOOK_EDITOR_RUNNABLE.bindTo(this.contextKeyService);\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t// this._editorFocus.set(true);\n" ], "file_path": "src/vs/workbench/contrib/notebook/browser/notebookEditorWidget.ts", "type": "replace", "edit_start_line_idx": 241 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as nls from 'vs/nls'; import * as objects from 'vs/base/common/objects'; import { isFunction, isObject, isArray, assertIsDefined } from 'vs/base/common/types'; import { IDiffEditor } from 'vs/editor/browser/editorBrowser'; import { IDiffEditorOptions, IEditorOptions as ICodeEditorOptions } from 'vs/editor/common/config/editorOptions'; import { BaseTextEditor, IEditorConfiguration } from 'vs/workbench/browser/parts/editor/textEditor'; import { TextEditorOptions, EditorInput, EditorOptions, TEXT_DIFF_EDITOR_ID, IEditorInputFactoryRegistry, Extensions as EditorInputExtensions, ITextDiffEditorPane, IEditorInput } from 'vs/workbench/common/editor'; import { DiffEditorInput } from 'vs/workbench/common/editor/diffEditorInput'; import { DiffNavigator } from 'vs/editor/browser/widget/diffNavigator'; import { DiffEditorWidget } from 'vs/editor/browser/widget/diffEditorWidget'; import { TextDiffEditorModel } from 'vs/workbench/common/editor/textDiffEditorModel'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IStorageService } from 'vs/platform/storage/common/storage'; import { ITextResourceConfigurationService } from 'vs/editor/common/services/textResourceConfigurationService'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IThemeService } from 'vs/platform/theme/common/themeService'; import { TextFileOperationError, TextFileOperationResult } from 'vs/workbench/services/textfile/common/textfiles'; import { ScrollType, IDiffEditorViewState, IDiffEditorModel } from 'vs/editor/common/editorCommon'; import { DisposableStore } from 'vs/base/common/lifecycle'; import { Registry } from 'vs/platform/registry/common/platform'; import { URI } from 'vs/base/common/uri'; import { Event } from 'vs/base/common/event'; import { IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService'; import { IEditorService, ACTIVE_GROUP } from 'vs/workbench/services/editor/common/editorService'; import { CancellationToken } from 'vs/base/common/cancellation'; import { EditorActivation, IEditorOptions } from 'vs/platform/editor/common/editor'; /** * The text editor that leverages the diff text editor for the editing experience. */ export class TextDiffEditor extends BaseTextEditor implements ITextDiffEditorPane { static readonly ID = TEXT_DIFF_EDITOR_ID; private diffNavigator: DiffNavigator | undefined; private readonly diffNavigatorDisposables = this._register(new DisposableStore()); constructor( @ITelemetryService telemetryService: ITelemetryService, @IInstantiationService instantiationService: IInstantiationService, @IStorageService storageService: IStorageService, @ITextResourceConfigurationService configurationService: ITextResourceConfigurationService, @IEditorService editorService: IEditorService, @IThemeService themeService: IThemeService, @IEditorGroupsService editorGroupService: IEditorGroupsService ) { super(TextDiffEditor.ID, telemetryService, instantiationService, storageService, configurationService, themeService, editorService, editorGroupService); } protected onWillCloseEditorInGroup(editor: IEditorInput): void { // React to editors closing to preserve or clear view state. This needs to happen // in the onWillCloseEditor because at that time the editor has not yet // been disposed and we can safely persist the view state still as needed. this.doSaveOrClearTextDiffEditorViewState(editor); } getTitle(): string { if (this.input) { return this.input.getName(); } return nls.localize('textDiffEditor', "Text Diff Editor"); } createEditorControl(parent: HTMLElement, configuration: ICodeEditorOptions): IDiffEditor { return this.instantiationService.createInstance(DiffEditorWidget, parent, configuration); } async setInput(input: EditorInput, options: EditorOptions | undefined, token: CancellationToken): Promise<void> { // Dispose previous diff navigator this.diffNavigatorDisposables.clear(); // Update/clear view settings if input changes this.doSaveOrClearTextDiffEditorViewState(this.input); // Set input and resolve await super.setInput(input, options, token); try { const resolvedModel = await input.resolve(); // Check for cancellation if (token.isCancellationRequested) { return undefined; } // Assert Model Instance if (!(resolvedModel instanceof TextDiffEditorModel) && this.openAsBinary(input, options)) { return undefined; } // Set Editor Model const diffEditor = assertIsDefined(this.getControl()); const resolvedDiffEditorModel = <TextDiffEditorModel>resolvedModel; diffEditor.setModel(resolvedDiffEditorModel.textDiffEditorModel); // Apply Options from TextOptions let optionsGotApplied = false; if (options && isFunction((<TextEditorOptions>options).apply)) { optionsGotApplied = (<TextEditorOptions>options).apply(diffEditor, ScrollType.Immediate); } // Otherwise restore View State let hasPreviousViewState = false; if (!optionsGotApplied) { hasPreviousViewState = this.restoreTextDiffEditorViewState(input, diffEditor); } // Diff navigator this.diffNavigator = new DiffNavigator(diffEditor, { alwaysRevealFirst: !optionsGotApplied && !hasPreviousViewState // only reveal first change if we had no options or viewstate }); this.diffNavigatorDisposables.add(this.diffNavigator); // Since the resolved model provides information about being readonly // or not, we apply it here to the editor even though the editor input // was already asked for being readonly or not. The rationale is that // a resolved model might have more specific information about being // readonly or not that the input did not have. diffEditor.updateOptions({ readOnly: resolvedDiffEditorModel.modifiedModel?.isReadonly(), originalEditable: !resolvedDiffEditorModel.originalModel?.isReadonly() }); } catch (error) { // In case we tried to open a file and the response indicates that this is not a text file, fallback to binary diff. if (this.isFileBinaryError(error) && this.openAsBinary(input, options)) { return; } throw error; } } private restoreTextDiffEditorViewState(editor: EditorInput, control: IDiffEditor): boolean { if (editor instanceof DiffEditorInput) { const resource = this.toDiffEditorViewStateResource(editor); if (resource) { const viewState = this.loadTextEditorViewState(resource); if (viewState) { control.restoreViewState(viewState); return true; } } } return false; } private openAsBinary(input: EditorInput, options: EditorOptions | undefined): boolean { if (input instanceof DiffEditorInput) { const originalInput = input.originalInput; const modifiedInput = input.modifiedInput; const binaryDiffInput = new DiffEditorInput(input.getName(), input.getDescription(), originalInput, modifiedInput, true); // Forward binary flag to input if supported const fileEditorInputFactory = Registry.as<IEditorInputFactoryRegistry>(EditorInputExtensions.EditorInputFactories).getFileEditorInputFactory(); if (fileEditorInputFactory.isFileEditorInput(originalInput)) { originalInput.setForceOpenAsBinary(); } if (fileEditorInputFactory.isFileEditorInput(modifiedInput)) { modifiedInput.setForceOpenAsBinary(); } // Make sure to not steal away the currently active group // because we are triggering another openEditor() call // and do not control the initial intent that resulted // in us now opening as binary. const preservingOptions: IEditorOptions = { activation: EditorActivation.PRESERVE, pinned: this.group?.isPinned(input), sticky: this.group?.isSticky(input) }; if (options) { options.overwrite(preservingOptions); } else { options = EditorOptions.create(preservingOptions); } // Replace this editor with the binary one this.editorService.replaceEditors([{ editor: input, replacement: binaryDiffInput, options }], this.group || ACTIVE_GROUP); return true; } return false; } protected computeConfiguration(configuration: IEditorConfiguration): ICodeEditorOptions { const editorConfiguration = super.computeConfiguration(configuration); // Handle diff editor specially by merging in diffEditor configuration if (isObject(configuration.diffEditor)) { objects.mixin(editorConfiguration, configuration.diffEditor); } return editorConfiguration; } protected getConfigurationOverrides(): ICodeEditorOptions { const options: IDiffEditorOptions = super.getConfigurationOverrides(); options.readOnly = this.input instanceof DiffEditorInput && this.input.modifiedInput.isReadonly(); options.originalEditable = this.input instanceof DiffEditorInput && !this.input.originalInput.isReadonly(); options.lineDecorationsWidth = '2ch'; return options; } private isFileBinaryError(error: Error[]): boolean; private isFileBinaryError(error: Error): boolean; private isFileBinaryError(error: Error | Error[]): boolean { if (isArray(error)) { const errors = <Error[]>error; return errors.some(error => this.isFileBinaryError(error)); } return (<TextFileOperationError>error).textFileOperationResult === TextFileOperationResult.FILE_IS_BINARY; } clearInput(): void { // Dispose previous diff navigator this.diffNavigatorDisposables.clear(); // Update/clear editor view state in settings this.doSaveOrClearTextDiffEditorViewState(this.input); // Clear Model const diffEditor = this.getControl(); if (diffEditor) { diffEditor.setModel(null); } // Pass to super super.clearInput(); } getDiffNavigator(): DiffNavigator | undefined { return this.diffNavigator; } getControl(): IDiffEditor | undefined { return super.getControl() as IDiffEditor | undefined; } protected loadTextEditorViewState(resource: URI): IDiffEditorViewState { return super.loadTextEditorViewState(resource) as IDiffEditorViewState; // overridden for text diff editor support } protected saveState(): void { // Update/clear editor view State this.doSaveOrClearTextDiffEditorViewState(this.input); super.saveState(); } private doSaveOrClearTextDiffEditorViewState(input: IEditorInput | undefined): void { if (!(input instanceof DiffEditorInput)) { return; // only supported for diff editor inputs } const resource = this.toDiffEditorViewStateResource(input); if (!resource) { return; // unable to retrieve input resource } // Clear view state if input is disposed or we are configured to not storing any state if (input.isDisposed() || (!this.shouldRestoreViewState && (!this.group || !this.group.isOpened(input)))) { super.clearTextEditorViewState([resource], this.group); } // Otherwise save it else { super.saveTextEditorViewState(resource); // Make sure to clean up when the input gets disposed Event.once(input.onDispose)(() => { super.clearTextEditorViewState([resource], this.group); }); } } protected retrieveTextEditorViewState(resource: URI): IDiffEditorViewState | null { return this.retrieveTextDiffEditorViewState(resource); // overridden for text diff editor support } private retrieveTextDiffEditorViewState(resource: URI): IDiffEditorViewState | null { const control = assertIsDefined(this.getControl()); const model = control.getModel(); if (!model || !model.modified || !model.original) { return null; // view state always needs a model } const modelUri = this.toDiffEditorViewStateResource(model); if (!modelUri) { return null; // model URI is needed to make sure we save the view state correctly } if (modelUri.toString() !== resource.toString()) { return null; // prevent saving view state for a model that is not the expected one } return control.saveViewState(); } private toDiffEditorViewStateResource(modelOrInput: IDiffEditorModel | DiffEditorInput): URI | undefined { let original: URI | undefined; let modified: URI | undefined; if (modelOrInput instanceof DiffEditorInput) { original = modelOrInput.originalInput.resource; modified = modelOrInput.modifiedInput.resource; } else { original = modelOrInput.original.uri; modified = modelOrInput.modified.uri; } if (!original || !modified) { return undefined; } // create a URI that is the Base64 concatenation of original + modified resource return URI.from({ scheme: 'diff', path: `${btoa(original.toString())}${btoa(modified.toString())}` }); } }
src/vs/workbench/browser/parts/editor/textDiffEditor.ts
0
https://github.com/microsoft/vscode/commit/9504dda6a717a0a0d45d992e21f2565f8a23f390
[ 0.00017915073840413243, 0.0001707227056613192, 0.00016490560665261, 0.00017051251779776067, 0.0000033242547488043783 ]
{ "id": 6, "code_window": [ "\t\t}\n", "\n", "\t\tif (viewState?.editorFocused) {\n", "\t\t\tthis._list?.focusView();\n", "\t\t\tconst cell = this._notebookViewModel?.viewCells[focusIdx];\n", "\t\t\tif (cell) {\n", "\t\t\t\tcell.focusMode = CellFocusMode.Editor;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t// this._list?.focusView();\n" ], "file_path": "src/vs/workbench/contrib/notebook/browser/notebookEditorWidget.ts", "type": "replace", "edit_start_line_idx": 684 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { getZoomLevel } from 'vs/base/browser/browser'; import * as DOM from 'vs/base/browser/dom'; import { IMouseWheelEvent, StandardMouseEvent } from 'vs/base/browser/mouseEvent'; import { CancellationTokenSource } from 'vs/base/common/cancellation'; import { Color, RGBA } from 'vs/base/common/color'; import { onUnexpectedError } from 'vs/base/common/errors'; import { Emitter, Event } from 'vs/base/common/event'; import { combinedDisposable, DisposableStore, Disposable, IDisposable, toDisposable } from 'vs/base/common/lifecycle'; import 'vs/css!./media/notebook'; import { ICodeEditor } from 'vs/editor/browser/editorBrowser'; import { IEditorOptions } from 'vs/editor/common/config/editorOptions'; import { BareFontInfo } from 'vs/editor/common/config/fontInfo'; import { Range } from 'vs/editor/common/core/range'; import { IEditor } from 'vs/editor/common/editorCommon'; import * as nls from 'vs/nls'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IContextKey, IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { IResourceEditorInput } from 'vs/platform/editor/common/editor'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage'; import { contrastBorder, editorBackground, focusBorder, foreground, registerColor, textBlockQuoteBackground, textBlockQuoteBorder, textLinkActiveForeground, textLinkForeground, textPreformatForeground, errorForeground, transparent, widgetShadow, listFocusBackground, listInactiveSelectionBackground, scrollbarSliderBackground, scrollbarSliderHoverBackground, scrollbarSliderActiveBackground } from 'vs/platform/theme/common/colorRegistry'; import { registerThemingParticipant } from 'vs/platform/theme/common/themeService'; import { EditorMemento } from 'vs/workbench/browser/parts/editor/baseEditor'; import { EditorOptions, IEditorMemento } from 'vs/workbench/common/editor'; import { CELL_MARGIN, CELL_RUN_GUTTER, EDITOR_BOTTOM_PADDING, EDITOR_TOP_MARGIN, EDITOR_TOP_PADDING, SCROLLABLE_ELEMENT_PADDING_TOP, BOTTOM_CELL_TOOLBAR_HEIGHT, CELL_BOTTOM_MARGIN, CODE_CELL_LEFT_MARGIN } from 'vs/workbench/contrib/notebook/browser/constants'; import { CellEditState, CellFocusMode, ICellRange, ICellViewModel, INotebookCellList, INotebookEditor, INotebookEditorContribution, INotebookEditorMouseEvent, NotebookLayoutInfo, NOTEBOOK_EDITOR_EDITABLE, NOTEBOOK_EDITOR_EXECUTING_NOTEBOOK, NOTEBOOK_EDITOR_FOCUSED, NOTEBOOK_EDITOR_RUNNABLE, NOTEBOOK_HAS_MULTIPLE_KERNELS, NOTEBOOK_OUTPUT_FOCUSED } from 'vs/workbench/contrib/notebook/browser/notebookBrowser'; import { NotebookEditorExtensionsRegistry } from 'vs/workbench/contrib/notebook/browser/notebookEditorExtensions'; import { NotebookCellList } from 'vs/workbench/contrib/notebook/browser/view/notebookCellList'; import { OutputRenderer } from 'vs/workbench/contrib/notebook/browser/view/output/outputRenderer'; import { BackLayerWebView } from 'vs/workbench/contrib/notebook/browser/view/renderers/backLayerWebView'; import { CellDragAndDropController, CodeCellRenderer, MarkdownCellRenderer, NotebookCellListDelegate } from 'vs/workbench/contrib/notebook/browser/view/renderers/cellRenderer'; import { CodeCellViewModel } from 'vs/workbench/contrib/notebook/browser/viewModel/codeCellViewModel'; import { NotebookEventDispatcher, NotebookLayoutChangedEvent } from 'vs/workbench/contrib/notebook/browser/viewModel/eventDispatcher'; import { CellViewModel, IModelDecorationsChangeAccessor, INotebookEditorViewState, NotebookViewModel } from 'vs/workbench/contrib/notebook/browser/viewModel/notebookViewModel'; import { CellKind, IProcessedOutput, INotebookKernelInfo, INotebookKernelInfoDto } from 'vs/workbench/contrib/notebook/common/notebookCommon'; import { INotebookService } from 'vs/workbench/contrib/notebook/common/notebookService'; import { Webview } from 'vs/workbench/contrib/webview/browser/webview'; import { IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService'; import { ILayoutService } from 'vs/platform/layout/browser/layoutService'; import { generateUuid } from 'vs/base/common/uuid'; import { Memento, MementoObject } from 'vs/workbench/common/memento'; import { NotebookTextModel } from 'vs/workbench/contrib/notebook/common/model/notebookTextModel'; import { URI } from 'vs/base/common/uri'; import { PANEL_BORDER } from 'vs/workbench/common/theme'; import { debugIconStartForeground } from 'vs/workbench/contrib/debug/browser/debugToolBar'; import { CellContextKeyManager } from 'vs/workbench/contrib/notebook/browser/view/renderers/cellContextKeys'; const $ = DOM.$; export class NotebookEditorOptions extends EditorOptions { readonly cellOptions?: IResourceEditorInput; constructor(options: Partial<NotebookEditorOptions>) { super(); this.overwrite(options); this.cellOptions = options.cellOptions; } with(options: Partial<NotebookEditorOptions>): NotebookEditorOptions { return new NotebookEditorOptions({ ...this, ...options }); } } export class NotebookEditorWidget extends Disposable implements INotebookEditor { static readonly ID: string = 'workbench.editor.notebook'; private static readonly EDITOR_MEMENTOS = new Map<string, EditorMemento<unknown>>(); private _overlayContainer!: HTMLElement; private _body!: HTMLElement; private _webview: BackLayerWebView | null = null; private _webviewTransparentCover: HTMLElement | null = null; private _list: INotebookCellList | undefined; private _dndController: CellDragAndDropController | null = null; private _renderedEditors: Map<ICellViewModel, ICodeEditor | undefined> = new Map(); private _eventDispatcher: NotebookEventDispatcher | undefined; private _notebookViewModel: NotebookViewModel | undefined; private _localStore: DisposableStore = this._register(new DisposableStore()); private _fontInfo: BareFontInfo | undefined; private _dimension: DOM.Dimension | null = null; private _shadowElementViewInfo: { height: number, width: number, top: number; left: number; } | null = null; private _editorFocus: IContextKey<boolean> | null = null; private _outputFocus: IContextKey<boolean> | null = null; private _editorEditable: IContextKey<boolean> | null = null; private _editorRunnable: IContextKey<boolean> | null = null; private _editorExecutingNotebook: IContextKey<boolean> | null = null; private _notebookHasMultipleKernels: IContextKey<boolean> | null = null; private _outputRenderer: OutputRenderer; protected readonly _contributions: { [key: string]: INotebookEditorContribution; }; private _scrollBeyondLastLine: boolean; private readonly _memento: Memento; private readonly _onDidFocusEmitter = this._register(new Emitter<void>()); public readonly onDidFocus = this._onDidFocusEmitter.event; private _cellContextKeyManager: CellContextKeyManager | null = null; private _isVisible = false; private readonly _uuid = generateUuid(); private _webiewFocused: boolean = false; private _isDisposed: boolean = false; get isDisposed() { return this._isDisposed; } private readonly _onDidChangeModel = this._register(new Emitter<NotebookTextModel | undefined>()); readonly onDidChangeModel: Event<NotebookTextModel | undefined> = this._onDidChangeModel.event; private readonly _onDidFocusEditorWidget = this._register(new Emitter<void>()); readonly onDidFocusEditorWidget = this._onDidFocusEditorWidget.event; set viewModel(newModel: NotebookViewModel | undefined) { this._notebookViewModel = newModel; this._onDidChangeModel.fire(newModel?.notebookDocument); } get viewModel() { return this._notebookViewModel; } get uri() { return this._notebookViewModel?.uri; } get textModel() { return this._notebookViewModel?.notebookDocument; } private _activeKernel: INotebookKernelInfo | undefined = undefined; private readonly _onDidChangeKernel = this._register(new Emitter<void>()); readonly onDidChangeKernel: Event<void> = this._onDidChangeKernel.event; get activeKernel() { return this._activeKernel; } set activeKernel(kernel: INotebookKernelInfo | undefined) { if (this._isDisposed) { return; } this._activeKernel = kernel; this._onDidChangeKernel.fire(); } private readonly _onDidChangeActiveEditor = this._register(new Emitter<this>()); readonly onDidChangeActiveEditor: Event<this> = this._onDidChangeActiveEditor.event; get activeCodeEditor(): IEditor | undefined { if (this._isDisposed) { return; } const [focused] = this._list!.getFocusedElements(); return this._renderedEditors.get(focused); } constructor( @IInstantiationService private readonly instantiationService: IInstantiationService, @IStorageService storageService: IStorageService, @INotebookService private notebookService: INotebookService, @IConfigurationService private readonly configurationService: IConfigurationService, @IContextKeyService readonly contextKeyService: IContextKeyService, @ILayoutService private readonly layoutService: ILayoutService ) { super(); this._memento = new Memento(NotebookEditorWidget.ID, storageService); this._outputRenderer = new OutputRenderer(this, this.instantiationService); this._contributions = {}; this._scrollBeyondLastLine = this.configurationService.getValue<boolean>('editor.scrollBeyondLastLine'); this.configurationService.onDidChangeConfiguration(e => { if (e.affectsConfiguration('editor.scrollBeyondLastLine')) { this._scrollBeyondLastLine = this.configurationService.getValue<boolean>('editor.scrollBeyondLastLine'); if (this._dimension && this._isVisible) { this.layout(this._dimension); } } }); this.notebookService.addNotebookEditor(this); } public getId(): string { return this._uuid; } hasModel() { return !!this._notebookViewModel; } //#region Editor Core protected getEditorMemento<T>(editorGroupService: IEditorGroupsService, key: string, limit: number = 10): IEditorMemento<T> { const mementoKey = `${NotebookEditorWidget.ID}${key}`; let editorMemento = NotebookEditorWidget.EDITOR_MEMENTOS.get(mementoKey); if (!editorMemento) { editorMemento = new EditorMemento(NotebookEditorWidget.ID, key, this.getMemento(StorageScope.WORKSPACE), limit, editorGroupService); NotebookEditorWidget.EDITOR_MEMENTOS.set(mementoKey, editorMemento); } return editorMemento as IEditorMemento<T>; } protected getMemento(scope: StorageScope): MementoObject { return this._memento.getMemento(scope); } public get isNotebookEditor() { return true; } updateEditorFocus() { // Note - focus going to the webview will fire 'blur', but the webview element will be // a descendent of the notebook editor root. const focused = DOM.isAncestor(document.activeElement, this._overlayContainer); this._editorFocus?.set(focused); this._notebookViewModel?.setFocus(focused); } hasFocus() { return this._editorFocus?.get() || false; } createEditor(): void { this._overlayContainer = document.createElement('div'); const id = generateUuid(); this._overlayContainer.id = `notebook-${id}`; this._overlayContainer.className = 'notebookOverlay'; DOM.addClass(this._overlayContainer, 'notebook-editor'); this._overlayContainer.style.visibility = 'hidden'; this.layoutService.container.appendChild(this._overlayContainer); this._createBody(this._overlayContainer); this._generateFontInfo(); this._editorFocus = NOTEBOOK_EDITOR_FOCUSED.bindTo(this.contextKeyService); this._editorFocus.set(true); this._isVisible = true; this._outputFocus = NOTEBOOK_OUTPUT_FOCUSED.bindTo(this.contextKeyService); this._editorEditable = NOTEBOOK_EDITOR_EDITABLE.bindTo(this.contextKeyService); this._editorEditable.set(true); this._editorRunnable = NOTEBOOK_EDITOR_RUNNABLE.bindTo(this.contextKeyService); this._editorRunnable.set(true); this._editorExecutingNotebook = NOTEBOOK_EDITOR_EXECUTING_NOTEBOOK.bindTo(this.contextKeyService); this._notebookHasMultipleKernels = NOTEBOOK_HAS_MULTIPLE_KERNELS.bindTo(this.contextKeyService); this._notebookHasMultipleKernels.set(false); const contributions = NotebookEditorExtensionsRegistry.getEditorContributions(); for (const desc of contributions) { try { const contribution = this.instantiationService.createInstance(desc.ctor, this); this._contributions[desc.id] = contribution; } catch (err) { onUnexpectedError(err); } } } private _generateFontInfo(): void { const editorOptions = this.configurationService.getValue<IEditorOptions>('editor'); this._fontInfo = BareFontInfo.createFromRawSettings(editorOptions, getZoomLevel()); } private _createBody(parent: HTMLElement): void { this._body = document.createElement('div'); DOM.addClass(this._body, 'cell-list-container'); this._createCellList(); DOM.append(parent, this._body); } private _createCellList(): void { DOM.addClass(this._body, 'cell-list-container'); this._dndController = this._register(new CellDragAndDropController(this, this._body)); const getScopedContextKeyService = (container?: HTMLElement) => this._list!.contextKeyService.createScoped(container); const renderers = [ this.instantiationService.createInstance(CodeCellRenderer, this, this._renderedEditors, this._dndController, getScopedContextKeyService), this.instantiationService.createInstance(MarkdownCellRenderer, this, this._dndController, this._renderedEditors, getScopedContextKeyService), ]; this._list = this.instantiationService.createInstance( NotebookCellList, 'NotebookCellList', this._body, this.instantiationService.createInstance(NotebookCellListDelegate), renderers, this.contextKeyService, { setRowLineHeight: false, setRowHeight: false, supportDynamicHeights: true, horizontalScrolling: false, keyboardSupport: false, mouseSupport: true, multipleSelectionSupport: false, enableKeyboardNavigation: true, additionalScrollHeight: 0, transformOptimization: false, styleController: (_suffix: string) => { return this._list!; }, overrideStyles: { listBackground: editorBackground, listActiveSelectionBackground: editorBackground, listActiveSelectionForeground: foreground, listFocusAndSelectionBackground: editorBackground, listFocusAndSelectionForeground: foreground, listFocusBackground: editorBackground, listFocusForeground: foreground, listHoverForeground: foreground, listHoverBackground: editorBackground, listHoverOutline: focusBorder, listFocusOutline: focusBorder, listInactiveSelectionBackground: editorBackground, listInactiveSelectionForeground: foreground, listInactiveFocusBackground: editorBackground, listInactiveFocusOutline: editorBackground, }, accessibilityProvider: { getAriaLabel() { return null; }, getWidgetAriaLabel() { return nls.localize('notebookTreeAriaLabel', "Notebook"); } } }, ); this._dndController.setList(this._list); // create Webview this._register(this._list); this._register(combinedDisposable(...renderers)); // transparent cover this._webviewTransparentCover = DOM.append(this._list.rowsContainer, $('.webview-cover')); this._webviewTransparentCover.style.display = 'none'; this._register(DOM.addStandardDisposableGenericMouseDownListner(this._overlayContainer, (e: StandardMouseEvent) => { if (DOM.hasClass(e.target, 'slider') && this._webviewTransparentCover) { this._webviewTransparentCover.style.display = 'block'; } })); this._register(DOM.addStandardDisposableGenericMouseUpListner(this._overlayContainer, () => { if (this._webviewTransparentCover) { // no matter when this._webviewTransparentCover.style.display = 'none'; } })); this._register(this._list.onMouseDown(e => { if (e.element) { this._onMouseDown.fire({ event: e.browserEvent, target: e.element }); } })); this._register(this._list.onMouseUp(e => { if (e.element) { this._onMouseUp.fire({ event: e.browserEvent, target: e.element }); } })); this._register(this._list.onDidChangeFocus(_e => this._onDidChangeActiveEditor.fire(this))); const widgetFocusTracker = DOM.trackFocus(this.getDomNode()); this._register(widgetFocusTracker); this._register(widgetFocusTracker.onDidFocus(() => this._onDidFocusEmitter.fire())); } getDomNode() { return this._overlayContainer; } onWillHide() { this._isVisible = false; this._editorFocus?.set(false); this._overlayContainer.style.visibility = 'hidden'; this._overlayContainer.style.left = '-50000px'; } getInnerWebview(): Webview | undefined { return this._webview?.webview; } focus() { this._isVisible = true; this._editorFocus?.set(true); if (this._webiewFocused) { this._webview?.focusWebview(); } else { const focus = this._list?.getFocus()[0]; if (typeof focus === 'number') { const element = this._notebookViewModel!.viewCells[focus]; if (element.focusMode === CellFocusMode.Editor) { element.editState = CellEditState.Editing; element.focusMode = CellFocusMode.Editor; this._onDidFocusEditorWidget.fire(); return; } } this._list?.domFocus(); } this._onDidFocusEditorWidget.fire(); } async setModel(textModel: NotebookTextModel, viewState: INotebookEditorViewState | undefined): Promise<void> { if (this._notebookViewModel === undefined || !this._notebookViewModel.equal(textModel)) { this._detachModel(); await this._attachModel(textModel, viewState); } else { this.restoreListViewState(viewState); } // clear state this._dndController?.clearGlobalDragState(); this._setKernels(textModel); this._localStore.add(this.notebookService.onDidChangeKernels(() => { if (this.activeKernel === undefined) { this._setKernels(textModel); } })); this._localStore.add(this._list!.onDidChangeFocus(() => { const focused = this._list!.getFocusedElements()[0]; if (focused) { if (!this._cellContextKeyManager) { this._cellContextKeyManager = this._localStore.add(new CellContextKeyManager(this.contextKeyService, textModel, focused as CellViewModel)); } this._cellContextKeyManager.updateForElement(focused as CellViewModel); } })); } async setOptions(options: NotebookEditorOptions | undefined) { // reveal cell if editor options tell to do so if (options?.cellOptions) { const cellOptions = options.cellOptions; const cell = this._notebookViewModel!.viewCells.find(cell => cell.uri.toString() === cellOptions.resource.toString()); if (cell) { this.selectElement(cell); this.revealInCenterIfOutsideViewport(cell); const editor = this._renderedEditors.get(cell)!; if (editor) { if (cellOptions.options?.selection) { const { selection } = cellOptions.options; editor.setSelection({ ...selection, endLineNumber: selection.endLineNumber || selection.startLineNumber, endColumn: selection.endColumn || selection.startColumn }); editor.revealPositionInCenterIfOutsideViewport({ lineNumber: selection.startLineNumber, column: selection.startColumn }); } if (!cellOptions.options?.preserveFocus) { editor.focus(); } } } } else if (this._notebookViewModel && this._notebookViewModel.viewCells.length === 1 && this._notebookViewModel.viewCells[0].cellKind === CellKind.Code) { // there is only one code cell in the document const cell = this._notebookViewModel!.viewCells[0]; if (cell.getTextLength() === 0) { // the cell is empty, very likely a template cell, focus it this.selectElement(cell); await this.revealLineInCenterAsync(cell, 1); const editor = this._renderedEditors.get(cell)!; if (editor) { editor.focus(); } } } } private _detachModel() { this._localStore.clear(); this._list?.detachViewModel(); this.viewModel?.dispose(); // avoid event this._notebookViewModel = undefined; // this.webview?.clearInsets(); // this.webview?.clearPreloadsCache(); this._webview?.dispose(); this._webview?.element.remove(); this._webview = null; this._list?.clear(); } private _setKernels(textModel: NotebookTextModel) { const provider = this.notebookService.getContributedNotebookProviders(this.viewModel!.uri)[0]; const availableKernels = this.notebookService.getContributedNotebookKernels(textModel.viewType, textModel.uri); if (provider.kernel && availableKernels.length > 0) { this._notebookHasMultipleKernels!.set(true); } else if (availableKernels.length > 1) { this._notebookHasMultipleKernels!.set(true); } else { this._notebookHasMultipleKernels!.set(false); } if (provider && provider.kernel) { // it has a builtin kernel, don't automatically choose a kernel this._loadKernelPreloads(provider.providerExtensionLocation, provider.kernel); return; } // the provider doesn't have a builtin kernel, choose a kernel this.activeKernel = availableKernels[0]; if (this.activeKernel) { this._loadKernelPreloads(this.activeKernel.extensionLocation, this.activeKernel); } } private _loadKernelPreloads(extensionLocation: URI, kernel: INotebookKernelInfoDto) { if (kernel.preloads) { this._webview?.updateKernelPreloads([extensionLocation], kernel.preloads.map(preload => URI.revive(preload))); } } private _updateForMetadata(): void { this._editorEditable?.set(!!this.viewModel!.metadata?.editable); this._editorRunnable?.set(!!this.viewModel!.metadata?.runnable); DOM.toggleClass(this._overlayContainer, 'notebook-editor-editable', !!this.viewModel!.metadata?.editable); DOM.toggleClass(this.getDomNode(), 'notebook-editor-editable', !!this.viewModel!.metadata?.editable); } private async _createWebview(id: string, resource: URI): Promise<void> { this._webview = this.instantiationService.createInstance(BackLayerWebView, this, id, resource); // attach the webview container to the DOM tree first this._list?.rowsContainer.insertAdjacentElement('afterbegin', this._webview.element); await this._webview.createWebview(); this._webview.webview.onDidBlur(() => { this._outputFocus?.set(false); this.updateEditorFocus(); if (this._overlayContainer.contains(document.activeElement)) { this._webiewFocused = false; } }); this._webview.webview.onDidFocus(() => { this._outputFocus?.set(true); this.updateEditorFocus(); this._onDidFocusEmitter.fire(); if (this._overlayContainer.contains(document.activeElement)) { this._webiewFocused = true; } }); this._localStore.add(this._webview.onMessage(({ message, forRenderer }) => { if (this.viewModel) { this.notebookService.onDidReceiveMessage(this.viewModel.viewType, this.getId(), forRenderer, message); } })); } private async _attachModel(textModel: NotebookTextModel, viewState: INotebookEditorViewState | undefined) { await this._createWebview(this.getId(), textModel.uri); this._eventDispatcher = new NotebookEventDispatcher(); this.viewModel = this.instantiationService.createInstance(NotebookViewModel, textModel.viewType, textModel, this._eventDispatcher, this.getLayoutInfo()); this._eventDispatcher.emit([new NotebookLayoutChangedEvent({ width: true, fontInfo: true }, this.getLayoutInfo())]); this._updateForMetadata(); this._localStore.add(this._eventDispatcher.onDidChangeMetadata(() => { this._updateForMetadata(); })); // restore view states, including contributions { // restore view state this.viewModel.restoreEditorViewState(viewState); // contribution state restore const contributionsState = viewState?.contributionsState || {}; const keys = Object.keys(this._contributions); for (let i = 0, len = keys.length; i < len; i++) { const id = keys[i]; const contribution = this._contributions[id]; if (typeof contribution.restoreViewState === 'function') { contribution.restoreViewState(contributionsState[id]); } } } this._webview?.updateRendererPreloads(this.viewModel.renderers); this._localStore.add(this._list!.onWillScroll(e => { this._webview!.updateViewScrollTop(-e.scrollTop, []); this._webviewTransparentCover!.style.top = `${e.scrollTop}px`; })); this._localStore.add(this._list!.onDidChangeContentHeight(() => { DOM.scheduleAtNextAnimationFrame(() => { if (this._isDisposed) { return; } const scrollTop = this._list?.scrollTop || 0; const scrollHeight = this._list?.scrollHeight || 0; this._webview!.element.style.height = `${scrollHeight}px`; if (this._webview?.insetMapping) { let updateItems: { cell: CodeCellViewModel, output: IProcessedOutput, cellTop: number }[] = []; let removedItems: IProcessedOutput[] = []; this._webview?.insetMapping.forEach((value, key) => { const cell = value.cell; const viewIndex = this._list?.getViewIndex(cell); if (viewIndex === undefined) { return; } if (cell.outputs.indexOf(key) < 0) { // output is already gone removedItems.push(key); } const cellTop = this._list?.getAbsoluteTopOfElement(cell) || 0; if (this._webview!.shouldUpdateInset(cell, key, cellTop)) { updateItems.push({ cell: cell, output: key, cellTop: cellTop }); } }); removedItems.forEach(output => this._webview?.removeInset(output)); if (updateItems.length) { this._webview?.updateViewScrollTop(-scrollTop, updateItems); } } }); })); this._list!.attachViewModel(this.viewModel); this._localStore.add(this._list!.onDidRemoveOutput(output => { this.removeInset(output); })); this._localStore.add(this._list!.onDidHideOutput(output => { this.hideInset(output); })); this._list!.layout(); this._dndController?.clearGlobalDragState(); // restore list state at last, it must be after list layout this.restoreListViewState(viewState); } restoreListViewState(viewState: INotebookEditorViewState | undefined): void { if (viewState?.scrollPosition !== undefined) { this._list!.scrollTop = viewState!.scrollPosition.top; this._list!.scrollLeft = viewState!.scrollPosition.left; } else { this._list!.scrollTop = 0; this._list!.scrollLeft = 0; } const focusIdx = typeof viewState?.focus === 'number' ? viewState.focus : 0; if (focusIdx < this._list!.length) { this._list!.setFocus([focusIdx]); this._list!.setSelection([focusIdx]); } else if (this._list!.length > 0) { this._list!.setFocus([0]); } if (viewState?.editorFocused) { this._list?.focusView(); const cell = this._notebookViewModel?.viewCells[focusIdx]; if (cell) { cell.focusMode = CellFocusMode.Editor; } } } getEditorViewState(): INotebookEditorViewState { const state = this._notebookViewModel?.getEditorViewState(); if (!state) { return { editingCells: {}, editorViewStates: {} }; } if (this._list) { state.scrollPosition = { left: this._list.scrollLeft, top: this._list.scrollTop }; let cellHeights: { [key: number]: number } = {}; for (let i = 0; i < this.viewModel!.length; i++) { const elm = this.viewModel!.viewCells[i] as CellViewModel; if (elm.cellKind === CellKind.Code) { cellHeights[i] = elm.layoutInfo.totalHeight; } else { cellHeights[i] = 0; } } state.cellTotalHeights = cellHeights; const focus = this._list.getFocus()[0]; if (typeof focus === 'number') { const element = this._notebookViewModel!.viewCells[focus]; if (element) { const itemDOM = this._list?.domElementOfElement(element); let editorFocused = !!(document.activeElement && itemDOM && itemDOM.contains(document.activeElement)); state.editorFocused = editorFocused; state.focus = focus; } } } // Save contribution view states const contributionsState: { [key: string]: unknown } = {}; const keys = Object.keys(this._contributions); for (const id of keys) { const contribution = this._contributions[id]; if (typeof contribution.saveViewState === 'function') { contributionsState[id] = contribution.saveViewState(); } } state.contributionsState = contributionsState; return state; } // private saveEditorViewState(input: NotebookEditorInput): void { // if (this.group && this.notebookViewModel) { // } // } // private loadTextEditorViewState(): INotebookEditorViewState | undefined { // return this.editorMemento.loadEditorState(this.group, input.resource); // } layout(dimension: DOM.Dimension, shadowElement?: HTMLElement): void { if (!shadowElement && this._shadowElementViewInfo === null) { this._dimension = dimension; return; } if (shadowElement) { const containerRect = shadowElement.getBoundingClientRect(); this._shadowElementViewInfo = { height: containerRect.height, width: containerRect.width, top: containerRect.top, left: containerRect.left }; } this._dimension = new DOM.Dimension(dimension.width, dimension.height); DOM.size(this._body, dimension.width, dimension.height); this._list?.updateOptions({ additionalScrollHeight: this._scrollBeyondLastLine ? dimension.height - SCROLLABLE_ELEMENT_PADDING_TOP : 0 }); this._list?.layout(dimension.height - SCROLLABLE_ELEMENT_PADDING_TOP, dimension.width); this._overlayContainer.style.visibility = 'visible'; this._overlayContainer.style.display = 'block'; this._overlayContainer.style.position = 'absolute'; this._overlayContainer.style.top = `${this._shadowElementViewInfo!.top}px`; this._overlayContainer.style.left = `${this._shadowElementViewInfo!.left}px`; this._overlayContainer.style.width = `${dimension ? dimension.width : this._shadowElementViewInfo!.width}px`; this._overlayContainer.style.height = `${dimension ? dimension.height : this._shadowElementViewInfo!.height}px`; if (this._webviewTransparentCover) { this._webviewTransparentCover.style.height = `${dimension.height}px`; this._webviewTransparentCover.style.width = `${dimension.width}px`; } this._eventDispatcher?.emit([new NotebookLayoutChangedEvent({ width: true, fontInfo: true }, this.getLayoutInfo())]); } // protected saveState(): void { // if (this.input instanceof NotebookEditorInput) { // this.saveEditorViewState(this.input); // } // super.saveState(); // } //#endregion //#region Editor Features selectElement(cell: ICellViewModel) { this._list?.selectElement(cell); // this.viewModel!.selectionHandles = [cell.handle]; } revealInView(cell: ICellViewModel) { this._list?.revealElementInView(cell); } revealInCenterIfOutsideViewport(cell: ICellViewModel) { this._list?.revealElementInCenterIfOutsideViewport(cell); } revealInCenter(cell: ICellViewModel) { this._list?.revealElementInCenter(cell); } async revealLineInViewAsync(cell: ICellViewModel, line: number): Promise<void> { return this._list?.revealElementLineInViewAsync(cell, line); } async revealLineInCenterAsync(cell: ICellViewModel, line: number): Promise<void> { return this._list?.revealElementLineInCenterAsync(cell, line); } async revealLineInCenterIfOutsideViewportAsync(cell: ICellViewModel, line: number): Promise<void> { return this._list?.revealElementLineInCenterIfOutsideViewportAsync(cell, line); } async revealRangeInViewAsync(cell: ICellViewModel, range: Range): Promise<void> { return this._list?.revealElementRangeInViewAsync(cell, range); } async revealRangeInCenterAsync(cell: ICellViewModel, range: Range): Promise<void> { return this._list?.revealElementRangeInCenterAsync(cell, range); } async revealRangeInCenterIfOutsideViewportAsync(cell: ICellViewModel, range: Range): Promise<void> { return this._list?.revealElementRangeInCenterIfOutsideViewportAsync(cell, range); } setCellSelection(cell: ICellViewModel, range: Range): void { this._list?.setCellSelection(cell, range); } changeDecorations<T>(callback: (changeAccessor: IModelDecorationsChangeAccessor) => T): T | null { return this._notebookViewModel?.changeDecorations<T>(callback) || null; } setHiddenAreas(_ranges: ICellRange[]): boolean { return this._list!.setHiddenAreas(_ranges, true); } //#endregion //#region Mouse Events private readonly _onMouseUp: Emitter<INotebookEditorMouseEvent> = this._register(new Emitter<INotebookEditorMouseEvent>()); public readonly onMouseUp: Event<INotebookEditorMouseEvent> = this._onMouseUp.event; private readonly _onMouseDown: Emitter<INotebookEditorMouseEvent> = this._register(new Emitter<INotebookEditorMouseEvent>()); public readonly onMouseDown: Event<INotebookEditorMouseEvent> = this._onMouseDown.event; private pendingLayouts = new WeakMap<ICellViewModel, IDisposable>(); //#endregion //#region Cell operations async layoutNotebookCell(cell: ICellViewModel, height: number): Promise<void> { const viewIndex = this._list!.getViewIndex(cell); if (viewIndex === undefined) { // the cell is hidden return; } let relayout = (cell: ICellViewModel, height: number) => { if (this._isDisposed) { return; } this._list?.updateElementHeight2(cell, height); }; if (this.pendingLayouts.has(cell)) { this.pendingLayouts.get(cell)!.dispose(); } let r: () => void; const layoutDisposable = DOM.scheduleAtNextAnimationFrame(() => { if (this._isDisposed) { return; } this.pendingLayouts.delete(cell); relayout(cell, height); r(); }); this.pendingLayouts.set(cell, toDisposable(() => { layoutDisposable.dispose(); r(); })); return new Promise(resolve => { r = resolve; }); } insertNotebookCell(cell: ICellViewModel | undefined, type: CellKind, direction: 'above' | 'below' = 'above', initialText: string = '', ui: boolean = false): CellViewModel | null { if (!this._notebookViewModel!.metadata.editable) { return null; } const index = cell ? this._notebookViewModel!.getCellIndex(cell) : 0; const nextIndex = ui ? this._notebookViewModel!.getNextVisibleCellIndex(index) : index + 1; const newLanguages = this._notebookViewModel!.languages; const language = (cell?.cellKind === CellKind.Code && type === CellKind.Code) ? cell.language : ((type === CellKind.Code && newLanguages && newLanguages.length) ? newLanguages[0] : 'markdown'); const insertIndex = cell ? (direction === 'above' ? index : nextIndex) : index; const newCell = this._notebookViewModel!.createCell(insertIndex, initialText.split(/\r?\n/g), language, type, undefined, true); return newCell as CellViewModel; } async splitNotebookCell(cell: ICellViewModel): Promise<CellViewModel[] | null> { const index = this._notebookViewModel!.getCellIndex(cell); return this._notebookViewModel!.splitNotebookCell(index); } async joinNotebookCells(cell: ICellViewModel, direction: 'above' | 'below', constraint?: CellKind): Promise<ICellViewModel | null> { const index = this._notebookViewModel!.getCellIndex(cell); const ret = await this._notebookViewModel!.joinNotebookCells(index, direction, constraint); if (ret) { ret.deletedCells.forEach(cell => { if (this.pendingLayouts.has(cell)) { this.pendingLayouts.get(cell)!.dispose(); } }); return ret.cell; } else { return null; } } async deleteNotebookCell(cell: ICellViewModel): Promise<boolean> { if (!this._notebookViewModel!.metadata.editable) { return false; } if (this.pendingLayouts.has(cell)) { this.pendingLayouts.get(cell)!.dispose(); } const index = this._notebookViewModel!.getCellIndex(cell); this._notebookViewModel!.deleteCell(index, true); return true; } async moveCellDown(cell: ICellViewModel): Promise<ICellViewModel | null> { if (!this._notebookViewModel!.metadata.editable) { return null; } const index = this._notebookViewModel!.getCellIndex(cell); if (index === this._notebookViewModel!.length - 1) { return null; } const newIdx = index + 1; return this._moveCellToIndex(index, newIdx); } async moveCellUp(cell: ICellViewModel): Promise<ICellViewModel | null> { if (!this._notebookViewModel!.metadata.editable) { return null; } const index = this._notebookViewModel!.getCellIndex(cell); if (index === 0) { return null; } const newIdx = index - 1; return this._moveCellToIndex(index, newIdx); } async moveCell(cell: ICellViewModel, relativeToCell: ICellViewModel, direction: 'above' | 'below'): Promise<ICellViewModel | null> { if (!this._notebookViewModel!.metadata.editable) { return null; } if (cell === relativeToCell) { return null; } const originalIdx = this._notebookViewModel!.getCellIndex(cell); const relativeToIndex = this._notebookViewModel!.getCellIndex(relativeToCell); let newIdx = direction === 'above' ? relativeToIndex : relativeToIndex + 1; if (originalIdx < newIdx) { newIdx--; } return this._moveCellToIndex(originalIdx, newIdx); } private async _moveCellToIndex(index: number, newIdx: number): Promise<ICellViewModel | null> { if (index === newIdx) { return null; } if (!this._notebookViewModel!.moveCellToIdx(index, newIdx, true)) { throw new Error('Notebook Editor move cell, index out of range'); } let r: (val: ICellViewModel | null) => void; DOM.scheduleAtNextAnimationFrame(() => { if (this._isDisposed) { r(null); } const viewCell = this._notebookViewModel!.viewCells[newIdx]; this._list?.revealElementInView(viewCell); r(viewCell); }); return new Promise(resolve => { r = resolve; }); } editNotebookCell(cell: CellViewModel): void { if (!cell.getEvaluatedMetadata(this._notebookViewModel!.metadata).editable) { return; } cell.editState = CellEditState.Editing; this._renderedEditors.get(cell)?.focus(); } getActiveCell() { let elements = this._list?.getFocusedElements(); if (elements && elements.length) { return elements[0]; } return undefined; } cancelNotebookExecution(): void { if (!this._notebookViewModel!.currentTokenSource) { throw new Error('Notebook is not executing'); } this._notebookViewModel!.currentTokenSource.cancel(); this._notebookViewModel!.currentTokenSource = undefined; } async executeNotebook(): Promise<void> { if (!this._notebookViewModel!.metadata.runnable) { return; } return this._executeNotebook(); } async _executeNotebook(): Promise<void> { if (this._notebookViewModel!.currentTokenSource) { return; } const tokenSource = new CancellationTokenSource(); try { this._editorExecutingNotebook!.set(true); this._notebookViewModel!.currentTokenSource = tokenSource; const provider = this.notebookService.getContributedNotebookProviders(this.viewModel!.uri)[0]; if (provider) { const viewType = provider.id; const notebookUri = this._notebookViewModel!.uri; if (this._activeKernel) { await this.notebookService.executeNotebook2(this._notebookViewModel!.viewType, this._notebookViewModel!.uri, this._activeKernel.id, tokenSource.token); } else if (provider.kernel) { return await this.notebookService.executeNotebook(viewType, notebookUri, true, tokenSource.token); } else { return await this.notebookService.executeNotebook(viewType, notebookUri, false, tokenSource.token); } } } finally { this._editorExecutingNotebook!.set(false); this._notebookViewModel!.currentTokenSource = undefined; tokenSource.dispose(); } } cancelNotebookCellExecution(cell: ICellViewModel): void { if (!cell.currentTokenSource) { throw new Error('Cell is not executing'); } cell.currentTokenSource.cancel(); cell.currentTokenSource = undefined; } async executeNotebookCell(cell: ICellViewModel): Promise<void> { if (cell.cellKind === CellKind.Markdown) { this.focusNotebookCell(cell, 'container'); return; } if (!cell.getEvaluatedMetadata(this._notebookViewModel!.metadata).runnable) { return; } const tokenSource = new CancellationTokenSource(); try { await this._executeNotebookCell(cell, tokenSource); } finally { tokenSource.dispose(); } } private async _executeNotebookCell(cell: ICellViewModel, tokenSource: CancellationTokenSource): Promise<void> { try { cell.currentTokenSource = tokenSource; const provider = this.notebookService.getContributedNotebookProviders(this.viewModel!.uri)[0]; if (provider) { const viewType = provider.id; const notebookUri = this._notebookViewModel!.uri; if (this._activeKernel) { return await this.notebookService.executeNotebookCell2(viewType, notebookUri, cell.handle, this._activeKernel.id, tokenSource.token); } else if (provider.kernel) { return await this.notebookService.executeNotebookCell(viewType, notebookUri, cell.handle, true, tokenSource.token); } else { return await this.notebookService.executeNotebookCell(viewType, notebookUri, cell.handle, false, tokenSource.token); } } } finally { cell.currentTokenSource = undefined; } } focusNotebookCell(cell: ICellViewModel, focusItem: 'editor' | 'container' | 'output') { if (this._isDisposed) { return; } if (focusItem === 'editor') { this.selectElement(cell); this._list?.focusView(); cell.editState = CellEditState.Editing; cell.focusMode = CellFocusMode.Editor; this.revealInCenterIfOutsideViewport(cell); } else if (focusItem === 'output') { this.selectElement(cell); this._list?.focusView(); if (!this._webview) { return; } this._webview.focusOutput(cell.id); cell.editState = CellEditState.Preview; cell.focusMode = CellFocusMode.Container; this.revealInCenterIfOutsideViewport(cell); } else { let itemDOM = this._list?.domElementOfElement(cell); if (document.activeElement && itemDOM && itemDOM.contains(document.activeElement)) { (document.activeElement as HTMLElement).blur(); } cell.editState = CellEditState.Preview; cell.focusMode = CellFocusMode.Container; this.selectElement(cell); this.revealInCenterIfOutsideViewport(cell); this._list?.focusView(); } } //#endregion //#region MISC getLayoutInfo(): NotebookLayoutInfo { if (!this._list) { throw new Error('Editor is not initalized successfully'); } return { width: this._dimension!.width, height: this._dimension!.height, fontInfo: this._fontInfo! }; } triggerScroll(event: IMouseWheelEvent) { this._list?.triggerScrollFromMouseWheelEvent(event); } async createInset(cell: CodeCellViewModel, output: IProcessedOutput, shadowContent: string, offset: number) { if (!this._webview) { return; } let preloads = this._notebookViewModel!.renderers; if (!this._webview!.insetMapping.has(output)) { let cellTop = this._list?.getAbsoluteTopOfElement(cell) || 0; await this._webview!.createInset(cell, output, cellTop, offset, shadowContent, preloads); } else { let cellTop = this._list?.getAbsoluteTopOfElement(cell) || 0; let scrollTop = this._list?.scrollTop || 0; this._webview!.updateViewScrollTop(-scrollTop, [{ cell: cell, output: output, cellTop: cellTop }]); } } removeInset(output: IProcessedOutput) { if (!this._webview) { return; } this._webview!.removeInset(output); } hideInset(output: IProcessedOutput) { if (!this._webview) { return; } this._webview!.hideInset(output); } getOutputRenderer(): OutputRenderer { return this._outputRenderer; } postMessage(forRendererId: string | undefined, message: any) { if (forRendererId === undefined) { this._webview?.webview.postMessage(message); } else { this._webview?.postRendererMessage(forRendererId, message); } } toggleClassName(className: string) { DOM.toggleClass(this._overlayContainer, className); } addClassName(className: string) { DOM.addClass(this._overlayContainer, className); } removeClassName(className: string) { DOM.removeClass(this._overlayContainer, className); } //#endregion //#region Editor Contributions public getContribution<T extends INotebookEditorContribution>(id: string): T { return <T>(this._contributions[id] || null); } //#endregion dispose() { this._isDisposed = true; // dispose webview first this._webview?.dispose(); this.notebookService.removeNotebookEditor(this); const keys = Object.keys(this._contributions); for (let i = 0, len = keys.length; i < len; i++) { const contributionId = keys[i]; this._contributions[contributionId].dispose(); } this._localStore.clear(); this._list?.dispose(); this._overlayContainer.remove(); this.viewModel?.dispose(); // this._layoutService.container.removeChild(this.overlayContainer); super.dispose(); } toJSON(): object { return { notebookHandle: this.viewModel?.handle }; } } export const notebookCellBorder = registerColor('notebook.cellBorderColor', { dark: transparent(PANEL_BORDER, .4), light: transparent(listInactiveSelectionBackground, 1), hc: PANEL_BORDER }, nls.localize('notebook.cellBorderColor', "The border color for notebook cells.")); export const focusedEditorBorderColor = registerColor('notebook.focusedEditorBorder', { light: focusBorder, dark: focusBorder, hc: focusBorder }, nls.localize('notebook.focusedEditorBorder', "The color of the notebook cell editor border.")); export const cellStatusIconSuccess = registerColor('notebookStatusSuccessIcon.foreground', { light: debugIconStartForeground, dark: debugIconStartForeground, hc: debugIconStartForeground }, nls.localize('notebookStatusSuccessIcon.foreground', "The error icon color of notebook cells in the cell status bar.")); export const cellStatusIconError = registerColor('notebookStatusErrorIcon.foreground', { light: errorForeground, dark: errorForeground, hc: errorForeground }, nls.localize('notebookStatusErrorIcon.foreground', "The error icon color of notebook cells in the cell status bar.")); export const cellStatusIconRunning = registerColor('notebookStatusRunningIcon.foreground', { light: foreground, dark: foreground, hc: foreground }, nls.localize('notebookStatusRunningIcon.foreground', "The running icon color of notebook cells in the cell status bar.")); export const notebookOutputContainerColor = registerColor('notebook.outputContainerBackgroundColor', { dark: notebookCellBorder, light: transparent(listFocusBackground, .4), hc: null }, nls.localize('notebook.outputContainerBackgroundColor', "The Color of the notebook output container background.")); // TODO currently also used for toolbar border, if we keep all of this, pick a generic name export const CELL_TOOLBAR_SEPERATOR = registerColor('notebook.cellToolbarSeperator', { dark: Color.fromHex('#808080').transparent(0.35), light: Color.fromHex('#808080').transparent(0.35), hc: contrastBorder }, nls.localize('notebook.cellToolbarSeperator', "The color of the seperator in the cell bottom toolbar")); export const focusedCellBackground = registerColor('notebook.focusedCellBackground', { dark: transparent(PANEL_BORDER, .4), light: transparent(listFocusBackground, .4), hc: null }, nls.localize('focusedCellBackground', "The background color of a cell when the cell is focused.")); export const cellHoverBackground = registerColor('notebook.cellHoverBackground', { dark: transparent(focusedCellBackground, .5), light: transparent(focusedCellBackground, .7), hc: null }, nls.localize('notebook.cellHoverBackground', "The background color of a cell when the cell is hovered.")); export const focusedCellBorder = registerColor('notebook.focusedCellBorder', { dark: Color.white.transparent(0.12), light: Color.black.transparent(0.12), hc: focusBorder }, nls.localize('notebook.focusedCellBorder', "The color of the cell's top and bottom border when the cell is focused.")); export const focusedCellShadow = registerColor('notebook.focusedCellShadow', { dark: transparent(widgetShadow, 0.6), light: transparent(widgetShadow, 0.4), hc: Color.transparent }, nls.localize('notebook.focusedCellShadow', "The color of the cell shadow when cells are focused.")); export const cellStatusBarItemHover = registerColor('notebook.cellStatusBarItemHoverBackground', { light: new Color(new RGBA(0, 0, 0, 0.08)), dark: new Color(new RGBA(255, 255, 255, 0.15)), hc: new Color(new RGBA(255, 255, 255, 0.15)), }, nls.localize('notebook.cellStatusBarItemHoverBackground', "The background color of notebook cell status bar items.")); export const cellInsertionIndicator = registerColor('notebook.cellInsertionIndicator', { light: focusBorder, dark: focusBorder, hc: focusBorder }, nls.localize('notebook.cellInsertionIndicator', "The color of the notebook cell insertion indicator.")); export const listScrollbarSliderBackground = registerColor('notebookScrollbarSlider.background', { dark: scrollbarSliderBackground, light: scrollbarSliderBackground, hc: scrollbarSliderBackground }, nls.localize('notebookScrollbarSliderBackground', "Notebook scrollbar slider background color.")); export const listScrollbarSliderHoverBackground = registerColor('notebookScrollbarSlider.hoverBackground', { dark: scrollbarSliderHoverBackground, light: scrollbarSliderHoverBackground, hc: scrollbarSliderHoverBackground }, nls.localize('notebookScrollbarSliderHoverBackground', "Notebook scrollbar slider background color when hovering.")); export const listScrollbarSliderActiveBackground = registerColor('notebookScrollbarSlider.activeBackground', { dark: scrollbarSliderActiveBackground, light: scrollbarSliderActiveBackground, hc: scrollbarSliderActiveBackground }, nls.localize('notebookScrollbarSliderActiveBackground', "Notebook scrollbar slider background color when clicked on.")); registerThemingParticipant((theme, collector) => { collector.addRule(`.notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element { padding-top: ${SCROLLABLE_ELEMENT_PADDING_TOP}px; box-sizing: border-box; }`); // const color = getExtraColor(theme, embeddedEditorBackground, { dark: 'rgba(0, 0, 0, .4)', extra_dark: 'rgba(200, 235, 255, .064)', light: '#f4f4f4', hc: null }); const color = theme.getColor(editorBackground); if (color) { collector.addRule(`.notebookOverlay .cell .monaco-editor-background, .notebookOverlay .cell .margin-view-overlays, .notebookOverlay .cell .cell-statusbar-container { background: ${color}; }`); collector.addRule(`.notebookOverlay .cell-drag-image .cell-editor-container > div { background: ${color} !important; }`); } const link = theme.getColor(textLinkForeground); if (link) { collector.addRule(`.notebookOverlay .output a, .notebookOverlay .cell.markdown a { color: ${link};} `); } const activeLink = theme.getColor(textLinkActiveForeground); if (activeLink) { collector.addRule(`.notebookOverlay .output a:hover, .notebookOverlay .cell .output a:active { color: ${activeLink}; }`); } const shortcut = theme.getColor(textPreformatForeground); if (shortcut) { collector.addRule(`.notebookOverlay code, .notebookOverlay .shortcut { color: ${shortcut}; }`); } const border = theme.getColor(contrastBorder); if (border) { collector.addRule(`.notebookOverlay .monaco-editor { border-color: ${border}; }`); } const quoteBackground = theme.getColor(textBlockQuoteBackground); if (quoteBackground) { collector.addRule(`.notebookOverlay blockquote { background: ${quoteBackground}; }`); } const quoteBorder = theme.getColor(textBlockQuoteBorder); if (quoteBorder) { collector.addRule(`.notebookOverlay blockquote { border-color: ${quoteBorder}; }`); } const containerBackground = theme.getColor(notebookOutputContainerColor); if (containerBackground) { collector.addRule(`.notebookOverlay .output { background-color: ${containerBackground}; }`); collector.addRule(`.notebookOverlay .output-element { background-color: ${containerBackground}; }`); } const editorBackgroundColor = theme.getColor(editorBackground); if (editorBackgroundColor) { collector.addRule(`.notebookOverlay .cell-statusbar-container { border-top: solid 1px ${editorBackgroundColor}; }`); collector.addRule(`.notebookOverlay .monaco-list-row > .monaco-toolbar { background-color: ${editorBackgroundColor}; }`); collector.addRule(`.notebookOverlay .monaco-list-row.cell-drag-image { background-color: ${editorBackgroundColor}; }`); } const cellToolbarSeperator = theme.getColor(CELL_TOOLBAR_SEPERATOR); if (cellToolbarSeperator) { collector.addRule(`.notebookOverlay .cell-bottom-toolbar-container .separator { background-color: ${cellToolbarSeperator} }`); collector.addRule(`.notebookOverlay .cell-bottom-toolbar-container .action-item:first-child::after { background-color: ${cellToolbarSeperator} }`); collector.addRule(`.notebookOverlay .monaco-list-row > .monaco-toolbar { border: solid 1px ${cellToolbarSeperator}; }`); } const focusedCellBackgroundColor = theme.getColor(focusedCellBackground); if (focusedCellBackgroundColor) { collector.addRule(`.notebookOverlay .code-cell-row.focused .cell-focus-indicator, .notebookOverlay .markdown-cell-row.focused { background-color: ${focusedCellBackgroundColor} !important; }`); } const cellHoverBackgroundColor = theme.getColor(cellHoverBackground); if (cellHoverBackgroundColor) { collector.addRule(`.notebookOverlay .code-cell-row:not(.focused):hover .cell-focus-indicator, .notebookOverlay .code-cell-row:not(.focused).cell-output-hover .cell-focus-indicator, .notebookOverlay .markdown-cell-row:not(.focused):hover { background-color: ${cellHoverBackgroundColor} !important; }`); } const focusedCellBorderColor = theme.getColor(focusedCellBorder); collector.addRule(`.monaco-workbench .notebookOverlay .monaco-list .monaco-list-row.focused .cell-focus-indicator-top:before, .monaco-workbench .notebookOverlay .monaco-list .monaco-list-row.focused .cell-focus-indicator-bottom:before, .monaco-workbench .notebookOverlay .monaco-list .markdown-cell-row.focused:before, .monaco-workbench .notebookOverlay .monaco-list .markdown-cell-row.focused:after { border-color: ${focusedCellBorderColor} !important; }`); const focusedEditorBorderColorColor = theme.getColor(focusedEditorBorderColor); if (focusedEditorBorderColorColor) { collector.addRule(`.notebookOverlay .monaco-list-row.cell-editor-focus .cell-editor-part:before { outline: solid 1px ${focusedEditorBorderColorColor}; }`); } const editorBorderColor = theme.getColor(notebookCellBorder); if (editorBorderColor) { collector.addRule(`.notebookOverlay .monaco-list-row .cell-editor-part:before { outline: solid 1px ${editorBorderColor}; }`); } const headingBorderColor = theme.getColor(notebookCellBorder); if (headingBorderColor) { collector.addRule(`.notebookOverlay .cell.markdown h1 { border-color: ${headingBorderColor}; }`); } const cellStatusSuccessIcon = theme.getColor(cellStatusIconSuccess); if (cellStatusSuccessIcon) { collector.addRule(`.monaco-workbench .notebookOverlay .cell-statusbar-container .cell-run-status .codicon-check { color: ${cellStatusSuccessIcon} }`); } const cellStatusErrorIcon = theme.getColor(cellStatusIconError); if (cellStatusErrorIcon) { collector.addRule(`.monaco-workbench .notebookOverlay .cell-statusbar-container .cell-run-status .codicon-error { color: ${cellStatusErrorIcon} }`); } const cellStatusRunningIcon = theme.getColor(cellStatusIconRunning); if (cellStatusRunningIcon) { collector.addRule(`.monaco-workbench .notebookOverlay .cell-statusbar-container .cell-run-status .codicon-sync { color: ${cellStatusRunningIcon} }`); } const cellStatusBarHoverBg = theme.getColor(cellStatusBarItemHover); if (cellStatusBarHoverBg) { collector.addRule(`.monaco-workbench .notebookOverlay .cell-statusbar-container .cell-language-picker:hover { background-color: ${cellStatusBarHoverBg}; }`); } const cellShadowColor = theme.getColor(focusedCellShadow); if (cellShadowColor) { // Code cells collector.addRule(`.monaco-workbench .notebookOverlay .monaco-list .monaco-list-row.focused .cell-shadow { box-shadow: 0px 0px 4px 2px ${cellShadowColor} }`); // Markdown cells collector.addRule(`.monaco-workbench .notebookOverlay .monaco-list .markdown-cell-row.focused { box-shadow: 0px 0px 4px 2px ${cellShadowColor} }`); } const cellInsertionIndicatorColor = theme.getColor(cellInsertionIndicator); if (cellInsertionIndicatorColor) { collector.addRule(`.notebookOverlay > .cell-list-container > .cell-list-insertion-indicator { background-color: ${cellInsertionIndicatorColor}; }`); } const scrollbarSliderBackgroundColor = theme.getColor(listScrollbarSliderBackground); if (scrollbarSliderBackgroundColor) { collector.addRule(` .notebookOverlay .cell-list-container > .monaco-list > .monaco-scrollable-element > .scrollbar > .slider { background: ${editorBackgroundColor}; } `); collector.addRule(` .notebookOverlay .cell-list-container > .monaco-list > .monaco-scrollable-element > .scrollbar > .slider:before { content: ""; width: 100%; height: 100%; position: absolute; background: ${scrollbarSliderBackgroundColor}; } `); /* hack to not have cells see through scroller */ } const scrollbarSliderHoverBackgroundColor = theme.getColor(listScrollbarSliderHoverBackground); if (scrollbarSliderHoverBackgroundColor) { collector.addRule(` .notebookOverlay .cell-list-container > .monaco-list > .monaco-scrollable-element > .scrollbar > .slider:hover { background: ${editorBackgroundColor}; } `); collector.addRule(` .notebookOverlay .cell-list-container > .monaco-list > .monaco-scrollable-element > .scrollbar > .slider:hover:before { content: ""; width: 100%; height: 100%; position: absolute; background: ${scrollbarSliderHoverBackgroundColor}; } `); /* hack to not have cells see through scroller */ } const scrollbarSliderActiveBackgroundColor = theme.getColor(listScrollbarSliderActiveBackground); if (scrollbarSliderActiveBackgroundColor) { collector.addRule(` .notebookOverlay .cell-list-container > .monaco-list > .monaco-scrollable-element > .scrollbar > .slider.active { background: ${editorBackgroundColor}; } `); collector.addRule(` .notebookOverlay .cell-list-container > .monaco-list > .monaco-scrollable-element > .scrollbar > .slider.active:before { content: ""; width: 100%; height: 100%; position: absolute; background: ${scrollbarSliderActiveBackgroundColor}; } `); /* hack to not have cells see through scroller */ } // Cell Margin collector.addRule(`.notebookOverlay .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row > div.cell { margin: 0px ${CELL_MARGIN * 2}px 0px ${CELL_MARGIN}px; }`); collector.addRule(`.notebookOverlay .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row > div.cell.code { margin-left: ${CODE_CELL_LEFT_MARGIN}px; }`); collector.addRule(`.notebookOverlay .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row { padding-top: ${EDITOR_TOP_MARGIN}px; }`); collector.addRule(`.notebookOverlay .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .markdown-cell-row { padding-bottom: ${CELL_BOTTOM_MARGIN}px; }`); collector.addRule(`.notebookOverlay .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .markdown-cell-row .cell-bottom-toolbar-container { margin-top: ${CELL_BOTTOM_MARGIN}px; }`); collector.addRule(`.notebookOverlay .output { margin: 0px ${CELL_MARGIN}px 0px ${CODE_CELL_LEFT_MARGIN + CELL_RUN_GUTTER}px; }`); collector.addRule(`.notebookOverlay .output { width: calc(100% - ${CODE_CELL_LEFT_MARGIN + CELL_RUN_GUTTER + (CELL_MARGIN * 2)}px); }`); collector.addRule(`.notebookOverlay .cell-bottom-toolbar-container { width: calc(100% - ${CELL_MARGIN * 2 + CELL_RUN_GUTTER}px); margin: 0px ${CELL_MARGIN * 2}px 0px ${CELL_MARGIN + CELL_RUN_GUTTER}px; }`); collector.addRule(`.notebookOverlay .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row > div.cell.markdown { padding-left: ${CELL_RUN_GUTTER}px; }`); collector.addRule(`.notebookOverlay .cell .run-button-container { width: ${CELL_RUN_GUTTER}px; }`); collector.addRule(`.notebookOverlay .cell-drag-image .cell-editor-container > div { padding: ${EDITOR_TOP_PADDING}px 16px ${EDITOR_BOTTOM_PADDING}px 16px; }`); collector.addRule(`.notebookOverlay .monaco-list .monaco-list-row .cell-focus-indicator-top { height: ${EDITOR_TOP_MARGIN}px; }`); collector.addRule(`.notebookOverlay .monaco-list .monaco-list-row .cell-focus-indicator-side { bottom: ${BOTTOM_CELL_TOOLBAR_HEIGHT}px; }`); collector.addRule(`.notebookOverlay .monaco-list .monaco-list-row.code-cell-row .cell-focus-indicator-left { width: ${CODE_CELL_LEFT_MARGIN + CELL_RUN_GUTTER}px; }`); collector.addRule(`.notebookOverlay .monaco-list .monaco-list-row.markdown-cell-row .cell-focus-indicator-left { width: ${CODE_CELL_LEFT_MARGIN}px; }`); collector.addRule(`.notebookOverlay .monaco-list .monaco-list-row .cell-focus-indicator.cell-focus-indicator-right { width: ${CELL_MARGIN * 2}px; }`); collector.addRule(`.notebookOverlay .monaco-list .monaco-list-row .cell-focus-indicator-bottom { height: ${CELL_BOTTOM_MARGIN}px; }`); collector.addRule(`.notebookOverlay .monaco-list .monaco-list-row .cell-shadow-container-bottom { top: ${CELL_BOTTOM_MARGIN}px; }`); });
src/vs/workbench/contrib/notebook/browser/notebookEditorWidget.ts
1
https://github.com/microsoft/vscode/commit/9504dda6a717a0a0d45d992e21f2565f8a23f390
[ 0.9988276362419128, 0.23234878480434418, 0.0001639831461943686, 0.00033176381839439273, 0.41560959815979004 ]
{ "id": 6, "code_window": [ "\t\t}\n", "\n", "\t\tif (viewState?.editorFocused) {\n", "\t\t\tthis._list?.focusView();\n", "\t\t\tconst cell = this._notebookViewModel?.viewCells[focusIdx];\n", "\t\t\tif (cell) {\n", "\t\t\t\tcell.focusMode = CellFocusMode.Editor;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t// this._list?.focusView();\n" ], "file_path": "src/vs/workbench/contrib/notebook/browser/notebookEditorWidget.ts", "type": "replace", "edit_start_line_idx": 684 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as browser from 'vs/base/browser/browser'; import { IPointerHandlerHelper } from 'vs/editor/browser/controller/mouseHandler'; import { IMouseTarget, MouseTargetType } from 'vs/editor/browser/editorBrowser'; import { ClientCoordinates, EditorMouseEvent, EditorPagePosition, PageCoordinates } from 'vs/editor/browser/editorDom'; import { PartFingerprint, PartFingerprints } from 'vs/editor/browser/view/viewPart'; import { ViewLine } from 'vs/editor/browser/viewParts/lines/viewLine'; import { IViewCursorRenderData } from 'vs/editor/browser/viewParts/viewCursors/viewCursor'; import { EditorLayoutInfo, EditorOption } from 'vs/editor/common/config/editorOptions'; import { Position } from 'vs/editor/common/core/position'; import { Range as EditorRange } from 'vs/editor/common/core/range'; import { HorizontalPosition } from 'vs/editor/common/view/renderingContext'; import { ViewContext } from 'vs/editor/common/view/viewContext'; import { IViewModel } from 'vs/editor/common/viewModel/viewModel'; import { CursorColumns } from 'vs/editor/common/controller/cursorCommon'; import * as dom from 'vs/base/browser/dom'; export interface IViewZoneData { viewZoneId: string; positionBefore: Position | null; positionAfter: Position | null; position: Position; afterLineNumber: number; } export interface IMarginData { isAfterLines: boolean; glyphMarginLeft: number; glyphMarginWidth: number; lineNumbersWidth: number; offsetX: number; } export interface IEmptyContentData { isAfterLines: boolean; horizontalDistanceToText?: number; } interface IETextRange { boundingHeight: number; boundingLeft: number; boundingTop: number; boundingWidth: number; htmlText: string; offsetLeft: number; offsetTop: number; text: string; collapse(start?: boolean): void; compareEndPoints(how: string, sourceRange: IETextRange): number; duplicate(): IETextRange; execCommand(cmdID: string, showUI?: boolean, value?: any): boolean; execCommandShowHelp(cmdID: string): boolean; expand(Unit: string): boolean; findText(string: string, count?: number, flags?: number): boolean; getBookmark(): string; getBoundingClientRect(): ClientRect; getClientRects(): ClientRectList; inRange(range: IETextRange): boolean; isEqual(range: IETextRange): boolean; move(unit: string, count?: number): number; moveEnd(unit: string, count?: number): number; moveStart(unit: string, count?: number): number; moveToBookmark(bookmark: string): boolean; moveToElementText(element: Element): void; moveToPoint(x: number, y: number): void; parentElement(): Element; pasteHTML(html: string): void; queryCommandEnabled(cmdID: string): boolean; queryCommandIndeterm(cmdID: string): boolean; queryCommandState(cmdID: string): boolean; queryCommandSupported(cmdID: string): boolean; queryCommandText(cmdID: string): string; queryCommandValue(cmdID: string): any; scrollIntoView(fStart?: boolean): void; select(): void; setEndPoint(how: string, SourceRange: IETextRange): void; } declare const IETextRange: { prototype: IETextRange; new(): IETextRange; }; interface IHitTestResult { position: Position | null; hitTarget: Element | null; } export class PointerHandlerLastRenderData { constructor( public readonly lastViewCursorsRenderData: IViewCursorRenderData[], public readonly lastTextareaPosition: Position | null ) { } } export class MouseTarget implements IMouseTarget { public readonly element: Element | null; public readonly type: MouseTargetType; public readonly mouseColumn: number; public readonly position: Position | null; public readonly range: EditorRange | null; public readonly detail: any; constructor(element: Element | null, type: MouseTargetType, mouseColumn: number = 0, position: Position | null = null, range: EditorRange | null = null, detail: any = null) { this.element = element; this.type = type; this.mouseColumn = mouseColumn; this.position = position; if (!range && position) { range = new EditorRange(position.lineNumber, position.column, position.lineNumber, position.column); } this.range = range; this.detail = detail; } private static _typeToString(type: MouseTargetType): string { if (type === MouseTargetType.TEXTAREA) { return 'TEXTAREA'; } if (type === MouseTargetType.GUTTER_GLYPH_MARGIN) { return 'GUTTER_GLYPH_MARGIN'; } if (type === MouseTargetType.GUTTER_LINE_NUMBERS) { return 'GUTTER_LINE_NUMBERS'; } if (type === MouseTargetType.GUTTER_LINE_DECORATIONS) { return 'GUTTER_LINE_DECORATIONS'; } if (type === MouseTargetType.GUTTER_VIEW_ZONE) { return 'GUTTER_VIEW_ZONE'; } if (type === MouseTargetType.CONTENT_TEXT) { return 'CONTENT_TEXT'; } if (type === MouseTargetType.CONTENT_EMPTY) { return 'CONTENT_EMPTY'; } if (type === MouseTargetType.CONTENT_VIEW_ZONE) { return 'CONTENT_VIEW_ZONE'; } if (type === MouseTargetType.CONTENT_WIDGET) { return 'CONTENT_WIDGET'; } if (type === MouseTargetType.OVERVIEW_RULER) { return 'OVERVIEW_RULER'; } if (type === MouseTargetType.SCROLLBAR) { return 'SCROLLBAR'; } if (type === MouseTargetType.OVERLAY_WIDGET) { return 'OVERLAY_WIDGET'; } return 'UNKNOWN'; } public static toString(target: IMouseTarget): string { return this._typeToString(target.type) + ': ' + target.position + ' - ' + target.range + ' - ' + target.detail; } public toString(): string { return MouseTarget.toString(this); } } class ElementPath { public static isTextArea(path: Uint8Array): boolean { return ( path.length === 2 && path[0] === PartFingerprint.OverflowGuard && path[1] === PartFingerprint.TextArea ); } public static isChildOfViewLines(path: Uint8Array): boolean { return ( path.length >= 4 && path[0] === PartFingerprint.OverflowGuard && path[3] === PartFingerprint.ViewLines ); } public static isStrictChildOfViewLines(path: Uint8Array): boolean { return ( path.length > 4 && path[0] === PartFingerprint.OverflowGuard && path[3] === PartFingerprint.ViewLines ); } public static isChildOfScrollableElement(path: Uint8Array): boolean { return ( path.length >= 2 && path[0] === PartFingerprint.OverflowGuard && path[1] === PartFingerprint.ScrollableElement ); } public static isChildOfMinimap(path: Uint8Array): boolean { return ( path.length >= 2 && path[0] === PartFingerprint.OverflowGuard && path[1] === PartFingerprint.Minimap ); } public static isChildOfContentWidgets(path: Uint8Array): boolean { return ( path.length >= 4 && path[0] === PartFingerprint.OverflowGuard && path[3] === PartFingerprint.ContentWidgets ); } public static isChildOfOverflowingContentWidgets(path: Uint8Array): boolean { return ( path.length >= 1 && path[0] === PartFingerprint.OverflowingContentWidgets ); } public static isChildOfOverlayWidgets(path: Uint8Array): boolean { return ( path.length >= 2 && path[0] === PartFingerprint.OverflowGuard && path[1] === PartFingerprint.OverlayWidgets ); } } export class HitTestContext { public readonly model: IViewModel; public readonly layoutInfo: EditorLayoutInfo; public readonly viewDomNode: HTMLElement; public readonly lineHeight: number; public readonly typicalHalfwidthCharacterWidth: number; public readonly lastRenderData: PointerHandlerLastRenderData; private readonly _context: ViewContext; private readonly _viewHelper: IPointerHandlerHelper; constructor(context: ViewContext, viewHelper: IPointerHandlerHelper, lastRenderData: PointerHandlerLastRenderData) { this.model = context.model; const options = context.configuration.options; this.layoutInfo = options.get(EditorOption.layoutInfo); this.viewDomNode = viewHelper.viewDomNode; this.lineHeight = options.get(EditorOption.lineHeight); this.typicalHalfwidthCharacterWidth = options.get(EditorOption.fontInfo).typicalHalfwidthCharacterWidth; this.lastRenderData = lastRenderData; this._context = context; this._viewHelper = viewHelper; } public getZoneAtCoord(mouseVerticalOffset: number): IViewZoneData | null { return HitTestContext.getZoneAtCoord(this._context, mouseVerticalOffset); } public static getZoneAtCoord(context: ViewContext, mouseVerticalOffset: number): IViewZoneData | null { // The target is either a view zone or the empty space after the last view-line const viewZoneWhitespace = context.viewLayout.getWhitespaceAtVerticalOffset(mouseVerticalOffset); if (viewZoneWhitespace) { let viewZoneMiddle = viewZoneWhitespace.verticalOffset + viewZoneWhitespace.height / 2, lineCount = context.model.getLineCount(), positionBefore: Position | null = null, position: Position | null, positionAfter: Position | null = null; if (viewZoneWhitespace.afterLineNumber !== lineCount) { // There are more lines after this view zone positionAfter = new Position(viewZoneWhitespace.afterLineNumber + 1, 1); } if (viewZoneWhitespace.afterLineNumber > 0) { // There are more lines above this view zone positionBefore = new Position(viewZoneWhitespace.afterLineNumber, context.model.getLineMaxColumn(viewZoneWhitespace.afterLineNumber)); } if (positionAfter === null) { position = positionBefore; } else if (positionBefore === null) { position = positionAfter; } else if (mouseVerticalOffset < viewZoneMiddle) { position = positionBefore; } else { position = positionAfter; } return { viewZoneId: viewZoneWhitespace.id, afterLineNumber: viewZoneWhitespace.afterLineNumber, positionBefore: positionBefore, positionAfter: positionAfter, position: position! }; } return null; } public getFullLineRangeAtCoord(mouseVerticalOffset: number): { range: EditorRange; isAfterLines: boolean; } { if (this._context.viewLayout.isAfterLines(mouseVerticalOffset)) { // Below the last line const lineNumber = this._context.model.getLineCount(); const maxLineColumn = this._context.model.getLineMaxColumn(lineNumber); return { range: new EditorRange(lineNumber, maxLineColumn, lineNumber, maxLineColumn), isAfterLines: true }; } const lineNumber = this._context.viewLayout.getLineNumberAtVerticalOffset(mouseVerticalOffset); const maxLineColumn = this._context.model.getLineMaxColumn(lineNumber); return { range: new EditorRange(lineNumber, 1, lineNumber, maxLineColumn), isAfterLines: false }; } public getLineNumberAtVerticalOffset(mouseVerticalOffset: number): number { return this._context.viewLayout.getLineNumberAtVerticalOffset(mouseVerticalOffset); } public isAfterLines(mouseVerticalOffset: number): boolean { return this._context.viewLayout.isAfterLines(mouseVerticalOffset); } public getVerticalOffsetForLineNumber(lineNumber: number): number { return this._context.viewLayout.getVerticalOffsetForLineNumber(lineNumber); } public findAttribute(element: Element, attr: string): string | null { return HitTestContext._findAttribute(element, attr, this._viewHelper.viewDomNode); } private static _findAttribute(element: Element, attr: string, stopAt: Element): string | null { while (element && element !== document.body) { if (element.hasAttribute && element.hasAttribute(attr)) { return element.getAttribute(attr); } if (element === stopAt) { return null; } element = <Element>element.parentNode; } return null; } public getLineWidth(lineNumber: number): number { return this._viewHelper.getLineWidth(lineNumber); } public visibleRangeForPosition(lineNumber: number, column: number): HorizontalPosition | null { return this._viewHelper.visibleRangeForPosition(lineNumber, column); } public getPositionFromDOMInfo(spanNode: HTMLElement, offset: number): Position | null { return this._viewHelper.getPositionFromDOMInfo(spanNode, offset); } public getCurrentScrollTop(): number { return this._context.viewLayout.getCurrentScrollTop(); } public getCurrentScrollLeft(): number { return this._context.viewLayout.getCurrentScrollLeft(); } } abstract class BareHitTestRequest { public readonly editorPos: EditorPagePosition; public readonly pos: PageCoordinates; public readonly mouseVerticalOffset: number; public readonly isInMarginArea: boolean; public readonly isInContentArea: boolean; public readonly mouseContentHorizontalOffset: number; protected readonly mouseColumn: number; constructor(ctx: HitTestContext, editorPos: EditorPagePosition, pos: PageCoordinates) { this.editorPos = editorPos; this.pos = pos; this.mouseVerticalOffset = Math.max(0, ctx.getCurrentScrollTop() + pos.y - editorPos.y); this.mouseContentHorizontalOffset = ctx.getCurrentScrollLeft() + pos.x - editorPos.x - ctx.layoutInfo.contentLeft; this.isInMarginArea = (pos.x - editorPos.x < ctx.layoutInfo.contentLeft && pos.x - editorPos.x >= ctx.layoutInfo.glyphMarginLeft); this.isInContentArea = !this.isInMarginArea; this.mouseColumn = Math.max(0, MouseTargetFactory._getMouseColumn(this.mouseContentHorizontalOffset, ctx.typicalHalfwidthCharacterWidth)); } } class HitTestRequest extends BareHitTestRequest { private readonly _ctx: HitTestContext; public readonly target: Element | null; public readonly targetPath: Uint8Array; constructor(ctx: HitTestContext, editorPos: EditorPagePosition, pos: PageCoordinates, target: Element | null) { super(ctx, editorPos, pos); this._ctx = ctx; if (target) { this.target = target; this.targetPath = PartFingerprints.collect(target, ctx.viewDomNode); } else { this.target = null; this.targetPath = new Uint8Array(0); } } public toString(): string { return `pos(${this.pos.x},${this.pos.y}), editorPos(${this.editorPos.x},${this.editorPos.y}), mouseVerticalOffset: ${this.mouseVerticalOffset}, mouseContentHorizontalOffset: ${this.mouseContentHorizontalOffset}\n\ttarget: ${this.target ? (<HTMLElement>this.target).outerHTML : null}`; } public fulfill(type: MouseTargetType, position: Position | null = null, range: EditorRange | null = null, detail: any = null): MouseTarget { let mouseColumn = this.mouseColumn; if (position && position.column < this._ctx.model.getLineMaxColumn(position.lineNumber)) { // Most likely, the line contains foreign decorations... mouseColumn = CursorColumns.visibleColumnFromColumn(this._ctx.model.getLineContent(position.lineNumber), position.column, this._ctx.model.getTextModelOptions().tabSize) + 1; } return new MouseTarget(this.target, type, mouseColumn, position, range, detail); } public withTarget(target: Element | null): HitTestRequest { return new HitTestRequest(this._ctx, this.editorPos, this.pos, target); } } interface ResolvedHitTestRequest extends HitTestRequest { readonly target: Element; } const EMPTY_CONTENT_AFTER_LINES: IEmptyContentData = { isAfterLines: true }; function createEmptyContentDataInLines(horizontalDistanceToText: number): IEmptyContentData { return { isAfterLines: false, horizontalDistanceToText: horizontalDistanceToText }; } export class MouseTargetFactory { private readonly _context: ViewContext; private readonly _viewHelper: IPointerHandlerHelper; constructor(context: ViewContext, viewHelper: IPointerHandlerHelper) { this._context = context; this._viewHelper = viewHelper; } public mouseTargetIsWidget(e: EditorMouseEvent): boolean { const t = <Element>e.target; const path = PartFingerprints.collect(t, this._viewHelper.viewDomNode); // Is it a content widget? if (ElementPath.isChildOfContentWidgets(path) || ElementPath.isChildOfOverflowingContentWidgets(path)) { return true; } // Is it an overlay widget? if (ElementPath.isChildOfOverlayWidgets(path)) { return true; } return false; } public createMouseTarget(lastRenderData: PointerHandlerLastRenderData, editorPos: EditorPagePosition, pos: PageCoordinates, target: HTMLElement | null): IMouseTarget { const ctx = new HitTestContext(this._context, this._viewHelper, lastRenderData); const request = new HitTestRequest(ctx, editorPos, pos, target); try { const r = MouseTargetFactory._createMouseTarget(ctx, request, false); // console.log(r.toString()); return r; } catch (err) { // console.log(err); return request.fulfill(MouseTargetType.UNKNOWN); } } private static _createMouseTarget(ctx: HitTestContext, request: HitTestRequest, domHitTestExecuted: boolean): MouseTarget { // console.log(`${domHitTestExecuted ? '=>' : ''}CAME IN REQUEST: ${request}`); // First ensure the request has a target if (request.target === null) { if (domHitTestExecuted) { // Still no target... and we have already executed hit test... return request.fulfill(MouseTargetType.UNKNOWN); } const hitTestResult = MouseTargetFactory._doHitTest(ctx, request); if (hitTestResult.position) { return MouseTargetFactory.createMouseTargetFromHitTestPosition(ctx, request, hitTestResult.position.lineNumber, hitTestResult.position.column); } return this._createMouseTarget(ctx, request.withTarget(hitTestResult.hitTarget), true); } // we know for a fact that request.target is not null const resolvedRequest = <ResolvedHitTestRequest>request; let result: MouseTarget | null = null; result = result || MouseTargetFactory._hitTestContentWidget(ctx, resolvedRequest); result = result || MouseTargetFactory._hitTestOverlayWidget(ctx, resolvedRequest); result = result || MouseTargetFactory._hitTestMinimap(ctx, resolvedRequest); result = result || MouseTargetFactory._hitTestScrollbarSlider(ctx, resolvedRequest); result = result || MouseTargetFactory._hitTestViewZone(ctx, resolvedRequest); result = result || MouseTargetFactory._hitTestMargin(ctx, resolvedRequest); result = result || MouseTargetFactory._hitTestViewCursor(ctx, resolvedRequest); result = result || MouseTargetFactory._hitTestTextArea(ctx, resolvedRequest); result = result || MouseTargetFactory._hitTestViewLines(ctx, resolvedRequest, domHitTestExecuted); result = result || MouseTargetFactory._hitTestScrollbar(ctx, resolvedRequest); return (result || request.fulfill(MouseTargetType.UNKNOWN)); } private static _hitTestContentWidget(ctx: HitTestContext, request: ResolvedHitTestRequest): MouseTarget | null { // Is it a content widget? if (ElementPath.isChildOfContentWidgets(request.targetPath) || ElementPath.isChildOfOverflowingContentWidgets(request.targetPath)) { const widgetId = ctx.findAttribute(request.target, 'widgetId'); if (widgetId) { return request.fulfill(MouseTargetType.CONTENT_WIDGET, null, null, widgetId); } else { return request.fulfill(MouseTargetType.UNKNOWN); } } return null; } private static _hitTestOverlayWidget(ctx: HitTestContext, request: ResolvedHitTestRequest): MouseTarget | null { // Is it an overlay widget? if (ElementPath.isChildOfOverlayWidgets(request.targetPath)) { const widgetId = ctx.findAttribute(request.target, 'widgetId'); if (widgetId) { return request.fulfill(MouseTargetType.OVERLAY_WIDGET, null, null, widgetId); } else { return request.fulfill(MouseTargetType.UNKNOWN); } } return null; } private static _hitTestViewCursor(ctx: HitTestContext, request: ResolvedHitTestRequest): MouseTarget | null { if (request.target) { // Check if we've hit a painted cursor const lastViewCursorsRenderData = ctx.lastRenderData.lastViewCursorsRenderData; for (const d of lastViewCursorsRenderData) { if (request.target === d.domNode) { return request.fulfill(MouseTargetType.CONTENT_TEXT, d.position); } } } if (request.isInContentArea) { // Edge has a bug when hit-testing the exact position of a cursor, // instead of returning the correct dom node, it returns the // first or last rendered view line dom node, therefore help it out // and first check if we are on top of a cursor const lastViewCursorsRenderData = ctx.lastRenderData.lastViewCursorsRenderData; const mouseContentHorizontalOffset = request.mouseContentHorizontalOffset; const mouseVerticalOffset = request.mouseVerticalOffset; for (const d of lastViewCursorsRenderData) { if (mouseContentHorizontalOffset < d.contentLeft) { // mouse position is to the left of the cursor continue; } if (mouseContentHorizontalOffset > d.contentLeft + d.width) { // mouse position is to the right of the cursor continue; } const cursorVerticalOffset = ctx.getVerticalOffsetForLineNumber(d.position.lineNumber); if ( cursorVerticalOffset <= mouseVerticalOffset && mouseVerticalOffset <= cursorVerticalOffset + d.height ) { return request.fulfill(MouseTargetType.CONTENT_TEXT, d.position); } } } return null; } private static _hitTestViewZone(ctx: HitTestContext, request: ResolvedHitTestRequest): MouseTarget | null { const viewZoneData = ctx.getZoneAtCoord(request.mouseVerticalOffset); if (viewZoneData) { const mouseTargetType = (request.isInContentArea ? MouseTargetType.CONTENT_VIEW_ZONE : MouseTargetType.GUTTER_VIEW_ZONE); return request.fulfill(mouseTargetType, viewZoneData.position, null, viewZoneData); } return null; } private static _hitTestTextArea(ctx: HitTestContext, request: ResolvedHitTestRequest): MouseTarget | null { // Is it the textarea? if (ElementPath.isTextArea(request.targetPath)) { if (ctx.lastRenderData.lastTextareaPosition) { return request.fulfill(MouseTargetType.CONTENT_TEXT, ctx.lastRenderData.lastTextareaPosition); } return request.fulfill(MouseTargetType.TEXTAREA, ctx.lastRenderData.lastTextareaPosition); } return null; } private static _hitTestMargin(ctx: HitTestContext, request: ResolvedHitTestRequest): MouseTarget | null { if (request.isInMarginArea) { const res = ctx.getFullLineRangeAtCoord(request.mouseVerticalOffset); const pos = res.range.getStartPosition(); let offset = Math.abs(request.pos.x - request.editorPos.x); const detail: IMarginData = { isAfterLines: res.isAfterLines, glyphMarginLeft: ctx.layoutInfo.glyphMarginLeft, glyphMarginWidth: ctx.layoutInfo.glyphMarginWidth, lineNumbersWidth: ctx.layoutInfo.lineNumbersWidth, offsetX: offset }; offset -= ctx.layoutInfo.glyphMarginLeft; if (offset <= ctx.layoutInfo.glyphMarginWidth) { // On the glyph margin return request.fulfill(MouseTargetType.GUTTER_GLYPH_MARGIN, pos, res.range, detail); } offset -= ctx.layoutInfo.glyphMarginWidth; if (offset <= ctx.layoutInfo.lineNumbersWidth) { // On the line numbers return request.fulfill(MouseTargetType.GUTTER_LINE_NUMBERS, pos, res.range, detail); } offset -= ctx.layoutInfo.lineNumbersWidth; // On the line decorations return request.fulfill(MouseTargetType.GUTTER_LINE_DECORATIONS, pos, res.range, detail); } return null; } private static _hitTestViewLines(ctx: HitTestContext, request: ResolvedHitTestRequest, domHitTestExecuted: boolean): MouseTarget | null { if (!ElementPath.isChildOfViewLines(request.targetPath)) { return null; } // Check if it is below any lines and any view zones if (ctx.isAfterLines(request.mouseVerticalOffset)) { // This most likely indicates it happened after the last view-line const lineCount = ctx.model.getLineCount(); const maxLineColumn = ctx.model.getLineMaxColumn(lineCount); return request.fulfill(MouseTargetType.CONTENT_EMPTY, new Position(lineCount, maxLineColumn), undefined, EMPTY_CONTENT_AFTER_LINES); } if (domHitTestExecuted) { // Check if we are hitting a view-line (can happen in the case of inline decorations on empty lines) // See https://github.com/Microsoft/vscode/issues/46942 if (ElementPath.isStrictChildOfViewLines(request.targetPath)) { const lineNumber = ctx.getLineNumberAtVerticalOffset(request.mouseVerticalOffset); if (ctx.model.getLineLength(lineNumber) === 0) { const lineWidth = ctx.getLineWidth(lineNumber); const detail = createEmptyContentDataInLines(request.mouseContentHorizontalOffset - lineWidth); return request.fulfill(MouseTargetType.CONTENT_EMPTY, new Position(lineNumber, 1), undefined, detail); } const lineWidth = ctx.getLineWidth(lineNumber); if (request.mouseContentHorizontalOffset >= lineWidth) { const detail = createEmptyContentDataInLines(request.mouseContentHorizontalOffset - lineWidth); const pos = new Position(lineNumber, ctx.model.getLineMaxColumn(lineNumber)); return request.fulfill(MouseTargetType.CONTENT_EMPTY, pos, undefined, detail); } } // We have already executed hit test... return request.fulfill(MouseTargetType.UNKNOWN); } const hitTestResult = MouseTargetFactory._doHitTest(ctx, request); if (hitTestResult.position) { return MouseTargetFactory.createMouseTargetFromHitTestPosition(ctx, request, hitTestResult.position.lineNumber, hitTestResult.position.column); } return this._createMouseTarget(ctx, request.withTarget(hitTestResult.hitTarget), true); } private static _hitTestMinimap(ctx: HitTestContext, request: ResolvedHitTestRequest): MouseTarget | null { if (ElementPath.isChildOfMinimap(request.targetPath)) { const possibleLineNumber = ctx.getLineNumberAtVerticalOffset(request.mouseVerticalOffset); const maxColumn = ctx.model.getLineMaxColumn(possibleLineNumber); return request.fulfill(MouseTargetType.SCROLLBAR, new Position(possibleLineNumber, maxColumn)); } return null; } private static _hitTestScrollbarSlider(ctx: HitTestContext, request: ResolvedHitTestRequest): MouseTarget | null { if (ElementPath.isChildOfScrollableElement(request.targetPath)) { if (request.target && request.target.nodeType === 1) { const className = request.target.className; if (className && /\b(slider|scrollbar)\b/.test(className)) { const possibleLineNumber = ctx.getLineNumberAtVerticalOffset(request.mouseVerticalOffset); const maxColumn = ctx.model.getLineMaxColumn(possibleLineNumber); return request.fulfill(MouseTargetType.SCROLLBAR, new Position(possibleLineNumber, maxColumn)); } } } return null; } private static _hitTestScrollbar(ctx: HitTestContext, request: ResolvedHitTestRequest): MouseTarget | null { // Is it the overview ruler? // Is it a child of the scrollable element? if (ElementPath.isChildOfScrollableElement(request.targetPath)) { const possibleLineNumber = ctx.getLineNumberAtVerticalOffset(request.mouseVerticalOffset); const maxColumn = ctx.model.getLineMaxColumn(possibleLineNumber); return request.fulfill(MouseTargetType.SCROLLBAR, new Position(possibleLineNumber, maxColumn)); } return null; } public getMouseColumn(editorPos: EditorPagePosition, pos: PageCoordinates): number { const options = this._context.configuration.options; const layoutInfo = options.get(EditorOption.layoutInfo); const mouseContentHorizontalOffset = this._context.viewLayout.getCurrentScrollLeft() + pos.x - editorPos.x - layoutInfo.contentLeft; return MouseTargetFactory._getMouseColumn(mouseContentHorizontalOffset, options.get(EditorOption.fontInfo).typicalHalfwidthCharacterWidth); } public static _getMouseColumn(mouseContentHorizontalOffset: number, typicalHalfwidthCharacterWidth: number): number { if (mouseContentHorizontalOffset < 0) { return 1; } const chars = Math.round(mouseContentHorizontalOffset / typicalHalfwidthCharacterWidth); return (chars + 1); } private static createMouseTargetFromHitTestPosition(ctx: HitTestContext, request: HitTestRequest, lineNumber: number, column: number): MouseTarget { const pos = new Position(lineNumber, column); const lineWidth = ctx.getLineWidth(lineNumber); if (request.mouseContentHorizontalOffset > lineWidth) { if (browser.isEdge && pos.column === 1) { // See https://github.com/Microsoft/vscode/issues/10875 const detail = createEmptyContentDataInLines(request.mouseContentHorizontalOffset - lineWidth); return request.fulfill(MouseTargetType.CONTENT_EMPTY, new Position(lineNumber, ctx.model.getLineMaxColumn(lineNumber)), undefined, detail); } const detail = createEmptyContentDataInLines(request.mouseContentHorizontalOffset - lineWidth); return request.fulfill(MouseTargetType.CONTENT_EMPTY, pos, undefined, detail); } const visibleRange = ctx.visibleRangeForPosition(lineNumber, column); if (!visibleRange) { return request.fulfill(MouseTargetType.UNKNOWN, pos); } const columnHorizontalOffset = visibleRange.left; if (request.mouseContentHorizontalOffset === columnHorizontalOffset) { return request.fulfill(MouseTargetType.CONTENT_TEXT, pos); } // Let's define a, b, c and check if the offset is in between them... interface OffsetColumn { offset: number; column: number; } const points: OffsetColumn[] = []; points.push({ offset: visibleRange.left, column: column }); if (column > 1) { const visibleRange = ctx.visibleRangeForPosition(lineNumber, column - 1); if (visibleRange) { points.push({ offset: visibleRange.left, column: column - 1 }); } } const lineMaxColumn = ctx.model.getLineMaxColumn(lineNumber); if (column < lineMaxColumn) { const visibleRange = ctx.visibleRangeForPosition(lineNumber, column + 1); if (visibleRange) { points.push({ offset: visibleRange.left, column: column + 1 }); } } points.sort((a, b) => a.offset - b.offset); for (let i = 1; i < points.length; i++) { const prev = points[i - 1]; const curr = points[i]; if (prev.offset <= request.mouseContentHorizontalOffset && request.mouseContentHorizontalOffset <= curr.offset) { const rng = new EditorRange(lineNumber, prev.column, lineNumber, curr.column); return request.fulfill(MouseTargetType.CONTENT_TEXT, pos, rng); } } return request.fulfill(MouseTargetType.CONTENT_TEXT, pos); } /** * Most probably WebKit browsers and Edge */ private static _doHitTestWithCaretRangeFromPoint(ctx: HitTestContext, request: BareHitTestRequest): IHitTestResult { // In Chrome, especially on Linux it is possible to click between lines, // so try to adjust the `hity` below so that it lands in the center of a line const lineNumber = ctx.getLineNumberAtVerticalOffset(request.mouseVerticalOffset); const lineVerticalOffset = ctx.getVerticalOffsetForLineNumber(lineNumber); const lineCenteredVerticalOffset = lineVerticalOffset + Math.floor(ctx.lineHeight / 2); let adjustedPageY = request.pos.y + (lineCenteredVerticalOffset - request.mouseVerticalOffset); if (adjustedPageY <= request.editorPos.y) { adjustedPageY = request.editorPos.y + 1; } if (adjustedPageY >= request.editorPos.y + ctx.layoutInfo.height) { adjustedPageY = request.editorPos.y + ctx.layoutInfo.height - 1; } const adjustedPage = new PageCoordinates(request.pos.x, adjustedPageY); const r = this._actualDoHitTestWithCaretRangeFromPoint(ctx, adjustedPage.toClientCoordinates()); if (r.position) { return r; } // Also try to hit test without the adjustment (for the edge cases that we are near the top or bottom) return this._actualDoHitTestWithCaretRangeFromPoint(ctx, request.pos.toClientCoordinates()); } private static _actualDoHitTestWithCaretRangeFromPoint(ctx: HitTestContext, coords: ClientCoordinates): IHitTestResult { const shadowRoot = dom.getShadowRoot(ctx.viewDomNode); let range: Range; if (shadowRoot) { if (typeof shadowRoot.caretRangeFromPoint === 'undefined') { range = shadowCaretRangeFromPoint(shadowRoot, coords.clientX, coords.clientY); } else { range = shadowRoot.caretRangeFromPoint(coords.clientX, coords.clientY); } } else { range = document.caretRangeFromPoint(coords.clientX, coords.clientY); } if (!range || !range.startContainer) { return { position: null, hitTarget: null }; } // Chrome always hits a TEXT_NODE, while Edge sometimes hits a token span const startContainer = range.startContainer; let hitTarget: HTMLElement | null = null; if (startContainer.nodeType === startContainer.TEXT_NODE) { // startContainer is expected to be the token text const parent1 = startContainer.parentNode; // expected to be the token span const parent2 = parent1 ? parent1.parentNode : null; // expected to be the view line container span const parent3 = parent2 ? parent2.parentNode : null; // expected to be the view line div const parent3ClassName = parent3 && parent3.nodeType === parent3.ELEMENT_NODE ? (<HTMLElement>parent3).className : null; if (parent3ClassName === ViewLine.CLASS_NAME) { const p = ctx.getPositionFromDOMInfo(<HTMLElement>parent1, range.startOffset); return { position: p, hitTarget: null }; } else { hitTarget = <HTMLElement>startContainer.parentNode; } } else if (startContainer.nodeType === startContainer.ELEMENT_NODE) { // startContainer is expected to be the token span const parent1 = startContainer.parentNode; // expected to be the view line container span const parent2 = parent1 ? parent1.parentNode : null; // expected to be the view line div const parent2ClassName = parent2 && parent2.nodeType === parent2.ELEMENT_NODE ? (<HTMLElement>parent2).className : null; if (parent2ClassName === ViewLine.CLASS_NAME) { const p = ctx.getPositionFromDOMInfo(<HTMLElement>startContainer, (<HTMLElement>startContainer).textContent!.length); return { position: p, hitTarget: null }; } else { hitTarget = <HTMLElement>startContainer; } } return { position: null, hitTarget: hitTarget }; } /** * Most probably Gecko */ private static _doHitTestWithCaretPositionFromPoint(ctx: HitTestContext, coords: ClientCoordinates): IHitTestResult { const hitResult: { offsetNode: Node; offset: number; } = (<any>document).caretPositionFromPoint(coords.clientX, coords.clientY); if (hitResult.offsetNode.nodeType === hitResult.offsetNode.TEXT_NODE) { // offsetNode is expected to be the token text const parent1 = hitResult.offsetNode.parentNode; // expected to be the token span const parent2 = parent1 ? parent1.parentNode : null; // expected to be the view line container span const parent3 = parent2 ? parent2.parentNode : null; // expected to be the view line div const parent3ClassName = parent3 && parent3.nodeType === parent3.ELEMENT_NODE ? (<HTMLElement>parent3).className : null; if (parent3ClassName === ViewLine.CLASS_NAME) { const p = ctx.getPositionFromDOMInfo(<HTMLElement>hitResult.offsetNode.parentNode, hitResult.offset); return { position: p, hitTarget: null }; } else { return { position: null, hitTarget: <HTMLElement>hitResult.offsetNode.parentNode }; } } // For inline decorations, Gecko returns the `<span>` of the line and the offset is the `<span>` with the inline decoration if (hitResult.offsetNode.nodeType === hitResult.offsetNode.ELEMENT_NODE) { const parent1 = hitResult.offsetNode.parentNode; // expected to be the view line div const parent1ClassName = parent1 && parent1.nodeType === parent1.ELEMENT_NODE ? (<HTMLElement>parent1).className : null; if (parent1ClassName === ViewLine.CLASS_NAME) { const tokenSpan = hitResult.offsetNode.childNodes[Math.min(hitResult.offset, hitResult.offsetNode.childNodes.length - 1)]; if (tokenSpan) { const p = ctx.getPositionFromDOMInfo(<HTMLElement>tokenSpan, 0); return { position: p, hitTarget: null }; } } } return { position: null, hitTarget: <HTMLElement>hitResult.offsetNode }; } /** * Most probably IE */ private static _doHitTestWithMoveToPoint(ctx: HitTestContext, coords: ClientCoordinates): IHitTestResult { let resultPosition: Position | null = null; let resultHitTarget: Element | null = null; const textRange: IETextRange = (<any>document.body).createTextRange(); try { textRange.moveToPoint(coords.clientX, coords.clientY); } catch (err) { return { position: null, hitTarget: null }; } textRange.collapse(true); // Now, let's do our best to figure out what we hit :) const parentElement = textRange ? textRange.parentElement() : null; const parent1 = parentElement ? parentElement.parentNode : null; const parent2 = parent1 ? parent1.parentNode : null; const parent2ClassName = parent2 && parent2.nodeType === parent2.ELEMENT_NODE ? (<HTMLElement>parent2).className : ''; if (parent2ClassName === ViewLine.CLASS_NAME) { const rangeToContainEntireSpan = textRange.duplicate(); rangeToContainEntireSpan.moveToElementText(parentElement!); rangeToContainEntireSpan.setEndPoint('EndToStart', textRange); resultPosition = ctx.getPositionFromDOMInfo(<HTMLElement>parentElement, rangeToContainEntireSpan.text.length); // Move range out of the span node, IE doesn't like having many ranges in // the same spot and will act badly for lines containing dashes ('-') rangeToContainEntireSpan.moveToElementText(ctx.viewDomNode); } else { // Looks like we've hit the hover or something foreign resultHitTarget = parentElement; } // Move range out of the span node, IE doesn't like having many ranges in // the same spot and will act badly for lines containing dashes ('-') textRange.moveToElementText(ctx.viewDomNode); return { position: resultPosition, hitTarget: resultHitTarget }; } private static _doHitTest(ctx: HitTestContext, request: BareHitTestRequest): IHitTestResult { // State of the art (18.10.2012): // The spec says browsers should support document.caretPositionFromPoint, but nobody implemented it (http://dev.w3.org/csswg/cssom-view/) // Gecko: // - they tried to implement it once, but failed: https://bugzilla.mozilla.org/show_bug.cgi?id=654352 // - however, they do give out rangeParent/rangeOffset properties on mouse events // Webkit: // - they have implemented a previous version of the spec which was using document.caretRangeFromPoint // IE: // - they have a proprietary method on ranges, moveToPoint: https://msdn.microsoft.com/en-us/library/ie/ms536632(v=vs.85).aspx // 24.08.2016: Edge has added WebKit's document.caretRangeFromPoint, but it is quite buggy // - when hit testing the cursor it returns the first or the last line in the viewport // - it inconsistently hits text nodes or span nodes, while WebKit only hits text nodes // - when toggling render whitespace on, and hit testing in the empty content after a line, it always hits offset 0 of the first span of the line // Thank you browsers for making this so 'easy' :) if (typeof document.caretRangeFromPoint === 'function') { return this._doHitTestWithCaretRangeFromPoint(ctx, request); } else if ((<any>document).caretPositionFromPoint) { return this._doHitTestWithCaretPositionFromPoint(ctx, request.pos.toClientCoordinates()); } else if ((<any>document.body).createTextRange) { return this._doHitTestWithMoveToPoint(ctx, request.pos.toClientCoordinates()); } return { position: null, hitTarget: null }; } } export function shadowCaretRangeFromPoint(shadowRoot: ShadowRoot, x: number, y: number): Range { const range = document.createRange(); // Get the element under the point let el: Element | null = shadowRoot.elementFromPoint(x, y); if (el !== null) { // Get the last child of the element until its firstChild is a text node // This assumes that the pointer is on the right of the line, out of the tokens // and that we want to get the offset of the last token of the line while (el && el.firstChild && el.firstChild.nodeType !== el.firstChild.TEXT_NODE) { el = <Element>el.lastChild; } // Grab its rect const rect = el.getBoundingClientRect(); // And its font const font = window.getComputedStyle(el, null).getPropertyValue('font'); // And also its txt content const text = (el as any).innerText; // Position the pixel cursor at the left of the element let pixelCursor = rect.left; let offset = 0; let step: number; // If the point is on the right of the box put the cursor after the last character if (x > rect.left + rect.width) { offset = text.length; } else { const charWidthReader = CharWidthReader.getInstance(); // Goes through all the characters of the innerText, and checks if the x of the point // belongs to the character. for (let i = 0; i < text.length + 1; i++) { // The step is half the width of the character step = charWidthReader.getCharWidth(text.charAt(i), font) / 2; // Move to the center of the character pixelCursor += step; // If the x of the point is smaller that the position of the cursor, the point is over that character if (x < pixelCursor) { offset = i; break; } // Move between the current character and the next pixelCursor += step; } } // Creates a range with the text node of the element and set the offset found range.setStart(el.firstChild!, offset); range.setEnd(el.firstChild!, offset); } return range; } class CharWidthReader { private static _INSTANCE: CharWidthReader | null = null; public static getInstance(): CharWidthReader { if (!CharWidthReader._INSTANCE) { CharWidthReader._INSTANCE = new CharWidthReader(); } return CharWidthReader._INSTANCE; } private readonly _cache: { [cacheKey: string]: number; }; private readonly _canvas: HTMLCanvasElement; private constructor() { this._cache = {}; this._canvas = document.createElement('canvas'); } public getCharWidth(char: string, font: string): number { const cacheKey = char + font; if (this._cache[cacheKey]) { return this._cache[cacheKey]; } const context = this._canvas.getContext('2d')!; context.font = font; const metrics = context.measureText(char); const width = metrics.width; this._cache[cacheKey] = width; return width; } }
src/vs/editor/browser/controller/mouseTarget.ts
0
https://github.com/microsoft/vscode/commit/9504dda6a717a0a0d45d992e21f2565f8a23f390
[ 0.0002721769269555807, 0.00017326253873761743, 0.00016279894043691456, 0.0001730207004584372, 0.000010160565580008551 ]
{ "id": 6, "code_window": [ "\t\t}\n", "\n", "\t\tif (viewState?.editorFocused) {\n", "\t\t\tthis._list?.focusView();\n", "\t\t\tconst cell = this._notebookViewModel?.viewCells[focusIdx];\n", "\t\t\tif (cell) {\n", "\t\t\t\tcell.focusMode = CellFocusMode.Editor;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t// this._list?.focusView();\n" ], "file_path": "src/vs/workbench/contrib/notebook/browser/notebookEditorWidget.ts", "type": "replace", "edit_start_line_idx": 684 }
<svg width="14px" height="14px" viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg"> <rect fill="#B9131A" x="0" y="0" width="100" height="100" rx="35" ry="35"/> <text x="50" y="75" font-size="75" text-anchor="middle" style="font-family: Menlo, Monaco, Consolas, &quot;Droid Sans Mono&quot;, &quot;Inconsolata&quot;, &quot;Courier New&quot;, monospace, &quot;Droid Sans Fallback&quot;;" fill="white"> D </text> </svg>
extensions/git/resources/icons/light/status-deleted.svg
0
https://github.com/microsoft/vscode/commit/9504dda6a717a0a0d45d992e21f2565f8a23f390
[ 0.0001721720036584884, 0.0001721720036584884, 0.0001721720036584884, 0.0001721720036584884, 0 ]
{ "id": 6, "code_window": [ "\t\t}\n", "\n", "\t\tif (viewState?.editorFocused) {\n", "\t\t\tthis._list?.focusView();\n", "\t\t\tconst cell = this._notebookViewModel?.viewCells[focusIdx];\n", "\t\t\tif (cell) {\n", "\t\t\t\tcell.focusMode = CellFocusMode.Editor;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t// this._list?.focusView();\n" ], "file_path": "src/vs/workbench/contrib/notebook/browser/notebookEditorWidget.ts", "type": "replace", "edit_start_line_idx": 684 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as assert from 'assert'; import { getNonWhitespacePrefix } from 'vs/workbench/contrib/snippets/browser/snippetsService'; import { Position } from 'vs/editor/common/core/position'; suite('getNonWhitespacePrefix', () => { function assertGetNonWhitespacePrefix(line: string, column: number, expected: string): void { let model = { getLineContent: (lineNumber: number) => line }; let actual = getNonWhitespacePrefix(model, new Position(1, column)); assert.equal(actual, expected); } test('empty line', () => { assertGetNonWhitespacePrefix('', 1, ''); }); test('singleWordLine', () => { assertGetNonWhitespacePrefix('something', 1, ''); assertGetNonWhitespacePrefix('something', 2, 's'); assertGetNonWhitespacePrefix('something', 3, 'so'); assertGetNonWhitespacePrefix('something', 4, 'som'); assertGetNonWhitespacePrefix('something', 5, 'some'); assertGetNonWhitespacePrefix('something', 6, 'somet'); assertGetNonWhitespacePrefix('something', 7, 'someth'); assertGetNonWhitespacePrefix('something', 8, 'somethi'); assertGetNonWhitespacePrefix('something', 9, 'somethin'); assertGetNonWhitespacePrefix('something', 10, 'something'); }); test('two word line', () => { assertGetNonWhitespacePrefix('something interesting', 1, ''); assertGetNonWhitespacePrefix('something interesting', 2, 's'); assertGetNonWhitespacePrefix('something interesting', 3, 'so'); assertGetNonWhitespacePrefix('something interesting', 4, 'som'); assertGetNonWhitespacePrefix('something interesting', 5, 'some'); assertGetNonWhitespacePrefix('something interesting', 6, 'somet'); assertGetNonWhitespacePrefix('something interesting', 7, 'someth'); assertGetNonWhitespacePrefix('something interesting', 8, 'somethi'); assertGetNonWhitespacePrefix('something interesting', 9, 'somethin'); assertGetNonWhitespacePrefix('something interesting', 10, 'something'); assertGetNonWhitespacePrefix('something interesting', 11, ''); assertGetNonWhitespacePrefix('something interesting', 12, 'i'); assertGetNonWhitespacePrefix('something interesting', 13, 'in'); assertGetNonWhitespacePrefix('something interesting', 14, 'int'); assertGetNonWhitespacePrefix('something interesting', 15, 'inte'); assertGetNonWhitespacePrefix('something interesting', 16, 'inter'); assertGetNonWhitespacePrefix('something interesting', 17, 'intere'); assertGetNonWhitespacePrefix('something interesting', 18, 'interes'); assertGetNonWhitespacePrefix('something interesting', 19, 'interest'); assertGetNonWhitespacePrefix('something interesting', 20, 'interesti'); assertGetNonWhitespacePrefix('something interesting', 21, 'interestin'); assertGetNonWhitespacePrefix('something interesting', 22, 'interesting'); }); test('many separators', () => { // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions?redirectlocale=en-US&redirectslug=JavaScript%2FGuide%2FRegular_Expressions#special-white-space // \s matches a single white space character, including space, tab, form feed, line feed. // Equivalent to [ \f\n\r\t\v\u00a0\u1680\u180e\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]. assertGetNonWhitespacePrefix('something interesting', 22, 'interesting'); assertGetNonWhitespacePrefix('something\tinteresting', 22, 'interesting'); assertGetNonWhitespacePrefix('something\finteresting', 22, 'interesting'); assertGetNonWhitespacePrefix('something\vinteresting', 22, 'interesting'); assertGetNonWhitespacePrefix('something\u00a0interesting', 22, 'interesting'); assertGetNonWhitespacePrefix('something\u2000interesting', 22, 'interesting'); assertGetNonWhitespacePrefix('something\u2028interesting', 22, 'interesting'); assertGetNonWhitespacePrefix('something\u3000interesting', 22, 'interesting'); assertGetNonWhitespacePrefix('something\ufeffinteresting', 22, 'interesting'); }); });
src/vs/workbench/contrib/snippets/test/browser/snippetsRegistry.test.ts
0
https://github.com/microsoft/vscode/commit/9504dda6a717a0a0d45d992e21f2565f8a23f390
[ 0.0001754297991283238, 0.00017257145373150706, 0.00016723746375646442, 0.00017351220594719052, 0.0000024179366846510675 ]
{ "id": 7, "code_window": [ "\t\tthis._register({ dispose() { cts.dispose(true); } });\n", "\t\traceCancellation(viewCell.resolveTextModel(), cts.token).then(model => {\n", "\t\t\tif (model && templateData.editor) {\n", "\t\t\t\ttemplateData.editor.setModel(model);\n", "\t\t\t\tviewCell.attachTextEditor(templateData.editor);\n", "\t\t\t\tif (notebookEditor.getActiveCell() === viewCell && viewCell.focusMode === CellFocusMode.Editor) {\n", "\t\t\t\t\ttemplateData.editor?.focus();\n", "\t\t\t\t}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\tif (notebookEditor.getActiveCell() === viewCell && viewCell.focusMode === CellFocusMode.Editor && this.notebookEditor.hasFocus()) {\n" ], "file_path": "src/vs/workbench/contrib/notebook/browser/view/renderers/codeCell.ts", "type": "replace", "edit_start_line_idx": 59 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { INotebookEditor, NOTEBOOK_EDITOR_FOCUSED, NOTEBOOK_IS_ACTIVE_EDITOR, NOTEBOOK_HAS_MULTIPLE_KERNELS } from 'vs/workbench/contrib/notebook/browser/notebookBrowser'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; import { IQuickInputService, QuickPickInput, IQuickPickItem } from 'vs/platform/quickinput/common/quickInput'; import { INotebookService } from 'vs/workbench/contrib/notebook/common/notebookService'; import * as nls from 'vs/nls'; import { registerAction2, Action2, MenuId } from 'vs/platform/actions/common/actions'; import { NOTEBOOK_ACTIONS_CATEGORY, INotebookCellActionContext } from 'vs/workbench/contrib/notebook/browser/contrib/coreActions'; import { ContextKeyExpr } from 'vs/platform/contextkey/common/contextkey'; import { ServicesAccessor } from 'vs/platform/instantiation/common/instantiation'; registerAction2(class extends Action2 { constructor() { super({ id: 'notebook.selectKernel', category: NOTEBOOK_ACTIONS_CATEGORY, title: nls.localize('notebookActions.selectKernel', "Select Notebook Kernel"), precondition: ContextKeyExpr.and(NOTEBOOK_IS_ACTIVE_EDITOR, NOTEBOOK_EDITOR_FOCUSED), icon: { id: 'codicon/server-environment' }, menu: { id: MenuId.EditorTitle, when: ContextKeyExpr.and(NOTEBOOK_IS_ACTIVE_EDITOR, NOTEBOOK_HAS_MULTIPLE_KERNELS), group: 'navigation', order: -2, }, f1: true }); } async run(accessor: ServicesAccessor, context?: INotebookCellActionContext): Promise<void> { const editorService = accessor.get<IEditorService>(IEditorService); const notebookService = accessor.get<INotebookService>(INotebookService); const quickInputService = accessor.get<IQuickInputService>(IQuickInputService); const activeEditorPane = editorService.activeEditorPane as unknown as { isNotebookEditor?: boolean } | undefined; if (!activeEditorPane?.isNotebookEditor) { return; } const editor = editorService.activeEditorPane?.getControl() as INotebookEditor; const activeKernel = editor.activeKernel; const availableKernels = notebookService.getContributedNotebookKernels(editor.viewModel!.viewType, editor.viewModel!.uri); const picks: QuickPickInput<IQuickPickItem & { run(): void; }>[] = availableKernels.map((a) => { return { id: a.id, label: a.label, picked: a.id === activeKernel?.id, description: a.extension.value + (a.id === activeKernel?.id ? nls.localize('currentActiveKernel', " (Currently Active)") : ''), run: () => { editor.activeKernel = a; } }; }); const provider = notebookService.getContributedNotebookProviders(editor.viewModel!.uri)[0]; if (provider.kernel) { picks.unshift({ id: provider.id, label: provider.displayName, picked: !activeKernel, // no active kernel, the builtin kernel of the provider is used description: activeKernel === undefined ? nls.localize('currentActiveBuiltinKernel', " (Currently Active)") : '', run: () => { editor.activeKernel = undefined; } }); } const action = await quickInputService.pick(picks, { placeHolder: nls.localize('pickAction', "Select Action"), matchOnDetail: true }); return action?.run(); } });
src/vs/workbench/contrib/notebook/browser/contrib/status/editorStatus.ts
1
https://github.com/microsoft/vscode/commit/9504dda6a717a0a0d45d992e21f2565f8a23f390
[ 0.0006323821726255119, 0.00024745153496041894, 0.00016431231051683426, 0.0001728740899125114, 0.0001530532172182575 ]
{ "id": 7, "code_window": [ "\t\tthis._register({ dispose() { cts.dispose(true); } });\n", "\t\traceCancellation(viewCell.resolveTextModel(), cts.token).then(model => {\n", "\t\t\tif (model && templateData.editor) {\n", "\t\t\t\ttemplateData.editor.setModel(model);\n", "\t\t\t\tviewCell.attachTextEditor(templateData.editor);\n", "\t\t\t\tif (notebookEditor.getActiveCell() === viewCell && viewCell.focusMode === CellFocusMode.Editor) {\n", "\t\t\t\t\ttemplateData.editor?.focus();\n", "\t\t\t\t}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\tif (notebookEditor.getActiveCell() === viewCell && viewCell.focusMode === CellFocusMode.Editor && this.notebookEditor.hasFocus()) {\n" ], "file_path": "src/vs/workbench/contrib/notebook/browser/view/renderers/codeCell.ts", "type": "replace", "edit_start_line_idx": 59 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as nls from 'vs/nls'; import { URI } from 'vs/base/common/uri'; import * as resources from 'vs/base/common/resources'; import * as json from 'vs/base/common/json'; import * as strings from 'vs/base/common/strings'; import { setProperty } from 'vs/base/common/jsonEdit'; import { Queue } from 'vs/base/common/async'; import { Edit } from 'vs/base/common/jsonFormatter'; import { IReference } from 'vs/base/common/lifecycle'; import { EditOperation } from 'vs/editor/common/core/editOperation'; import { Registry } from 'vs/platform/registry/common/platform'; import { Range } from 'vs/editor/common/core/range'; import { Selection } from 'vs/editor/common/core/selection'; import { IWorkspaceContextService, WorkbenchState } from 'vs/platform/workspace/common/workspace'; import { IEnvironmentService } from 'vs/platform/environment/common/environment'; import { ITextFileService } from 'vs/workbench/services/textfile/common/textfiles'; import { IConfigurationService, IConfigurationOverrides, keyFromOverrideIdentifier } from 'vs/platform/configuration/common/configuration'; import { FOLDER_SETTINGS_PATH, WORKSPACE_STANDALONE_CONFIGURATIONS, TASKS_CONFIGURATION_KEY, LAUNCH_CONFIGURATION_KEY, USER_STANDALONE_CONFIGURATIONS, TASKS_DEFAULT } from 'vs/workbench/services/configuration/common/configuration'; import { IFileService, FileOperationError, FileOperationResult } from 'vs/platform/files/common/files'; import { ITextModelService, IResolvedTextEditorModel } from 'vs/editor/common/services/resolverService'; import { OVERRIDE_PROPERTY_PATTERN, IConfigurationRegistry, Extensions as ConfigurationExtensions, ConfigurationScope } from 'vs/platform/configuration/common/configurationRegistry'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; import { ITextModel } from 'vs/editor/common/model'; import { INotificationService, Severity } from 'vs/platform/notification/common/notification'; import { IPreferencesService } from 'vs/workbench/services/preferences/common/preferences'; import { withUndefinedAsNull, withNullAsUndefined } from 'vs/base/common/types'; import { IRemoteAgentService } from 'vs/workbench/services/remote/common/remoteAgentService'; export const enum ConfigurationEditingErrorCode { /** * Error when trying to write a configuration key that is not registered. */ ERROR_UNKNOWN_KEY, /** * Error when trying to write an application setting into workspace settings. */ ERROR_INVALID_WORKSPACE_CONFIGURATION_APPLICATION, /** * Error when trying to write a machne setting into workspace settings. */ ERROR_INVALID_WORKSPACE_CONFIGURATION_MACHINE, /** * Error when trying to write an invalid folder configuration key to folder settings. */ ERROR_INVALID_FOLDER_CONFIGURATION, /** * Error when trying to write to user target but not supported for provided key. */ ERROR_INVALID_USER_TARGET, /** * Error when trying to write to user target but not supported for provided key. */ ERROR_INVALID_WORKSPACE_TARGET, /** * Error when trying to write a configuration key to folder target */ ERROR_INVALID_FOLDER_TARGET, /** * Error when trying to write to language specific setting but not supported for preovided key */ ERROR_INVALID_RESOURCE_LANGUAGE_CONFIGURATION, /** * Error when trying to write to the workspace configuration without having a workspace opened. */ ERROR_NO_WORKSPACE_OPENED, /** * Error when trying to write and save to the configuration file while it is dirty in the editor. */ ERROR_CONFIGURATION_FILE_DIRTY, /** * Error when trying to write and save to the configuration file while it is not the latest in the disk. */ ERROR_CONFIGURATION_FILE_MODIFIED_SINCE, /** * Error when trying to write to a configuration file that contains JSON errors. */ ERROR_INVALID_CONFIGURATION } export class ConfigurationEditingError extends Error { constructor(message: string, public code: ConfigurationEditingErrorCode) { super(message); } } export interface IConfigurationValue { key: string; value: any; } export interface IConfigurationEditingOptions { /** * If `true`, do not saves the configuration. Default is `false`. */ donotSave?: boolean; /** * If `true`, do not notifies the error to user by showing the message box. Default is `false`. */ donotNotifyError?: boolean; /** * Scope of configuration to be written into. */ scopes?: IConfigurationOverrides; } export const enum EditableConfigurationTarget { USER_LOCAL = 1, USER_REMOTE, WORKSPACE, WORKSPACE_FOLDER } interface IConfigurationEditOperation extends IConfigurationValue { target: EditableConfigurationTarget; jsonPath: json.JSONPath; resource?: URI; workspaceStandAloneConfigurationKey?: string; } interface ConfigurationEditingOptions extends IConfigurationEditingOptions { force?: boolean; } export class ConfigurationEditingService { public _serviceBrand: undefined; private queue: Queue<void>; private remoteSettingsResource: URI | null = null; constructor( @IConfigurationService private readonly configurationService: IConfigurationService, @IWorkspaceContextService private readonly contextService: IWorkspaceContextService, @IEnvironmentService private readonly environmentService: IEnvironmentService, @IFileService private readonly fileService: IFileService, @ITextModelService private readonly textModelResolverService: ITextModelService, @ITextFileService private readonly textFileService: ITextFileService, @INotificationService private readonly notificationService: INotificationService, @IPreferencesService private readonly preferencesService: IPreferencesService, @IEditorService private readonly editorService: IEditorService, @IRemoteAgentService remoteAgentService: IRemoteAgentService ) { this.queue = new Queue<void>(); remoteAgentService.getEnvironment().then(environment => { if (environment) { this.remoteSettingsResource = environment.settingsPath; } }); } writeConfiguration(target: EditableConfigurationTarget, value: IConfigurationValue, options: IConfigurationEditingOptions = {}): Promise<void> { const operation = this.getConfigurationEditOperation(target, value, options.scopes || {}); return Promise.resolve(this.queue.queue(() => this.doWriteConfiguration(operation, options) // queue up writes to prevent race conditions .then(() => { }, async error => { if (!options.donotNotifyError) { await this.onError(error, operation, options.scopes); } return Promise.reject(error); }))); } private async doWriteConfiguration(operation: IConfigurationEditOperation, options: ConfigurationEditingOptions): Promise<void> { const checkDirtyConfiguration = !(options.force || options.donotSave); const saveConfiguration = options.force || !options.donotSave; const reference = await this.resolveAndValidate(operation.target, operation, checkDirtyConfiguration, options.scopes || {}); try { await this.writeToBuffer(reference.object.textEditorModel, operation, saveConfiguration); } catch (error) { if ((<FileOperationError>error).fileOperationResult === FileOperationResult.FILE_MODIFIED_SINCE) { await this.textFileService.revert(operation.resource!); return this.reject(ConfigurationEditingErrorCode.ERROR_CONFIGURATION_FILE_MODIFIED_SINCE, operation.target, operation); } throw error; } finally { reference.dispose(); } } private async writeToBuffer(model: ITextModel, operation: IConfigurationEditOperation, save: boolean): Promise<any> { const edit = this.getEdits(model, operation)[0]; if (edit && this.applyEditsToBuffer(edit, model) && save) { await this.textFileService.save(operation.resource!, { skipSaveParticipants: true /* programmatic change */, ignoreErrorHandler: true /* handle error self */ }); } } private applyEditsToBuffer(edit: Edit, model: ITextModel): boolean { const startPosition = model.getPositionAt(edit.offset); const endPosition = model.getPositionAt(edit.offset + edit.length); const range = new Range(startPosition.lineNumber, startPosition.column, endPosition.lineNumber, endPosition.column); let currentText = model.getValueInRange(range); if (edit.content !== currentText) { const editOperation = currentText ? EditOperation.replace(range, edit.content) : EditOperation.insert(startPosition, edit.content); model.pushEditOperations([new Selection(startPosition.lineNumber, startPosition.column, startPosition.lineNumber, startPosition.column)], [editOperation], () => []); return true; } return false; } private async onError(error: ConfigurationEditingError, operation: IConfigurationEditOperation, scopes: IConfigurationOverrides | undefined): Promise<void> { switch (error.code) { case ConfigurationEditingErrorCode.ERROR_INVALID_CONFIGURATION: this.onInvalidConfigurationError(error, operation); break; case ConfigurationEditingErrorCode.ERROR_CONFIGURATION_FILE_DIRTY: this.onConfigurationFileDirtyError(error, operation, scopes); break; case ConfigurationEditingErrorCode.ERROR_CONFIGURATION_FILE_MODIFIED_SINCE: return this.doWriteConfiguration(operation, { scopes }); default: this.notificationService.error(error.message); } } private onInvalidConfigurationError(error: ConfigurationEditingError, operation: IConfigurationEditOperation,): void { const openStandAloneConfigurationActionLabel = operation.workspaceStandAloneConfigurationKey === TASKS_CONFIGURATION_KEY ? nls.localize('openTasksConfiguration', "Open Tasks Configuration") : operation.workspaceStandAloneConfigurationKey === LAUNCH_CONFIGURATION_KEY ? nls.localize('openLaunchConfiguration', "Open Launch Configuration") : null; if (openStandAloneConfigurationActionLabel) { this.notificationService.prompt(Severity.Error, error.message, [{ label: openStandAloneConfigurationActionLabel, run: () => this.openFile(operation.resource!) }] ); } else { this.notificationService.prompt(Severity.Error, error.message, [{ label: nls.localize('open', "Open Settings"), run: () => this.openSettings(operation) }] ); } } private onConfigurationFileDirtyError(error: ConfigurationEditingError, operation: IConfigurationEditOperation, scopes: IConfigurationOverrides | undefined): void { const openStandAloneConfigurationActionLabel = operation.workspaceStandAloneConfigurationKey === TASKS_CONFIGURATION_KEY ? nls.localize('openTasksConfiguration', "Open Tasks Configuration") : operation.workspaceStandAloneConfigurationKey === LAUNCH_CONFIGURATION_KEY ? nls.localize('openLaunchConfiguration', "Open Launch Configuration") : null; if (openStandAloneConfigurationActionLabel) { this.notificationService.prompt(Severity.Error, error.message, [{ label: nls.localize('saveAndRetry', "Save and Retry"), run: () => { const key = operation.key ? `${operation.workspaceStandAloneConfigurationKey}.${operation.key}` : operation.workspaceStandAloneConfigurationKey!; this.writeConfiguration(operation.target, { key, value: operation.value }, <ConfigurationEditingOptions>{ force: true, scopes }); } }, { label: openStandAloneConfigurationActionLabel, run: () => this.openFile(operation.resource!) }] ); } else { this.notificationService.prompt(Severity.Error, error.message, [{ label: nls.localize('saveAndRetry', "Save and Retry"), run: () => this.writeConfiguration(operation.target, { key: operation.key, value: operation.value }, <ConfigurationEditingOptions>{ force: true, scopes }) }, { label: nls.localize('open', "Open Settings"), run: () => this.openSettings(operation) }] ); } } private openSettings(operation: IConfigurationEditOperation): void { switch (operation.target) { case EditableConfigurationTarget.USER_LOCAL: this.preferencesService.openGlobalSettings(true); break; case EditableConfigurationTarget.USER_REMOTE: this.preferencesService.openRemoteSettings(); break; case EditableConfigurationTarget.WORKSPACE: this.preferencesService.openWorkspaceSettings(true); break; case EditableConfigurationTarget.WORKSPACE_FOLDER: if (operation.resource) { const workspaceFolder = this.contextService.getWorkspaceFolder(operation.resource); if (workspaceFolder) { this.preferencesService.openFolderSettings(workspaceFolder.uri, true); } } break; } } private openFile(resource: URI): void { this.editorService.openEditor({ resource }); } private reject<T = never>(code: ConfigurationEditingErrorCode, target: EditableConfigurationTarget, operation: IConfigurationEditOperation): Promise<T> { const message = this.toErrorMessage(code, target, operation); return Promise.reject(new ConfigurationEditingError(message, code)); } private toErrorMessage(error: ConfigurationEditingErrorCode, target: EditableConfigurationTarget, operation: IConfigurationEditOperation): string { switch (error) { // API constraints case ConfigurationEditingErrorCode.ERROR_UNKNOWN_KEY: return nls.localize('errorUnknownKey', "Unable to write to {0} because {1} is not a registered configuration.", this.stringifyTarget(target), operation.key); case ConfigurationEditingErrorCode.ERROR_INVALID_WORKSPACE_CONFIGURATION_APPLICATION: return nls.localize('errorInvalidWorkspaceConfigurationApplication', "Unable to write {0} to Workspace Settings. This setting can be written only into User settings.", operation.key); case ConfigurationEditingErrorCode.ERROR_INVALID_WORKSPACE_CONFIGURATION_MACHINE: return nls.localize('errorInvalidWorkspaceConfigurationMachine', "Unable to write {0} to Workspace Settings. This setting can be written only into User settings.", operation.key); case ConfigurationEditingErrorCode.ERROR_INVALID_FOLDER_CONFIGURATION: return nls.localize('errorInvalidFolderConfiguration', "Unable to write to Folder Settings because {0} does not support the folder resource scope.", operation.key); case ConfigurationEditingErrorCode.ERROR_INVALID_USER_TARGET: return nls.localize('errorInvalidUserTarget', "Unable to write to User Settings because {0} does not support for global scope.", operation.key); case ConfigurationEditingErrorCode.ERROR_INVALID_WORKSPACE_TARGET: return nls.localize('errorInvalidWorkspaceTarget', "Unable to write to Workspace Settings because {0} does not support for workspace scope in a multi folder workspace.", operation.key); case ConfigurationEditingErrorCode.ERROR_INVALID_FOLDER_TARGET: return nls.localize('errorInvalidFolderTarget', "Unable to write to Folder Settings because no resource is provided."); case ConfigurationEditingErrorCode.ERROR_INVALID_RESOURCE_LANGUAGE_CONFIGURATION: return nls.localize('errorInvalidResourceLanguageConfiguraiton', "Unable to write to Language Settings because {0} is not a resource language setting.", operation.key); case ConfigurationEditingErrorCode.ERROR_NO_WORKSPACE_OPENED: return nls.localize('errorNoWorkspaceOpened', "Unable to write to {0} because no workspace is opened. Please open a workspace first and try again.", this.stringifyTarget(target)); // User issues case ConfigurationEditingErrorCode.ERROR_INVALID_CONFIGURATION: { if (operation.workspaceStandAloneConfigurationKey === TASKS_CONFIGURATION_KEY) { return nls.localize('errorInvalidTaskConfiguration', "Unable to write into the tasks configuration file. Please open it to correct errors/warnings in it and try again."); } if (operation.workspaceStandAloneConfigurationKey === LAUNCH_CONFIGURATION_KEY) { return nls.localize('errorInvalidLaunchConfiguration', "Unable to write into the launch configuration file. Please open it to correct errors/warnings in it and try again."); } switch (target) { case EditableConfigurationTarget.USER_LOCAL: return nls.localize('errorInvalidConfiguration', "Unable to write into user settings. Please open the user settings to correct errors/warnings in it and try again."); case EditableConfigurationTarget.USER_REMOTE: return nls.localize('errorInvalidRemoteConfiguration', "Unable to write into remote user settings. Please open the remote user settings to correct errors/warnings in it and try again."); case EditableConfigurationTarget.WORKSPACE: return nls.localize('errorInvalidConfigurationWorkspace', "Unable to write into workspace settings. Please open the workspace settings to correct errors/warnings in the file and try again."); case EditableConfigurationTarget.WORKSPACE_FOLDER: let workspaceFolderName: string = '<<unknown>>'; if (operation.resource) { const folder = this.contextService.getWorkspaceFolder(operation.resource); if (folder) { workspaceFolderName = folder.name; } } return nls.localize('errorInvalidConfigurationFolder', "Unable to write into folder settings. Please open the '{0}' folder settings to correct errors/warnings in it and try again.", workspaceFolderName); } return ''; } case ConfigurationEditingErrorCode.ERROR_CONFIGURATION_FILE_DIRTY: { if (operation.workspaceStandAloneConfigurationKey === TASKS_CONFIGURATION_KEY) { return nls.localize('errorTasksConfigurationFileDirty', "Unable to write into tasks configuration file because the file is dirty. Please save it first and then try again."); } if (operation.workspaceStandAloneConfigurationKey === LAUNCH_CONFIGURATION_KEY) { return nls.localize('errorLaunchConfigurationFileDirty', "Unable to write into launch configuration file because the file is dirty. Please save it first and then try again."); } switch (target) { case EditableConfigurationTarget.USER_LOCAL: return nls.localize('errorConfigurationFileDirty', "Unable to write into user settings because the file is dirty. Please save the user settings file first and then try again."); case EditableConfigurationTarget.USER_REMOTE: return nls.localize('errorRemoteConfigurationFileDirty', "Unable to write into remote user settings because the file is dirty. Please save the remote user settings file first and then try again."); case EditableConfigurationTarget.WORKSPACE: return nls.localize('errorConfigurationFileDirtyWorkspace', "Unable to write into workspace settings because the file is dirty. Please save the workspace settings file first and then try again."); case EditableConfigurationTarget.WORKSPACE_FOLDER: let workspaceFolderName: string = '<<unknown>>'; if (operation.resource) { const folder = this.contextService.getWorkspaceFolder(operation.resource); if (folder) { workspaceFolderName = folder.name; } } return nls.localize('errorConfigurationFileDirtyFolder', "Unable to write into folder settings because the file is dirty. Please save the '{0}' folder settings file first and then try again.", workspaceFolderName); } return ''; } case ConfigurationEditingErrorCode.ERROR_CONFIGURATION_FILE_MODIFIED_SINCE: if (operation.workspaceStandAloneConfigurationKey === TASKS_CONFIGURATION_KEY) { return nls.localize('errorTasksConfigurationFileModifiedSince', "Unable to write into tasks configuration file because the content of the file is newer."); } if (operation.workspaceStandAloneConfigurationKey === LAUNCH_CONFIGURATION_KEY) { return nls.localize('errorLaunchConfigurationFileModifiedSince', "Unable to write into launch configuration file because the content of the file is newer."); } switch (target) { case EditableConfigurationTarget.USER_LOCAL: return nls.localize('errorConfigurationFileModifiedSince', "Unable to write into user settings because the content of the file is newer."); case EditableConfigurationTarget.USER_REMOTE: return nls.localize('errorRemoteConfigurationFileModifiedSince', "Unable to write into remote user settings because the content of the file is newer."); case EditableConfigurationTarget.WORKSPACE: return nls.localize('errorConfigurationFileModifiedSinceWorkspace', "Unable to write into workspace settings because the content of the file is newer."); case EditableConfigurationTarget.WORKSPACE_FOLDER: return nls.localize('errorConfigurationFileModifiedSinceFolder', "Unable to write into folder settings because the content of the file is newer."); } } } private stringifyTarget(target: EditableConfigurationTarget): string { switch (target) { case EditableConfigurationTarget.USER_LOCAL: return nls.localize('userTarget', "User Settings"); case EditableConfigurationTarget.USER_REMOTE: return nls.localize('remoteUserTarget', "Remote User Settings"); case EditableConfigurationTarget.WORKSPACE: return nls.localize('workspaceTarget', "Workspace Settings"); case EditableConfigurationTarget.WORKSPACE_FOLDER: return nls.localize('folderTarget', "Folder Settings"); } return ''; } private getEdits(model: ITextModel, edit: IConfigurationEditOperation): Edit[] { const { tabSize, insertSpaces } = model.getOptions(); const eol = model.getEOL(); const { value, jsonPath } = edit; // Without jsonPath, the entire configuration file is being replaced, so we just use JSON.stringify if (!jsonPath.length) { const content = JSON.stringify(value, null, insertSpaces ? strings.repeat(' ', tabSize) : '\t'); return [{ content, length: model.getValue().length, offset: 0 }]; } return setProperty(model.getValue(), jsonPath, value, { tabSize, insertSpaces, eol }); } private defaultResourceValue(resource: URI): string { const basename: string = resources.basename(resource); const configurationValue: string = basename.substr(0, basename.length - resources.extname(resource).length); switch (configurationValue) { case TASKS_CONFIGURATION_KEY: return TASKS_DEFAULT; default: return '{}'; } } private async resolveModelReference(resource: URI): Promise<IReference<IResolvedTextEditorModel>> { const exists = await this.fileService.exists(resource); if (!exists) { await this.textFileService.write(resource, this.defaultResourceValue(resource), { encoding: 'utf8' }); } return this.textModelResolverService.createModelReference(resource); } private hasParseErrors(model: ITextModel, operation: IConfigurationEditOperation): boolean { // If we write to a workspace standalone file and replace the entire contents (no key provided) // we can return here because any parse errors can safely be ignored since all contents are replaced if (operation.workspaceStandAloneConfigurationKey && !operation.key) { return false; } const parseErrors: json.ParseError[] = []; json.parse(model.getValue(), parseErrors, { allowTrailingComma: true, allowEmptyContent: true }); return parseErrors.length > 0; } private resolveAndValidate(target: EditableConfigurationTarget, operation: IConfigurationEditOperation, checkDirty: boolean, overrides: IConfigurationOverrides): Promise<IReference<IResolvedTextEditorModel>> { // Any key must be a known setting from the registry (unless this is a standalone config) if (!operation.workspaceStandAloneConfigurationKey) { const validKeys = this.configurationService.keys().default; if (validKeys.indexOf(operation.key) < 0 && !OVERRIDE_PROPERTY_PATTERN.test(operation.key)) { return this.reject(ConfigurationEditingErrorCode.ERROR_UNKNOWN_KEY, target, operation); } } if (operation.workspaceStandAloneConfigurationKey) { // Global launches are not supported if ((operation.workspaceStandAloneConfigurationKey !== TASKS_CONFIGURATION_KEY) && (target === EditableConfigurationTarget.USER_LOCAL || target === EditableConfigurationTarget.USER_REMOTE)) { return this.reject(ConfigurationEditingErrorCode.ERROR_INVALID_USER_TARGET, target, operation); } } // Target cannot be workspace or folder if no workspace opened if ((target === EditableConfigurationTarget.WORKSPACE || target === EditableConfigurationTarget.WORKSPACE_FOLDER) && this.contextService.getWorkbenchState() === WorkbenchState.EMPTY) { return this.reject(ConfigurationEditingErrorCode.ERROR_NO_WORKSPACE_OPENED, target, operation); } if (target === EditableConfigurationTarget.WORKSPACE) { if (!operation.workspaceStandAloneConfigurationKey && !OVERRIDE_PROPERTY_PATTERN.test(operation.key)) { const configurationProperties = Registry.as<IConfigurationRegistry>(ConfigurationExtensions.Configuration).getConfigurationProperties(); if (configurationProperties[operation.key].scope === ConfigurationScope.APPLICATION) { return this.reject(ConfigurationEditingErrorCode.ERROR_INVALID_WORKSPACE_CONFIGURATION_APPLICATION, target, operation); } if (configurationProperties[operation.key].scope === ConfigurationScope.MACHINE) { return this.reject(ConfigurationEditingErrorCode.ERROR_INVALID_WORKSPACE_CONFIGURATION_MACHINE, target, operation); } } } if (target === EditableConfigurationTarget.WORKSPACE_FOLDER) { if (!operation.resource) { return this.reject(ConfigurationEditingErrorCode.ERROR_INVALID_FOLDER_TARGET, target, operation); } if (!operation.workspaceStandAloneConfigurationKey && !OVERRIDE_PROPERTY_PATTERN.test(operation.key)) { const configurationProperties = Registry.as<IConfigurationRegistry>(ConfigurationExtensions.Configuration).getConfigurationProperties(); if (!(configurationProperties[operation.key].scope === ConfigurationScope.RESOURCE || configurationProperties[operation.key].scope === ConfigurationScope.LANGUAGE_OVERRIDABLE)) { return this.reject(ConfigurationEditingErrorCode.ERROR_INVALID_FOLDER_CONFIGURATION, target, operation); } } } if (overrides.overrideIdentifier) { const configurationProperties = Registry.as<IConfigurationRegistry>(ConfigurationExtensions.Configuration).getConfigurationProperties(); if (configurationProperties[operation.key].scope !== ConfigurationScope.LANGUAGE_OVERRIDABLE) { return this.reject(ConfigurationEditingErrorCode.ERROR_INVALID_RESOURCE_LANGUAGE_CONFIGURATION, target, operation); } } if (!operation.resource) { return this.reject(ConfigurationEditingErrorCode.ERROR_INVALID_FOLDER_TARGET, target, operation); } return this.resolveModelReference(operation.resource) .then(reference => { const model = reference.object.textEditorModel; if (this.hasParseErrors(model, operation)) { reference.dispose(); return this.reject<typeof reference>(ConfigurationEditingErrorCode.ERROR_INVALID_CONFIGURATION, target, operation); } // Target cannot be dirty if not writing into buffer if (checkDirty && operation.resource && this.textFileService.isDirty(operation.resource)) { reference.dispose(); return this.reject<typeof reference>(ConfigurationEditingErrorCode.ERROR_CONFIGURATION_FILE_DIRTY, target, operation); } return reference; }); } private getConfigurationEditOperation(target: EditableConfigurationTarget, config: IConfigurationValue, overrides: IConfigurationOverrides): IConfigurationEditOperation { // Check for standalone workspace configurations if (config.key) { const standaloneConfigurationMap = target === EditableConfigurationTarget.USER_LOCAL ? USER_STANDALONE_CONFIGURATIONS : WORKSPACE_STANDALONE_CONFIGURATIONS; const standaloneConfigurationKeys = Object.keys(standaloneConfigurationMap); for (const key of standaloneConfigurationKeys) { const resource = this.getConfigurationFileResource(target, standaloneConfigurationMap[key], overrides.resource); // Check for prefix if (config.key === key) { const jsonPath = this.isWorkspaceConfigurationResource(resource) ? [key] : []; return { key: jsonPath[jsonPath.length - 1], jsonPath, value: config.value, resource: withNullAsUndefined(resource), workspaceStandAloneConfigurationKey: key, target }; } // Check for prefix.<setting> const keyPrefix = `${key}.`; if (config.key.indexOf(keyPrefix) === 0) { const jsonPath = this.isWorkspaceConfigurationResource(resource) ? [key, config.key.substr(keyPrefix.length)] : [config.key.substr(keyPrefix.length)]; return { key: jsonPath[jsonPath.length - 1], jsonPath, value: config.value, resource: withNullAsUndefined(resource), workspaceStandAloneConfigurationKey: key, target }; } } } let key = config.key; let jsonPath = overrides.overrideIdentifier ? [keyFromOverrideIdentifier(overrides.overrideIdentifier), key] : [key]; if (target === EditableConfigurationTarget.USER_LOCAL || target === EditableConfigurationTarget.USER_REMOTE) { return { key, jsonPath, value: config.value, resource: withNullAsUndefined(this.getConfigurationFileResource(target, '', null)), target }; } const resource = this.getConfigurationFileResource(target, FOLDER_SETTINGS_PATH, overrides.resource); if (this.isWorkspaceConfigurationResource(resource)) { jsonPath = ['settings', ...jsonPath]; } return { key, jsonPath, value: config.value, resource: withNullAsUndefined(resource), target }; } private isWorkspaceConfigurationResource(resource: URI | null): boolean { const workspace = this.contextService.getWorkspace(); return !!(workspace.configuration && resource && workspace.configuration.fsPath === resource.fsPath); } private getConfigurationFileResource(target: EditableConfigurationTarget, relativePath: string, resource: URI | null | undefined): URI | null { if (target === EditableConfigurationTarget.USER_LOCAL) { if (relativePath) { return resources.joinPath(resources.dirname(this.environmentService.settingsResource), relativePath); } else { return this.environmentService.settingsResource; } } if (target === EditableConfigurationTarget.USER_REMOTE) { return this.remoteSettingsResource; } const workbenchState = this.contextService.getWorkbenchState(); if (workbenchState !== WorkbenchState.EMPTY) { const workspace = this.contextService.getWorkspace(); if (target === EditableConfigurationTarget.WORKSPACE) { if (workbenchState === WorkbenchState.WORKSPACE) { return withUndefinedAsNull(workspace.configuration); } if (workbenchState === WorkbenchState.FOLDER) { return workspace.folders[0].toResource(relativePath); } } if (target === EditableConfigurationTarget.WORKSPACE_FOLDER) { if (resource) { const folder = this.contextService.getWorkspaceFolder(resource); if (folder) { return folder.toResource(relativePath); } } } } return null; } }
src/vs/workbench/services/configuration/common/configurationEditingService.ts
0
https://github.com/microsoft/vscode/commit/9504dda6a717a0a0d45d992e21f2565f8a23f390
[ 0.0004393932467792183, 0.00017651572125032544, 0.00016361672896891832, 0.0001731645897962153, 0.00003383984585525468 ]
{ "id": 7, "code_window": [ "\t\tthis._register({ dispose() { cts.dispose(true); } });\n", "\t\traceCancellation(viewCell.resolveTextModel(), cts.token).then(model => {\n", "\t\t\tif (model && templateData.editor) {\n", "\t\t\t\ttemplateData.editor.setModel(model);\n", "\t\t\t\tviewCell.attachTextEditor(templateData.editor);\n", "\t\t\t\tif (notebookEditor.getActiveCell() === viewCell && viewCell.focusMode === CellFocusMode.Editor) {\n", "\t\t\t\t\ttemplateData.editor?.focus();\n", "\t\t\t\t}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\tif (notebookEditor.getActiveCell() === viewCell && viewCell.focusMode === CellFocusMode.Editor && this.notebookEditor.hasFocus()) {\n" ], "file_path": "src/vs/workbench/contrib/notebook/browser/view/renderers/codeCell.ts", "type": "replace", "edit_start_line_idx": 59 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { URI } from 'vs/base/common/uri'; import { IListService } from 'vs/platform/list/browser/listService'; import { OpenEditor, IExplorerService } from 'vs/workbench/contrib/files/common/files'; import { toResource, SideBySideEditor, IEditorIdentifier } from 'vs/workbench/common/editor'; import { List } from 'vs/base/browser/ui/list/listWidget'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; import { ExplorerItem } from 'vs/workbench/contrib/files/common/explorerModel'; import { coalesce } from 'vs/base/common/arrays'; import { AsyncDataTree } from 'vs/base/browser/ui/tree/asyncDataTree'; import { IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService'; function getFocus(listService: IListService): unknown | undefined { let list = listService.lastFocusedList; if (list?.getHTMLElement() === document.activeElement) { let focus: unknown; if (list instanceof List) { const focused = list.getFocusedElements(); if (focused.length) { focus = focused[0]; } } else if (list instanceof AsyncDataTree) { const focused = list.getFocus(); if (focused.length) { focus = focused[0]; } } return focus; } return undefined; } // Commands can get exeucted from a command pallete, from a context menu or from some list using a keybinding // To cover all these cases we need to properly compute the resource on which the command is being executed export function getResourceForCommand(resource: URI | object | undefined, listService: IListService, editorService: IEditorService): URI | undefined { if (URI.isUri(resource)) { return resource; } const focus = getFocus(listService); if (focus instanceof ExplorerItem) { return focus.resource; } else if (focus instanceof OpenEditor) { return focus.getResource(); } return editorService.activeEditor ? toResource(editorService.activeEditor, { supportSideBySide: SideBySideEditor.PRIMARY }) : undefined; } export function getMultiSelectedResources(resource: URI | object | undefined, listService: IListService, editorService: IEditorService, explorerService: IExplorerService): Array<URI> { const list = listService.lastFocusedList; if (list?.getHTMLElement() === document.activeElement) { // Explorer if (list instanceof AsyncDataTree && list.getFocus().every(item => item instanceof ExplorerItem)) { // Explorer const context = explorerService.getContext(true); if (context.length) { return context.map(c => c.resource); } } // Open editors view if (list instanceof List) { const selection = coalesce(list.getSelectedElements().filter(s => s instanceof OpenEditor).map((oe: OpenEditor) => oe.getResource())); const focusedElements = list.getFocusedElements(); const focus = focusedElements.length ? focusedElements[0] : undefined; let mainUriStr: string | undefined = undefined; if (URI.isUri(resource)) { mainUriStr = resource.toString(); } else if (focus instanceof OpenEditor) { const focusedResource = focus.getResource(); mainUriStr = focusedResource ? focusedResource.toString() : undefined; } // We only respect the selection if it contains the main element. if (selection.some(s => s.toString() === mainUriStr)) { return selection; } } } const result = getResourceForCommand(resource, listService, editorService); return !!result ? [result] : []; } export function getOpenEditorsViewMultiSelection(listService: IListService, editorGroupService: IEditorGroupsService): Array<IEditorIdentifier> | undefined { const list = listService.lastFocusedList; if (list?.getHTMLElement() === document.activeElement) { // Open editors view if (list instanceof List) { const selection = coalesce(list.getSelectedElements().filter(s => s instanceof OpenEditor)); const focusedElements = list.getFocusedElements(); const focus = focusedElements.length ? focusedElements[0] : undefined; let mainEditor: IEditorIdentifier | undefined = undefined; if (focus instanceof OpenEditor) { mainEditor = focus; } // We only respect the selection if it contains the main element. if (selection.some(s => s === mainEditor)) { return selection; } } } return undefined; }
src/vs/workbench/contrib/files/browser/files.ts
0
https://github.com/microsoft/vscode/commit/9504dda6a717a0a0d45d992e21f2565f8a23f390
[ 0.00017647234199102968, 0.00017310796829406172, 0.00016809326189104468, 0.00017359467165078968, 0.000002570907554400037 ]
{ "id": 7, "code_window": [ "\t\tthis._register({ dispose() { cts.dispose(true); } });\n", "\t\traceCancellation(viewCell.resolveTextModel(), cts.token).then(model => {\n", "\t\t\tif (model && templateData.editor) {\n", "\t\t\t\ttemplateData.editor.setModel(model);\n", "\t\t\t\tviewCell.attachTextEditor(templateData.editor);\n", "\t\t\t\tif (notebookEditor.getActiveCell() === viewCell && viewCell.focusMode === CellFocusMode.Editor) {\n", "\t\t\t\t\ttemplateData.editor?.focus();\n", "\t\t\t\t}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\tif (notebookEditor.getActiveCell() === viewCell && viewCell.focusMode === CellFocusMode.Editor && this.notebookEditor.hasFocus()) {\n" ], "file_path": "src/vs/workbench/contrib/notebook/browser/view/renderers/codeCell.ts", "type": "replace", "edit_start_line_idx": 59 }
{ "comments": { "lineComment": "//", "blockComment": [ "/*", "*/" ] }, "brackets": [ ["{", "}"], ["[", "]"], ["(", ")"] ], "autoClosingPairs": [ ["{", "}"], ["[", "]"], ["(", ")"], { "open": "\"", "close": "\"", "notIn": ["string"] }, { "open": "'", "close": "'", "notIn": ["string"] }, { "open": "/**", "close": " */", "notIn": ["string"] } ], "surroundingPairs": [ ["{", "}"], ["[", "]"], ["(", ")"], ["\"", "\""], ["'", "'"], ["<", ">"] ], "folding": { "markers": { "start": "^\\s*//\\s*(?:(?:#?region\\b)|(?:<editor-fold\\b))", "end": "^\\s*//\\s*(?:(?:#?endregion\\b)|(?:</editor-fold>))" } } }
extensions/java/language-configuration.json
0
https://github.com/microsoft/vscode/commit/9504dda6a717a0a0d45d992e21f2565f8a23f390
[ 0.0001752581010805443, 0.00017360333004035056, 0.00017102892161346972, 0.00017406315600965172, 0.0000015905288819340058 ]
{ "id": 8, "code_window": [ "\t\t\t\t\tthis.onCellHeightChange(realContentHeight);\n", "\t\t\t\t}\n", "\n", "\t\t\t\tif (this.notebookEditor.getActiveCell() === this.viewCell && viewCell.focusMode === CellFocusMode.Editor) {\n", "\t\t\t\t\ttemplateData.editor?.focus();\n", "\t\t\t\t}\n", "\t\t\t}\n", "\t\t});\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\tif (this.notebookEditor.getActiveCell() === this.viewCell && viewCell.focusMode === CellFocusMode.Editor && this.notebookEditor.hasFocus()) {\n" ], "file_path": "src/vs/workbench/contrib/notebook/browser/view/renderers/codeCell.ts", "type": "replace", "edit_start_line_idx": 68 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { getZoomLevel } from 'vs/base/browser/browser'; import * as DOM from 'vs/base/browser/dom'; import { IMouseWheelEvent, StandardMouseEvent } from 'vs/base/browser/mouseEvent'; import { CancellationTokenSource } from 'vs/base/common/cancellation'; import { Color, RGBA } from 'vs/base/common/color'; import { onUnexpectedError } from 'vs/base/common/errors'; import { Emitter, Event } from 'vs/base/common/event'; import { combinedDisposable, DisposableStore, Disposable, IDisposable, toDisposable } from 'vs/base/common/lifecycle'; import 'vs/css!./media/notebook'; import { ICodeEditor } from 'vs/editor/browser/editorBrowser'; import { IEditorOptions } from 'vs/editor/common/config/editorOptions'; import { BareFontInfo } from 'vs/editor/common/config/fontInfo'; import { Range } from 'vs/editor/common/core/range'; import { IEditor } from 'vs/editor/common/editorCommon'; import * as nls from 'vs/nls'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IContextKey, IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { IResourceEditorInput } from 'vs/platform/editor/common/editor'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage'; import { contrastBorder, editorBackground, focusBorder, foreground, registerColor, textBlockQuoteBackground, textBlockQuoteBorder, textLinkActiveForeground, textLinkForeground, textPreformatForeground, errorForeground, transparent, widgetShadow, listFocusBackground, listInactiveSelectionBackground, scrollbarSliderBackground, scrollbarSliderHoverBackground, scrollbarSliderActiveBackground } from 'vs/platform/theme/common/colorRegistry'; import { registerThemingParticipant } from 'vs/platform/theme/common/themeService'; import { EditorMemento } from 'vs/workbench/browser/parts/editor/baseEditor'; import { EditorOptions, IEditorMemento } from 'vs/workbench/common/editor'; import { CELL_MARGIN, CELL_RUN_GUTTER, EDITOR_BOTTOM_PADDING, EDITOR_TOP_MARGIN, EDITOR_TOP_PADDING, SCROLLABLE_ELEMENT_PADDING_TOP, BOTTOM_CELL_TOOLBAR_HEIGHT, CELL_BOTTOM_MARGIN, CODE_CELL_LEFT_MARGIN } from 'vs/workbench/contrib/notebook/browser/constants'; import { CellEditState, CellFocusMode, ICellRange, ICellViewModel, INotebookCellList, INotebookEditor, INotebookEditorContribution, INotebookEditorMouseEvent, NotebookLayoutInfo, NOTEBOOK_EDITOR_EDITABLE, NOTEBOOK_EDITOR_EXECUTING_NOTEBOOK, NOTEBOOK_EDITOR_FOCUSED, NOTEBOOK_EDITOR_RUNNABLE, NOTEBOOK_HAS_MULTIPLE_KERNELS, NOTEBOOK_OUTPUT_FOCUSED } from 'vs/workbench/contrib/notebook/browser/notebookBrowser'; import { NotebookEditorExtensionsRegistry } from 'vs/workbench/contrib/notebook/browser/notebookEditorExtensions'; import { NotebookCellList } from 'vs/workbench/contrib/notebook/browser/view/notebookCellList'; import { OutputRenderer } from 'vs/workbench/contrib/notebook/browser/view/output/outputRenderer'; import { BackLayerWebView } from 'vs/workbench/contrib/notebook/browser/view/renderers/backLayerWebView'; import { CellDragAndDropController, CodeCellRenderer, MarkdownCellRenderer, NotebookCellListDelegate } from 'vs/workbench/contrib/notebook/browser/view/renderers/cellRenderer'; import { CodeCellViewModel } from 'vs/workbench/contrib/notebook/browser/viewModel/codeCellViewModel'; import { NotebookEventDispatcher, NotebookLayoutChangedEvent } from 'vs/workbench/contrib/notebook/browser/viewModel/eventDispatcher'; import { CellViewModel, IModelDecorationsChangeAccessor, INotebookEditorViewState, NotebookViewModel } from 'vs/workbench/contrib/notebook/browser/viewModel/notebookViewModel'; import { CellKind, IProcessedOutput, INotebookKernelInfo, INotebookKernelInfoDto } from 'vs/workbench/contrib/notebook/common/notebookCommon'; import { INotebookService } from 'vs/workbench/contrib/notebook/common/notebookService'; import { Webview } from 'vs/workbench/contrib/webview/browser/webview'; import { IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService'; import { ILayoutService } from 'vs/platform/layout/browser/layoutService'; import { generateUuid } from 'vs/base/common/uuid'; import { Memento, MementoObject } from 'vs/workbench/common/memento'; import { NotebookTextModel } from 'vs/workbench/contrib/notebook/common/model/notebookTextModel'; import { URI } from 'vs/base/common/uri'; import { PANEL_BORDER } from 'vs/workbench/common/theme'; import { debugIconStartForeground } from 'vs/workbench/contrib/debug/browser/debugToolBar'; import { CellContextKeyManager } from 'vs/workbench/contrib/notebook/browser/view/renderers/cellContextKeys'; const $ = DOM.$; export class NotebookEditorOptions extends EditorOptions { readonly cellOptions?: IResourceEditorInput; constructor(options: Partial<NotebookEditorOptions>) { super(); this.overwrite(options); this.cellOptions = options.cellOptions; } with(options: Partial<NotebookEditorOptions>): NotebookEditorOptions { return new NotebookEditorOptions({ ...this, ...options }); } } export class NotebookEditorWidget extends Disposable implements INotebookEditor { static readonly ID: string = 'workbench.editor.notebook'; private static readonly EDITOR_MEMENTOS = new Map<string, EditorMemento<unknown>>(); private _overlayContainer!: HTMLElement; private _body!: HTMLElement; private _webview: BackLayerWebView | null = null; private _webviewTransparentCover: HTMLElement | null = null; private _list: INotebookCellList | undefined; private _dndController: CellDragAndDropController | null = null; private _renderedEditors: Map<ICellViewModel, ICodeEditor | undefined> = new Map(); private _eventDispatcher: NotebookEventDispatcher | undefined; private _notebookViewModel: NotebookViewModel | undefined; private _localStore: DisposableStore = this._register(new DisposableStore()); private _fontInfo: BareFontInfo | undefined; private _dimension: DOM.Dimension | null = null; private _shadowElementViewInfo: { height: number, width: number, top: number; left: number; } | null = null; private _editorFocus: IContextKey<boolean> | null = null; private _outputFocus: IContextKey<boolean> | null = null; private _editorEditable: IContextKey<boolean> | null = null; private _editorRunnable: IContextKey<boolean> | null = null; private _editorExecutingNotebook: IContextKey<boolean> | null = null; private _notebookHasMultipleKernels: IContextKey<boolean> | null = null; private _outputRenderer: OutputRenderer; protected readonly _contributions: { [key: string]: INotebookEditorContribution; }; private _scrollBeyondLastLine: boolean; private readonly _memento: Memento; private readonly _onDidFocusEmitter = this._register(new Emitter<void>()); public readonly onDidFocus = this._onDidFocusEmitter.event; private _cellContextKeyManager: CellContextKeyManager | null = null; private _isVisible = false; private readonly _uuid = generateUuid(); private _webiewFocused: boolean = false; private _isDisposed: boolean = false; get isDisposed() { return this._isDisposed; } private readonly _onDidChangeModel = this._register(new Emitter<NotebookTextModel | undefined>()); readonly onDidChangeModel: Event<NotebookTextModel | undefined> = this._onDidChangeModel.event; private readonly _onDidFocusEditorWidget = this._register(new Emitter<void>()); readonly onDidFocusEditorWidget = this._onDidFocusEditorWidget.event; set viewModel(newModel: NotebookViewModel | undefined) { this._notebookViewModel = newModel; this._onDidChangeModel.fire(newModel?.notebookDocument); } get viewModel() { return this._notebookViewModel; } get uri() { return this._notebookViewModel?.uri; } get textModel() { return this._notebookViewModel?.notebookDocument; } private _activeKernel: INotebookKernelInfo | undefined = undefined; private readonly _onDidChangeKernel = this._register(new Emitter<void>()); readonly onDidChangeKernel: Event<void> = this._onDidChangeKernel.event; get activeKernel() { return this._activeKernel; } set activeKernel(kernel: INotebookKernelInfo | undefined) { if (this._isDisposed) { return; } this._activeKernel = kernel; this._onDidChangeKernel.fire(); } private readonly _onDidChangeActiveEditor = this._register(new Emitter<this>()); readonly onDidChangeActiveEditor: Event<this> = this._onDidChangeActiveEditor.event; get activeCodeEditor(): IEditor | undefined { if (this._isDisposed) { return; } const [focused] = this._list!.getFocusedElements(); return this._renderedEditors.get(focused); } constructor( @IInstantiationService private readonly instantiationService: IInstantiationService, @IStorageService storageService: IStorageService, @INotebookService private notebookService: INotebookService, @IConfigurationService private readonly configurationService: IConfigurationService, @IContextKeyService readonly contextKeyService: IContextKeyService, @ILayoutService private readonly layoutService: ILayoutService ) { super(); this._memento = new Memento(NotebookEditorWidget.ID, storageService); this._outputRenderer = new OutputRenderer(this, this.instantiationService); this._contributions = {}; this._scrollBeyondLastLine = this.configurationService.getValue<boolean>('editor.scrollBeyondLastLine'); this.configurationService.onDidChangeConfiguration(e => { if (e.affectsConfiguration('editor.scrollBeyondLastLine')) { this._scrollBeyondLastLine = this.configurationService.getValue<boolean>('editor.scrollBeyondLastLine'); if (this._dimension && this._isVisible) { this.layout(this._dimension); } } }); this.notebookService.addNotebookEditor(this); } public getId(): string { return this._uuid; } hasModel() { return !!this._notebookViewModel; } //#region Editor Core protected getEditorMemento<T>(editorGroupService: IEditorGroupsService, key: string, limit: number = 10): IEditorMemento<T> { const mementoKey = `${NotebookEditorWidget.ID}${key}`; let editorMemento = NotebookEditorWidget.EDITOR_MEMENTOS.get(mementoKey); if (!editorMemento) { editorMemento = new EditorMemento(NotebookEditorWidget.ID, key, this.getMemento(StorageScope.WORKSPACE), limit, editorGroupService); NotebookEditorWidget.EDITOR_MEMENTOS.set(mementoKey, editorMemento); } return editorMemento as IEditorMemento<T>; } protected getMemento(scope: StorageScope): MementoObject { return this._memento.getMemento(scope); } public get isNotebookEditor() { return true; } updateEditorFocus() { // Note - focus going to the webview will fire 'blur', but the webview element will be // a descendent of the notebook editor root. const focused = DOM.isAncestor(document.activeElement, this._overlayContainer); this._editorFocus?.set(focused); this._notebookViewModel?.setFocus(focused); } hasFocus() { return this._editorFocus?.get() || false; } createEditor(): void { this._overlayContainer = document.createElement('div'); const id = generateUuid(); this._overlayContainer.id = `notebook-${id}`; this._overlayContainer.className = 'notebookOverlay'; DOM.addClass(this._overlayContainer, 'notebook-editor'); this._overlayContainer.style.visibility = 'hidden'; this.layoutService.container.appendChild(this._overlayContainer); this._createBody(this._overlayContainer); this._generateFontInfo(); this._editorFocus = NOTEBOOK_EDITOR_FOCUSED.bindTo(this.contextKeyService); this._editorFocus.set(true); this._isVisible = true; this._outputFocus = NOTEBOOK_OUTPUT_FOCUSED.bindTo(this.contextKeyService); this._editorEditable = NOTEBOOK_EDITOR_EDITABLE.bindTo(this.contextKeyService); this._editorEditable.set(true); this._editorRunnable = NOTEBOOK_EDITOR_RUNNABLE.bindTo(this.contextKeyService); this._editorRunnable.set(true); this._editorExecutingNotebook = NOTEBOOK_EDITOR_EXECUTING_NOTEBOOK.bindTo(this.contextKeyService); this._notebookHasMultipleKernels = NOTEBOOK_HAS_MULTIPLE_KERNELS.bindTo(this.contextKeyService); this._notebookHasMultipleKernels.set(false); const contributions = NotebookEditorExtensionsRegistry.getEditorContributions(); for (const desc of contributions) { try { const contribution = this.instantiationService.createInstance(desc.ctor, this); this._contributions[desc.id] = contribution; } catch (err) { onUnexpectedError(err); } } } private _generateFontInfo(): void { const editorOptions = this.configurationService.getValue<IEditorOptions>('editor'); this._fontInfo = BareFontInfo.createFromRawSettings(editorOptions, getZoomLevel()); } private _createBody(parent: HTMLElement): void { this._body = document.createElement('div'); DOM.addClass(this._body, 'cell-list-container'); this._createCellList(); DOM.append(parent, this._body); } private _createCellList(): void { DOM.addClass(this._body, 'cell-list-container'); this._dndController = this._register(new CellDragAndDropController(this, this._body)); const getScopedContextKeyService = (container?: HTMLElement) => this._list!.contextKeyService.createScoped(container); const renderers = [ this.instantiationService.createInstance(CodeCellRenderer, this, this._renderedEditors, this._dndController, getScopedContextKeyService), this.instantiationService.createInstance(MarkdownCellRenderer, this, this._dndController, this._renderedEditors, getScopedContextKeyService), ]; this._list = this.instantiationService.createInstance( NotebookCellList, 'NotebookCellList', this._body, this.instantiationService.createInstance(NotebookCellListDelegate), renderers, this.contextKeyService, { setRowLineHeight: false, setRowHeight: false, supportDynamicHeights: true, horizontalScrolling: false, keyboardSupport: false, mouseSupport: true, multipleSelectionSupport: false, enableKeyboardNavigation: true, additionalScrollHeight: 0, transformOptimization: false, styleController: (_suffix: string) => { return this._list!; }, overrideStyles: { listBackground: editorBackground, listActiveSelectionBackground: editorBackground, listActiveSelectionForeground: foreground, listFocusAndSelectionBackground: editorBackground, listFocusAndSelectionForeground: foreground, listFocusBackground: editorBackground, listFocusForeground: foreground, listHoverForeground: foreground, listHoverBackground: editorBackground, listHoverOutline: focusBorder, listFocusOutline: focusBorder, listInactiveSelectionBackground: editorBackground, listInactiveSelectionForeground: foreground, listInactiveFocusBackground: editorBackground, listInactiveFocusOutline: editorBackground, }, accessibilityProvider: { getAriaLabel() { return null; }, getWidgetAriaLabel() { return nls.localize('notebookTreeAriaLabel', "Notebook"); } } }, ); this._dndController.setList(this._list); // create Webview this._register(this._list); this._register(combinedDisposable(...renderers)); // transparent cover this._webviewTransparentCover = DOM.append(this._list.rowsContainer, $('.webview-cover')); this._webviewTransparentCover.style.display = 'none'; this._register(DOM.addStandardDisposableGenericMouseDownListner(this._overlayContainer, (e: StandardMouseEvent) => { if (DOM.hasClass(e.target, 'slider') && this._webviewTransparentCover) { this._webviewTransparentCover.style.display = 'block'; } })); this._register(DOM.addStandardDisposableGenericMouseUpListner(this._overlayContainer, () => { if (this._webviewTransparentCover) { // no matter when this._webviewTransparentCover.style.display = 'none'; } })); this._register(this._list.onMouseDown(e => { if (e.element) { this._onMouseDown.fire({ event: e.browserEvent, target: e.element }); } })); this._register(this._list.onMouseUp(e => { if (e.element) { this._onMouseUp.fire({ event: e.browserEvent, target: e.element }); } })); this._register(this._list.onDidChangeFocus(_e => this._onDidChangeActiveEditor.fire(this))); const widgetFocusTracker = DOM.trackFocus(this.getDomNode()); this._register(widgetFocusTracker); this._register(widgetFocusTracker.onDidFocus(() => this._onDidFocusEmitter.fire())); } getDomNode() { return this._overlayContainer; } onWillHide() { this._isVisible = false; this._editorFocus?.set(false); this._overlayContainer.style.visibility = 'hidden'; this._overlayContainer.style.left = '-50000px'; } getInnerWebview(): Webview | undefined { return this._webview?.webview; } focus() { this._isVisible = true; this._editorFocus?.set(true); if (this._webiewFocused) { this._webview?.focusWebview(); } else { const focus = this._list?.getFocus()[0]; if (typeof focus === 'number') { const element = this._notebookViewModel!.viewCells[focus]; if (element.focusMode === CellFocusMode.Editor) { element.editState = CellEditState.Editing; element.focusMode = CellFocusMode.Editor; this._onDidFocusEditorWidget.fire(); return; } } this._list?.domFocus(); } this._onDidFocusEditorWidget.fire(); } async setModel(textModel: NotebookTextModel, viewState: INotebookEditorViewState | undefined): Promise<void> { if (this._notebookViewModel === undefined || !this._notebookViewModel.equal(textModel)) { this._detachModel(); await this._attachModel(textModel, viewState); } else { this.restoreListViewState(viewState); } // clear state this._dndController?.clearGlobalDragState(); this._setKernels(textModel); this._localStore.add(this.notebookService.onDidChangeKernels(() => { if (this.activeKernel === undefined) { this._setKernels(textModel); } })); this._localStore.add(this._list!.onDidChangeFocus(() => { const focused = this._list!.getFocusedElements()[0]; if (focused) { if (!this._cellContextKeyManager) { this._cellContextKeyManager = this._localStore.add(new CellContextKeyManager(this.contextKeyService, textModel, focused as CellViewModel)); } this._cellContextKeyManager.updateForElement(focused as CellViewModel); } })); } async setOptions(options: NotebookEditorOptions | undefined) { // reveal cell if editor options tell to do so if (options?.cellOptions) { const cellOptions = options.cellOptions; const cell = this._notebookViewModel!.viewCells.find(cell => cell.uri.toString() === cellOptions.resource.toString()); if (cell) { this.selectElement(cell); this.revealInCenterIfOutsideViewport(cell); const editor = this._renderedEditors.get(cell)!; if (editor) { if (cellOptions.options?.selection) { const { selection } = cellOptions.options; editor.setSelection({ ...selection, endLineNumber: selection.endLineNumber || selection.startLineNumber, endColumn: selection.endColumn || selection.startColumn }); editor.revealPositionInCenterIfOutsideViewport({ lineNumber: selection.startLineNumber, column: selection.startColumn }); } if (!cellOptions.options?.preserveFocus) { editor.focus(); } } } } else if (this._notebookViewModel && this._notebookViewModel.viewCells.length === 1 && this._notebookViewModel.viewCells[0].cellKind === CellKind.Code) { // there is only one code cell in the document const cell = this._notebookViewModel!.viewCells[0]; if (cell.getTextLength() === 0) { // the cell is empty, very likely a template cell, focus it this.selectElement(cell); await this.revealLineInCenterAsync(cell, 1); const editor = this._renderedEditors.get(cell)!; if (editor) { editor.focus(); } } } } private _detachModel() { this._localStore.clear(); this._list?.detachViewModel(); this.viewModel?.dispose(); // avoid event this._notebookViewModel = undefined; // this.webview?.clearInsets(); // this.webview?.clearPreloadsCache(); this._webview?.dispose(); this._webview?.element.remove(); this._webview = null; this._list?.clear(); } private _setKernels(textModel: NotebookTextModel) { const provider = this.notebookService.getContributedNotebookProviders(this.viewModel!.uri)[0]; const availableKernels = this.notebookService.getContributedNotebookKernels(textModel.viewType, textModel.uri); if (provider.kernel && availableKernels.length > 0) { this._notebookHasMultipleKernels!.set(true); } else if (availableKernels.length > 1) { this._notebookHasMultipleKernels!.set(true); } else { this._notebookHasMultipleKernels!.set(false); } if (provider && provider.kernel) { // it has a builtin kernel, don't automatically choose a kernel this._loadKernelPreloads(provider.providerExtensionLocation, provider.kernel); return; } // the provider doesn't have a builtin kernel, choose a kernel this.activeKernel = availableKernels[0]; if (this.activeKernel) { this._loadKernelPreloads(this.activeKernel.extensionLocation, this.activeKernel); } } private _loadKernelPreloads(extensionLocation: URI, kernel: INotebookKernelInfoDto) { if (kernel.preloads) { this._webview?.updateKernelPreloads([extensionLocation], kernel.preloads.map(preload => URI.revive(preload))); } } private _updateForMetadata(): void { this._editorEditable?.set(!!this.viewModel!.metadata?.editable); this._editorRunnable?.set(!!this.viewModel!.metadata?.runnable); DOM.toggleClass(this._overlayContainer, 'notebook-editor-editable', !!this.viewModel!.metadata?.editable); DOM.toggleClass(this.getDomNode(), 'notebook-editor-editable', !!this.viewModel!.metadata?.editable); } private async _createWebview(id: string, resource: URI): Promise<void> { this._webview = this.instantiationService.createInstance(BackLayerWebView, this, id, resource); // attach the webview container to the DOM tree first this._list?.rowsContainer.insertAdjacentElement('afterbegin', this._webview.element); await this._webview.createWebview(); this._webview.webview.onDidBlur(() => { this._outputFocus?.set(false); this.updateEditorFocus(); if (this._overlayContainer.contains(document.activeElement)) { this._webiewFocused = false; } }); this._webview.webview.onDidFocus(() => { this._outputFocus?.set(true); this.updateEditorFocus(); this._onDidFocusEmitter.fire(); if (this._overlayContainer.contains(document.activeElement)) { this._webiewFocused = true; } }); this._localStore.add(this._webview.onMessage(({ message, forRenderer }) => { if (this.viewModel) { this.notebookService.onDidReceiveMessage(this.viewModel.viewType, this.getId(), forRenderer, message); } })); } private async _attachModel(textModel: NotebookTextModel, viewState: INotebookEditorViewState | undefined) { await this._createWebview(this.getId(), textModel.uri); this._eventDispatcher = new NotebookEventDispatcher(); this.viewModel = this.instantiationService.createInstance(NotebookViewModel, textModel.viewType, textModel, this._eventDispatcher, this.getLayoutInfo()); this._eventDispatcher.emit([new NotebookLayoutChangedEvent({ width: true, fontInfo: true }, this.getLayoutInfo())]); this._updateForMetadata(); this._localStore.add(this._eventDispatcher.onDidChangeMetadata(() => { this._updateForMetadata(); })); // restore view states, including contributions { // restore view state this.viewModel.restoreEditorViewState(viewState); // contribution state restore const contributionsState = viewState?.contributionsState || {}; const keys = Object.keys(this._contributions); for (let i = 0, len = keys.length; i < len; i++) { const id = keys[i]; const contribution = this._contributions[id]; if (typeof contribution.restoreViewState === 'function') { contribution.restoreViewState(contributionsState[id]); } } } this._webview?.updateRendererPreloads(this.viewModel.renderers); this._localStore.add(this._list!.onWillScroll(e => { this._webview!.updateViewScrollTop(-e.scrollTop, []); this._webviewTransparentCover!.style.top = `${e.scrollTop}px`; })); this._localStore.add(this._list!.onDidChangeContentHeight(() => { DOM.scheduleAtNextAnimationFrame(() => { if (this._isDisposed) { return; } const scrollTop = this._list?.scrollTop || 0; const scrollHeight = this._list?.scrollHeight || 0; this._webview!.element.style.height = `${scrollHeight}px`; if (this._webview?.insetMapping) { let updateItems: { cell: CodeCellViewModel, output: IProcessedOutput, cellTop: number }[] = []; let removedItems: IProcessedOutput[] = []; this._webview?.insetMapping.forEach((value, key) => { const cell = value.cell; const viewIndex = this._list?.getViewIndex(cell); if (viewIndex === undefined) { return; } if (cell.outputs.indexOf(key) < 0) { // output is already gone removedItems.push(key); } const cellTop = this._list?.getAbsoluteTopOfElement(cell) || 0; if (this._webview!.shouldUpdateInset(cell, key, cellTop)) { updateItems.push({ cell: cell, output: key, cellTop: cellTop }); } }); removedItems.forEach(output => this._webview?.removeInset(output)); if (updateItems.length) { this._webview?.updateViewScrollTop(-scrollTop, updateItems); } } }); })); this._list!.attachViewModel(this.viewModel); this._localStore.add(this._list!.onDidRemoveOutput(output => { this.removeInset(output); })); this._localStore.add(this._list!.onDidHideOutput(output => { this.hideInset(output); })); this._list!.layout(); this._dndController?.clearGlobalDragState(); // restore list state at last, it must be after list layout this.restoreListViewState(viewState); } restoreListViewState(viewState: INotebookEditorViewState | undefined): void { if (viewState?.scrollPosition !== undefined) { this._list!.scrollTop = viewState!.scrollPosition.top; this._list!.scrollLeft = viewState!.scrollPosition.left; } else { this._list!.scrollTop = 0; this._list!.scrollLeft = 0; } const focusIdx = typeof viewState?.focus === 'number' ? viewState.focus : 0; if (focusIdx < this._list!.length) { this._list!.setFocus([focusIdx]); this._list!.setSelection([focusIdx]); } else if (this._list!.length > 0) { this._list!.setFocus([0]); } if (viewState?.editorFocused) { this._list?.focusView(); const cell = this._notebookViewModel?.viewCells[focusIdx]; if (cell) { cell.focusMode = CellFocusMode.Editor; } } } getEditorViewState(): INotebookEditorViewState { const state = this._notebookViewModel?.getEditorViewState(); if (!state) { return { editingCells: {}, editorViewStates: {} }; } if (this._list) { state.scrollPosition = { left: this._list.scrollLeft, top: this._list.scrollTop }; let cellHeights: { [key: number]: number } = {}; for (let i = 0; i < this.viewModel!.length; i++) { const elm = this.viewModel!.viewCells[i] as CellViewModel; if (elm.cellKind === CellKind.Code) { cellHeights[i] = elm.layoutInfo.totalHeight; } else { cellHeights[i] = 0; } } state.cellTotalHeights = cellHeights; const focus = this._list.getFocus()[0]; if (typeof focus === 'number') { const element = this._notebookViewModel!.viewCells[focus]; if (element) { const itemDOM = this._list?.domElementOfElement(element); let editorFocused = !!(document.activeElement && itemDOM && itemDOM.contains(document.activeElement)); state.editorFocused = editorFocused; state.focus = focus; } } } // Save contribution view states const contributionsState: { [key: string]: unknown } = {}; const keys = Object.keys(this._contributions); for (const id of keys) { const contribution = this._contributions[id]; if (typeof contribution.saveViewState === 'function') { contributionsState[id] = contribution.saveViewState(); } } state.contributionsState = contributionsState; return state; } // private saveEditorViewState(input: NotebookEditorInput): void { // if (this.group && this.notebookViewModel) { // } // } // private loadTextEditorViewState(): INotebookEditorViewState | undefined { // return this.editorMemento.loadEditorState(this.group, input.resource); // } layout(dimension: DOM.Dimension, shadowElement?: HTMLElement): void { if (!shadowElement && this._shadowElementViewInfo === null) { this._dimension = dimension; return; } if (shadowElement) { const containerRect = shadowElement.getBoundingClientRect(); this._shadowElementViewInfo = { height: containerRect.height, width: containerRect.width, top: containerRect.top, left: containerRect.left }; } this._dimension = new DOM.Dimension(dimension.width, dimension.height); DOM.size(this._body, dimension.width, dimension.height); this._list?.updateOptions({ additionalScrollHeight: this._scrollBeyondLastLine ? dimension.height - SCROLLABLE_ELEMENT_PADDING_TOP : 0 }); this._list?.layout(dimension.height - SCROLLABLE_ELEMENT_PADDING_TOP, dimension.width); this._overlayContainer.style.visibility = 'visible'; this._overlayContainer.style.display = 'block'; this._overlayContainer.style.position = 'absolute'; this._overlayContainer.style.top = `${this._shadowElementViewInfo!.top}px`; this._overlayContainer.style.left = `${this._shadowElementViewInfo!.left}px`; this._overlayContainer.style.width = `${dimension ? dimension.width : this._shadowElementViewInfo!.width}px`; this._overlayContainer.style.height = `${dimension ? dimension.height : this._shadowElementViewInfo!.height}px`; if (this._webviewTransparentCover) { this._webviewTransparentCover.style.height = `${dimension.height}px`; this._webviewTransparentCover.style.width = `${dimension.width}px`; } this._eventDispatcher?.emit([new NotebookLayoutChangedEvent({ width: true, fontInfo: true }, this.getLayoutInfo())]); } // protected saveState(): void { // if (this.input instanceof NotebookEditorInput) { // this.saveEditorViewState(this.input); // } // super.saveState(); // } //#endregion //#region Editor Features selectElement(cell: ICellViewModel) { this._list?.selectElement(cell); // this.viewModel!.selectionHandles = [cell.handle]; } revealInView(cell: ICellViewModel) { this._list?.revealElementInView(cell); } revealInCenterIfOutsideViewport(cell: ICellViewModel) { this._list?.revealElementInCenterIfOutsideViewport(cell); } revealInCenter(cell: ICellViewModel) { this._list?.revealElementInCenter(cell); } async revealLineInViewAsync(cell: ICellViewModel, line: number): Promise<void> { return this._list?.revealElementLineInViewAsync(cell, line); } async revealLineInCenterAsync(cell: ICellViewModel, line: number): Promise<void> { return this._list?.revealElementLineInCenterAsync(cell, line); } async revealLineInCenterIfOutsideViewportAsync(cell: ICellViewModel, line: number): Promise<void> { return this._list?.revealElementLineInCenterIfOutsideViewportAsync(cell, line); } async revealRangeInViewAsync(cell: ICellViewModel, range: Range): Promise<void> { return this._list?.revealElementRangeInViewAsync(cell, range); } async revealRangeInCenterAsync(cell: ICellViewModel, range: Range): Promise<void> { return this._list?.revealElementRangeInCenterAsync(cell, range); } async revealRangeInCenterIfOutsideViewportAsync(cell: ICellViewModel, range: Range): Promise<void> { return this._list?.revealElementRangeInCenterIfOutsideViewportAsync(cell, range); } setCellSelection(cell: ICellViewModel, range: Range): void { this._list?.setCellSelection(cell, range); } changeDecorations<T>(callback: (changeAccessor: IModelDecorationsChangeAccessor) => T): T | null { return this._notebookViewModel?.changeDecorations<T>(callback) || null; } setHiddenAreas(_ranges: ICellRange[]): boolean { return this._list!.setHiddenAreas(_ranges, true); } //#endregion //#region Mouse Events private readonly _onMouseUp: Emitter<INotebookEditorMouseEvent> = this._register(new Emitter<INotebookEditorMouseEvent>()); public readonly onMouseUp: Event<INotebookEditorMouseEvent> = this._onMouseUp.event; private readonly _onMouseDown: Emitter<INotebookEditorMouseEvent> = this._register(new Emitter<INotebookEditorMouseEvent>()); public readonly onMouseDown: Event<INotebookEditorMouseEvent> = this._onMouseDown.event; private pendingLayouts = new WeakMap<ICellViewModel, IDisposable>(); //#endregion //#region Cell operations async layoutNotebookCell(cell: ICellViewModel, height: number): Promise<void> { const viewIndex = this._list!.getViewIndex(cell); if (viewIndex === undefined) { // the cell is hidden return; } let relayout = (cell: ICellViewModel, height: number) => { if (this._isDisposed) { return; } this._list?.updateElementHeight2(cell, height); }; if (this.pendingLayouts.has(cell)) { this.pendingLayouts.get(cell)!.dispose(); } let r: () => void; const layoutDisposable = DOM.scheduleAtNextAnimationFrame(() => { if (this._isDisposed) { return; } this.pendingLayouts.delete(cell); relayout(cell, height); r(); }); this.pendingLayouts.set(cell, toDisposable(() => { layoutDisposable.dispose(); r(); })); return new Promise(resolve => { r = resolve; }); } insertNotebookCell(cell: ICellViewModel | undefined, type: CellKind, direction: 'above' | 'below' = 'above', initialText: string = '', ui: boolean = false): CellViewModel | null { if (!this._notebookViewModel!.metadata.editable) { return null; } const index = cell ? this._notebookViewModel!.getCellIndex(cell) : 0; const nextIndex = ui ? this._notebookViewModel!.getNextVisibleCellIndex(index) : index + 1; const newLanguages = this._notebookViewModel!.languages; const language = (cell?.cellKind === CellKind.Code && type === CellKind.Code) ? cell.language : ((type === CellKind.Code && newLanguages && newLanguages.length) ? newLanguages[0] : 'markdown'); const insertIndex = cell ? (direction === 'above' ? index : nextIndex) : index; const newCell = this._notebookViewModel!.createCell(insertIndex, initialText.split(/\r?\n/g), language, type, undefined, true); return newCell as CellViewModel; } async splitNotebookCell(cell: ICellViewModel): Promise<CellViewModel[] | null> { const index = this._notebookViewModel!.getCellIndex(cell); return this._notebookViewModel!.splitNotebookCell(index); } async joinNotebookCells(cell: ICellViewModel, direction: 'above' | 'below', constraint?: CellKind): Promise<ICellViewModel | null> { const index = this._notebookViewModel!.getCellIndex(cell); const ret = await this._notebookViewModel!.joinNotebookCells(index, direction, constraint); if (ret) { ret.deletedCells.forEach(cell => { if (this.pendingLayouts.has(cell)) { this.pendingLayouts.get(cell)!.dispose(); } }); return ret.cell; } else { return null; } } async deleteNotebookCell(cell: ICellViewModel): Promise<boolean> { if (!this._notebookViewModel!.metadata.editable) { return false; } if (this.pendingLayouts.has(cell)) { this.pendingLayouts.get(cell)!.dispose(); } const index = this._notebookViewModel!.getCellIndex(cell); this._notebookViewModel!.deleteCell(index, true); return true; } async moveCellDown(cell: ICellViewModel): Promise<ICellViewModel | null> { if (!this._notebookViewModel!.metadata.editable) { return null; } const index = this._notebookViewModel!.getCellIndex(cell); if (index === this._notebookViewModel!.length - 1) { return null; } const newIdx = index + 1; return this._moveCellToIndex(index, newIdx); } async moveCellUp(cell: ICellViewModel): Promise<ICellViewModel | null> { if (!this._notebookViewModel!.metadata.editable) { return null; } const index = this._notebookViewModel!.getCellIndex(cell); if (index === 0) { return null; } const newIdx = index - 1; return this._moveCellToIndex(index, newIdx); } async moveCell(cell: ICellViewModel, relativeToCell: ICellViewModel, direction: 'above' | 'below'): Promise<ICellViewModel | null> { if (!this._notebookViewModel!.metadata.editable) { return null; } if (cell === relativeToCell) { return null; } const originalIdx = this._notebookViewModel!.getCellIndex(cell); const relativeToIndex = this._notebookViewModel!.getCellIndex(relativeToCell); let newIdx = direction === 'above' ? relativeToIndex : relativeToIndex + 1; if (originalIdx < newIdx) { newIdx--; } return this._moveCellToIndex(originalIdx, newIdx); } private async _moveCellToIndex(index: number, newIdx: number): Promise<ICellViewModel | null> { if (index === newIdx) { return null; } if (!this._notebookViewModel!.moveCellToIdx(index, newIdx, true)) { throw new Error('Notebook Editor move cell, index out of range'); } let r: (val: ICellViewModel | null) => void; DOM.scheduleAtNextAnimationFrame(() => { if (this._isDisposed) { r(null); } const viewCell = this._notebookViewModel!.viewCells[newIdx]; this._list?.revealElementInView(viewCell); r(viewCell); }); return new Promise(resolve => { r = resolve; }); } editNotebookCell(cell: CellViewModel): void { if (!cell.getEvaluatedMetadata(this._notebookViewModel!.metadata).editable) { return; } cell.editState = CellEditState.Editing; this._renderedEditors.get(cell)?.focus(); } getActiveCell() { let elements = this._list?.getFocusedElements(); if (elements && elements.length) { return elements[0]; } return undefined; } cancelNotebookExecution(): void { if (!this._notebookViewModel!.currentTokenSource) { throw new Error('Notebook is not executing'); } this._notebookViewModel!.currentTokenSource.cancel(); this._notebookViewModel!.currentTokenSource = undefined; } async executeNotebook(): Promise<void> { if (!this._notebookViewModel!.metadata.runnable) { return; } return this._executeNotebook(); } async _executeNotebook(): Promise<void> { if (this._notebookViewModel!.currentTokenSource) { return; } const tokenSource = new CancellationTokenSource(); try { this._editorExecutingNotebook!.set(true); this._notebookViewModel!.currentTokenSource = tokenSource; const provider = this.notebookService.getContributedNotebookProviders(this.viewModel!.uri)[0]; if (provider) { const viewType = provider.id; const notebookUri = this._notebookViewModel!.uri; if (this._activeKernel) { await this.notebookService.executeNotebook2(this._notebookViewModel!.viewType, this._notebookViewModel!.uri, this._activeKernel.id, tokenSource.token); } else if (provider.kernel) { return await this.notebookService.executeNotebook(viewType, notebookUri, true, tokenSource.token); } else { return await this.notebookService.executeNotebook(viewType, notebookUri, false, tokenSource.token); } } } finally { this._editorExecutingNotebook!.set(false); this._notebookViewModel!.currentTokenSource = undefined; tokenSource.dispose(); } } cancelNotebookCellExecution(cell: ICellViewModel): void { if (!cell.currentTokenSource) { throw new Error('Cell is not executing'); } cell.currentTokenSource.cancel(); cell.currentTokenSource = undefined; } async executeNotebookCell(cell: ICellViewModel): Promise<void> { if (cell.cellKind === CellKind.Markdown) { this.focusNotebookCell(cell, 'container'); return; } if (!cell.getEvaluatedMetadata(this._notebookViewModel!.metadata).runnable) { return; } const tokenSource = new CancellationTokenSource(); try { await this._executeNotebookCell(cell, tokenSource); } finally { tokenSource.dispose(); } } private async _executeNotebookCell(cell: ICellViewModel, tokenSource: CancellationTokenSource): Promise<void> { try { cell.currentTokenSource = tokenSource; const provider = this.notebookService.getContributedNotebookProviders(this.viewModel!.uri)[0]; if (provider) { const viewType = provider.id; const notebookUri = this._notebookViewModel!.uri; if (this._activeKernel) { return await this.notebookService.executeNotebookCell2(viewType, notebookUri, cell.handle, this._activeKernel.id, tokenSource.token); } else if (provider.kernel) { return await this.notebookService.executeNotebookCell(viewType, notebookUri, cell.handle, true, tokenSource.token); } else { return await this.notebookService.executeNotebookCell(viewType, notebookUri, cell.handle, false, tokenSource.token); } } } finally { cell.currentTokenSource = undefined; } } focusNotebookCell(cell: ICellViewModel, focusItem: 'editor' | 'container' | 'output') { if (this._isDisposed) { return; } if (focusItem === 'editor') { this.selectElement(cell); this._list?.focusView(); cell.editState = CellEditState.Editing; cell.focusMode = CellFocusMode.Editor; this.revealInCenterIfOutsideViewport(cell); } else if (focusItem === 'output') { this.selectElement(cell); this._list?.focusView(); if (!this._webview) { return; } this._webview.focusOutput(cell.id); cell.editState = CellEditState.Preview; cell.focusMode = CellFocusMode.Container; this.revealInCenterIfOutsideViewport(cell); } else { let itemDOM = this._list?.domElementOfElement(cell); if (document.activeElement && itemDOM && itemDOM.contains(document.activeElement)) { (document.activeElement as HTMLElement).blur(); } cell.editState = CellEditState.Preview; cell.focusMode = CellFocusMode.Container; this.selectElement(cell); this.revealInCenterIfOutsideViewport(cell); this._list?.focusView(); } } //#endregion //#region MISC getLayoutInfo(): NotebookLayoutInfo { if (!this._list) { throw new Error('Editor is not initalized successfully'); } return { width: this._dimension!.width, height: this._dimension!.height, fontInfo: this._fontInfo! }; } triggerScroll(event: IMouseWheelEvent) { this._list?.triggerScrollFromMouseWheelEvent(event); } async createInset(cell: CodeCellViewModel, output: IProcessedOutput, shadowContent: string, offset: number) { if (!this._webview) { return; } let preloads = this._notebookViewModel!.renderers; if (!this._webview!.insetMapping.has(output)) { let cellTop = this._list?.getAbsoluteTopOfElement(cell) || 0; await this._webview!.createInset(cell, output, cellTop, offset, shadowContent, preloads); } else { let cellTop = this._list?.getAbsoluteTopOfElement(cell) || 0; let scrollTop = this._list?.scrollTop || 0; this._webview!.updateViewScrollTop(-scrollTop, [{ cell: cell, output: output, cellTop: cellTop }]); } } removeInset(output: IProcessedOutput) { if (!this._webview) { return; } this._webview!.removeInset(output); } hideInset(output: IProcessedOutput) { if (!this._webview) { return; } this._webview!.hideInset(output); } getOutputRenderer(): OutputRenderer { return this._outputRenderer; } postMessage(forRendererId: string | undefined, message: any) { if (forRendererId === undefined) { this._webview?.webview.postMessage(message); } else { this._webview?.postRendererMessage(forRendererId, message); } } toggleClassName(className: string) { DOM.toggleClass(this._overlayContainer, className); } addClassName(className: string) { DOM.addClass(this._overlayContainer, className); } removeClassName(className: string) { DOM.removeClass(this._overlayContainer, className); } //#endregion //#region Editor Contributions public getContribution<T extends INotebookEditorContribution>(id: string): T { return <T>(this._contributions[id] || null); } //#endregion dispose() { this._isDisposed = true; // dispose webview first this._webview?.dispose(); this.notebookService.removeNotebookEditor(this); const keys = Object.keys(this._contributions); for (let i = 0, len = keys.length; i < len; i++) { const contributionId = keys[i]; this._contributions[contributionId].dispose(); } this._localStore.clear(); this._list?.dispose(); this._overlayContainer.remove(); this.viewModel?.dispose(); // this._layoutService.container.removeChild(this.overlayContainer); super.dispose(); } toJSON(): object { return { notebookHandle: this.viewModel?.handle }; } } export const notebookCellBorder = registerColor('notebook.cellBorderColor', { dark: transparent(PANEL_BORDER, .4), light: transparent(listInactiveSelectionBackground, 1), hc: PANEL_BORDER }, nls.localize('notebook.cellBorderColor', "The border color for notebook cells.")); export const focusedEditorBorderColor = registerColor('notebook.focusedEditorBorder', { light: focusBorder, dark: focusBorder, hc: focusBorder }, nls.localize('notebook.focusedEditorBorder', "The color of the notebook cell editor border.")); export const cellStatusIconSuccess = registerColor('notebookStatusSuccessIcon.foreground', { light: debugIconStartForeground, dark: debugIconStartForeground, hc: debugIconStartForeground }, nls.localize('notebookStatusSuccessIcon.foreground', "The error icon color of notebook cells in the cell status bar.")); export const cellStatusIconError = registerColor('notebookStatusErrorIcon.foreground', { light: errorForeground, dark: errorForeground, hc: errorForeground }, nls.localize('notebookStatusErrorIcon.foreground', "The error icon color of notebook cells in the cell status bar.")); export const cellStatusIconRunning = registerColor('notebookStatusRunningIcon.foreground', { light: foreground, dark: foreground, hc: foreground }, nls.localize('notebookStatusRunningIcon.foreground', "The running icon color of notebook cells in the cell status bar.")); export const notebookOutputContainerColor = registerColor('notebook.outputContainerBackgroundColor', { dark: notebookCellBorder, light: transparent(listFocusBackground, .4), hc: null }, nls.localize('notebook.outputContainerBackgroundColor', "The Color of the notebook output container background.")); // TODO currently also used for toolbar border, if we keep all of this, pick a generic name export const CELL_TOOLBAR_SEPERATOR = registerColor('notebook.cellToolbarSeperator', { dark: Color.fromHex('#808080').transparent(0.35), light: Color.fromHex('#808080').transparent(0.35), hc: contrastBorder }, nls.localize('notebook.cellToolbarSeperator', "The color of the seperator in the cell bottom toolbar")); export const focusedCellBackground = registerColor('notebook.focusedCellBackground', { dark: transparent(PANEL_BORDER, .4), light: transparent(listFocusBackground, .4), hc: null }, nls.localize('focusedCellBackground', "The background color of a cell when the cell is focused.")); export const cellHoverBackground = registerColor('notebook.cellHoverBackground', { dark: transparent(focusedCellBackground, .5), light: transparent(focusedCellBackground, .7), hc: null }, nls.localize('notebook.cellHoverBackground', "The background color of a cell when the cell is hovered.")); export const focusedCellBorder = registerColor('notebook.focusedCellBorder', { dark: Color.white.transparent(0.12), light: Color.black.transparent(0.12), hc: focusBorder }, nls.localize('notebook.focusedCellBorder', "The color of the cell's top and bottom border when the cell is focused.")); export const focusedCellShadow = registerColor('notebook.focusedCellShadow', { dark: transparent(widgetShadow, 0.6), light: transparent(widgetShadow, 0.4), hc: Color.transparent }, nls.localize('notebook.focusedCellShadow', "The color of the cell shadow when cells are focused.")); export const cellStatusBarItemHover = registerColor('notebook.cellStatusBarItemHoverBackground', { light: new Color(new RGBA(0, 0, 0, 0.08)), dark: new Color(new RGBA(255, 255, 255, 0.15)), hc: new Color(new RGBA(255, 255, 255, 0.15)), }, nls.localize('notebook.cellStatusBarItemHoverBackground', "The background color of notebook cell status bar items.")); export const cellInsertionIndicator = registerColor('notebook.cellInsertionIndicator', { light: focusBorder, dark: focusBorder, hc: focusBorder }, nls.localize('notebook.cellInsertionIndicator', "The color of the notebook cell insertion indicator.")); export const listScrollbarSliderBackground = registerColor('notebookScrollbarSlider.background', { dark: scrollbarSliderBackground, light: scrollbarSliderBackground, hc: scrollbarSliderBackground }, nls.localize('notebookScrollbarSliderBackground', "Notebook scrollbar slider background color.")); export const listScrollbarSliderHoverBackground = registerColor('notebookScrollbarSlider.hoverBackground', { dark: scrollbarSliderHoverBackground, light: scrollbarSliderHoverBackground, hc: scrollbarSliderHoverBackground }, nls.localize('notebookScrollbarSliderHoverBackground', "Notebook scrollbar slider background color when hovering.")); export const listScrollbarSliderActiveBackground = registerColor('notebookScrollbarSlider.activeBackground', { dark: scrollbarSliderActiveBackground, light: scrollbarSliderActiveBackground, hc: scrollbarSliderActiveBackground }, nls.localize('notebookScrollbarSliderActiveBackground', "Notebook scrollbar slider background color when clicked on.")); registerThemingParticipant((theme, collector) => { collector.addRule(`.notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element { padding-top: ${SCROLLABLE_ELEMENT_PADDING_TOP}px; box-sizing: border-box; }`); // const color = getExtraColor(theme, embeddedEditorBackground, { dark: 'rgba(0, 0, 0, .4)', extra_dark: 'rgba(200, 235, 255, .064)', light: '#f4f4f4', hc: null }); const color = theme.getColor(editorBackground); if (color) { collector.addRule(`.notebookOverlay .cell .monaco-editor-background, .notebookOverlay .cell .margin-view-overlays, .notebookOverlay .cell .cell-statusbar-container { background: ${color}; }`); collector.addRule(`.notebookOverlay .cell-drag-image .cell-editor-container > div { background: ${color} !important; }`); } const link = theme.getColor(textLinkForeground); if (link) { collector.addRule(`.notebookOverlay .output a, .notebookOverlay .cell.markdown a { color: ${link};} `); } const activeLink = theme.getColor(textLinkActiveForeground); if (activeLink) { collector.addRule(`.notebookOverlay .output a:hover, .notebookOverlay .cell .output a:active { color: ${activeLink}; }`); } const shortcut = theme.getColor(textPreformatForeground); if (shortcut) { collector.addRule(`.notebookOverlay code, .notebookOverlay .shortcut { color: ${shortcut}; }`); } const border = theme.getColor(contrastBorder); if (border) { collector.addRule(`.notebookOverlay .monaco-editor { border-color: ${border}; }`); } const quoteBackground = theme.getColor(textBlockQuoteBackground); if (quoteBackground) { collector.addRule(`.notebookOverlay blockquote { background: ${quoteBackground}; }`); } const quoteBorder = theme.getColor(textBlockQuoteBorder); if (quoteBorder) { collector.addRule(`.notebookOverlay blockquote { border-color: ${quoteBorder}; }`); } const containerBackground = theme.getColor(notebookOutputContainerColor); if (containerBackground) { collector.addRule(`.notebookOverlay .output { background-color: ${containerBackground}; }`); collector.addRule(`.notebookOverlay .output-element { background-color: ${containerBackground}; }`); } const editorBackgroundColor = theme.getColor(editorBackground); if (editorBackgroundColor) { collector.addRule(`.notebookOverlay .cell-statusbar-container { border-top: solid 1px ${editorBackgroundColor}; }`); collector.addRule(`.notebookOverlay .monaco-list-row > .monaco-toolbar { background-color: ${editorBackgroundColor}; }`); collector.addRule(`.notebookOverlay .monaco-list-row.cell-drag-image { background-color: ${editorBackgroundColor}; }`); } const cellToolbarSeperator = theme.getColor(CELL_TOOLBAR_SEPERATOR); if (cellToolbarSeperator) { collector.addRule(`.notebookOverlay .cell-bottom-toolbar-container .separator { background-color: ${cellToolbarSeperator} }`); collector.addRule(`.notebookOverlay .cell-bottom-toolbar-container .action-item:first-child::after { background-color: ${cellToolbarSeperator} }`); collector.addRule(`.notebookOverlay .monaco-list-row > .monaco-toolbar { border: solid 1px ${cellToolbarSeperator}; }`); } const focusedCellBackgroundColor = theme.getColor(focusedCellBackground); if (focusedCellBackgroundColor) { collector.addRule(`.notebookOverlay .code-cell-row.focused .cell-focus-indicator, .notebookOverlay .markdown-cell-row.focused { background-color: ${focusedCellBackgroundColor} !important; }`); } const cellHoverBackgroundColor = theme.getColor(cellHoverBackground); if (cellHoverBackgroundColor) { collector.addRule(`.notebookOverlay .code-cell-row:not(.focused):hover .cell-focus-indicator, .notebookOverlay .code-cell-row:not(.focused).cell-output-hover .cell-focus-indicator, .notebookOverlay .markdown-cell-row:not(.focused):hover { background-color: ${cellHoverBackgroundColor} !important; }`); } const focusedCellBorderColor = theme.getColor(focusedCellBorder); collector.addRule(`.monaco-workbench .notebookOverlay .monaco-list .monaco-list-row.focused .cell-focus-indicator-top:before, .monaco-workbench .notebookOverlay .monaco-list .monaco-list-row.focused .cell-focus-indicator-bottom:before, .monaco-workbench .notebookOverlay .monaco-list .markdown-cell-row.focused:before, .monaco-workbench .notebookOverlay .monaco-list .markdown-cell-row.focused:after { border-color: ${focusedCellBorderColor} !important; }`); const focusedEditorBorderColorColor = theme.getColor(focusedEditorBorderColor); if (focusedEditorBorderColorColor) { collector.addRule(`.notebookOverlay .monaco-list-row.cell-editor-focus .cell-editor-part:before { outline: solid 1px ${focusedEditorBorderColorColor}; }`); } const editorBorderColor = theme.getColor(notebookCellBorder); if (editorBorderColor) { collector.addRule(`.notebookOverlay .monaco-list-row .cell-editor-part:before { outline: solid 1px ${editorBorderColor}; }`); } const headingBorderColor = theme.getColor(notebookCellBorder); if (headingBorderColor) { collector.addRule(`.notebookOverlay .cell.markdown h1 { border-color: ${headingBorderColor}; }`); } const cellStatusSuccessIcon = theme.getColor(cellStatusIconSuccess); if (cellStatusSuccessIcon) { collector.addRule(`.monaco-workbench .notebookOverlay .cell-statusbar-container .cell-run-status .codicon-check { color: ${cellStatusSuccessIcon} }`); } const cellStatusErrorIcon = theme.getColor(cellStatusIconError); if (cellStatusErrorIcon) { collector.addRule(`.monaco-workbench .notebookOverlay .cell-statusbar-container .cell-run-status .codicon-error { color: ${cellStatusErrorIcon} }`); } const cellStatusRunningIcon = theme.getColor(cellStatusIconRunning); if (cellStatusRunningIcon) { collector.addRule(`.monaco-workbench .notebookOverlay .cell-statusbar-container .cell-run-status .codicon-sync { color: ${cellStatusRunningIcon} }`); } const cellStatusBarHoverBg = theme.getColor(cellStatusBarItemHover); if (cellStatusBarHoverBg) { collector.addRule(`.monaco-workbench .notebookOverlay .cell-statusbar-container .cell-language-picker:hover { background-color: ${cellStatusBarHoverBg}; }`); } const cellShadowColor = theme.getColor(focusedCellShadow); if (cellShadowColor) { // Code cells collector.addRule(`.monaco-workbench .notebookOverlay .monaco-list .monaco-list-row.focused .cell-shadow { box-shadow: 0px 0px 4px 2px ${cellShadowColor} }`); // Markdown cells collector.addRule(`.monaco-workbench .notebookOverlay .monaco-list .markdown-cell-row.focused { box-shadow: 0px 0px 4px 2px ${cellShadowColor} }`); } const cellInsertionIndicatorColor = theme.getColor(cellInsertionIndicator); if (cellInsertionIndicatorColor) { collector.addRule(`.notebookOverlay > .cell-list-container > .cell-list-insertion-indicator { background-color: ${cellInsertionIndicatorColor}; }`); } const scrollbarSliderBackgroundColor = theme.getColor(listScrollbarSliderBackground); if (scrollbarSliderBackgroundColor) { collector.addRule(` .notebookOverlay .cell-list-container > .monaco-list > .monaco-scrollable-element > .scrollbar > .slider { background: ${editorBackgroundColor}; } `); collector.addRule(` .notebookOverlay .cell-list-container > .monaco-list > .monaco-scrollable-element > .scrollbar > .slider:before { content: ""; width: 100%; height: 100%; position: absolute; background: ${scrollbarSliderBackgroundColor}; } `); /* hack to not have cells see through scroller */ } const scrollbarSliderHoverBackgroundColor = theme.getColor(listScrollbarSliderHoverBackground); if (scrollbarSliderHoverBackgroundColor) { collector.addRule(` .notebookOverlay .cell-list-container > .monaco-list > .monaco-scrollable-element > .scrollbar > .slider:hover { background: ${editorBackgroundColor}; } `); collector.addRule(` .notebookOverlay .cell-list-container > .monaco-list > .monaco-scrollable-element > .scrollbar > .slider:hover:before { content: ""; width: 100%; height: 100%; position: absolute; background: ${scrollbarSliderHoverBackgroundColor}; } `); /* hack to not have cells see through scroller */ } const scrollbarSliderActiveBackgroundColor = theme.getColor(listScrollbarSliderActiveBackground); if (scrollbarSliderActiveBackgroundColor) { collector.addRule(` .notebookOverlay .cell-list-container > .monaco-list > .monaco-scrollable-element > .scrollbar > .slider.active { background: ${editorBackgroundColor}; } `); collector.addRule(` .notebookOverlay .cell-list-container > .monaco-list > .monaco-scrollable-element > .scrollbar > .slider.active:before { content: ""; width: 100%; height: 100%; position: absolute; background: ${scrollbarSliderActiveBackgroundColor}; } `); /* hack to not have cells see through scroller */ } // Cell Margin collector.addRule(`.notebookOverlay .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row > div.cell { margin: 0px ${CELL_MARGIN * 2}px 0px ${CELL_MARGIN}px; }`); collector.addRule(`.notebookOverlay .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row > div.cell.code { margin-left: ${CODE_CELL_LEFT_MARGIN}px; }`); collector.addRule(`.notebookOverlay .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row { padding-top: ${EDITOR_TOP_MARGIN}px; }`); collector.addRule(`.notebookOverlay .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .markdown-cell-row { padding-bottom: ${CELL_BOTTOM_MARGIN}px; }`); collector.addRule(`.notebookOverlay .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .markdown-cell-row .cell-bottom-toolbar-container { margin-top: ${CELL_BOTTOM_MARGIN}px; }`); collector.addRule(`.notebookOverlay .output { margin: 0px ${CELL_MARGIN}px 0px ${CODE_CELL_LEFT_MARGIN + CELL_RUN_GUTTER}px; }`); collector.addRule(`.notebookOverlay .output { width: calc(100% - ${CODE_CELL_LEFT_MARGIN + CELL_RUN_GUTTER + (CELL_MARGIN * 2)}px); }`); collector.addRule(`.notebookOverlay .cell-bottom-toolbar-container { width: calc(100% - ${CELL_MARGIN * 2 + CELL_RUN_GUTTER}px); margin: 0px ${CELL_MARGIN * 2}px 0px ${CELL_MARGIN + CELL_RUN_GUTTER}px; }`); collector.addRule(`.notebookOverlay .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row > div.cell.markdown { padding-left: ${CELL_RUN_GUTTER}px; }`); collector.addRule(`.notebookOverlay .cell .run-button-container { width: ${CELL_RUN_GUTTER}px; }`); collector.addRule(`.notebookOverlay .cell-drag-image .cell-editor-container > div { padding: ${EDITOR_TOP_PADDING}px 16px ${EDITOR_BOTTOM_PADDING}px 16px; }`); collector.addRule(`.notebookOverlay .monaco-list .monaco-list-row .cell-focus-indicator-top { height: ${EDITOR_TOP_MARGIN}px; }`); collector.addRule(`.notebookOverlay .monaco-list .monaco-list-row .cell-focus-indicator-side { bottom: ${BOTTOM_CELL_TOOLBAR_HEIGHT}px; }`); collector.addRule(`.notebookOverlay .monaco-list .monaco-list-row.code-cell-row .cell-focus-indicator-left { width: ${CODE_CELL_LEFT_MARGIN + CELL_RUN_GUTTER}px; }`); collector.addRule(`.notebookOverlay .monaco-list .monaco-list-row.markdown-cell-row .cell-focus-indicator-left { width: ${CODE_CELL_LEFT_MARGIN}px; }`); collector.addRule(`.notebookOverlay .monaco-list .monaco-list-row .cell-focus-indicator.cell-focus-indicator-right { width: ${CELL_MARGIN * 2}px; }`); collector.addRule(`.notebookOverlay .monaco-list .monaco-list-row .cell-focus-indicator-bottom { height: ${CELL_BOTTOM_MARGIN}px; }`); collector.addRule(`.notebookOverlay .monaco-list .monaco-list-row .cell-shadow-container-bottom { top: ${CELL_BOTTOM_MARGIN}px; }`); });
src/vs/workbench/contrib/notebook/browser/notebookEditorWidget.ts
1
https://github.com/microsoft/vscode/commit/9504dda6a717a0a0d45d992e21f2565f8a23f390
[ 0.009180285967886448, 0.0003899007278960198, 0.0001616188237676397, 0.00017147489415947348, 0.0008850437588989735 ]
{ "id": 8, "code_window": [ "\t\t\t\t\tthis.onCellHeightChange(realContentHeight);\n", "\t\t\t\t}\n", "\n", "\t\t\t\tif (this.notebookEditor.getActiveCell() === this.viewCell && viewCell.focusMode === CellFocusMode.Editor) {\n", "\t\t\t\t\ttemplateData.editor?.focus();\n", "\t\t\t\t}\n", "\t\t\t}\n", "\t\t});\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\tif (this.notebookEditor.getActiveCell() === this.viewCell && viewCell.focusMode === CellFocusMode.Editor && this.notebookEditor.hasFocus()) {\n" ], "file_path": "src/vs/workbench/contrib/notebook/browser/view/renderers/codeCell.ts", "type": "replace", "edit_start_line_idx": 68 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import 'vs/css!./media/notabstitlecontrol'; import { toResource, Verbosity, IEditorInput, IEditorPartOptions, SideBySideEditor } from 'vs/workbench/common/editor'; import { TitleControl, IToolbarActions } from 'vs/workbench/browser/parts/editor/titleControl'; import { ResourceLabel, IResourceLabel } from 'vs/workbench/browser/labels'; import { TAB_ACTIVE_FOREGROUND, TAB_UNFOCUSED_ACTIVE_FOREGROUND } from 'vs/workbench/common/theme'; import { EventType as TouchEventType, GestureEvent, Gesture } from 'vs/base/browser/touch'; import { addDisposableListener, EventType, addClass, EventHelper, removeClass, toggleClass, Dimension } from 'vs/base/browser/dom'; import { EDITOR_TITLE_HEIGHT } from 'vs/workbench/browser/parts/editor/editor'; import { IAction } from 'vs/base/common/actions'; import { CLOSE_EDITOR_COMMAND_ID } from 'vs/workbench/browser/parts/editor/editorCommands'; import { Color } from 'vs/base/common/color'; import { withNullAsUndefined, assertIsDefined, assertAllDefined } from 'vs/base/common/types'; interface IRenderedEditorLabel { editor?: IEditorInput; pinned: boolean; } export class NoTabsTitleControl extends TitleControl { private titleContainer: HTMLElement | undefined; private editorLabel: IResourceLabel | undefined; private activeLabel: IRenderedEditorLabel = Object.create(null); protected create(parent: HTMLElement): void { const titleContainer = this.titleContainer = parent; titleContainer.draggable = true; //Container listeners this.registerContainerListeners(titleContainer); // Gesture Support this._register(Gesture.addTarget(titleContainer)); const labelContainer = document.createElement('div'); addClass(labelContainer, 'label-container'); titleContainer.appendChild(labelContainer); // Editor Label this.editorLabel = this._register(this.instantiationService.createInstance(ResourceLabel, labelContainer, undefined)).element; this._register(addDisposableListener(this.editorLabel.element, EventType.CLICK, e => this.onTitleLabelClick(e))); // Breadcrumbs this.createBreadcrumbsControl(labelContainer, { showFileIcons: false, showSymbolIcons: true, showDecorationColors: false, breadcrumbsBackground: () => Color.transparent }); toggleClass(titleContainer, 'breadcrumbs', Boolean(this.breadcrumbsControl)); this._register({ dispose: () => removeClass(titleContainer, 'breadcrumbs') }); // import to remove because the container is a shared dom node // Right Actions Container const actionsContainer = document.createElement('div'); addClass(actionsContainer, 'title-actions'); titleContainer.appendChild(actionsContainer); // Editor actions toolbar this.createEditorActionsToolBar(actionsContainer); } private registerContainerListeners(titleContainer: HTMLElement): void { // Group dragging this.enableGroupDragging(titleContainer); // Pin on double click this._register(addDisposableListener(titleContainer, EventType.DBLCLICK, (e: MouseEvent) => this.onTitleDoubleClick(e))); // Detect mouse click this._register(addDisposableListener(titleContainer, EventType.AUXCLICK, (e: MouseEvent) => this.onTitleAuxClick(e))); // Detect touch this._register(addDisposableListener(titleContainer, TouchEventType.Tap, (e: GestureEvent) => this.onTitleTap(e))); // Context Menu this._register(addDisposableListener(titleContainer, EventType.CONTEXT_MENU, (e: Event) => { if (this.group.activeEditor) { this.onContextMenu(this.group.activeEditor, e, titleContainer); } })); this._register(addDisposableListener(titleContainer, TouchEventType.Contextmenu, (e: Event) => { if (this.group.activeEditor) { this.onContextMenu(this.group.activeEditor, e, titleContainer); } })); } private onTitleLabelClick(e: MouseEvent): void { EventHelper.stop(e, false); // delayed to let the onTitleClick() come first which can cause a focus change which can close quick access setTimeout(() => this.quickInputService.quickAccess.show()); } private onTitleDoubleClick(e: MouseEvent): void { EventHelper.stop(e); this.group.pinEditor(); } private onTitleAuxClick(e: MouseEvent): void { if (e.button === 1 /* Middle Button */ && this.group.activeEditor) { EventHelper.stop(e, true /* for https://github.com/Microsoft/vscode/issues/56715 */); this.group.closeEditor(this.group.activeEditor); } } private onTitleTap(e: GestureEvent): void { // TODO@rebornix gesture tap should open the quick access // editorGroupView will focus on the editor again when there are mouse/pointer/touch down events // we need to wait a bit as `GesureEvent.Tap` is generated from `touchstart` and then `touchend` evnets, which are not an atom event. setTimeout(() => this.quickInputService.quickAccess.show(), 50); } getPreferredHeight(): number { return EDITOR_TITLE_HEIGHT; } openEditor(editor: IEditorInput): void { const activeEditorChanged = this.ifActiveEditorChanged(() => this.redraw()); if (!activeEditorChanged) { this.ifActiveEditorPropertiesChanged(() => this.redraw()); } } closeEditor(editor: IEditorInput): void { this.ifActiveEditorChanged(() => this.redraw()); } closeEditors(editors: IEditorInput[]): void { this.ifActiveEditorChanged(() => this.redraw()); } moveEditor(editor: IEditorInput, fromIndex: number, targetIndex: number): void { this.ifActiveEditorChanged(() => this.redraw()); } pinEditor(editor: IEditorInput): void { this.ifEditorIsActive(editor, () => this.redraw()); } stickEditor(editor: IEditorInput): void { // Sticky editors are not presented any different with tabs disabled } unstickEditor(editor: IEditorInput): void { // Sticky editors are not presented any different with tabs disabled } setActive(isActive: boolean): void { this.redraw(); } updateEditorLabel(editor: IEditorInput): void { this.ifEditorIsActive(editor, () => this.redraw()); } updateEditorLabels(): void { if (this.group.activeEditor) { this.updateEditorLabel(this.group.activeEditor); // we only have the active one to update } } updateEditorDirty(editor: IEditorInput): void { this.ifEditorIsActive(editor, () => { const titleContainer = assertIsDefined(this.titleContainer); // Signal dirty (unless saving) if (editor.isDirty() && !editor.isSaving()) { addClass(titleContainer, 'dirty'); } // Otherwise, clear dirty else { removeClass(titleContainer, 'dirty'); } }); } updateOptions(oldOptions: IEditorPartOptions, newOptions: IEditorPartOptions): void { if (oldOptions.labelFormat !== newOptions.labelFormat) { this.redraw(); } } updateStyles(): void { this.redraw(); } protected handleBreadcrumbsEnablementChange(): void { const titleContainer = assertIsDefined(this.titleContainer); toggleClass(titleContainer, 'breadcrumbs', Boolean(this.breadcrumbsControl)); this.redraw(); } private ifActiveEditorChanged(fn: () => void): boolean { if ( !this.activeLabel.editor && this.group.activeEditor || // active editor changed from null => editor this.activeLabel.editor && !this.group.activeEditor || // active editor changed from editor => null (!this.activeLabel.editor || !this.group.isActive(this.activeLabel.editor)) // active editor changed from editorA => editorB ) { fn(); return true; } return false; } private ifActiveEditorPropertiesChanged(fn: () => void): void { if (!this.activeLabel.editor || !this.group.activeEditor) { return; // need an active editor to check for properties changed } if (this.activeLabel.pinned !== this.group.isPinned(this.group.activeEditor)) { fn(); // only run if pinned state has changed } } private ifEditorIsActive(editor: IEditorInput, fn: () => void): void { if (this.group.isActive(editor)) { fn(); // only run if editor is current active } } private redraw(): void { const editor = withNullAsUndefined(this.group.activeEditor); const isEditorPinned = editor ? this.group.isPinned(editor) : false; const isGroupActive = this.accessor.activeGroup === this.group; this.activeLabel = { editor, pinned: isEditorPinned }; // Update Breadcrumbs if (this.breadcrumbsControl) { if (isGroupActive) { this.breadcrumbsControl.update(); toggleClass(this.breadcrumbsControl.domNode, 'preview', !isEditorPinned); } else { this.breadcrumbsControl.hide(); } } // Clear if there is no editor const [titleContainer, editorLabel] = assertAllDefined(this.titleContainer, this.editorLabel); if (!editor) { removeClass(titleContainer, 'dirty'); editorLabel.clear(); this.clearEditorActionsToolbar(); } // Otherwise render it else { // Dirty state this.updateEditorDirty(editor); // Editor Label const { labelFormat } = this.accessor.partOptions; let description: string; if (this.breadcrumbsControl && !this.breadcrumbsControl.isHidden()) { description = ''; // hide description when showing breadcrumbs } else if (labelFormat === 'default' && !isGroupActive) { description = ''; // hide description when group is not active and style is 'default' } else { description = editor.getDescription(this.getVerbosity(labelFormat)) || ''; } let title = editor.getTitle(Verbosity.LONG); if (description === title) { title = ''; // dont repeat what is already shown } editorLabel.setResource( { resource: toResource(editor, { supportSideBySide: SideBySideEditor.BOTH }), name: editor.getName(), description }, { title, italic: !isEditorPinned, extraClasses: ['no-tabs', 'title-label'] } ); if (isGroupActive) { editorLabel.element.style.color = this.getColor(TAB_ACTIVE_FOREGROUND) || ''; } else { editorLabel.element.style.color = this.getColor(TAB_UNFOCUSED_ACTIVE_FOREGROUND) || ''; } // Update Editor Actions Toolbar this.updateEditorActionsToolbar(); } } private getVerbosity(style: string | undefined): Verbosity { switch (style) { case 'short': return Verbosity.SHORT; case 'long': return Verbosity.LONG; default: return Verbosity.MEDIUM; } } protected prepareEditorActions(editorActions: IToolbarActions): { primaryEditorActions: IAction[], secondaryEditorActions: IAction[] } { const isGroupActive = this.accessor.activeGroup === this.group; // Group active: show all actions if (isGroupActive) { return super.prepareEditorActions(editorActions); } // Group inactive: only show close action return { primaryEditorActions: editorActions.primary.filter(action => action.id === CLOSE_EDITOR_COMMAND_ID), secondaryEditorActions: [] }; } layout(dimension: Dimension): void { if (this.breadcrumbsControl) { this.breadcrumbsControl.layout(undefined); } } }
src/vs/workbench/browser/parts/editor/noTabsTitleControl.ts
0
https://github.com/microsoft/vscode/commit/9504dda6a717a0a0d45d992e21f2565f8a23f390
[ 0.001145818387158215, 0.00020300511096138507, 0.00016427502851001918, 0.00016932112339418381, 0.00016801906167529523 ]
{ "id": 8, "code_window": [ "\t\t\t\t\tthis.onCellHeightChange(realContentHeight);\n", "\t\t\t\t}\n", "\n", "\t\t\t\tif (this.notebookEditor.getActiveCell() === this.viewCell && viewCell.focusMode === CellFocusMode.Editor) {\n", "\t\t\t\t\ttemplateData.editor?.focus();\n", "\t\t\t\t}\n", "\t\t\t}\n", "\t\t});\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\tif (this.notebookEditor.getActiveCell() === this.viewCell && viewCell.focusMode === CellFocusMode.Editor && this.notebookEditor.hasFocus()) {\n" ], "file_path": "src/vs/workbench/contrib/notebook/browser/view/renderers/codeCell.ts", "type": "replace", "edit_start_line_idx": 68 }
{ "tabSize": 4, "indentSize": 4, "convertTabsToSpaces": false, "insertSpaceAfterCommaDelimiter": true, "insertSpaceAfterSemicolonInForStatements": true, "insertSpaceBeforeAndAfterBinaryOperators": true, "insertSpaceAfterKeywordsInControlFlowStatements": true, "insertSpaceAfterFunctionKeywordForAnonymousFunctions": true, "insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis": false, "insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets": false, "insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces": false, "insertSpaceBeforeFunctionParenthesis": false, "placeOpenBraceOnNewLineForFunctions": false, "placeOpenBraceOnNewLineForControlBlocks": false }
tsfmt.json
0
https://github.com/microsoft/vscode/commit/9504dda6a717a0a0d45d992e21f2565f8a23f390
[ 0.00017304098582826555, 0.00017119752010330558, 0.0001693540543783456, 0.00017119752010330558, 0.0000018434657249599695 ]
{ "id": 8, "code_window": [ "\t\t\t\t\tthis.onCellHeightChange(realContentHeight);\n", "\t\t\t\t}\n", "\n", "\t\t\t\tif (this.notebookEditor.getActiveCell() === this.viewCell && viewCell.focusMode === CellFocusMode.Editor) {\n", "\t\t\t\t\ttemplateData.editor?.focus();\n", "\t\t\t\t}\n", "\t\t\t}\n", "\t\t});\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\tif (this.notebookEditor.getActiveCell() === this.viewCell && viewCell.focusMode === CellFocusMode.Editor && this.notebookEditor.hasFocus()) {\n" ], "file_path": "src/vs/workbench/contrib/notebook/browser/view/renderers/codeCell.ts", "type": "replace", "edit_start_line_idx": 68 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ .monaco-editor .rename-box { z-index: 100; color: inherit; } .monaco-editor .rename-box.preview { padding: 3px 3px 0 3px; } .monaco-editor .rename-box .rename-input { padding: 3px; width: calc(100% - 6px); } .monaco-editor .rename-box .rename-label { display: none; opacity: .8; } .monaco-editor .rename-box.preview .rename-label { display: inherit; }
src/vs/editor/contrib/rename/renameInputField.css
0
https://github.com/microsoft/vscode/commit/9504dda6a717a0a0d45d992e21f2565f8a23f390
[ 0.0001770737289916724, 0.00017603329615667462, 0.00017490585742052644, 0.00017612033116165549, 8.871666068444028e-7 ]
{ "id": 9, "code_window": [ "\t\t}\n", "\t}\n", "\n", "\tprivate focusEditorIfNeeded() {\n", "\t\tif (this.viewCell.focusMode === CellFocusMode.Editor) {\n", "\t\t\tthis.editor?.focus();\n", "\t\t}\n", "\t}\n", "\n", "\tprivate layoutEditor(dimension: IDimension): void {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tif (this.viewCell.focusMode === CellFocusMode.Editor && this.notebookEditor.hasFocus()) {\n" ], "file_path": "src/vs/workbench/contrib/notebook/browser/view/renderers/markdownCell.ts", "type": "replace", "edit_start_line_idx": 229 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { getZoomLevel } from 'vs/base/browser/browser'; import * as DOM from 'vs/base/browser/dom'; import { IMouseWheelEvent, StandardMouseEvent } from 'vs/base/browser/mouseEvent'; import { CancellationTokenSource } from 'vs/base/common/cancellation'; import { Color, RGBA } from 'vs/base/common/color'; import { onUnexpectedError } from 'vs/base/common/errors'; import { Emitter, Event } from 'vs/base/common/event'; import { combinedDisposable, DisposableStore, Disposable, IDisposable, toDisposable } from 'vs/base/common/lifecycle'; import 'vs/css!./media/notebook'; import { ICodeEditor } from 'vs/editor/browser/editorBrowser'; import { IEditorOptions } from 'vs/editor/common/config/editorOptions'; import { BareFontInfo } from 'vs/editor/common/config/fontInfo'; import { Range } from 'vs/editor/common/core/range'; import { IEditor } from 'vs/editor/common/editorCommon'; import * as nls from 'vs/nls'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IContextKey, IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { IResourceEditorInput } from 'vs/platform/editor/common/editor'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage'; import { contrastBorder, editorBackground, focusBorder, foreground, registerColor, textBlockQuoteBackground, textBlockQuoteBorder, textLinkActiveForeground, textLinkForeground, textPreformatForeground, errorForeground, transparent, widgetShadow, listFocusBackground, listInactiveSelectionBackground, scrollbarSliderBackground, scrollbarSliderHoverBackground, scrollbarSliderActiveBackground } from 'vs/platform/theme/common/colorRegistry'; import { registerThemingParticipant } from 'vs/platform/theme/common/themeService'; import { EditorMemento } from 'vs/workbench/browser/parts/editor/baseEditor'; import { EditorOptions, IEditorMemento } from 'vs/workbench/common/editor'; import { CELL_MARGIN, CELL_RUN_GUTTER, EDITOR_BOTTOM_PADDING, EDITOR_TOP_MARGIN, EDITOR_TOP_PADDING, SCROLLABLE_ELEMENT_PADDING_TOP, BOTTOM_CELL_TOOLBAR_HEIGHT, CELL_BOTTOM_MARGIN, CODE_CELL_LEFT_MARGIN } from 'vs/workbench/contrib/notebook/browser/constants'; import { CellEditState, CellFocusMode, ICellRange, ICellViewModel, INotebookCellList, INotebookEditor, INotebookEditorContribution, INotebookEditorMouseEvent, NotebookLayoutInfo, NOTEBOOK_EDITOR_EDITABLE, NOTEBOOK_EDITOR_EXECUTING_NOTEBOOK, NOTEBOOK_EDITOR_FOCUSED, NOTEBOOK_EDITOR_RUNNABLE, NOTEBOOK_HAS_MULTIPLE_KERNELS, NOTEBOOK_OUTPUT_FOCUSED } from 'vs/workbench/contrib/notebook/browser/notebookBrowser'; import { NotebookEditorExtensionsRegistry } from 'vs/workbench/contrib/notebook/browser/notebookEditorExtensions'; import { NotebookCellList } from 'vs/workbench/contrib/notebook/browser/view/notebookCellList'; import { OutputRenderer } from 'vs/workbench/contrib/notebook/browser/view/output/outputRenderer'; import { BackLayerWebView } from 'vs/workbench/contrib/notebook/browser/view/renderers/backLayerWebView'; import { CellDragAndDropController, CodeCellRenderer, MarkdownCellRenderer, NotebookCellListDelegate } from 'vs/workbench/contrib/notebook/browser/view/renderers/cellRenderer'; import { CodeCellViewModel } from 'vs/workbench/contrib/notebook/browser/viewModel/codeCellViewModel'; import { NotebookEventDispatcher, NotebookLayoutChangedEvent } from 'vs/workbench/contrib/notebook/browser/viewModel/eventDispatcher'; import { CellViewModel, IModelDecorationsChangeAccessor, INotebookEditorViewState, NotebookViewModel } from 'vs/workbench/contrib/notebook/browser/viewModel/notebookViewModel'; import { CellKind, IProcessedOutput, INotebookKernelInfo, INotebookKernelInfoDto } from 'vs/workbench/contrib/notebook/common/notebookCommon'; import { INotebookService } from 'vs/workbench/contrib/notebook/common/notebookService'; import { Webview } from 'vs/workbench/contrib/webview/browser/webview'; import { IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService'; import { ILayoutService } from 'vs/platform/layout/browser/layoutService'; import { generateUuid } from 'vs/base/common/uuid'; import { Memento, MementoObject } from 'vs/workbench/common/memento'; import { NotebookTextModel } from 'vs/workbench/contrib/notebook/common/model/notebookTextModel'; import { URI } from 'vs/base/common/uri'; import { PANEL_BORDER } from 'vs/workbench/common/theme'; import { debugIconStartForeground } from 'vs/workbench/contrib/debug/browser/debugToolBar'; import { CellContextKeyManager } from 'vs/workbench/contrib/notebook/browser/view/renderers/cellContextKeys'; const $ = DOM.$; export class NotebookEditorOptions extends EditorOptions { readonly cellOptions?: IResourceEditorInput; constructor(options: Partial<NotebookEditorOptions>) { super(); this.overwrite(options); this.cellOptions = options.cellOptions; } with(options: Partial<NotebookEditorOptions>): NotebookEditorOptions { return new NotebookEditorOptions({ ...this, ...options }); } } export class NotebookEditorWidget extends Disposable implements INotebookEditor { static readonly ID: string = 'workbench.editor.notebook'; private static readonly EDITOR_MEMENTOS = new Map<string, EditorMemento<unknown>>(); private _overlayContainer!: HTMLElement; private _body!: HTMLElement; private _webview: BackLayerWebView | null = null; private _webviewTransparentCover: HTMLElement | null = null; private _list: INotebookCellList | undefined; private _dndController: CellDragAndDropController | null = null; private _renderedEditors: Map<ICellViewModel, ICodeEditor | undefined> = new Map(); private _eventDispatcher: NotebookEventDispatcher | undefined; private _notebookViewModel: NotebookViewModel | undefined; private _localStore: DisposableStore = this._register(new DisposableStore()); private _fontInfo: BareFontInfo | undefined; private _dimension: DOM.Dimension | null = null; private _shadowElementViewInfo: { height: number, width: number, top: number; left: number; } | null = null; private _editorFocus: IContextKey<boolean> | null = null; private _outputFocus: IContextKey<boolean> | null = null; private _editorEditable: IContextKey<boolean> | null = null; private _editorRunnable: IContextKey<boolean> | null = null; private _editorExecutingNotebook: IContextKey<boolean> | null = null; private _notebookHasMultipleKernels: IContextKey<boolean> | null = null; private _outputRenderer: OutputRenderer; protected readonly _contributions: { [key: string]: INotebookEditorContribution; }; private _scrollBeyondLastLine: boolean; private readonly _memento: Memento; private readonly _onDidFocusEmitter = this._register(new Emitter<void>()); public readonly onDidFocus = this._onDidFocusEmitter.event; private _cellContextKeyManager: CellContextKeyManager | null = null; private _isVisible = false; private readonly _uuid = generateUuid(); private _webiewFocused: boolean = false; private _isDisposed: boolean = false; get isDisposed() { return this._isDisposed; } private readonly _onDidChangeModel = this._register(new Emitter<NotebookTextModel | undefined>()); readonly onDidChangeModel: Event<NotebookTextModel | undefined> = this._onDidChangeModel.event; private readonly _onDidFocusEditorWidget = this._register(new Emitter<void>()); readonly onDidFocusEditorWidget = this._onDidFocusEditorWidget.event; set viewModel(newModel: NotebookViewModel | undefined) { this._notebookViewModel = newModel; this._onDidChangeModel.fire(newModel?.notebookDocument); } get viewModel() { return this._notebookViewModel; } get uri() { return this._notebookViewModel?.uri; } get textModel() { return this._notebookViewModel?.notebookDocument; } private _activeKernel: INotebookKernelInfo | undefined = undefined; private readonly _onDidChangeKernel = this._register(new Emitter<void>()); readonly onDidChangeKernel: Event<void> = this._onDidChangeKernel.event; get activeKernel() { return this._activeKernel; } set activeKernel(kernel: INotebookKernelInfo | undefined) { if (this._isDisposed) { return; } this._activeKernel = kernel; this._onDidChangeKernel.fire(); } private readonly _onDidChangeActiveEditor = this._register(new Emitter<this>()); readonly onDidChangeActiveEditor: Event<this> = this._onDidChangeActiveEditor.event; get activeCodeEditor(): IEditor | undefined { if (this._isDisposed) { return; } const [focused] = this._list!.getFocusedElements(); return this._renderedEditors.get(focused); } constructor( @IInstantiationService private readonly instantiationService: IInstantiationService, @IStorageService storageService: IStorageService, @INotebookService private notebookService: INotebookService, @IConfigurationService private readonly configurationService: IConfigurationService, @IContextKeyService readonly contextKeyService: IContextKeyService, @ILayoutService private readonly layoutService: ILayoutService ) { super(); this._memento = new Memento(NotebookEditorWidget.ID, storageService); this._outputRenderer = new OutputRenderer(this, this.instantiationService); this._contributions = {}; this._scrollBeyondLastLine = this.configurationService.getValue<boolean>('editor.scrollBeyondLastLine'); this.configurationService.onDidChangeConfiguration(e => { if (e.affectsConfiguration('editor.scrollBeyondLastLine')) { this._scrollBeyondLastLine = this.configurationService.getValue<boolean>('editor.scrollBeyondLastLine'); if (this._dimension && this._isVisible) { this.layout(this._dimension); } } }); this.notebookService.addNotebookEditor(this); } public getId(): string { return this._uuid; } hasModel() { return !!this._notebookViewModel; } //#region Editor Core protected getEditorMemento<T>(editorGroupService: IEditorGroupsService, key: string, limit: number = 10): IEditorMemento<T> { const mementoKey = `${NotebookEditorWidget.ID}${key}`; let editorMemento = NotebookEditorWidget.EDITOR_MEMENTOS.get(mementoKey); if (!editorMemento) { editorMemento = new EditorMemento(NotebookEditorWidget.ID, key, this.getMemento(StorageScope.WORKSPACE), limit, editorGroupService); NotebookEditorWidget.EDITOR_MEMENTOS.set(mementoKey, editorMemento); } return editorMemento as IEditorMemento<T>; } protected getMemento(scope: StorageScope): MementoObject { return this._memento.getMemento(scope); } public get isNotebookEditor() { return true; } updateEditorFocus() { // Note - focus going to the webview will fire 'blur', but the webview element will be // a descendent of the notebook editor root. const focused = DOM.isAncestor(document.activeElement, this._overlayContainer); this._editorFocus?.set(focused); this._notebookViewModel?.setFocus(focused); } hasFocus() { return this._editorFocus?.get() || false; } createEditor(): void { this._overlayContainer = document.createElement('div'); const id = generateUuid(); this._overlayContainer.id = `notebook-${id}`; this._overlayContainer.className = 'notebookOverlay'; DOM.addClass(this._overlayContainer, 'notebook-editor'); this._overlayContainer.style.visibility = 'hidden'; this.layoutService.container.appendChild(this._overlayContainer); this._createBody(this._overlayContainer); this._generateFontInfo(); this._editorFocus = NOTEBOOK_EDITOR_FOCUSED.bindTo(this.contextKeyService); this._editorFocus.set(true); this._isVisible = true; this._outputFocus = NOTEBOOK_OUTPUT_FOCUSED.bindTo(this.contextKeyService); this._editorEditable = NOTEBOOK_EDITOR_EDITABLE.bindTo(this.contextKeyService); this._editorEditable.set(true); this._editorRunnable = NOTEBOOK_EDITOR_RUNNABLE.bindTo(this.contextKeyService); this._editorRunnable.set(true); this._editorExecutingNotebook = NOTEBOOK_EDITOR_EXECUTING_NOTEBOOK.bindTo(this.contextKeyService); this._notebookHasMultipleKernels = NOTEBOOK_HAS_MULTIPLE_KERNELS.bindTo(this.contextKeyService); this._notebookHasMultipleKernels.set(false); const contributions = NotebookEditorExtensionsRegistry.getEditorContributions(); for (const desc of contributions) { try { const contribution = this.instantiationService.createInstance(desc.ctor, this); this._contributions[desc.id] = contribution; } catch (err) { onUnexpectedError(err); } } } private _generateFontInfo(): void { const editorOptions = this.configurationService.getValue<IEditorOptions>('editor'); this._fontInfo = BareFontInfo.createFromRawSettings(editorOptions, getZoomLevel()); } private _createBody(parent: HTMLElement): void { this._body = document.createElement('div'); DOM.addClass(this._body, 'cell-list-container'); this._createCellList(); DOM.append(parent, this._body); } private _createCellList(): void { DOM.addClass(this._body, 'cell-list-container'); this._dndController = this._register(new CellDragAndDropController(this, this._body)); const getScopedContextKeyService = (container?: HTMLElement) => this._list!.contextKeyService.createScoped(container); const renderers = [ this.instantiationService.createInstance(CodeCellRenderer, this, this._renderedEditors, this._dndController, getScopedContextKeyService), this.instantiationService.createInstance(MarkdownCellRenderer, this, this._dndController, this._renderedEditors, getScopedContextKeyService), ]; this._list = this.instantiationService.createInstance( NotebookCellList, 'NotebookCellList', this._body, this.instantiationService.createInstance(NotebookCellListDelegate), renderers, this.contextKeyService, { setRowLineHeight: false, setRowHeight: false, supportDynamicHeights: true, horizontalScrolling: false, keyboardSupport: false, mouseSupport: true, multipleSelectionSupport: false, enableKeyboardNavigation: true, additionalScrollHeight: 0, transformOptimization: false, styleController: (_suffix: string) => { return this._list!; }, overrideStyles: { listBackground: editorBackground, listActiveSelectionBackground: editorBackground, listActiveSelectionForeground: foreground, listFocusAndSelectionBackground: editorBackground, listFocusAndSelectionForeground: foreground, listFocusBackground: editorBackground, listFocusForeground: foreground, listHoverForeground: foreground, listHoverBackground: editorBackground, listHoverOutline: focusBorder, listFocusOutline: focusBorder, listInactiveSelectionBackground: editorBackground, listInactiveSelectionForeground: foreground, listInactiveFocusBackground: editorBackground, listInactiveFocusOutline: editorBackground, }, accessibilityProvider: { getAriaLabel() { return null; }, getWidgetAriaLabel() { return nls.localize('notebookTreeAriaLabel', "Notebook"); } } }, ); this._dndController.setList(this._list); // create Webview this._register(this._list); this._register(combinedDisposable(...renderers)); // transparent cover this._webviewTransparentCover = DOM.append(this._list.rowsContainer, $('.webview-cover')); this._webviewTransparentCover.style.display = 'none'; this._register(DOM.addStandardDisposableGenericMouseDownListner(this._overlayContainer, (e: StandardMouseEvent) => { if (DOM.hasClass(e.target, 'slider') && this._webviewTransparentCover) { this._webviewTransparentCover.style.display = 'block'; } })); this._register(DOM.addStandardDisposableGenericMouseUpListner(this._overlayContainer, () => { if (this._webviewTransparentCover) { // no matter when this._webviewTransparentCover.style.display = 'none'; } })); this._register(this._list.onMouseDown(e => { if (e.element) { this._onMouseDown.fire({ event: e.browserEvent, target: e.element }); } })); this._register(this._list.onMouseUp(e => { if (e.element) { this._onMouseUp.fire({ event: e.browserEvent, target: e.element }); } })); this._register(this._list.onDidChangeFocus(_e => this._onDidChangeActiveEditor.fire(this))); const widgetFocusTracker = DOM.trackFocus(this.getDomNode()); this._register(widgetFocusTracker); this._register(widgetFocusTracker.onDidFocus(() => this._onDidFocusEmitter.fire())); } getDomNode() { return this._overlayContainer; } onWillHide() { this._isVisible = false; this._editorFocus?.set(false); this._overlayContainer.style.visibility = 'hidden'; this._overlayContainer.style.left = '-50000px'; } getInnerWebview(): Webview | undefined { return this._webview?.webview; } focus() { this._isVisible = true; this._editorFocus?.set(true); if (this._webiewFocused) { this._webview?.focusWebview(); } else { const focus = this._list?.getFocus()[0]; if (typeof focus === 'number') { const element = this._notebookViewModel!.viewCells[focus]; if (element.focusMode === CellFocusMode.Editor) { element.editState = CellEditState.Editing; element.focusMode = CellFocusMode.Editor; this._onDidFocusEditorWidget.fire(); return; } } this._list?.domFocus(); } this._onDidFocusEditorWidget.fire(); } async setModel(textModel: NotebookTextModel, viewState: INotebookEditorViewState | undefined): Promise<void> { if (this._notebookViewModel === undefined || !this._notebookViewModel.equal(textModel)) { this._detachModel(); await this._attachModel(textModel, viewState); } else { this.restoreListViewState(viewState); } // clear state this._dndController?.clearGlobalDragState(); this._setKernels(textModel); this._localStore.add(this.notebookService.onDidChangeKernels(() => { if (this.activeKernel === undefined) { this._setKernels(textModel); } })); this._localStore.add(this._list!.onDidChangeFocus(() => { const focused = this._list!.getFocusedElements()[0]; if (focused) { if (!this._cellContextKeyManager) { this._cellContextKeyManager = this._localStore.add(new CellContextKeyManager(this.contextKeyService, textModel, focused as CellViewModel)); } this._cellContextKeyManager.updateForElement(focused as CellViewModel); } })); } async setOptions(options: NotebookEditorOptions | undefined) { // reveal cell if editor options tell to do so if (options?.cellOptions) { const cellOptions = options.cellOptions; const cell = this._notebookViewModel!.viewCells.find(cell => cell.uri.toString() === cellOptions.resource.toString()); if (cell) { this.selectElement(cell); this.revealInCenterIfOutsideViewport(cell); const editor = this._renderedEditors.get(cell)!; if (editor) { if (cellOptions.options?.selection) { const { selection } = cellOptions.options; editor.setSelection({ ...selection, endLineNumber: selection.endLineNumber || selection.startLineNumber, endColumn: selection.endColumn || selection.startColumn }); editor.revealPositionInCenterIfOutsideViewport({ lineNumber: selection.startLineNumber, column: selection.startColumn }); } if (!cellOptions.options?.preserveFocus) { editor.focus(); } } } } else if (this._notebookViewModel && this._notebookViewModel.viewCells.length === 1 && this._notebookViewModel.viewCells[0].cellKind === CellKind.Code) { // there is only one code cell in the document const cell = this._notebookViewModel!.viewCells[0]; if (cell.getTextLength() === 0) { // the cell is empty, very likely a template cell, focus it this.selectElement(cell); await this.revealLineInCenterAsync(cell, 1); const editor = this._renderedEditors.get(cell)!; if (editor) { editor.focus(); } } } } private _detachModel() { this._localStore.clear(); this._list?.detachViewModel(); this.viewModel?.dispose(); // avoid event this._notebookViewModel = undefined; // this.webview?.clearInsets(); // this.webview?.clearPreloadsCache(); this._webview?.dispose(); this._webview?.element.remove(); this._webview = null; this._list?.clear(); } private _setKernels(textModel: NotebookTextModel) { const provider = this.notebookService.getContributedNotebookProviders(this.viewModel!.uri)[0]; const availableKernels = this.notebookService.getContributedNotebookKernels(textModel.viewType, textModel.uri); if (provider.kernel && availableKernels.length > 0) { this._notebookHasMultipleKernels!.set(true); } else if (availableKernels.length > 1) { this._notebookHasMultipleKernels!.set(true); } else { this._notebookHasMultipleKernels!.set(false); } if (provider && provider.kernel) { // it has a builtin kernel, don't automatically choose a kernel this._loadKernelPreloads(provider.providerExtensionLocation, provider.kernel); return; } // the provider doesn't have a builtin kernel, choose a kernel this.activeKernel = availableKernels[0]; if (this.activeKernel) { this._loadKernelPreloads(this.activeKernel.extensionLocation, this.activeKernel); } } private _loadKernelPreloads(extensionLocation: URI, kernel: INotebookKernelInfoDto) { if (kernel.preloads) { this._webview?.updateKernelPreloads([extensionLocation], kernel.preloads.map(preload => URI.revive(preload))); } } private _updateForMetadata(): void { this._editorEditable?.set(!!this.viewModel!.metadata?.editable); this._editorRunnable?.set(!!this.viewModel!.metadata?.runnable); DOM.toggleClass(this._overlayContainer, 'notebook-editor-editable', !!this.viewModel!.metadata?.editable); DOM.toggleClass(this.getDomNode(), 'notebook-editor-editable', !!this.viewModel!.metadata?.editable); } private async _createWebview(id: string, resource: URI): Promise<void> { this._webview = this.instantiationService.createInstance(BackLayerWebView, this, id, resource); // attach the webview container to the DOM tree first this._list?.rowsContainer.insertAdjacentElement('afterbegin', this._webview.element); await this._webview.createWebview(); this._webview.webview.onDidBlur(() => { this._outputFocus?.set(false); this.updateEditorFocus(); if (this._overlayContainer.contains(document.activeElement)) { this._webiewFocused = false; } }); this._webview.webview.onDidFocus(() => { this._outputFocus?.set(true); this.updateEditorFocus(); this._onDidFocusEmitter.fire(); if (this._overlayContainer.contains(document.activeElement)) { this._webiewFocused = true; } }); this._localStore.add(this._webview.onMessage(({ message, forRenderer }) => { if (this.viewModel) { this.notebookService.onDidReceiveMessage(this.viewModel.viewType, this.getId(), forRenderer, message); } })); } private async _attachModel(textModel: NotebookTextModel, viewState: INotebookEditorViewState | undefined) { await this._createWebview(this.getId(), textModel.uri); this._eventDispatcher = new NotebookEventDispatcher(); this.viewModel = this.instantiationService.createInstance(NotebookViewModel, textModel.viewType, textModel, this._eventDispatcher, this.getLayoutInfo()); this._eventDispatcher.emit([new NotebookLayoutChangedEvent({ width: true, fontInfo: true }, this.getLayoutInfo())]); this._updateForMetadata(); this._localStore.add(this._eventDispatcher.onDidChangeMetadata(() => { this._updateForMetadata(); })); // restore view states, including contributions { // restore view state this.viewModel.restoreEditorViewState(viewState); // contribution state restore const contributionsState = viewState?.contributionsState || {}; const keys = Object.keys(this._contributions); for (let i = 0, len = keys.length; i < len; i++) { const id = keys[i]; const contribution = this._contributions[id]; if (typeof contribution.restoreViewState === 'function') { contribution.restoreViewState(contributionsState[id]); } } } this._webview?.updateRendererPreloads(this.viewModel.renderers); this._localStore.add(this._list!.onWillScroll(e => { this._webview!.updateViewScrollTop(-e.scrollTop, []); this._webviewTransparentCover!.style.top = `${e.scrollTop}px`; })); this._localStore.add(this._list!.onDidChangeContentHeight(() => { DOM.scheduleAtNextAnimationFrame(() => { if (this._isDisposed) { return; } const scrollTop = this._list?.scrollTop || 0; const scrollHeight = this._list?.scrollHeight || 0; this._webview!.element.style.height = `${scrollHeight}px`; if (this._webview?.insetMapping) { let updateItems: { cell: CodeCellViewModel, output: IProcessedOutput, cellTop: number }[] = []; let removedItems: IProcessedOutput[] = []; this._webview?.insetMapping.forEach((value, key) => { const cell = value.cell; const viewIndex = this._list?.getViewIndex(cell); if (viewIndex === undefined) { return; } if (cell.outputs.indexOf(key) < 0) { // output is already gone removedItems.push(key); } const cellTop = this._list?.getAbsoluteTopOfElement(cell) || 0; if (this._webview!.shouldUpdateInset(cell, key, cellTop)) { updateItems.push({ cell: cell, output: key, cellTop: cellTop }); } }); removedItems.forEach(output => this._webview?.removeInset(output)); if (updateItems.length) { this._webview?.updateViewScrollTop(-scrollTop, updateItems); } } }); })); this._list!.attachViewModel(this.viewModel); this._localStore.add(this._list!.onDidRemoveOutput(output => { this.removeInset(output); })); this._localStore.add(this._list!.onDidHideOutput(output => { this.hideInset(output); })); this._list!.layout(); this._dndController?.clearGlobalDragState(); // restore list state at last, it must be after list layout this.restoreListViewState(viewState); } restoreListViewState(viewState: INotebookEditorViewState | undefined): void { if (viewState?.scrollPosition !== undefined) { this._list!.scrollTop = viewState!.scrollPosition.top; this._list!.scrollLeft = viewState!.scrollPosition.left; } else { this._list!.scrollTop = 0; this._list!.scrollLeft = 0; } const focusIdx = typeof viewState?.focus === 'number' ? viewState.focus : 0; if (focusIdx < this._list!.length) { this._list!.setFocus([focusIdx]); this._list!.setSelection([focusIdx]); } else if (this._list!.length > 0) { this._list!.setFocus([0]); } if (viewState?.editorFocused) { this._list?.focusView(); const cell = this._notebookViewModel?.viewCells[focusIdx]; if (cell) { cell.focusMode = CellFocusMode.Editor; } } } getEditorViewState(): INotebookEditorViewState { const state = this._notebookViewModel?.getEditorViewState(); if (!state) { return { editingCells: {}, editorViewStates: {} }; } if (this._list) { state.scrollPosition = { left: this._list.scrollLeft, top: this._list.scrollTop }; let cellHeights: { [key: number]: number } = {}; for (let i = 0; i < this.viewModel!.length; i++) { const elm = this.viewModel!.viewCells[i] as CellViewModel; if (elm.cellKind === CellKind.Code) { cellHeights[i] = elm.layoutInfo.totalHeight; } else { cellHeights[i] = 0; } } state.cellTotalHeights = cellHeights; const focus = this._list.getFocus()[0]; if (typeof focus === 'number') { const element = this._notebookViewModel!.viewCells[focus]; if (element) { const itemDOM = this._list?.domElementOfElement(element); let editorFocused = !!(document.activeElement && itemDOM && itemDOM.contains(document.activeElement)); state.editorFocused = editorFocused; state.focus = focus; } } } // Save contribution view states const contributionsState: { [key: string]: unknown } = {}; const keys = Object.keys(this._contributions); for (const id of keys) { const contribution = this._contributions[id]; if (typeof contribution.saveViewState === 'function') { contributionsState[id] = contribution.saveViewState(); } } state.contributionsState = contributionsState; return state; } // private saveEditorViewState(input: NotebookEditorInput): void { // if (this.group && this.notebookViewModel) { // } // } // private loadTextEditorViewState(): INotebookEditorViewState | undefined { // return this.editorMemento.loadEditorState(this.group, input.resource); // } layout(dimension: DOM.Dimension, shadowElement?: HTMLElement): void { if (!shadowElement && this._shadowElementViewInfo === null) { this._dimension = dimension; return; } if (shadowElement) { const containerRect = shadowElement.getBoundingClientRect(); this._shadowElementViewInfo = { height: containerRect.height, width: containerRect.width, top: containerRect.top, left: containerRect.left }; } this._dimension = new DOM.Dimension(dimension.width, dimension.height); DOM.size(this._body, dimension.width, dimension.height); this._list?.updateOptions({ additionalScrollHeight: this._scrollBeyondLastLine ? dimension.height - SCROLLABLE_ELEMENT_PADDING_TOP : 0 }); this._list?.layout(dimension.height - SCROLLABLE_ELEMENT_PADDING_TOP, dimension.width); this._overlayContainer.style.visibility = 'visible'; this._overlayContainer.style.display = 'block'; this._overlayContainer.style.position = 'absolute'; this._overlayContainer.style.top = `${this._shadowElementViewInfo!.top}px`; this._overlayContainer.style.left = `${this._shadowElementViewInfo!.left}px`; this._overlayContainer.style.width = `${dimension ? dimension.width : this._shadowElementViewInfo!.width}px`; this._overlayContainer.style.height = `${dimension ? dimension.height : this._shadowElementViewInfo!.height}px`; if (this._webviewTransparentCover) { this._webviewTransparentCover.style.height = `${dimension.height}px`; this._webviewTransparentCover.style.width = `${dimension.width}px`; } this._eventDispatcher?.emit([new NotebookLayoutChangedEvent({ width: true, fontInfo: true }, this.getLayoutInfo())]); } // protected saveState(): void { // if (this.input instanceof NotebookEditorInput) { // this.saveEditorViewState(this.input); // } // super.saveState(); // } //#endregion //#region Editor Features selectElement(cell: ICellViewModel) { this._list?.selectElement(cell); // this.viewModel!.selectionHandles = [cell.handle]; } revealInView(cell: ICellViewModel) { this._list?.revealElementInView(cell); } revealInCenterIfOutsideViewport(cell: ICellViewModel) { this._list?.revealElementInCenterIfOutsideViewport(cell); } revealInCenter(cell: ICellViewModel) { this._list?.revealElementInCenter(cell); } async revealLineInViewAsync(cell: ICellViewModel, line: number): Promise<void> { return this._list?.revealElementLineInViewAsync(cell, line); } async revealLineInCenterAsync(cell: ICellViewModel, line: number): Promise<void> { return this._list?.revealElementLineInCenterAsync(cell, line); } async revealLineInCenterIfOutsideViewportAsync(cell: ICellViewModel, line: number): Promise<void> { return this._list?.revealElementLineInCenterIfOutsideViewportAsync(cell, line); } async revealRangeInViewAsync(cell: ICellViewModel, range: Range): Promise<void> { return this._list?.revealElementRangeInViewAsync(cell, range); } async revealRangeInCenterAsync(cell: ICellViewModel, range: Range): Promise<void> { return this._list?.revealElementRangeInCenterAsync(cell, range); } async revealRangeInCenterIfOutsideViewportAsync(cell: ICellViewModel, range: Range): Promise<void> { return this._list?.revealElementRangeInCenterIfOutsideViewportAsync(cell, range); } setCellSelection(cell: ICellViewModel, range: Range): void { this._list?.setCellSelection(cell, range); } changeDecorations<T>(callback: (changeAccessor: IModelDecorationsChangeAccessor) => T): T | null { return this._notebookViewModel?.changeDecorations<T>(callback) || null; } setHiddenAreas(_ranges: ICellRange[]): boolean { return this._list!.setHiddenAreas(_ranges, true); } //#endregion //#region Mouse Events private readonly _onMouseUp: Emitter<INotebookEditorMouseEvent> = this._register(new Emitter<INotebookEditorMouseEvent>()); public readonly onMouseUp: Event<INotebookEditorMouseEvent> = this._onMouseUp.event; private readonly _onMouseDown: Emitter<INotebookEditorMouseEvent> = this._register(new Emitter<INotebookEditorMouseEvent>()); public readonly onMouseDown: Event<INotebookEditorMouseEvent> = this._onMouseDown.event; private pendingLayouts = new WeakMap<ICellViewModel, IDisposable>(); //#endregion //#region Cell operations async layoutNotebookCell(cell: ICellViewModel, height: number): Promise<void> { const viewIndex = this._list!.getViewIndex(cell); if (viewIndex === undefined) { // the cell is hidden return; } let relayout = (cell: ICellViewModel, height: number) => { if (this._isDisposed) { return; } this._list?.updateElementHeight2(cell, height); }; if (this.pendingLayouts.has(cell)) { this.pendingLayouts.get(cell)!.dispose(); } let r: () => void; const layoutDisposable = DOM.scheduleAtNextAnimationFrame(() => { if (this._isDisposed) { return; } this.pendingLayouts.delete(cell); relayout(cell, height); r(); }); this.pendingLayouts.set(cell, toDisposable(() => { layoutDisposable.dispose(); r(); })); return new Promise(resolve => { r = resolve; }); } insertNotebookCell(cell: ICellViewModel | undefined, type: CellKind, direction: 'above' | 'below' = 'above', initialText: string = '', ui: boolean = false): CellViewModel | null { if (!this._notebookViewModel!.metadata.editable) { return null; } const index = cell ? this._notebookViewModel!.getCellIndex(cell) : 0; const nextIndex = ui ? this._notebookViewModel!.getNextVisibleCellIndex(index) : index + 1; const newLanguages = this._notebookViewModel!.languages; const language = (cell?.cellKind === CellKind.Code && type === CellKind.Code) ? cell.language : ((type === CellKind.Code && newLanguages && newLanguages.length) ? newLanguages[0] : 'markdown'); const insertIndex = cell ? (direction === 'above' ? index : nextIndex) : index; const newCell = this._notebookViewModel!.createCell(insertIndex, initialText.split(/\r?\n/g), language, type, undefined, true); return newCell as CellViewModel; } async splitNotebookCell(cell: ICellViewModel): Promise<CellViewModel[] | null> { const index = this._notebookViewModel!.getCellIndex(cell); return this._notebookViewModel!.splitNotebookCell(index); } async joinNotebookCells(cell: ICellViewModel, direction: 'above' | 'below', constraint?: CellKind): Promise<ICellViewModel | null> { const index = this._notebookViewModel!.getCellIndex(cell); const ret = await this._notebookViewModel!.joinNotebookCells(index, direction, constraint); if (ret) { ret.deletedCells.forEach(cell => { if (this.pendingLayouts.has(cell)) { this.pendingLayouts.get(cell)!.dispose(); } }); return ret.cell; } else { return null; } } async deleteNotebookCell(cell: ICellViewModel): Promise<boolean> { if (!this._notebookViewModel!.metadata.editable) { return false; } if (this.pendingLayouts.has(cell)) { this.pendingLayouts.get(cell)!.dispose(); } const index = this._notebookViewModel!.getCellIndex(cell); this._notebookViewModel!.deleteCell(index, true); return true; } async moveCellDown(cell: ICellViewModel): Promise<ICellViewModel | null> { if (!this._notebookViewModel!.metadata.editable) { return null; } const index = this._notebookViewModel!.getCellIndex(cell); if (index === this._notebookViewModel!.length - 1) { return null; } const newIdx = index + 1; return this._moveCellToIndex(index, newIdx); } async moveCellUp(cell: ICellViewModel): Promise<ICellViewModel | null> { if (!this._notebookViewModel!.metadata.editable) { return null; } const index = this._notebookViewModel!.getCellIndex(cell); if (index === 0) { return null; } const newIdx = index - 1; return this._moveCellToIndex(index, newIdx); } async moveCell(cell: ICellViewModel, relativeToCell: ICellViewModel, direction: 'above' | 'below'): Promise<ICellViewModel | null> { if (!this._notebookViewModel!.metadata.editable) { return null; } if (cell === relativeToCell) { return null; } const originalIdx = this._notebookViewModel!.getCellIndex(cell); const relativeToIndex = this._notebookViewModel!.getCellIndex(relativeToCell); let newIdx = direction === 'above' ? relativeToIndex : relativeToIndex + 1; if (originalIdx < newIdx) { newIdx--; } return this._moveCellToIndex(originalIdx, newIdx); } private async _moveCellToIndex(index: number, newIdx: number): Promise<ICellViewModel | null> { if (index === newIdx) { return null; } if (!this._notebookViewModel!.moveCellToIdx(index, newIdx, true)) { throw new Error('Notebook Editor move cell, index out of range'); } let r: (val: ICellViewModel | null) => void; DOM.scheduleAtNextAnimationFrame(() => { if (this._isDisposed) { r(null); } const viewCell = this._notebookViewModel!.viewCells[newIdx]; this._list?.revealElementInView(viewCell); r(viewCell); }); return new Promise(resolve => { r = resolve; }); } editNotebookCell(cell: CellViewModel): void { if (!cell.getEvaluatedMetadata(this._notebookViewModel!.metadata).editable) { return; } cell.editState = CellEditState.Editing; this._renderedEditors.get(cell)?.focus(); } getActiveCell() { let elements = this._list?.getFocusedElements(); if (elements && elements.length) { return elements[0]; } return undefined; } cancelNotebookExecution(): void { if (!this._notebookViewModel!.currentTokenSource) { throw new Error('Notebook is not executing'); } this._notebookViewModel!.currentTokenSource.cancel(); this._notebookViewModel!.currentTokenSource = undefined; } async executeNotebook(): Promise<void> { if (!this._notebookViewModel!.metadata.runnable) { return; } return this._executeNotebook(); } async _executeNotebook(): Promise<void> { if (this._notebookViewModel!.currentTokenSource) { return; } const tokenSource = new CancellationTokenSource(); try { this._editorExecutingNotebook!.set(true); this._notebookViewModel!.currentTokenSource = tokenSource; const provider = this.notebookService.getContributedNotebookProviders(this.viewModel!.uri)[0]; if (provider) { const viewType = provider.id; const notebookUri = this._notebookViewModel!.uri; if (this._activeKernel) { await this.notebookService.executeNotebook2(this._notebookViewModel!.viewType, this._notebookViewModel!.uri, this._activeKernel.id, tokenSource.token); } else if (provider.kernel) { return await this.notebookService.executeNotebook(viewType, notebookUri, true, tokenSource.token); } else { return await this.notebookService.executeNotebook(viewType, notebookUri, false, tokenSource.token); } } } finally { this._editorExecutingNotebook!.set(false); this._notebookViewModel!.currentTokenSource = undefined; tokenSource.dispose(); } } cancelNotebookCellExecution(cell: ICellViewModel): void { if (!cell.currentTokenSource) { throw new Error('Cell is not executing'); } cell.currentTokenSource.cancel(); cell.currentTokenSource = undefined; } async executeNotebookCell(cell: ICellViewModel): Promise<void> { if (cell.cellKind === CellKind.Markdown) { this.focusNotebookCell(cell, 'container'); return; } if (!cell.getEvaluatedMetadata(this._notebookViewModel!.metadata).runnable) { return; } const tokenSource = new CancellationTokenSource(); try { await this._executeNotebookCell(cell, tokenSource); } finally { tokenSource.dispose(); } } private async _executeNotebookCell(cell: ICellViewModel, tokenSource: CancellationTokenSource): Promise<void> { try { cell.currentTokenSource = tokenSource; const provider = this.notebookService.getContributedNotebookProviders(this.viewModel!.uri)[0]; if (provider) { const viewType = provider.id; const notebookUri = this._notebookViewModel!.uri; if (this._activeKernel) { return await this.notebookService.executeNotebookCell2(viewType, notebookUri, cell.handle, this._activeKernel.id, tokenSource.token); } else if (provider.kernel) { return await this.notebookService.executeNotebookCell(viewType, notebookUri, cell.handle, true, tokenSource.token); } else { return await this.notebookService.executeNotebookCell(viewType, notebookUri, cell.handle, false, tokenSource.token); } } } finally { cell.currentTokenSource = undefined; } } focusNotebookCell(cell: ICellViewModel, focusItem: 'editor' | 'container' | 'output') { if (this._isDisposed) { return; } if (focusItem === 'editor') { this.selectElement(cell); this._list?.focusView(); cell.editState = CellEditState.Editing; cell.focusMode = CellFocusMode.Editor; this.revealInCenterIfOutsideViewport(cell); } else if (focusItem === 'output') { this.selectElement(cell); this._list?.focusView(); if (!this._webview) { return; } this._webview.focusOutput(cell.id); cell.editState = CellEditState.Preview; cell.focusMode = CellFocusMode.Container; this.revealInCenterIfOutsideViewport(cell); } else { let itemDOM = this._list?.domElementOfElement(cell); if (document.activeElement && itemDOM && itemDOM.contains(document.activeElement)) { (document.activeElement as HTMLElement).blur(); } cell.editState = CellEditState.Preview; cell.focusMode = CellFocusMode.Container; this.selectElement(cell); this.revealInCenterIfOutsideViewport(cell); this._list?.focusView(); } } //#endregion //#region MISC getLayoutInfo(): NotebookLayoutInfo { if (!this._list) { throw new Error('Editor is not initalized successfully'); } return { width: this._dimension!.width, height: this._dimension!.height, fontInfo: this._fontInfo! }; } triggerScroll(event: IMouseWheelEvent) { this._list?.triggerScrollFromMouseWheelEvent(event); } async createInset(cell: CodeCellViewModel, output: IProcessedOutput, shadowContent: string, offset: number) { if (!this._webview) { return; } let preloads = this._notebookViewModel!.renderers; if (!this._webview!.insetMapping.has(output)) { let cellTop = this._list?.getAbsoluteTopOfElement(cell) || 0; await this._webview!.createInset(cell, output, cellTop, offset, shadowContent, preloads); } else { let cellTop = this._list?.getAbsoluteTopOfElement(cell) || 0; let scrollTop = this._list?.scrollTop || 0; this._webview!.updateViewScrollTop(-scrollTop, [{ cell: cell, output: output, cellTop: cellTop }]); } } removeInset(output: IProcessedOutput) { if (!this._webview) { return; } this._webview!.removeInset(output); } hideInset(output: IProcessedOutput) { if (!this._webview) { return; } this._webview!.hideInset(output); } getOutputRenderer(): OutputRenderer { return this._outputRenderer; } postMessage(forRendererId: string | undefined, message: any) { if (forRendererId === undefined) { this._webview?.webview.postMessage(message); } else { this._webview?.postRendererMessage(forRendererId, message); } } toggleClassName(className: string) { DOM.toggleClass(this._overlayContainer, className); } addClassName(className: string) { DOM.addClass(this._overlayContainer, className); } removeClassName(className: string) { DOM.removeClass(this._overlayContainer, className); } //#endregion //#region Editor Contributions public getContribution<T extends INotebookEditorContribution>(id: string): T { return <T>(this._contributions[id] || null); } //#endregion dispose() { this._isDisposed = true; // dispose webview first this._webview?.dispose(); this.notebookService.removeNotebookEditor(this); const keys = Object.keys(this._contributions); for (let i = 0, len = keys.length; i < len; i++) { const contributionId = keys[i]; this._contributions[contributionId].dispose(); } this._localStore.clear(); this._list?.dispose(); this._overlayContainer.remove(); this.viewModel?.dispose(); // this._layoutService.container.removeChild(this.overlayContainer); super.dispose(); } toJSON(): object { return { notebookHandle: this.viewModel?.handle }; } } export const notebookCellBorder = registerColor('notebook.cellBorderColor', { dark: transparent(PANEL_BORDER, .4), light: transparent(listInactiveSelectionBackground, 1), hc: PANEL_BORDER }, nls.localize('notebook.cellBorderColor', "The border color for notebook cells.")); export const focusedEditorBorderColor = registerColor('notebook.focusedEditorBorder', { light: focusBorder, dark: focusBorder, hc: focusBorder }, nls.localize('notebook.focusedEditorBorder', "The color of the notebook cell editor border.")); export const cellStatusIconSuccess = registerColor('notebookStatusSuccessIcon.foreground', { light: debugIconStartForeground, dark: debugIconStartForeground, hc: debugIconStartForeground }, nls.localize('notebookStatusSuccessIcon.foreground', "The error icon color of notebook cells in the cell status bar.")); export const cellStatusIconError = registerColor('notebookStatusErrorIcon.foreground', { light: errorForeground, dark: errorForeground, hc: errorForeground }, nls.localize('notebookStatusErrorIcon.foreground', "The error icon color of notebook cells in the cell status bar.")); export const cellStatusIconRunning = registerColor('notebookStatusRunningIcon.foreground', { light: foreground, dark: foreground, hc: foreground }, nls.localize('notebookStatusRunningIcon.foreground', "The running icon color of notebook cells in the cell status bar.")); export const notebookOutputContainerColor = registerColor('notebook.outputContainerBackgroundColor', { dark: notebookCellBorder, light: transparent(listFocusBackground, .4), hc: null }, nls.localize('notebook.outputContainerBackgroundColor', "The Color of the notebook output container background.")); // TODO currently also used for toolbar border, if we keep all of this, pick a generic name export const CELL_TOOLBAR_SEPERATOR = registerColor('notebook.cellToolbarSeperator', { dark: Color.fromHex('#808080').transparent(0.35), light: Color.fromHex('#808080').transparent(0.35), hc: contrastBorder }, nls.localize('notebook.cellToolbarSeperator', "The color of the seperator in the cell bottom toolbar")); export const focusedCellBackground = registerColor('notebook.focusedCellBackground', { dark: transparent(PANEL_BORDER, .4), light: transparent(listFocusBackground, .4), hc: null }, nls.localize('focusedCellBackground', "The background color of a cell when the cell is focused.")); export const cellHoverBackground = registerColor('notebook.cellHoverBackground', { dark: transparent(focusedCellBackground, .5), light: transparent(focusedCellBackground, .7), hc: null }, nls.localize('notebook.cellHoverBackground', "The background color of a cell when the cell is hovered.")); export const focusedCellBorder = registerColor('notebook.focusedCellBorder', { dark: Color.white.transparent(0.12), light: Color.black.transparent(0.12), hc: focusBorder }, nls.localize('notebook.focusedCellBorder', "The color of the cell's top and bottom border when the cell is focused.")); export const focusedCellShadow = registerColor('notebook.focusedCellShadow', { dark: transparent(widgetShadow, 0.6), light: transparent(widgetShadow, 0.4), hc: Color.transparent }, nls.localize('notebook.focusedCellShadow', "The color of the cell shadow when cells are focused.")); export const cellStatusBarItemHover = registerColor('notebook.cellStatusBarItemHoverBackground', { light: new Color(new RGBA(0, 0, 0, 0.08)), dark: new Color(new RGBA(255, 255, 255, 0.15)), hc: new Color(new RGBA(255, 255, 255, 0.15)), }, nls.localize('notebook.cellStatusBarItemHoverBackground', "The background color of notebook cell status bar items.")); export const cellInsertionIndicator = registerColor('notebook.cellInsertionIndicator', { light: focusBorder, dark: focusBorder, hc: focusBorder }, nls.localize('notebook.cellInsertionIndicator', "The color of the notebook cell insertion indicator.")); export const listScrollbarSliderBackground = registerColor('notebookScrollbarSlider.background', { dark: scrollbarSliderBackground, light: scrollbarSliderBackground, hc: scrollbarSliderBackground }, nls.localize('notebookScrollbarSliderBackground', "Notebook scrollbar slider background color.")); export const listScrollbarSliderHoverBackground = registerColor('notebookScrollbarSlider.hoverBackground', { dark: scrollbarSliderHoverBackground, light: scrollbarSliderHoverBackground, hc: scrollbarSliderHoverBackground }, nls.localize('notebookScrollbarSliderHoverBackground', "Notebook scrollbar slider background color when hovering.")); export const listScrollbarSliderActiveBackground = registerColor('notebookScrollbarSlider.activeBackground', { dark: scrollbarSliderActiveBackground, light: scrollbarSliderActiveBackground, hc: scrollbarSliderActiveBackground }, nls.localize('notebookScrollbarSliderActiveBackground', "Notebook scrollbar slider background color when clicked on.")); registerThemingParticipant((theme, collector) => { collector.addRule(`.notebookOverlay > .cell-list-container > .monaco-list > .monaco-scrollable-element { padding-top: ${SCROLLABLE_ELEMENT_PADDING_TOP}px; box-sizing: border-box; }`); // const color = getExtraColor(theme, embeddedEditorBackground, { dark: 'rgba(0, 0, 0, .4)', extra_dark: 'rgba(200, 235, 255, .064)', light: '#f4f4f4', hc: null }); const color = theme.getColor(editorBackground); if (color) { collector.addRule(`.notebookOverlay .cell .monaco-editor-background, .notebookOverlay .cell .margin-view-overlays, .notebookOverlay .cell .cell-statusbar-container { background: ${color}; }`); collector.addRule(`.notebookOverlay .cell-drag-image .cell-editor-container > div { background: ${color} !important; }`); } const link = theme.getColor(textLinkForeground); if (link) { collector.addRule(`.notebookOverlay .output a, .notebookOverlay .cell.markdown a { color: ${link};} `); } const activeLink = theme.getColor(textLinkActiveForeground); if (activeLink) { collector.addRule(`.notebookOverlay .output a:hover, .notebookOverlay .cell .output a:active { color: ${activeLink}; }`); } const shortcut = theme.getColor(textPreformatForeground); if (shortcut) { collector.addRule(`.notebookOverlay code, .notebookOverlay .shortcut { color: ${shortcut}; }`); } const border = theme.getColor(contrastBorder); if (border) { collector.addRule(`.notebookOverlay .monaco-editor { border-color: ${border}; }`); } const quoteBackground = theme.getColor(textBlockQuoteBackground); if (quoteBackground) { collector.addRule(`.notebookOverlay blockquote { background: ${quoteBackground}; }`); } const quoteBorder = theme.getColor(textBlockQuoteBorder); if (quoteBorder) { collector.addRule(`.notebookOverlay blockquote { border-color: ${quoteBorder}; }`); } const containerBackground = theme.getColor(notebookOutputContainerColor); if (containerBackground) { collector.addRule(`.notebookOverlay .output { background-color: ${containerBackground}; }`); collector.addRule(`.notebookOverlay .output-element { background-color: ${containerBackground}; }`); } const editorBackgroundColor = theme.getColor(editorBackground); if (editorBackgroundColor) { collector.addRule(`.notebookOverlay .cell-statusbar-container { border-top: solid 1px ${editorBackgroundColor}; }`); collector.addRule(`.notebookOverlay .monaco-list-row > .monaco-toolbar { background-color: ${editorBackgroundColor}; }`); collector.addRule(`.notebookOverlay .monaco-list-row.cell-drag-image { background-color: ${editorBackgroundColor}; }`); } const cellToolbarSeperator = theme.getColor(CELL_TOOLBAR_SEPERATOR); if (cellToolbarSeperator) { collector.addRule(`.notebookOverlay .cell-bottom-toolbar-container .separator { background-color: ${cellToolbarSeperator} }`); collector.addRule(`.notebookOverlay .cell-bottom-toolbar-container .action-item:first-child::after { background-color: ${cellToolbarSeperator} }`); collector.addRule(`.notebookOverlay .monaco-list-row > .monaco-toolbar { border: solid 1px ${cellToolbarSeperator}; }`); } const focusedCellBackgroundColor = theme.getColor(focusedCellBackground); if (focusedCellBackgroundColor) { collector.addRule(`.notebookOverlay .code-cell-row.focused .cell-focus-indicator, .notebookOverlay .markdown-cell-row.focused { background-color: ${focusedCellBackgroundColor} !important; }`); } const cellHoverBackgroundColor = theme.getColor(cellHoverBackground); if (cellHoverBackgroundColor) { collector.addRule(`.notebookOverlay .code-cell-row:not(.focused):hover .cell-focus-indicator, .notebookOverlay .code-cell-row:not(.focused).cell-output-hover .cell-focus-indicator, .notebookOverlay .markdown-cell-row:not(.focused):hover { background-color: ${cellHoverBackgroundColor} !important; }`); } const focusedCellBorderColor = theme.getColor(focusedCellBorder); collector.addRule(`.monaco-workbench .notebookOverlay .monaco-list .monaco-list-row.focused .cell-focus-indicator-top:before, .monaco-workbench .notebookOverlay .monaco-list .monaco-list-row.focused .cell-focus-indicator-bottom:before, .monaco-workbench .notebookOverlay .monaco-list .markdown-cell-row.focused:before, .monaco-workbench .notebookOverlay .monaco-list .markdown-cell-row.focused:after { border-color: ${focusedCellBorderColor} !important; }`); const focusedEditorBorderColorColor = theme.getColor(focusedEditorBorderColor); if (focusedEditorBorderColorColor) { collector.addRule(`.notebookOverlay .monaco-list-row.cell-editor-focus .cell-editor-part:before { outline: solid 1px ${focusedEditorBorderColorColor}; }`); } const editorBorderColor = theme.getColor(notebookCellBorder); if (editorBorderColor) { collector.addRule(`.notebookOverlay .monaco-list-row .cell-editor-part:before { outline: solid 1px ${editorBorderColor}; }`); } const headingBorderColor = theme.getColor(notebookCellBorder); if (headingBorderColor) { collector.addRule(`.notebookOverlay .cell.markdown h1 { border-color: ${headingBorderColor}; }`); } const cellStatusSuccessIcon = theme.getColor(cellStatusIconSuccess); if (cellStatusSuccessIcon) { collector.addRule(`.monaco-workbench .notebookOverlay .cell-statusbar-container .cell-run-status .codicon-check { color: ${cellStatusSuccessIcon} }`); } const cellStatusErrorIcon = theme.getColor(cellStatusIconError); if (cellStatusErrorIcon) { collector.addRule(`.monaco-workbench .notebookOverlay .cell-statusbar-container .cell-run-status .codicon-error { color: ${cellStatusErrorIcon} }`); } const cellStatusRunningIcon = theme.getColor(cellStatusIconRunning); if (cellStatusRunningIcon) { collector.addRule(`.monaco-workbench .notebookOverlay .cell-statusbar-container .cell-run-status .codicon-sync { color: ${cellStatusRunningIcon} }`); } const cellStatusBarHoverBg = theme.getColor(cellStatusBarItemHover); if (cellStatusBarHoverBg) { collector.addRule(`.monaco-workbench .notebookOverlay .cell-statusbar-container .cell-language-picker:hover { background-color: ${cellStatusBarHoverBg}; }`); } const cellShadowColor = theme.getColor(focusedCellShadow); if (cellShadowColor) { // Code cells collector.addRule(`.monaco-workbench .notebookOverlay .monaco-list .monaco-list-row.focused .cell-shadow { box-shadow: 0px 0px 4px 2px ${cellShadowColor} }`); // Markdown cells collector.addRule(`.monaco-workbench .notebookOverlay .monaco-list .markdown-cell-row.focused { box-shadow: 0px 0px 4px 2px ${cellShadowColor} }`); } const cellInsertionIndicatorColor = theme.getColor(cellInsertionIndicator); if (cellInsertionIndicatorColor) { collector.addRule(`.notebookOverlay > .cell-list-container > .cell-list-insertion-indicator { background-color: ${cellInsertionIndicatorColor}; }`); } const scrollbarSliderBackgroundColor = theme.getColor(listScrollbarSliderBackground); if (scrollbarSliderBackgroundColor) { collector.addRule(` .notebookOverlay .cell-list-container > .monaco-list > .monaco-scrollable-element > .scrollbar > .slider { background: ${editorBackgroundColor}; } `); collector.addRule(` .notebookOverlay .cell-list-container > .monaco-list > .monaco-scrollable-element > .scrollbar > .slider:before { content: ""; width: 100%; height: 100%; position: absolute; background: ${scrollbarSliderBackgroundColor}; } `); /* hack to not have cells see through scroller */ } const scrollbarSliderHoverBackgroundColor = theme.getColor(listScrollbarSliderHoverBackground); if (scrollbarSliderHoverBackgroundColor) { collector.addRule(` .notebookOverlay .cell-list-container > .monaco-list > .monaco-scrollable-element > .scrollbar > .slider:hover { background: ${editorBackgroundColor}; } `); collector.addRule(` .notebookOverlay .cell-list-container > .monaco-list > .monaco-scrollable-element > .scrollbar > .slider:hover:before { content: ""; width: 100%; height: 100%; position: absolute; background: ${scrollbarSliderHoverBackgroundColor}; } `); /* hack to not have cells see through scroller */ } const scrollbarSliderActiveBackgroundColor = theme.getColor(listScrollbarSliderActiveBackground); if (scrollbarSliderActiveBackgroundColor) { collector.addRule(` .notebookOverlay .cell-list-container > .monaco-list > .monaco-scrollable-element > .scrollbar > .slider.active { background: ${editorBackgroundColor}; } `); collector.addRule(` .notebookOverlay .cell-list-container > .monaco-list > .monaco-scrollable-element > .scrollbar > .slider.active:before { content: ""; width: 100%; height: 100%; position: absolute; background: ${scrollbarSliderActiveBackgroundColor}; } `); /* hack to not have cells see through scroller */ } // Cell Margin collector.addRule(`.notebookOverlay .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row > div.cell { margin: 0px ${CELL_MARGIN * 2}px 0px ${CELL_MARGIN}px; }`); collector.addRule(`.notebookOverlay .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row > div.cell.code { margin-left: ${CODE_CELL_LEFT_MARGIN}px; }`); collector.addRule(`.notebookOverlay .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row { padding-top: ${EDITOR_TOP_MARGIN}px; }`); collector.addRule(`.notebookOverlay .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .markdown-cell-row { padding-bottom: ${CELL_BOTTOM_MARGIN}px; }`); collector.addRule(`.notebookOverlay .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .markdown-cell-row .cell-bottom-toolbar-container { margin-top: ${CELL_BOTTOM_MARGIN}px; }`); collector.addRule(`.notebookOverlay .output { margin: 0px ${CELL_MARGIN}px 0px ${CODE_CELL_LEFT_MARGIN + CELL_RUN_GUTTER}px; }`); collector.addRule(`.notebookOverlay .output { width: calc(100% - ${CODE_CELL_LEFT_MARGIN + CELL_RUN_GUTTER + (CELL_MARGIN * 2)}px); }`); collector.addRule(`.notebookOverlay .cell-bottom-toolbar-container { width: calc(100% - ${CELL_MARGIN * 2 + CELL_RUN_GUTTER}px); margin: 0px ${CELL_MARGIN * 2}px 0px ${CELL_MARGIN + CELL_RUN_GUTTER}px; }`); collector.addRule(`.notebookOverlay .cell-list-container > .monaco-list > .monaco-scrollable-element > .monaco-list-rows > .monaco-list-row > div.cell.markdown { padding-left: ${CELL_RUN_GUTTER}px; }`); collector.addRule(`.notebookOverlay .cell .run-button-container { width: ${CELL_RUN_GUTTER}px; }`); collector.addRule(`.notebookOverlay .cell-drag-image .cell-editor-container > div { padding: ${EDITOR_TOP_PADDING}px 16px ${EDITOR_BOTTOM_PADDING}px 16px; }`); collector.addRule(`.notebookOverlay .monaco-list .monaco-list-row .cell-focus-indicator-top { height: ${EDITOR_TOP_MARGIN}px; }`); collector.addRule(`.notebookOverlay .monaco-list .monaco-list-row .cell-focus-indicator-side { bottom: ${BOTTOM_CELL_TOOLBAR_HEIGHT}px; }`); collector.addRule(`.notebookOverlay .monaco-list .monaco-list-row.code-cell-row .cell-focus-indicator-left { width: ${CODE_CELL_LEFT_MARGIN + CELL_RUN_GUTTER}px; }`); collector.addRule(`.notebookOverlay .monaco-list .monaco-list-row.markdown-cell-row .cell-focus-indicator-left { width: ${CODE_CELL_LEFT_MARGIN}px; }`); collector.addRule(`.notebookOverlay .monaco-list .monaco-list-row .cell-focus-indicator.cell-focus-indicator-right { width: ${CELL_MARGIN * 2}px; }`); collector.addRule(`.notebookOverlay .monaco-list .monaco-list-row .cell-focus-indicator-bottom { height: ${CELL_BOTTOM_MARGIN}px; }`); collector.addRule(`.notebookOverlay .monaco-list .monaco-list-row .cell-shadow-container-bottom { top: ${CELL_BOTTOM_MARGIN}px; }`); });
src/vs/workbench/contrib/notebook/browser/notebookEditorWidget.ts
1
https://github.com/microsoft/vscode/commit/9504dda6a717a0a0d45d992e21f2565f8a23f390
[ 0.03845512121915817, 0.0010182263795286417, 0.0001642012648517266, 0.0001707869378151372, 0.004108197055757046 ]
{ "id": 9, "code_window": [ "\t\t}\n", "\t}\n", "\n", "\tprivate focusEditorIfNeeded() {\n", "\t\tif (this.viewCell.focusMode === CellFocusMode.Editor) {\n", "\t\t\tthis.editor?.focus();\n", "\t\t}\n", "\t}\n", "\n", "\tprivate layoutEditor(dimension: IDimension): void {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tif (this.viewCell.focusMode === CellFocusMode.Editor && this.notebookEditor.hasFocus()) {\n" ], "file_path": "src/vs/workbench/contrib/notebook/browser/view/renderers/markdownCell.ts", "type": "replace", "edit_start_line_idx": 229 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as assert from 'assert'; import { ConfigurationModel, DefaultConfigurationModel, ConfigurationChangeEvent, ConfigurationModelParser, Configuration, mergeChanges, AllKeysConfigurationChangeEvent } from 'vs/platform/configuration/common/configurationModels'; import { Extensions, IConfigurationRegistry } from 'vs/platform/configuration/common/configurationRegistry'; import { Registry } from 'vs/platform/registry/common/platform'; import { URI } from 'vs/base/common/uri'; import { Workspace, WorkspaceFolder } from 'vs/platform/workspace/common/workspace'; import { join } from 'vs/base/common/path'; import { ConfigurationTarget } from 'vs/platform/configuration/common/configuration'; suite('ConfigurationModel', () => { test('setValue for a key that has no sections and not defined', () => { let testObject = new ConfigurationModel({ 'a': { 'b': 1 } }, ['a.b']); testObject.setValue('f', 1); assert.deepEqual(testObject.contents, { 'a': { 'b': 1 }, 'f': 1 }); assert.deepEqual(testObject.keys, ['a.b', 'f']); }); test('setValue for a key that has no sections and defined', () => { let testObject = new ConfigurationModel({ 'a': { 'b': 1 }, 'f': 1 }, ['a.b', 'f']); testObject.setValue('f', 3); assert.deepEqual(testObject.contents, { 'a': { 'b': 1 }, 'f': 3 }); assert.deepEqual(testObject.keys, ['a.b', 'f']); }); test('setValue for a key that has sections and not defined', () => { let testObject = new ConfigurationModel({ 'a': { 'b': 1 }, 'f': 1 }, ['a.b', 'f']); testObject.setValue('b.c', 1); assert.deepEqual(testObject.contents, { 'a': { 'b': 1 }, 'b': { 'c': 1 }, 'f': 1 }); assert.deepEqual(testObject.keys, ['a.b', 'f', 'b.c']); }); test('setValue for a key that has sections and defined', () => { let testObject = new ConfigurationModel({ 'a': { 'b': 1 }, 'b': { 'c': 1 }, 'f': 1 }, ['a.b', 'b.c', 'f']); testObject.setValue('b.c', 3); assert.deepEqual(testObject.contents, { 'a': { 'b': 1 }, 'b': { 'c': 3 }, 'f': 1 }); assert.deepEqual(testObject.keys, ['a.b', 'b.c', 'f']); }); test('setValue for a key that has sections and sub section not defined', () => { let testObject = new ConfigurationModel({ 'a': { 'b': 1 }, 'f': 1 }, ['a.b', 'f']); testObject.setValue('a.c', 1); assert.deepEqual(testObject.contents, { 'a': { 'b': 1, 'c': 1 }, 'f': 1 }); assert.deepEqual(testObject.keys, ['a.b', 'f', 'a.c']); }); test('setValue for a key that has sections and sub section defined', () => { let testObject = new ConfigurationModel({ 'a': { 'b': 1, 'c': 1 }, 'f': 1 }, ['a.b', 'a.c', 'f']); testObject.setValue('a.c', 3); assert.deepEqual(testObject.contents, { 'a': { 'b': 1, 'c': 3 }, 'f': 1 }); assert.deepEqual(testObject.keys, ['a.b', 'a.c', 'f']); }); test('setValue for a key that has sections and last section is added', () => { let testObject = new ConfigurationModel({ 'a': { 'b': {} }, 'f': 1 }, ['a.b', 'f']); testObject.setValue('a.b.c', 1); assert.deepEqual(testObject.contents, { 'a': { 'b': { 'c': 1 } }, 'f': 1 }); assert.deepEqual(testObject.keys, ['a.b.c', 'f']); }); test('removeValue: remove a non existing key', () => { let testObject = new ConfigurationModel({ 'a': { 'b': 2 } }, ['a.b']); testObject.removeValue('a.b.c'); assert.deepEqual(testObject.contents, { 'a': { 'b': 2 } }); assert.deepEqual(testObject.keys, ['a.b']); }); test('removeValue: remove a single segmented key', () => { let testObject = new ConfigurationModel({ 'a': 1 }, ['a']); testObject.removeValue('a'); assert.deepEqual(testObject.contents, {}); assert.deepEqual(testObject.keys, []); }); test('removeValue: remove a multi segmented key', () => { let testObject = new ConfigurationModel({ 'a': { 'b': 1 } }, ['a.b']); testObject.removeValue('a.b'); assert.deepEqual(testObject.contents, {}); assert.deepEqual(testObject.keys, []); }); test('get overriding configuration model for an existing identifier', () => { let testObject = new ConfigurationModel( { 'a': { 'b': 1 }, 'f': 1 }, [], [{ identifiers: ['c'], contents: { 'a': { 'd': 1 } }, keys: ['a'] }]); assert.deepEqual(testObject.override('c').contents, { 'a': { 'b': 1, 'd': 1 }, 'f': 1 }); }); test('get overriding configuration model for an identifier that does not exist', () => { let testObject = new ConfigurationModel( { 'a': { 'b': 1 }, 'f': 1 }, [], [{ identifiers: ['c'], contents: { 'a': { 'd': 1 } }, keys: ['a'] }]); assert.deepEqual(testObject.override('xyz').contents, { 'a': { 'b': 1 }, 'f': 1 }); }); test('get overriding configuration when one of the keys does not exist in base', () => { let testObject = new ConfigurationModel( { 'a': { 'b': 1 }, 'f': 1 }, [], [{ identifiers: ['c'], contents: { 'a': { 'd': 1 }, 'g': 1 }, keys: ['a', 'g'] }]); assert.deepEqual(testObject.override('c').contents, { 'a': { 'b': 1, 'd': 1 }, 'f': 1, 'g': 1 }); }); test('get overriding configuration when one of the key in base is not of object type', () => { let testObject = new ConfigurationModel( { 'a': { 'b': 1 }, 'f': 1 }, [], [{ identifiers: ['c'], contents: { 'a': { 'd': 1 }, 'f': { 'g': 1 } }, keys: ['a', 'f'] }]); assert.deepEqual(testObject.override('c').contents, { 'a': { 'b': 1, 'd': 1 }, 'f': { 'g': 1 } }); }); test('get overriding configuration when one of the key in overriding contents is not of object type', () => { let testObject = new ConfigurationModel( { 'a': { 'b': 1 }, 'f': { 'g': 1 } }, [], [{ identifiers: ['c'], contents: { 'a': { 'd': 1 }, 'f': 1 }, keys: ['a', 'f'] }]); assert.deepEqual(testObject.override('c').contents, { 'a': { 'b': 1, 'd': 1 }, 'f': 1 }); }); test('get overriding configuration if the value of overriding identifier is not object', () => { let testObject = new ConfigurationModel( { 'a': { 'b': 1 }, 'f': { 'g': 1 } }, [], [{ identifiers: ['c'], contents: 'abc', keys: [] }]); assert.deepEqual(testObject.override('c').contents, { 'a': { 'b': 1 }, 'f': { 'g': 1 } }); }); test('get overriding configuration if the value of overriding identifier is an empty object', () => { let testObject = new ConfigurationModel( { 'a': { 'b': 1 }, 'f': { 'g': 1 } }, [], [{ identifiers: ['c'], contents: {}, keys: [] }]); assert.deepEqual(testObject.override('c').contents, { 'a': { 'b': 1 }, 'f': { 'g': 1 } }); }); test('simple merge', () => { let base = new ConfigurationModel({ 'a': 1, 'b': 2 }, ['a', 'b']); let add = new ConfigurationModel({ 'a': 3, 'c': 4 }, ['a', 'c']); let result = base.merge(add); assert.deepEqual(result.contents, { 'a': 3, 'b': 2, 'c': 4 }); assert.deepEqual(result.keys, ['a', 'b', 'c']); }); test('recursive merge', () => { let base = new ConfigurationModel({ 'a': { 'b': 1 } }, ['a.b']); let add = new ConfigurationModel({ 'a': { 'b': 2 } }, ['a.b']); let result = base.merge(add); assert.deepEqual(result.contents, { 'a': { 'b': 2 } }); assert.deepEqual(result.getValue('a'), { 'b': 2 }); assert.deepEqual(result.keys, ['a.b']); }); test('simple merge overrides', () => { let base = new ConfigurationModel({ 'a': { 'b': 1 } }, ['a.b'], [{ identifiers: ['c'], contents: { 'a': 2 }, keys: ['a'] }]); let add = new ConfigurationModel({ 'a': { 'b': 2 } }, ['a.b'], [{ identifiers: ['c'], contents: { 'b': 2 }, keys: ['b'] }]); let result = base.merge(add); assert.deepEqual(result.contents, { 'a': { 'b': 2 } }); assert.deepEqual(result.overrides, [{ identifiers: ['c'], contents: { 'a': 2, 'b': 2 }, keys: ['a'] }]); assert.deepEqual(result.override('c').contents, { 'a': 2, 'b': 2 }); assert.deepEqual(result.keys, ['a.b']); }); test('recursive merge overrides', () => { let base = new ConfigurationModel({ 'a': { 'b': 1 }, 'f': 1 }, ['a.b', 'f'], [{ identifiers: ['c'], contents: { 'a': { 'd': 1 } }, keys: ['a'] }]); let add = new ConfigurationModel({ 'a': { 'b': 2 } }, ['a.b'], [{ identifiers: ['c'], contents: { 'a': { 'e': 2 } }, keys: ['a'] }]); let result = base.merge(add); assert.deepEqual(result.contents, { 'a': { 'b': 2 }, 'f': 1 }); assert.deepEqual(result.overrides, [{ identifiers: ['c'], contents: { 'a': { 'd': 1, 'e': 2 } }, keys: ['a'] }]); assert.deepEqual(result.override('c').contents, { 'a': { 'b': 2, 'd': 1, 'e': 2 }, 'f': 1 }); assert.deepEqual(result.keys, ['a.b', 'f']); }); test('merge overrides when frozen', () => { let model1 = new ConfigurationModel({ 'a': { 'b': 1 }, 'f': 1 }, ['a.b', 'f'], [{ identifiers: ['c'], contents: { 'a': { 'd': 1 } }, keys: ['a'] }]).freeze(); let model2 = new ConfigurationModel({ 'a': { 'b': 2 } }, ['a.b'], [{ identifiers: ['c'], contents: { 'a': { 'e': 2 } }, keys: ['a'] }]).freeze(); let result = new ConfigurationModel().merge(model1, model2); assert.deepEqual(result.contents, { 'a': { 'b': 2 }, 'f': 1 }); assert.deepEqual(result.overrides, [{ identifiers: ['c'], contents: { 'a': { 'd': 1, 'e': 2 } }, keys: ['a'] }]); assert.deepEqual(result.override('c').contents, { 'a': { 'b': 2, 'd': 1, 'e': 2 }, 'f': 1 }); assert.deepEqual(result.keys, ['a.b', 'f']); }); test('Test contents while getting an existing property', () => { let testObject = new ConfigurationModel({ 'a': 1 }); assert.deepEqual(testObject.getValue('a'), 1); testObject = new ConfigurationModel({ 'a': { 'b': 1 } }); assert.deepEqual(testObject.getValue('a'), { 'b': 1 }); }); test('Test contents are undefined for non existing properties', () => { const testObject = new ConfigurationModel({ awesome: true }); assert.deepEqual(testObject.getValue('unknownproperty'), undefined); }); test('Test override gives all content merged with overrides', () => { const testObject = new ConfigurationModel({ 'a': 1, 'c': 1 }, [], [{ identifiers: ['b'], contents: { 'a': 2 }, keys: ['a'] }]); assert.deepEqual(testObject.override('b').contents, { 'a': 2, 'c': 1 }); }); }); suite('CustomConfigurationModel', () => { test('simple merge using models', () => { let base = new ConfigurationModelParser('base'); base.parseContent(JSON.stringify({ 'a': 1, 'b': 2 })); let add = new ConfigurationModelParser('add'); add.parseContent(JSON.stringify({ 'a': 3, 'c': 4 })); let result = base.configurationModel.merge(add.configurationModel); assert.deepEqual(result.contents, { 'a': 3, 'b': 2, 'c': 4 }); }); test('simple merge with an undefined contents', () => { let base = new ConfigurationModelParser('base'); base.parseContent(JSON.stringify({ 'a': 1, 'b': 2 })); let add = new ConfigurationModelParser('add'); let result = base.configurationModel.merge(add.configurationModel); assert.deepEqual(result.contents, { 'a': 1, 'b': 2 }); base = new ConfigurationModelParser('base'); add = new ConfigurationModelParser('add'); add.parseContent(JSON.stringify({ 'a': 1, 'b': 2 })); result = base.configurationModel.merge(add.configurationModel); assert.deepEqual(result.contents, { 'a': 1, 'b': 2 }); base = new ConfigurationModelParser('base'); add = new ConfigurationModelParser('add'); result = base.configurationModel.merge(add.configurationModel); assert.deepEqual(result.contents, {}); }); test('Recursive merge using config models', () => { let base = new ConfigurationModelParser('base'); base.parseContent(JSON.stringify({ 'a': { 'b': 1 } })); let add = new ConfigurationModelParser('add'); add.parseContent(JSON.stringify({ 'a': { 'b': 2 } })); let result = base.configurationModel.merge(add.configurationModel); assert.deepEqual(result.contents, { 'a': { 'b': 2 } }); }); test('Test contents while getting an existing property', () => { let testObject = new ConfigurationModelParser('test'); testObject.parseContent(JSON.stringify({ 'a': 1 })); assert.deepEqual(testObject.configurationModel.getValue('a'), 1); testObject.parseContent(JSON.stringify({ 'a': { 'b': 1 } })); assert.deepEqual(testObject.configurationModel.getValue('a'), { 'b': 1 }); }); test('Test contents are undefined for non existing properties', () => { const testObject = new ConfigurationModelParser('test'); testObject.parseContent(JSON.stringify({ awesome: true })); assert.deepEqual(testObject.configurationModel.getValue('unknownproperty'), undefined); }); test('Test contents are undefined for undefined config', () => { const testObject = new ConfigurationModelParser('test'); assert.deepEqual(testObject.configurationModel.getValue('unknownproperty'), undefined); }); test('Test configWithOverrides gives all content merged with overrides', () => { const testObject = new ConfigurationModelParser('test'); testObject.parseContent(JSON.stringify({ 'a': 1, 'c': 1, '[b]': { 'a': 2 } })); assert.deepEqual(testObject.configurationModel.override('b').contents, { 'a': 2, 'c': 1, '[b]': { 'a': 2 } }); }); test('Test configWithOverrides gives empty contents', () => { const testObject = new ConfigurationModelParser('test'); assert.deepEqual(testObject.configurationModel.override('b').contents, {}); }); test('Test update with empty data', () => { const testObject = new ConfigurationModelParser('test'); testObject.parseContent(''); assert.deepEqual(testObject.configurationModel.contents, {}); assert.deepEqual(testObject.configurationModel.keys, []); testObject.parseContent(null!); assert.deepEqual(testObject.configurationModel.contents, {}); assert.deepEqual(testObject.configurationModel.keys, []); testObject.parseContent(undefined!); assert.deepEqual(testObject.configurationModel.contents, {}); assert.deepEqual(testObject.configurationModel.keys, []); }); test('Test registering the same property again', () => { Registry.as<IConfigurationRegistry>(Extensions.Configuration).registerConfiguration({ 'id': 'a', 'order': 1, 'title': 'a', 'type': 'object', 'properties': { 'a': { 'description': 'a', 'type': 'boolean', 'default': true, } } }); Registry.as<IConfigurationRegistry>(Extensions.Configuration).registerConfiguration({ 'id': 'a', 'order': 1, 'title': 'a', 'type': 'object', 'properties': { 'a': { 'description': 'a', 'type': 'boolean', 'default': false, } } }); assert.equal(true, new DefaultConfigurationModel().getValue('a')); }); }); suite('Configuration', () => { test('Test inspect for overrideIdentifiers', () => { const defaultConfigurationModel = parseConfigurationModel({ '[l1]': { 'a': 1 }, '[l2]': { 'b': 1 } }); const userConfigurationModel = parseConfigurationModel({ '[l3]': { 'a': 2 } }); const workspaceConfigurationModel = parseConfigurationModel({ '[l1]': { 'a': 3 }, '[l4]': { 'a': 3 } }); const testObject: Configuration = new Configuration(defaultConfigurationModel, userConfigurationModel, new ConfigurationModel(), workspaceConfigurationModel); const { overrideIdentifiers } = testObject.inspect('a', {}, undefined); assert.deepEqual(overrideIdentifiers, ['l1', 'l3', 'l4']); }); test('Test update value', () => { const parser = new ConfigurationModelParser('test'); parser.parseContent(JSON.stringify({ 'a': 1 })); const testObject: Configuration = new Configuration(parser.configurationModel, new ConfigurationModel()); testObject.updateValue('a', 2); assert.equal(testObject.getValue('a', {}, undefined), 2); }); test('Test update value after inspect', () => { const parser = new ConfigurationModelParser('test'); parser.parseContent(JSON.stringify({ 'a': 1 })); const testObject: Configuration = new Configuration(parser.configurationModel, new ConfigurationModel()); testObject.inspect('a', {}, undefined); testObject.updateValue('a', 2); assert.equal(testObject.getValue('a', {}, undefined), 2); }); test('Test compare and update default configuration', () => { const testObject = new Configuration(new ConfigurationModel(), new ConfigurationModel()); testObject.updateDefaultConfiguration(toConfigurationModel({ 'editor.lineNumbers': 'on', })); const actual = testObject.compareAndUpdateDefaultConfiguration(toConfigurationModel({ 'editor.lineNumbers': 'off', '[markdown]': { 'editor.wordWrap': 'off' } }), ['editor.lineNumbers', '[markdown]']); assert.deepEqual(actual, { keys: ['editor.lineNumbers', '[markdown]'], overrides: [['markdown', ['editor.wordWrap']]] }); }); test('Test compare and update user configuration', () => { const testObject = new Configuration(new ConfigurationModel(), new ConfigurationModel()); testObject.updateLocalUserConfiguration(toConfigurationModel({ 'editor.lineNumbers': 'off', 'editor.fontSize': 12, '[typescript]': { 'editor.wordWrap': 'off' } })); const actual = testObject.compareAndUpdateLocalUserConfiguration(toConfigurationModel({ 'editor.lineNumbers': 'on', 'window.zoomLevel': 1, '[typescript]': { 'editor.wordWrap': 'on', 'editor.insertSpaces': false } })); assert.deepEqual(actual, { keys: ['window.zoomLevel', 'editor.lineNumbers', '[typescript]', 'editor.fontSize'], overrides: [['typescript', ['editor.insertSpaces', 'editor.wordWrap']]] }); }); test('Test compare and update workspace configuration', () => { const testObject = new Configuration(new ConfigurationModel(), new ConfigurationModel()); testObject.updateWorkspaceConfiguration(toConfigurationModel({ 'editor.lineNumbers': 'off', 'editor.fontSize': 12, '[typescript]': { 'editor.wordWrap': 'off' } })); const actual = testObject.compareAndUpdateWorkspaceConfiguration(toConfigurationModel({ 'editor.lineNumbers': 'on', 'window.zoomLevel': 1, '[typescript]': { 'editor.wordWrap': 'on', 'editor.insertSpaces': false } })); assert.deepEqual(actual, { keys: ['window.zoomLevel', 'editor.lineNumbers', '[typescript]', 'editor.fontSize'], overrides: [['typescript', ['editor.insertSpaces', 'editor.wordWrap']]] }); }); test('Test compare and update workspace folder configuration', () => { const testObject = new Configuration(new ConfigurationModel(), new ConfigurationModel()); testObject.updateFolderConfiguration(URI.file('file1'), toConfigurationModel({ 'editor.lineNumbers': 'off', 'editor.fontSize': 12, '[typescript]': { 'editor.wordWrap': 'off' } })); const actual = testObject.compareAndUpdateFolderConfiguration(URI.file('file1'), toConfigurationModel({ 'editor.lineNumbers': 'on', 'window.zoomLevel': 1, '[typescript]': { 'editor.wordWrap': 'on', 'editor.insertSpaces': false } })); assert.deepEqual(actual, { keys: ['window.zoomLevel', 'editor.lineNumbers', '[typescript]', 'editor.fontSize'], overrides: [['typescript', ['editor.insertSpaces', 'editor.wordWrap']]] }); }); test('Test compare and delete workspace folder configuration', () => { const testObject = new Configuration(new ConfigurationModel(), new ConfigurationModel()); testObject.updateFolderConfiguration(URI.file('file1'), toConfigurationModel({ 'editor.lineNumbers': 'off', 'editor.fontSize': 12, '[typescript]': { 'editor.wordWrap': 'off' } })); const actual = testObject.compareAndDeleteFolderConfiguration(URI.file('file1')); assert.deepEqual(actual, { keys: ['editor.lineNumbers', 'editor.fontSize', '[typescript]'], overrides: [['typescript', ['editor.wordWrap']]] }); }); function parseConfigurationModel(content: any): ConfigurationModel { const parser = new ConfigurationModelParser('test'); parser.parseContent(JSON.stringify(content)); return parser.configurationModel; } }); suite('ConfigurationChangeEvent', () => { test('changeEvent affecting keys with new configuration', () => { const configuration = new Configuration(new ConfigurationModel(), new ConfigurationModel()); const change = configuration.compareAndUpdateLocalUserConfiguration(toConfigurationModel({ 'window.zoomLevel': 1, 'workbench.editor.enablePreview': false, 'files.autoSave': 'off', })); let testObject = new ConfigurationChangeEvent(change, undefined, configuration); assert.deepEqual(testObject.affectedKeys, ['window.zoomLevel', 'workbench.editor.enablePreview', 'files.autoSave']); assert.ok(testObject.affectsConfiguration('window.zoomLevel')); assert.ok(testObject.affectsConfiguration('window')); assert.ok(testObject.affectsConfiguration('workbench.editor.enablePreview')); assert.ok(testObject.affectsConfiguration('workbench.editor')); assert.ok(testObject.affectsConfiguration('workbench')); assert.ok(testObject.affectsConfiguration('files')); assert.ok(testObject.affectsConfiguration('files.autoSave')); assert.ok(!testObject.affectsConfiguration('files.exclude')); assert.ok(!testObject.affectsConfiguration('[markdown]')); assert.ok(!testObject.affectsConfiguration('editor')); }); test('changeEvent affecting keys when configuration changed', () => { const configuration = new Configuration(new ConfigurationModel(), new ConfigurationModel()); configuration.updateLocalUserConfiguration(toConfigurationModel({ 'window.zoomLevel': 2, 'workbench.editor.enablePreview': true, 'files.autoSave': 'off', })); const data = configuration.toData(); const change = configuration.compareAndUpdateLocalUserConfiguration(toConfigurationModel({ 'window.zoomLevel': 1, 'workbench.editor.enablePreview': false, 'files.autoSave': 'off', })); let testObject = new ConfigurationChangeEvent(change, { data }, configuration); assert.deepEqual(testObject.affectedKeys, ['window.zoomLevel', 'workbench.editor.enablePreview']); assert.ok(testObject.affectsConfiguration('window.zoomLevel')); assert.ok(testObject.affectsConfiguration('window')); assert.ok(testObject.affectsConfiguration('workbench.editor.enablePreview')); assert.ok(testObject.affectsConfiguration('workbench.editor')); assert.ok(testObject.affectsConfiguration('workbench')); assert.ok(!testObject.affectsConfiguration('files')); assert.ok(!testObject.affectsConfiguration('[markdown]')); assert.ok(!testObject.affectsConfiguration('editor')); }); test('changeEvent affecting overrides with new configuration', () => { const configuration = new Configuration(new ConfigurationModel(), new ConfigurationModel()); const change = configuration.compareAndUpdateLocalUserConfiguration(toConfigurationModel({ 'files.autoSave': 'off', '[markdown]': { 'editor.wordWrap': 'off' } })); let testObject = new ConfigurationChangeEvent(change, undefined, configuration); assert.deepEqual(testObject.affectedKeys, ['files.autoSave', '[markdown]', 'editor.wordWrap']); assert.ok(testObject.affectsConfiguration('files')); assert.ok(testObject.affectsConfiguration('files.autoSave')); assert.ok(!testObject.affectsConfiguration('files.exclude')); assert.ok(testObject.affectsConfiguration('[markdown]')); assert.ok(!testObject.affectsConfiguration('[markdown].editor')); assert.ok(!testObject.affectsConfiguration('[markdown].workbench')); assert.ok(testObject.affectsConfiguration('editor')); assert.ok(testObject.affectsConfiguration('editor.wordWrap')); assert.ok(testObject.affectsConfiguration('editor', { overrideIdentifier: 'markdown' })); assert.ok(testObject.affectsConfiguration('editor.wordWrap', { overrideIdentifier: 'markdown' })); assert.ok(!testObject.affectsConfiguration('editor', { overrideIdentifier: 'json' })); assert.ok(!testObject.affectsConfiguration('editor.fontSize', { overrideIdentifier: 'markdown' })); assert.ok(!testObject.affectsConfiguration('editor.fontSize')); assert.ok(!testObject.affectsConfiguration('window')); }); test('changeEvent affecting overrides when configuration changed', () => { const configuration = new Configuration(new ConfigurationModel(), new ConfigurationModel()); configuration.updateLocalUserConfiguration(toConfigurationModel({ 'workbench.editor.enablePreview': true, '[markdown]': { 'editor.fontSize': 12, 'editor.wordWrap': 'off' }, 'files.autoSave': 'off', })); const data = configuration.toData(); const change = configuration.compareAndUpdateLocalUserConfiguration(toConfigurationModel({ 'files.autoSave': 'off', '[markdown]': { 'editor.fontSize': 13, 'editor.wordWrap': 'off' }, 'window.zoomLevel': 1, })); let testObject = new ConfigurationChangeEvent(change, { data }, configuration); assert.deepEqual(testObject.affectedKeys, ['window.zoomLevel', '[markdown]', 'workbench.editor.enablePreview', 'editor.fontSize']); assert.ok(!testObject.affectsConfiguration('files')); assert.ok(testObject.affectsConfiguration('[markdown]')); assert.ok(!testObject.affectsConfiguration('[markdown].editor')); assert.ok(!testObject.affectsConfiguration('[markdown].editor.fontSize')); assert.ok(!testObject.affectsConfiguration('[markdown].editor.wordWrap')); assert.ok(!testObject.affectsConfiguration('[markdown].workbench')); assert.ok(testObject.affectsConfiguration('editor')); assert.ok(testObject.affectsConfiguration('editor', { overrideIdentifier: 'markdown' })); assert.ok(testObject.affectsConfiguration('editor.fontSize', { overrideIdentifier: 'markdown' })); assert.ok(!testObject.affectsConfiguration('editor.wordWrap')); assert.ok(!testObject.affectsConfiguration('editor.wordWrap', { overrideIdentifier: 'markdown' })); assert.ok(!testObject.affectsConfiguration('editor', { overrideIdentifier: 'json' })); assert.ok(!testObject.affectsConfiguration('editor.fontSize', { overrideIdentifier: 'json' })); assert.ok(testObject.affectsConfiguration('window')); assert.ok(testObject.affectsConfiguration('window.zoomLevel')); assert.ok(testObject.affectsConfiguration('window', { overrideIdentifier: 'markdown' })); assert.ok(testObject.affectsConfiguration('window.zoomLevel', { overrideIdentifier: 'markdown' })); assert.ok(testObject.affectsConfiguration('workbench')); assert.ok(testObject.affectsConfiguration('workbench.editor')); assert.ok(testObject.affectsConfiguration('workbench.editor.enablePreview')); assert.ok(testObject.affectsConfiguration('workbench', { overrideIdentifier: 'markdown' })); assert.ok(testObject.affectsConfiguration('workbench.editor', { overrideIdentifier: 'markdown' })); }); test('changeEvent affecting workspace folders', () => { const configuration = new Configuration(new ConfigurationModel(), new ConfigurationModel()); configuration.updateWorkspaceConfiguration(toConfigurationModel({ 'window.title': 'custom' })); configuration.updateFolderConfiguration(URI.file('folder1'), toConfigurationModel({ 'window.zoomLevel': 2, 'window.restoreFullscreen': true })); configuration.updateFolderConfiguration(URI.file('folder2'), toConfigurationModel({ 'workbench.editor.enablePreview': true, 'window.restoreWindows': true })); const data = configuration.toData(); const workspace = new Workspace('a', [new WorkspaceFolder({ index: 0, name: 'a', uri: URI.file('folder1') }), new WorkspaceFolder({ index: 1, name: 'b', uri: URI.file('folder2') }), new WorkspaceFolder({ index: 2, name: 'c', uri: URI.file('folder3') })]); const change = mergeChanges( configuration.compareAndUpdateWorkspaceConfiguration(toConfigurationModel({ 'window.title': 'native' })), configuration.compareAndUpdateFolderConfiguration(URI.file('folder1'), toConfigurationModel({ 'window.zoomLevel': 1, 'window.restoreFullscreen': false })), configuration.compareAndUpdateFolderConfiguration(URI.file('folder2'), toConfigurationModel({ 'workbench.editor.enablePreview': false, 'window.restoreWindows': false })) ); let testObject = new ConfigurationChangeEvent(change, { data, workspace }, configuration, workspace); assert.deepEqual(testObject.affectedKeys, ['window.title', 'window.zoomLevel', 'window.restoreFullscreen', 'workbench.editor.enablePreview', 'window.restoreWindows']); assert.ok(testObject.affectsConfiguration('window.zoomLevel')); assert.ok(testObject.affectsConfiguration('window.zoomLevel', { resource: URI.file('folder1') })); assert.ok(testObject.affectsConfiguration('window.zoomLevel', { resource: URI.file(join('folder1', 'file1')) })); assert.ok(!testObject.affectsConfiguration('window.zoomLevel', { resource: URI.file('file1') })); assert.ok(!testObject.affectsConfiguration('window.zoomLevel', { resource: URI.file('file2') })); assert.ok(!testObject.affectsConfiguration('window.zoomLevel', { resource: URI.file(join('folder2', 'file2')) })); assert.ok(!testObject.affectsConfiguration('window.zoomLevel', { resource: URI.file(join('folder3', 'file3')) })); assert.ok(testObject.affectsConfiguration('window.restoreFullscreen')); assert.ok(testObject.affectsConfiguration('window.restoreFullscreen', { resource: URI.file(join('folder1', 'file1')) })); assert.ok(testObject.affectsConfiguration('window.restoreFullscreen', { resource: URI.file('folder1') })); assert.ok(!testObject.affectsConfiguration('window.restoreFullscreen', { resource: URI.file('file1') })); assert.ok(!testObject.affectsConfiguration('window.restoreFullscreen', { resource: URI.file('file2') })); assert.ok(!testObject.affectsConfiguration('window.restoreFullscreen', { resource: URI.file(join('folder2', 'file2')) })); assert.ok(!testObject.affectsConfiguration('window.restoreFullscreen', { resource: URI.file(join('folder3', 'file3')) })); assert.ok(testObject.affectsConfiguration('window.restoreWindows')); assert.ok(testObject.affectsConfiguration('window.restoreWindows', { resource: URI.file('folder2') })); assert.ok(testObject.affectsConfiguration('window.restoreWindows', { resource: URI.file(join('folder2', 'file2')) })); assert.ok(!testObject.affectsConfiguration('window.restoreWindows', { resource: URI.file('file2') })); assert.ok(!testObject.affectsConfiguration('window.restoreWindows', { resource: URI.file(join('folder1', 'file1')) })); assert.ok(!testObject.affectsConfiguration('window.restoreWindows', { resource: URI.file(join('folder3', 'file3')) })); assert.ok(testObject.affectsConfiguration('window.title')); assert.ok(testObject.affectsConfiguration('window.title', { resource: URI.file('folder1') })); assert.ok(testObject.affectsConfiguration('window.title', { resource: URI.file(join('folder1', 'file1')) })); assert.ok(testObject.affectsConfiguration('window.title', { resource: URI.file('folder2') })); assert.ok(testObject.affectsConfiguration('window.title', { resource: URI.file(join('folder2', 'file2')) })); assert.ok(testObject.affectsConfiguration('window.title', { resource: URI.file('folder3') })); assert.ok(testObject.affectsConfiguration('window.title', { resource: URI.file(join('folder3', 'file3')) })); assert.ok(testObject.affectsConfiguration('window.title', { resource: URI.file('file1') })); assert.ok(testObject.affectsConfiguration('window.title', { resource: URI.file('file2') })); assert.ok(testObject.affectsConfiguration('window.title', { resource: URI.file('file3') })); assert.ok(testObject.affectsConfiguration('window')); assert.ok(testObject.affectsConfiguration('window', { resource: URI.file('folder1') })); assert.ok(testObject.affectsConfiguration('window', { resource: URI.file(join('folder1', 'file1')) })); assert.ok(testObject.affectsConfiguration('window', { resource: URI.file('folder2') })); assert.ok(testObject.affectsConfiguration('window', { resource: URI.file(join('folder2', 'file2')) })); assert.ok(testObject.affectsConfiguration('window', { resource: URI.file('folder3') })); assert.ok(testObject.affectsConfiguration('window', { resource: URI.file(join('folder3', 'file3')) })); assert.ok(testObject.affectsConfiguration('window', { resource: URI.file('file1') })); assert.ok(testObject.affectsConfiguration('window', { resource: URI.file('file2') })); assert.ok(testObject.affectsConfiguration('window', { resource: URI.file('file3') })); assert.ok(testObject.affectsConfiguration('workbench.editor.enablePreview')); assert.ok(testObject.affectsConfiguration('workbench.editor.enablePreview', { resource: URI.file('folder2') })); assert.ok(testObject.affectsConfiguration('workbench.editor.enablePreview', { resource: URI.file(join('folder2', 'file2')) })); assert.ok(!testObject.affectsConfiguration('workbench.editor.enablePreview', { resource: URI.file('folder1') })); assert.ok(!testObject.affectsConfiguration('workbench.editor.enablePreview', { resource: URI.file(join('folder1', 'file1')) })); assert.ok(!testObject.affectsConfiguration('workbench.editor.enablePreview', { resource: URI.file('folder3') })); assert.ok(testObject.affectsConfiguration('workbench.editor')); assert.ok(testObject.affectsConfiguration('workbench.editor', { resource: URI.file('folder2') })); assert.ok(testObject.affectsConfiguration('workbench.editor', { resource: URI.file(join('folder2', 'file2')) })); assert.ok(!testObject.affectsConfiguration('workbench.editor', { resource: URI.file('folder1') })); assert.ok(!testObject.affectsConfiguration('workbench.editor', { resource: URI.file(join('folder1', 'file1')) })); assert.ok(!testObject.affectsConfiguration('workbench.editor', { resource: URI.file('folder3') })); assert.ok(testObject.affectsConfiguration('workbench')); assert.ok(testObject.affectsConfiguration('workbench', { resource: URI.file('folder2') })); assert.ok(testObject.affectsConfiguration('workbench', { resource: URI.file(join('folder2', 'file2')) })); assert.ok(!testObject.affectsConfiguration('workbench', { resource: URI.file('folder1') })); assert.ok(!testObject.affectsConfiguration('workbench', { resource: URI.file('folder3') })); assert.ok(!testObject.affectsConfiguration('files')); assert.ok(!testObject.affectsConfiguration('files', { resource: URI.file('folder1') })); assert.ok(!testObject.affectsConfiguration('files', { resource: URI.file(join('folder1', 'file1')) })); assert.ok(!testObject.affectsConfiguration('files', { resource: URI.file('folder2') })); assert.ok(!testObject.affectsConfiguration('files', { resource: URI.file(join('folder2', 'file2')) })); assert.ok(!testObject.affectsConfiguration('files', { resource: URI.file('folder3') })); assert.ok(!testObject.affectsConfiguration('files', { resource: URI.file(join('folder3', 'file3')) })); }); test('changeEvent - all', () => { const configuration = new Configuration(new ConfigurationModel(), new ConfigurationModel()); configuration.updateFolderConfiguration(URI.file('file1'), toConfigurationModel({ 'window.zoomLevel': 2, 'window.restoreFullscreen': true })); const data = configuration.toData(); const change = mergeChanges( configuration.compareAndUpdateDefaultConfiguration(toConfigurationModel({ 'editor.lineNumbers': 'off', '[markdown]': { 'editor.wordWrap': 'off' } }), ['editor.lineNumbers', '[markdown]']), configuration.compareAndUpdateLocalUserConfiguration(toConfigurationModel({ '[json]': { 'editor.lineNumbers': 'relative' } })), configuration.compareAndUpdateWorkspaceConfiguration(toConfigurationModel({ 'window.title': 'custom' })), configuration.compareAndDeleteFolderConfiguration(URI.file('file1')), configuration.compareAndUpdateFolderConfiguration(URI.file('file2'), toConfigurationModel({ 'workbench.editor.enablePreview': true, 'window.restoreWindows': true }))); const workspace = new Workspace('a', [new WorkspaceFolder({ index: 0, name: 'a', uri: URI.file('file1') }), new WorkspaceFolder({ index: 1, name: 'b', uri: URI.file('file2') }), new WorkspaceFolder({ index: 2, name: 'c', uri: URI.file('folder3') })]); const testObject = new ConfigurationChangeEvent(change, { data, workspace }, configuration, workspace); assert.deepEqual(testObject.affectedKeys, ['editor.lineNumbers', '[markdown]', '[json]', 'window.title', 'window.zoomLevel', 'window.restoreFullscreen', 'workbench.editor.enablePreview', 'window.restoreWindows', 'editor.wordWrap']); assert.ok(testObject.affectsConfiguration('window.title')); assert.ok(testObject.affectsConfiguration('window.title', { resource: URI.file('file1') })); assert.ok(testObject.affectsConfiguration('window.title', { resource: URI.file('file2') })); assert.ok(testObject.affectsConfiguration('window')); assert.ok(testObject.affectsConfiguration('window', { resource: URI.file('file1') })); assert.ok(testObject.affectsConfiguration('window', { resource: URI.file('file2') })); assert.ok(testObject.affectsConfiguration('window.zoomLevel')); assert.ok(testObject.affectsConfiguration('window.zoomLevel', { resource: URI.file('file1') })); assert.ok(!testObject.affectsConfiguration('window.zoomLevel', { resource: URI.file('file2') })); assert.ok(testObject.affectsConfiguration('window.restoreFullscreen')); assert.ok(testObject.affectsConfiguration('window.restoreFullscreen', { resource: URI.file('file1') })); assert.ok(!testObject.affectsConfiguration('window.restoreFullscreen', { resource: URI.file('file2') })); assert.ok(testObject.affectsConfiguration('window.restoreWindows')); assert.ok(testObject.affectsConfiguration('window.restoreWindows', { resource: URI.file('file2') })); assert.ok(!testObject.affectsConfiguration('window.restoreWindows', { resource: URI.file('file1') })); assert.ok(testObject.affectsConfiguration('workbench.editor.enablePreview')); assert.ok(testObject.affectsConfiguration('workbench.editor.enablePreview', { resource: URI.file('file2') })); assert.ok(!testObject.affectsConfiguration('workbench.editor.enablePreview', { resource: URI.file('file1') })); assert.ok(testObject.affectsConfiguration('workbench.editor')); assert.ok(testObject.affectsConfiguration('workbench.editor', { resource: URI.file('file2') })); assert.ok(!testObject.affectsConfiguration('workbench.editor', { resource: URI.file('file1') })); assert.ok(testObject.affectsConfiguration('workbench')); assert.ok(testObject.affectsConfiguration('workbench', { resource: URI.file('file2') })); assert.ok(!testObject.affectsConfiguration('workbench', { resource: URI.file('file1') })); assert.ok(!testObject.affectsConfiguration('files')); assert.ok(!testObject.affectsConfiguration('files', { resource: URI.file('file1') })); assert.ok(!testObject.affectsConfiguration('files', { resource: URI.file('file2') })); assert.ok(testObject.affectsConfiguration('editor')); assert.ok(testObject.affectsConfiguration('editor', { resource: URI.file('file1') })); assert.ok(testObject.affectsConfiguration('editor', { resource: URI.file('file2') })); assert.ok(testObject.affectsConfiguration('editor', { resource: URI.file('file1'), overrideIdentifier: 'json' })); assert.ok(testObject.affectsConfiguration('editor', { resource: URI.file('file1'), overrideIdentifier: 'markdown' })); assert.ok(testObject.affectsConfiguration('editor', { resource: URI.file('file1'), overrideIdentifier: 'typescript' })); assert.ok(testObject.affectsConfiguration('editor', { resource: URI.file('file2'), overrideIdentifier: 'json' })); assert.ok(testObject.affectsConfiguration('editor', { resource: URI.file('file2'), overrideIdentifier: 'markdown' })); assert.ok(testObject.affectsConfiguration('editor', { resource: URI.file('file2'), overrideIdentifier: 'typescript' })); assert.ok(testObject.affectsConfiguration('editor.lineNumbers')); assert.ok(testObject.affectsConfiguration('editor.lineNumbers', { resource: URI.file('file1') })); assert.ok(testObject.affectsConfiguration('editor.lineNumbers', { resource: URI.file('file2') })); assert.ok(testObject.affectsConfiguration('editor.lineNumbers', { resource: URI.file('file1'), overrideIdentifier: 'json' })); assert.ok(testObject.affectsConfiguration('editor.lineNumbers', { resource: URI.file('file1'), overrideIdentifier: 'markdown' })); assert.ok(testObject.affectsConfiguration('editor.lineNumbers', { resource: URI.file('file1'), overrideIdentifier: 'typescript' })); assert.ok(testObject.affectsConfiguration('editor.lineNumbers', { resource: URI.file('file2'), overrideIdentifier: 'json' })); assert.ok(testObject.affectsConfiguration('editor.lineNumbers', { resource: URI.file('file2'), overrideIdentifier: 'markdown' })); assert.ok(testObject.affectsConfiguration('editor.lineNumbers', { resource: URI.file('file2'), overrideIdentifier: 'typescript' })); assert.ok(testObject.affectsConfiguration('editor.wordWrap')); assert.ok(!testObject.affectsConfiguration('editor.wordWrap', { resource: URI.file('file1') })); assert.ok(!testObject.affectsConfiguration('editor.wordWrap', { resource: URI.file('file2') })); assert.ok(!testObject.affectsConfiguration('editor.wordWrap', { resource: URI.file('file1'), overrideIdentifier: 'json' })); assert.ok(testObject.affectsConfiguration('editor.wordWrap', { resource: URI.file('file1'), overrideIdentifier: 'markdown' })); assert.ok(!testObject.affectsConfiguration('editor.wordWrap', { resource: URI.file('file1'), overrideIdentifier: 'typescript' })); assert.ok(!testObject.affectsConfiguration('editor.wordWrap', { resource: URI.file('file2'), overrideIdentifier: 'json' })); assert.ok(testObject.affectsConfiguration('editor.wordWrap', { resource: URI.file('file2'), overrideIdentifier: 'markdown' })); assert.ok(!testObject.affectsConfiguration('editor.wordWrap', { resource: URI.file('file2'), overrideIdentifier: 'typescript' })); assert.ok(!testObject.affectsConfiguration('editor.fontSize')); assert.ok(!testObject.affectsConfiguration('editor.fontSize', { resource: URI.file('file1') })); assert.ok(!testObject.affectsConfiguration('editor.fontSize', { resource: URI.file('file2') })); }); test('changeEvent affecting tasks and launches', () => { const configuration = new Configuration(new ConfigurationModel(), new ConfigurationModel()); const change = configuration.compareAndUpdateLocalUserConfiguration(toConfigurationModel({ 'launch': { 'configuraiton': {} }, 'launch.version': 1, 'tasks': { 'version': 2 } })); let testObject = new ConfigurationChangeEvent(change, undefined, configuration); assert.deepEqual(testObject.affectedKeys, ['launch', 'launch.version', 'tasks']); assert.ok(testObject.affectsConfiguration('launch')); assert.ok(testObject.affectsConfiguration('launch.version')); assert.ok(testObject.affectsConfiguration('tasks')); }); }); suite('AllKeysConfigurationChangeEvent', () => { test('changeEvent', () => { const configuration = new Configuration(new ConfigurationModel(), new ConfigurationModel()); configuration.updateDefaultConfiguration(toConfigurationModel({ 'editor.lineNumbers': 'off', '[markdown]': { 'editor.wordWrap': 'off' } })); configuration.updateLocalUserConfiguration(toConfigurationModel({ '[json]': { 'editor.lineNumbers': 'relative' } })); configuration.updateWorkspaceConfiguration(toConfigurationModel({ 'window.title': 'custom' })); configuration.updateFolderConfiguration(URI.file('file1'), toConfigurationModel({ 'window.zoomLevel': 2, 'window.restoreFullscreen': true })); configuration.updateFolderConfiguration(URI.file('file2'), toConfigurationModel({ 'workbench.editor.enablePreview': true, 'window.restoreWindows': true })); const workspace = new Workspace('a', [new WorkspaceFolder({ index: 0, name: 'a', uri: URI.file('file1') }), new WorkspaceFolder({ index: 1, name: 'b', uri: URI.file('file2') }), new WorkspaceFolder({ index: 2, name: 'c', uri: URI.file('folder3') })]); let testObject = new AllKeysConfigurationChangeEvent(configuration, workspace, ConfigurationTarget.USER, null); assert.deepEqual(testObject.affectedKeys, ['editor.lineNumbers', '[markdown]', '[json]', 'window.title', 'window.zoomLevel', 'window.restoreFullscreen', 'workbench.editor.enablePreview', 'window.restoreWindows']); assert.ok(testObject.affectsConfiguration('window.title')); assert.ok(testObject.affectsConfiguration('window.title', { resource: URI.file('file1') })); assert.ok(testObject.affectsConfiguration('window.title', { resource: URI.file('file2') })); assert.ok(testObject.affectsConfiguration('window')); assert.ok(testObject.affectsConfiguration('window', { resource: URI.file('file1') })); assert.ok(testObject.affectsConfiguration('window', { resource: URI.file('file2') })); assert.ok(testObject.affectsConfiguration('window.zoomLevel')); assert.ok(testObject.affectsConfiguration('window.zoomLevel', { resource: URI.file('file1') })); assert.ok(!testObject.affectsConfiguration('window.zoomLevel', { resource: URI.file('file2') })); assert.ok(testObject.affectsConfiguration('window.restoreFullscreen')); assert.ok(testObject.affectsConfiguration('window.restoreFullscreen', { resource: URI.file('file1') })); assert.ok(!testObject.affectsConfiguration('window.restoreFullscreen', { resource: URI.file('file2') })); assert.ok(testObject.affectsConfiguration('window.restoreWindows')); assert.ok(testObject.affectsConfiguration('window.restoreWindows', { resource: URI.file('file2') })); assert.ok(!testObject.affectsConfiguration('window.restoreWindows', { resource: URI.file('file1') })); assert.ok(testObject.affectsConfiguration('workbench.editor.enablePreview')); assert.ok(testObject.affectsConfiguration('workbench.editor.enablePreview', { resource: URI.file('file2') })); assert.ok(!testObject.affectsConfiguration('workbench.editor.enablePreview', { resource: URI.file('file1') })); assert.ok(testObject.affectsConfiguration('workbench.editor')); assert.ok(testObject.affectsConfiguration('workbench.editor', { resource: URI.file('file2') })); assert.ok(!testObject.affectsConfiguration('workbench.editor', { resource: URI.file('file1') })); assert.ok(testObject.affectsConfiguration('workbench')); assert.ok(testObject.affectsConfiguration('workbench', { resource: URI.file('file2') })); assert.ok(!testObject.affectsConfiguration('workbench', { resource: URI.file('file1') })); assert.ok(!testObject.affectsConfiguration('files')); assert.ok(!testObject.affectsConfiguration('files', { resource: URI.file('file1') })); assert.ok(!testObject.affectsConfiguration('files', { resource: URI.file('file2') })); assert.ok(testObject.affectsConfiguration('editor')); assert.ok(testObject.affectsConfiguration('editor', { resource: URI.file('file1') })); assert.ok(testObject.affectsConfiguration('editor', { resource: URI.file('file2') })); assert.ok(testObject.affectsConfiguration('editor', { resource: URI.file('file1'), overrideIdentifier: 'json' })); assert.ok(testObject.affectsConfiguration('editor', { resource: URI.file('file1'), overrideIdentifier: 'markdown' })); assert.ok(testObject.affectsConfiguration('editor', { resource: URI.file('file1'), overrideIdentifier: 'typescript' })); assert.ok(testObject.affectsConfiguration('editor', { resource: URI.file('file2'), overrideIdentifier: 'json' })); assert.ok(testObject.affectsConfiguration('editor', { resource: URI.file('file2'), overrideIdentifier: 'markdown' })); assert.ok(testObject.affectsConfiguration('editor', { resource: URI.file('file2'), overrideIdentifier: 'typescript' })); assert.ok(testObject.affectsConfiguration('editor.lineNumbers')); assert.ok(testObject.affectsConfiguration('editor.lineNumbers', { resource: URI.file('file1') })); assert.ok(testObject.affectsConfiguration('editor.lineNumbers', { resource: URI.file('file2') })); assert.ok(testObject.affectsConfiguration('editor.lineNumbers', { resource: URI.file('file1'), overrideIdentifier: 'json' })); assert.ok(testObject.affectsConfiguration('editor.lineNumbers', { resource: URI.file('file1'), overrideIdentifier: 'markdown' })); assert.ok(testObject.affectsConfiguration('editor.lineNumbers', { resource: URI.file('file1'), overrideIdentifier: 'typescript' })); assert.ok(testObject.affectsConfiguration('editor.lineNumbers', { resource: URI.file('file2'), overrideIdentifier: 'json' })); assert.ok(testObject.affectsConfiguration('editor.lineNumbers', { resource: URI.file('file2'), overrideIdentifier: 'markdown' })); assert.ok(testObject.affectsConfiguration('editor.lineNumbers', { resource: URI.file('file2'), overrideIdentifier: 'typescript' })); assert.ok(!testObject.affectsConfiguration('editor.wordWrap')); assert.ok(!testObject.affectsConfiguration('editor.wordWrap', { resource: URI.file('file1') })); assert.ok(!testObject.affectsConfiguration('editor.wordWrap', { resource: URI.file('file2') })); assert.ok(!testObject.affectsConfiguration('editor.wordWrap', { resource: URI.file('file1'), overrideIdentifier: 'json' })); assert.ok(!testObject.affectsConfiguration('editor.wordWrap', { resource: URI.file('file1'), overrideIdentifier: 'markdown' })); assert.ok(!testObject.affectsConfiguration('editor.wordWrap', { resource: URI.file('file1'), overrideIdentifier: 'typescript' })); assert.ok(!testObject.affectsConfiguration('editor.wordWrap', { resource: URI.file('file2'), overrideIdentifier: 'json' })); assert.ok(!testObject.affectsConfiguration('editor.wordWrap', { resource: URI.file('file2'), overrideIdentifier: 'markdown' })); assert.ok(!testObject.affectsConfiguration('editor.wordWrap', { resource: URI.file('file2'), overrideIdentifier: 'typescript' })); assert.ok(!testObject.affectsConfiguration('editor.fontSize')); assert.ok(!testObject.affectsConfiguration('editor.fontSize', { resource: URI.file('file1') })); assert.ok(!testObject.affectsConfiguration('editor.fontSize', { resource: URI.file('file2') })); }); }); function toConfigurationModel(obj: any): ConfigurationModel { const parser = new ConfigurationModelParser('test'); parser.parseContent(JSON.stringify(obj)); return parser.configurationModel; }
src/vs/platform/configuration/test/common/configurationModels.test.ts
0
https://github.com/microsoft/vscode/commit/9504dda6a717a0a0d45d992e21f2565f8a23f390
[ 0.00018007023027166724, 0.00017206939810421318, 0.00016557508206460625, 0.0001721856533549726, 0.000003142209152429132 ]
{ "id": 9, "code_window": [ "\t\t}\n", "\t}\n", "\n", "\tprivate focusEditorIfNeeded() {\n", "\t\tif (this.viewCell.focusMode === CellFocusMode.Editor) {\n", "\t\t\tthis.editor?.focus();\n", "\t\t}\n", "\t}\n", "\n", "\tprivate layoutEditor(dimension: IDimension): void {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tif (this.viewCell.focusMode === CellFocusMode.Editor && this.notebookEditor.hasFocus()) {\n" ], "file_path": "src/vs/workbench/contrib/notebook/browser/view/renderers/markdownCell.ts", "type": "replace", "edit_start_line_idx": 229 }
{ "name": "theme-solarized-dark", "displayName": "%displayName%", "description": "%description%", "version": "1.0.0", "publisher": "vscode", "license": "MIT", "engines": { "vscode": "*" }, "contributes": { "themes": [ { "label": "Solarized Dark", "uiTheme": "vs-dark", "path": "./themes/solarized-dark-color-theme.json" } ] } }
extensions/theme-solarized-dark/package.json
0
https://github.com/microsoft/vscode/commit/9504dda6a717a0a0d45d992e21f2565f8a23f390
[ 0.0001753170945448801, 0.00017433783796150237, 0.00017335858137812465, 0.00017433783796150237, 9.79256583377719e-7 ]
{ "id": 9, "code_window": [ "\t\t}\n", "\t}\n", "\n", "\tprivate focusEditorIfNeeded() {\n", "\t\tif (this.viewCell.focusMode === CellFocusMode.Editor) {\n", "\t\t\tthis.editor?.focus();\n", "\t\t}\n", "\t}\n", "\n", "\tprivate layoutEditor(dimension: IDimension): void {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tif (this.viewCell.focusMode === CellFocusMode.Editor && this.notebookEditor.hasFocus()) {\n" ], "file_path": "src/vs/workbench/contrib/notebook/browser/view/renderers/markdownCell.ts", "type": "replace", "edit_start_line_idx": 229 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import 'vs/css!./media/notabstitlecontrol'; import { toResource, Verbosity, IEditorInput, IEditorPartOptions, SideBySideEditor } from 'vs/workbench/common/editor'; import { TitleControl, IToolbarActions } from 'vs/workbench/browser/parts/editor/titleControl'; import { ResourceLabel, IResourceLabel } from 'vs/workbench/browser/labels'; import { TAB_ACTIVE_FOREGROUND, TAB_UNFOCUSED_ACTIVE_FOREGROUND } from 'vs/workbench/common/theme'; import { EventType as TouchEventType, GestureEvent, Gesture } from 'vs/base/browser/touch'; import { addDisposableListener, EventType, addClass, EventHelper, removeClass, toggleClass, Dimension } from 'vs/base/browser/dom'; import { EDITOR_TITLE_HEIGHT } from 'vs/workbench/browser/parts/editor/editor'; import { IAction } from 'vs/base/common/actions'; import { CLOSE_EDITOR_COMMAND_ID } from 'vs/workbench/browser/parts/editor/editorCommands'; import { Color } from 'vs/base/common/color'; import { withNullAsUndefined, assertIsDefined, assertAllDefined } from 'vs/base/common/types'; interface IRenderedEditorLabel { editor?: IEditorInput; pinned: boolean; } export class NoTabsTitleControl extends TitleControl { private titleContainer: HTMLElement | undefined; private editorLabel: IResourceLabel | undefined; private activeLabel: IRenderedEditorLabel = Object.create(null); protected create(parent: HTMLElement): void { const titleContainer = this.titleContainer = parent; titleContainer.draggable = true; //Container listeners this.registerContainerListeners(titleContainer); // Gesture Support this._register(Gesture.addTarget(titleContainer)); const labelContainer = document.createElement('div'); addClass(labelContainer, 'label-container'); titleContainer.appendChild(labelContainer); // Editor Label this.editorLabel = this._register(this.instantiationService.createInstance(ResourceLabel, labelContainer, undefined)).element; this._register(addDisposableListener(this.editorLabel.element, EventType.CLICK, e => this.onTitleLabelClick(e))); // Breadcrumbs this.createBreadcrumbsControl(labelContainer, { showFileIcons: false, showSymbolIcons: true, showDecorationColors: false, breadcrumbsBackground: () => Color.transparent }); toggleClass(titleContainer, 'breadcrumbs', Boolean(this.breadcrumbsControl)); this._register({ dispose: () => removeClass(titleContainer, 'breadcrumbs') }); // import to remove because the container is a shared dom node // Right Actions Container const actionsContainer = document.createElement('div'); addClass(actionsContainer, 'title-actions'); titleContainer.appendChild(actionsContainer); // Editor actions toolbar this.createEditorActionsToolBar(actionsContainer); } private registerContainerListeners(titleContainer: HTMLElement): void { // Group dragging this.enableGroupDragging(titleContainer); // Pin on double click this._register(addDisposableListener(titleContainer, EventType.DBLCLICK, (e: MouseEvent) => this.onTitleDoubleClick(e))); // Detect mouse click this._register(addDisposableListener(titleContainer, EventType.AUXCLICK, (e: MouseEvent) => this.onTitleAuxClick(e))); // Detect touch this._register(addDisposableListener(titleContainer, TouchEventType.Tap, (e: GestureEvent) => this.onTitleTap(e))); // Context Menu this._register(addDisposableListener(titleContainer, EventType.CONTEXT_MENU, (e: Event) => { if (this.group.activeEditor) { this.onContextMenu(this.group.activeEditor, e, titleContainer); } })); this._register(addDisposableListener(titleContainer, TouchEventType.Contextmenu, (e: Event) => { if (this.group.activeEditor) { this.onContextMenu(this.group.activeEditor, e, titleContainer); } })); } private onTitleLabelClick(e: MouseEvent): void { EventHelper.stop(e, false); // delayed to let the onTitleClick() come first which can cause a focus change which can close quick access setTimeout(() => this.quickInputService.quickAccess.show()); } private onTitleDoubleClick(e: MouseEvent): void { EventHelper.stop(e); this.group.pinEditor(); } private onTitleAuxClick(e: MouseEvent): void { if (e.button === 1 /* Middle Button */ && this.group.activeEditor) { EventHelper.stop(e, true /* for https://github.com/Microsoft/vscode/issues/56715 */); this.group.closeEditor(this.group.activeEditor); } } private onTitleTap(e: GestureEvent): void { // TODO@rebornix gesture tap should open the quick access // editorGroupView will focus on the editor again when there are mouse/pointer/touch down events // we need to wait a bit as `GesureEvent.Tap` is generated from `touchstart` and then `touchend` evnets, which are not an atom event. setTimeout(() => this.quickInputService.quickAccess.show(), 50); } getPreferredHeight(): number { return EDITOR_TITLE_HEIGHT; } openEditor(editor: IEditorInput): void { const activeEditorChanged = this.ifActiveEditorChanged(() => this.redraw()); if (!activeEditorChanged) { this.ifActiveEditorPropertiesChanged(() => this.redraw()); } } closeEditor(editor: IEditorInput): void { this.ifActiveEditorChanged(() => this.redraw()); } closeEditors(editors: IEditorInput[]): void { this.ifActiveEditorChanged(() => this.redraw()); } moveEditor(editor: IEditorInput, fromIndex: number, targetIndex: number): void { this.ifActiveEditorChanged(() => this.redraw()); } pinEditor(editor: IEditorInput): void { this.ifEditorIsActive(editor, () => this.redraw()); } stickEditor(editor: IEditorInput): void { // Sticky editors are not presented any different with tabs disabled } unstickEditor(editor: IEditorInput): void { // Sticky editors are not presented any different with tabs disabled } setActive(isActive: boolean): void { this.redraw(); } updateEditorLabel(editor: IEditorInput): void { this.ifEditorIsActive(editor, () => this.redraw()); } updateEditorLabels(): void { if (this.group.activeEditor) { this.updateEditorLabel(this.group.activeEditor); // we only have the active one to update } } updateEditorDirty(editor: IEditorInput): void { this.ifEditorIsActive(editor, () => { const titleContainer = assertIsDefined(this.titleContainer); // Signal dirty (unless saving) if (editor.isDirty() && !editor.isSaving()) { addClass(titleContainer, 'dirty'); } // Otherwise, clear dirty else { removeClass(titleContainer, 'dirty'); } }); } updateOptions(oldOptions: IEditorPartOptions, newOptions: IEditorPartOptions): void { if (oldOptions.labelFormat !== newOptions.labelFormat) { this.redraw(); } } updateStyles(): void { this.redraw(); } protected handleBreadcrumbsEnablementChange(): void { const titleContainer = assertIsDefined(this.titleContainer); toggleClass(titleContainer, 'breadcrumbs', Boolean(this.breadcrumbsControl)); this.redraw(); } private ifActiveEditorChanged(fn: () => void): boolean { if ( !this.activeLabel.editor && this.group.activeEditor || // active editor changed from null => editor this.activeLabel.editor && !this.group.activeEditor || // active editor changed from editor => null (!this.activeLabel.editor || !this.group.isActive(this.activeLabel.editor)) // active editor changed from editorA => editorB ) { fn(); return true; } return false; } private ifActiveEditorPropertiesChanged(fn: () => void): void { if (!this.activeLabel.editor || !this.group.activeEditor) { return; // need an active editor to check for properties changed } if (this.activeLabel.pinned !== this.group.isPinned(this.group.activeEditor)) { fn(); // only run if pinned state has changed } } private ifEditorIsActive(editor: IEditorInput, fn: () => void): void { if (this.group.isActive(editor)) { fn(); // only run if editor is current active } } private redraw(): void { const editor = withNullAsUndefined(this.group.activeEditor); const isEditorPinned = editor ? this.group.isPinned(editor) : false; const isGroupActive = this.accessor.activeGroup === this.group; this.activeLabel = { editor, pinned: isEditorPinned }; // Update Breadcrumbs if (this.breadcrumbsControl) { if (isGroupActive) { this.breadcrumbsControl.update(); toggleClass(this.breadcrumbsControl.domNode, 'preview', !isEditorPinned); } else { this.breadcrumbsControl.hide(); } } // Clear if there is no editor const [titleContainer, editorLabel] = assertAllDefined(this.titleContainer, this.editorLabel); if (!editor) { removeClass(titleContainer, 'dirty'); editorLabel.clear(); this.clearEditorActionsToolbar(); } // Otherwise render it else { // Dirty state this.updateEditorDirty(editor); // Editor Label const { labelFormat } = this.accessor.partOptions; let description: string; if (this.breadcrumbsControl && !this.breadcrumbsControl.isHidden()) { description = ''; // hide description when showing breadcrumbs } else if (labelFormat === 'default' && !isGroupActive) { description = ''; // hide description when group is not active and style is 'default' } else { description = editor.getDescription(this.getVerbosity(labelFormat)) || ''; } let title = editor.getTitle(Verbosity.LONG); if (description === title) { title = ''; // dont repeat what is already shown } editorLabel.setResource( { resource: toResource(editor, { supportSideBySide: SideBySideEditor.BOTH }), name: editor.getName(), description }, { title, italic: !isEditorPinned, extraClasses: ['no-tabs', 'title-label'] } ); if (isGroupActive) { editorLabel.element.style.color = this.getColor(TAB_ACTIVE_FOREGROUND) || ''; } else { editorLabel.element.style.color = this.getColor(TAB_UNFOCUSED_ACTIVE_FOREGROUND) || ''; } // Update Editor Actions Toolbar this.updateEditorActionsToolbar(); } } private getVerbosity(style: string | undefined): Verbosity { switch (style) { case 'short': return Verbosity.SHORT; case 'long': return Verbosity.LONG; default: return Verbosity.MEDIUM; } } protected prepareEditorActions(editorActions: IToolbarActions): { primaryEditorActions: IAction[], secondaryEditorActions: IAction[] } { const isGroupActive = this.accessor.activeGroup === this.group; // Group active: show all actions if (isGroupActive) { return super.prepareEditorActions(editorActions); } // Group inactive: only show close action return { primaryEditorActions: editorActions.primary.filter(action => action.id === CLOSE_EDITOR_COMMAND_ID), secondaryEditorActions: [] }; } layout(dimension: Dimension): void { if (this.breadcrumbsControl) { this.breadcrumbsControl.layout(undefined); } } }
src/vs/workbench/browser/parts/editor/noTabsTitleControl.ts
0
https://github.com/microsoft/vscode/commit/9504dda6a717a0a0d45d992e21f2565f8a23f390
[ 0.0020584429148584604, 0.00022848622757010162, 0.00016593273903708905, 0.00016970207798294723, 0.0003235504846088588 ]
{ "id": 0, "code_window": [ "\tpublic getId(): string {\n", "\t\treturn this.id;\n", "\t}\n", "\n", "\t/**\n", "\t * The label of the entry to identify it from others in the list\n", "\t */\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t/**\n", "\t * The prefix to show in front of the label if any\n", "\t */\n", "\tpublic getPrefix(): string {\n", "\t\treturn null;\n", "\t}\n", "\n" ], "file_path": "src/vs/base/parts/quickopen/browser/quickOpenModel.ts", "type": "add", "edit_start_line_idx": 50 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import WinJS = require('vs/base/common/winjs.base'); import Types = require('vs/base/common/types'); import URI from 'vs/base/common/uri'; import Tree = require('vs/base/parts/tree/common/tree'); import {IQuickNavigateConfiguration, IModel, IDataSource, IFilter, IRenderer, IRunner, Mode} from './quickOpen'; import ActionsRenderer = require('vs/base/parts/tree/browser/actionsRenderer'); import Actions = require('vs/base/common/actions'); import {compareAnything} from 'vs/base/common/comparers'; import ActionBar = require('vs/base/browser/ui/actionbar/actionbar'); import TreeDefaults = require('vs/base/parts/tree/browser/treeDefaults'); import HighlightedLabel = require('vs/base/browser/ui/highlightedlabel/highlightedLabel'); import DOM = require('vs/base/browser/dom'); export interface IContext { event: any; quickNavigateConfiguration: IQuickNavigateConfiguration; } export interface IHighlight { start: number; end: number; } let IDS = 0; export class QuickOpenEntry { private id: string; private labelHighlights: IHighlight[]; private descriptionHighlights: IHighlight[]; private hidden: boolean; constructor(highlights: IHighlight[] = []) { this.id = (IDS++).toString(); this.labelHighlights = highlights; this.descriptionHighlights = []; } /** * A unique identifier for the entry */ public getId(): string { return this.id; } /** * The label of the entry to identify it from others in the list */ public getLabel(): string { return null; } /** * Meta information about the entry that is optional and can be shown to the right of the label */ public getMeta(): string { return null; } /** * The icon of the entry to identify it from others in the list */ public getIcon(): string { return null; } /** * A secondary description that is optional and can be shown right to the label */ public getDescription(): string { return null; } /** * A resource for this entry. Resource URIs can be used to compare different kinds of entries and group * them together. */ public getResource(): URI { return null; } /** * Allows to reuse the same model while filtering. Hidden entries will not show up in the viewer. */ public isHidden(): boolean { return this.hidden; } /** * Allows to reuse the same model while filtering. Hidden entries will not show up in the viewer. */ public setHidden(hidden: boolean): void { this.hidden = hidden; } /** * Allows to set highlight ranges that should show up for the entry label and optionally description if set. */ public setHighlights(labelHighlights: IHighlight[], descriptionHighlights?: IHighlight[]): void { this.labelHighlights = labelHighlights; this.descriptionHighlights = descriptionHighlights; } /** * Allows to return highlight ranges that should show up for the entry label and description. */ public getHighlights(): [IHighlight[] /* Label */, IHighlight[] /* Description */] { return [this.labelHighlights, this.descriptionHighlights]; } /** * Called when the entry is selected for opening. Returns a boolean value indicating if an action was performed or not. * The mode parameter gives an indication if the element is previewed (using arrow keys) or opened. * * The context parameter provides additional context information how the run was triggered. */ public run(mode: Mode, context: IContext): boolean { return false; } /** * A good default sort implementation for quick open entries */ public static compare(elementA: QuickOpenEntry, elementB: QuickOpenEntry, lookFor: string): number { // Give matches with label highlights higher priority over // those with only description highlights const labelHighlightsA = elementA.getHighlights()[0] || []; const labelHighlightsB = elementB.getHighlights()[0] || []; if (labelHighlightsA.length && !labelHighlightsB.length) { return -1; } else if (!labelHighlightsA.length && labelHighlightsB.length) { return 1; } // Sort by name/path let nameA = elementA.getLabel(); let nameB = elementB.getLabel(); if (nameA === nameB) { let resourceA = elementA.getResource(); let resourceB = elementB.getResource(); if (resourceA && resourceB) { nameA = elementA.getResource().fsPath; nameB = elementB.getResource().fsPath; } } return compareAnything(nameA, nameB, lookFor); } } export class QuickOpenEntryItem extends QuickOpenEntry { /** * Must return the height as being used by the render function. */ public getHeight(): number { return 0; } /** * Allows to present the quick open entry in a custom way inside the tree. */ public render(tree: Tree.ITree, container: HTMLElement, previousCleanupFn: Tree.IElementCallback): Tree.IElementCallback { return null; } } export class QuickOpenEntryGroup extends QuickOpenEntry { private entry: QuickOpenEntry; private groupLabel: string; private withBorder: boolean; constructor(entry?: QuickOpenEntry, groupLabel?: string, withBorder?: boolean) { super(); this.entry = entry; this.groupLabel = groupLabel; this.withBorder = withBorder; } /** * The label of the group or null if none. */ public getGroupLabel(): string { return this.groupLabel; } public setGroupLabel(groupLabel: string): void { this.groupLabel = groupLabel; } /** * Whether to show a border on top of the group entry or not. */ public showBorder(): boolean { return this.withBorder; } public setShowBorder(showBorder: boolean): void { this.withBorder = showBorder; } public getLabel(): string { return this.entry ? this.entry.getLabel() : super.getLabel(); } public getMeta(): string { return this.entry ? this.entry.getMeta() : super.getMeta(); } public getResource(): URI { return this.entry ? this.entry.getResource() : super.getResource(); } public getIcon(): string { return this.entry ? this.entry.getIcon() : super.getIcon(); } public getDescription(): string { return this.entry ? this.entry.getDescription() : super.getDescription(); } public getEntry(): QuickOpenEntry { return this.entry; } public getHighlights(): [IHighlight[], IHighlight[]] { return this.entry ? this.entry.getHighlights() : super.getHighlights(); } public isHidden(): boolean { return this.entry ? this.entry.isHidden() : super.isHidden(); } public setHighlights(labelHighlights: IHighlight[], descriptionHighlights?: IHighlight[]): void { this.entry ? this.entry.setHighlights(labelHighlights, descriptionHighlights) : super.setHighlights(labelHighlights, descriptionHighlights); } public setHidden(hidden: boolean): void { this.entry ? this.entry.setHidden(hidden) : super.setHidden(hidden); } public run(mode: Mode, context: IContext): boolean { return this.entry ? this.entry.run(mode, context) : super.run(mode, context); } } const templateEntry = 'quickOpenEntry'; const templateEntryGroup = 'quickOpenEntryGroup'; const templateEntryItem = 'quickOpenEntryItem'; class EntryItemRenderer extends TreeDefaults.LegacyRenderer { public getTemplateId(tree: Tree.ITree, element: any): string { return templateEntryItem; } protected render(tree: Tree.ITree, element: any, container: HTMLElement, previousCleanupFn?: Tree.IElementCallback): Tree.IElementCallback { if (element instanceof QuickOpenEntryItem) { return (<QuickOpenEntryItem>element).render(tree, container, previousCleanupFn); } return super.render(tree, element, container, previousCleanupFn); } } class NoActionProvider implements ActionsRenderer.IActionProvider { public hasActions(tree: Tree.ITree, element: any): boolean { return false; } public getActions(tree: Tree.ITree, element: any): WinJS.TPromise<Actions.IAction[]> { return WinJS.Promise.as(null); } public hasSecondaryActions(tree: Tree.ITree, element: any): boolean { return false; } public getSecondaryActions(tree: Tree.ITree, element: any): WinJS.TPromise<Actions.IAction[]> { return WinJS.Promise.as(null); } public getActionItem(tree: Tree.ITree, element: any, action: Actions.Action): ActionBar.IActionItem { return null; } } export interface IQuickOpenEntryTemplateData { container: HTMLElement; icon: HTMLSpanElement; label: HighlightedLabel.HighlightedLabel; meta: HTMLSpanElement; description: HighlightedLabel.HighlightedLabel; actionBar: ActionBar.ActionBar; } export interface IQuickOpenEntryGroupTemplateData extends IQuickOpenEntryTemplateData { group: HTMLDivElement; } class Renderer implements IRenderer<QuickOpenEntry> { private actionProvider: ActionsRenderer.IActionProvider; private actionRunner: Actions.IActionRunner; private entryItemRenderer: EntryItemRenderer; constructor(actionProvider: ActionsRenderer.IActionProvider = new NoActionProvider(), actionRunner: Actions.IActionRunner = null) { this.actionProvider = actionProvider; this.actionRunner = actionRunner; this.entryItemRenderer = new EntryItemRenderer(); } public getHeight(entry: QuickOpenEntry): number { if (entry instanceof QuickOpenEntryItem) { return (<QuickOpenEntryItem>entry).getHeight(); } return 24; } public getTemplateId(entry: QuickOpenEntry): string { if (entry instanceof QuickOpenEntryItem) { return templateEntryItem; } if (entry instanceof QuickOpenEntryGroup) { return templateEntryGroup; } return templateEntry; } public renderTemplate(templateId: string, container: HTMLElement): IQuickOpenEntryGroupTemplateData { // Entry Item if (templateId === templateEntryItem) { return this.entryItemRenderer.renderTemplate(null, templateId, container); } // Entry Group let group: HTMLDivElement; if (templateId === templateEntryGroup) { group = document.createElement('div'); DOM.addClass(group, 'results-group'); container.appendChild(group); } // Action Bar DOM.addClass(container, 'actions'); let entryContainer = document.createElement('div'); DOM.addClass(entryContainer, 'sub-content'); container.appendChild(entryContainer); let actionBarContainer = document.createElement('div'); DOM.addClass(actionBarContainer, 'primary-action-bar'); container.appendChild(actionBarContainer); let actionBar = new ActionBar.ActionBar(actionBarContainer, { actionRunner: this.actionRunner }); // Entry let entry = document.createElement('div'); DOM.addClass(entry, 'quick-open-entry'); entryContainer.appendChild(entry); // Icon let icon = document.createElement('span'); entry.appendChild(icon); // Label let label = new HighlightedLabel.HighlightedLabel(entry); // Meta let meta = document.createElement('span'); entry.appendChild(meta); DOM.addClass(meta, 'quick-open-entry-meta'); // Description let descriptionContainer = document.createElement('span'); entry.appendChild(descriptionContainer); DOM.addClass(descriptionContainer, 'quick-open-entry-description'); let description = new HighlightedLabel.HighlightedLabel(descriptionContainer); return { container: container, icon: icon, label: label, meta: meta, description: description, group: group, actionBar: actionBar }; } public renderElement(entry: QuickOpenEntry, templateId: string, templateData: any): void { // Entry Item if (templateId === templateEntryItem) { this.entryItemRenderer.renderElement(null, entry, templateId, <TreeDefaults.ILegacyTemplateData>templateData); return; } let data: IQuickOpenEntryTemplateData = templateData; // Action Bar if (this.actionProvider.hasActions(null, entry)) { DOM.addClass(data.container, 'has-actions'); } else { DOM.removeClass(data.container, 'has-actions'); } data.actionBar.context = entry; // make sure the context is the current element this.actionProvider.getActions(null, entry).then((actions) => { // TODO@Ben this will not work anymore as soon as quick open has more actions // but as long as there is only one are ok if (data.actionBar.isEmpty() && actions && actions.length > 0) { data.actionBar.push(actions, { icon: true, label: false }); } else if (!data.actionBar.isEmpty() && (!actions || actions.length === 0)) { data.actionBar.clear(); } }); // Entry group if (entry instanceof QuickOpenEntryGroup) { let group = <QuickOpenEntryGroup>entry; // Border if (group.showBorder()) { DOM.addClass(data.container, 'results-group-separator'); } else { DOM.removeClass(data.container, 'results-group-separator'); } // Group Label let groupLabel = group.getGroupLabel() || ''; (<IQuickOpenEntryGroupTemplateData>templateData).group.textContent = groupLabel; } // Normal Entry if (entry instanceof QuickOpenEntry) { let highlights = entry.getHighlights(); // Icon let iconClass = entry.getIcon() ? ('quick-open-entry-icon ' + entry.getIcon()) : ''; data.icon.className = iconClass; // Label let labelHighlights = highlights[0]; data.label.set(entry.getLabel() || '', labelHighlights || []); // Meta let metaLabel = entry.getMeta() || ''; data.meta.textContent = metaLabel; // Description let descriptionHighlights = highlights[1]; data.description.set(entry.getDescription() || '', descriptionHighlights || []); } } public disposeTemplate(templateId: string, templateData: any): void { if (templateId === templateEntryItem) { this.entryItemRenderer.disposeTemplate(null, templateId, templateData); } } } export class QuickOpenModel implements IModel<QuickOpenEntry>, IDataSource<QuickOpenEntry>, IFilter<QuickOpenEntry>, IRunner<QuickOpenEntry> { private _entries: QuickOpenEntry[]; private _dataSource: IDataSource<QuickOpenEntry>; private _renderer: IRenderer<QuickOpenEntry>; private _filter: IFilter<QuickOpenEntry>; private _runner: IRunner<QuickOpenEntry>; constructor(entries: QuickOpenEntry[] = [], actionProvider: ActionsRenderer.IActionProvider = new NoActionProvider()) { this._entries = entries; this._dataSource = this; this._renderer = new Renderer(actionProvider); this._filter = this; this._runner = this; } public get entries() { return this._entries; } public get dataSource() { return this._dataSource; } public get renderer() { return this._renderer; } public get filter() { return this._filter; } public get runner() { return this._runner; } public set entries(entries: QuickOpenEntry[]) { this._entries = entries; } /** * Adds entries that should show up in the quick open viewer. */ public addEntries(entries: QuickOpenEntry[]): void { if (Types.isArray(entries)) { this._entries = this._entries.concat(entries); } } /** * Set the entries that should show up in the quick open viewer. */ public setEntries(entries: QuickOpenEntry[]): void { if (Types.isArray(entries)) { this._entries = entries; } } /** * Get the entries that should show up in the quick open viewer. * * @visibleOnly optional parameter to only return visible entries */ public getEntries(visibleOnly?: boolean): QuickOpenEntry[] { if (visibleOnly) { return this._entries.filter((e) => !e.isHidden()); } return this._entries; } getId(entry: QuickOpenEntry): string { return entry.getId(); } getLabel(entry: QuickOpenEntry): string { return entry.getLabel(); } isVisible<T>(entry: QuickOpenEntry): boolean { return !entry.isHidden(); } run(entry: QuickOpenEntry, mode: Mode, context: IContext): boolean { return entry.run(mode, context); } }
src/vs/base/parts/quickopen/browser/quickOpenModel.ts
1
https://github.com/microsoft/vscode/commit/bfef57fbab0a12949de803076577f9de4b8fec22
[ 0.8208068013191223, 0.015711015090346336, 0.00016464559303130955, 0.00017201417358592153, 0.10872486978769302 ]
{ "id": 0, "code_window": [ "\tpublic getId(): string {\n", "\t\treturn this.id;\n", "\t}\n", "\n", "\t/**\n", "\t * The label of the entry to identify it from others in the list\n", "\t */\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t/**\n", "\t * The prefix to show in front of the label if any\n", "\t */\n", "\tpublic getPrefix(): string {\n", "\t\treturn null;\n", "\t}\n", "\n" ], "file_path": "src/vs/base/parts/quickopen/browser/quickOpenModel.ts", "type": "add", "edit_start_line_idx": 50 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import {ITree, IElementCallback} from 'vs/base/parts/tree/common/tree'; import {TPromise} from 'vs/base/common/winjs.base'; import {EventProvider} from 'vs/base/common/eventProvider'; import {IQuickNavigateConfiguration, IAutoFocus} from 'vs/base/parts/quickopen/browser/quickOpen'; import {createDecorator, ServiceIdentifier} from 'vs/platform/instantiation/common/instantiation'; import {IEditorInput} from 'vs/platform/editor/common/editor'; export interface IPickOpenEntry { id?: string; label: string; description?: string; } export interface IPickOpenEntryItem extends IPickOpenEntry { height?: number; render?: (tree: ITree, container: HTMLElement, previousCleanupFn: IElementCallback) => IElementCallback; } export interface IPickOptions { /** * an optional string to show as place holder in the input box to guide the user what she picks on */ placeHolder?: string; /** * optional auto focus settings */ autoFocus?: IAutoFocus; /** * an optional flag to include the description when filtering the picks */ matchOnDescription?: boolean; } export interface IInputOptions { /** * the value to prefill in the input box */ value?: string; /** * the text to display underneath the input box */ prompt?: string; /** * an optional string to show as place holder in the input box to guide the user what to type */ placeHolder?: string; /** * set to true to show a password prompt that will not show the typed value */ password?: boolean; } export var IQuickOpenService = createDecorator<IQuickOpenService>('quickOpenService') export interface IQuickOpenService { serviceId : ServiceIdentifier<any>; /** * Asks the container to show the quick open control with the optional prefix set. If the optional parameter * is set for quick navigation mode, the quick open control will quickly navigate when the quick navigate * key is pressed and will run the selection after the ctrl key is released. * * The returned promise completes when quick open is closing. */ show(prefix?: string, quickNavigateConfiguration?: IQuickNavigateConfiguration): TPromise<void>; /** * Refreshes the quick open control. No-op, if the control is hidden. * If an input is provided, then the operation will only succeed if that same input is still * in the quick open control. */ refresh(input?: string): TPromise<void>; /** * Returns the sorted list of editor inputs that have been opened by the user. */ getEditorHistory(): IEditorInput[]; /** * Removes an editor history entry by the given input. */ removeEditorHistoryEntry(input: IEditorInput): void; /** * A convenient way to bring up quick open as a picker with custom elements. This bypasses the quick open handler * registry and just leverages the quick open widget to select any kind of entries. * * Passing in a promise will allow you to resolve the elements in the background while quick open will show a * progress bar spinning. */ pick(picks: TPromise<string[]>, options?: IPickOptions): TPromise<string>; pick<T extends IPickOpenEntry>(picks: TPromise<T[]>, options?: IPickOptions): TPromise<T>; pick(picks: string[], options?: IPickOptions): TPromise<string>; pick<T extends IPickOpenEntry>(picks: T[], options?: IPickOptions): TPromise<T>; /** * Should not be used by clients. Will cause any opened quick open widget to navigate in the result set. */ quickNavigate(configuration: IQuickNavigateConfiguration, next: boolean): void; /** * Opens the quick open box for user input and returns a promise with the user typed value if any. */ input(options?: IInputOptions): TPromise<string>; /** * Allows to register on the event that quick open is showing */ onShow: EventProvider<() => void>; /** * Allows to register on the event that quick open is hiding */ onHide: EventProvider<() => void>; }
src/vs/workbench/services/quickopen/browser/quickOpenService.ts
0
https://github.com/microsoft/vscode/commit/bfef57fbab0a12949de803076577f9de4b8fec22
[ 0.00202201958745718, 0.0003949468955397606, 0.00016539583157282323, 0.00018461233412381262, 0.0005006081191822886 ]
{ "id": 0, "code_window": [ "\tpublic getId(): string {\n", "\t\treturn this.id;\n", "\t}\n", "\n", "\t/**\n", "\t * The label of the entry to identify it from others in the list\n", "\t */\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t/**\n", "\t * The prefix to show in front of the label if any\n", "\t */\n", "\tpublic getPrefix(): string {\n", "\t\treturn null;\n", "\t}\n", "\n" ], "file_path": "src/vs/base/parts/quickopen/browser/quickOpenModel.ts", "type": "add", "edit_start_line_idx": 50 }
<?xml version='1.0' standalone='no' ?> <svg xmlns='http://www.w3.org/2000/svg' version='1.1' width='10px' height='10px'> <g style="fill:grey;"> <circle cx='5' cy='1' r='1' style='opacity:0.3;'> <animate attributeType='CSS' attributeName='opacity' from='1' to='0.3' dur='0.6s' repeatCount='indefinite' begin='0s' /> </circle> <circle cx='7.8284' cy='2.1716' r='1' style='opacity:0.3;'> <animate attributeType='CSS' attributeName='opacity' from='1' to='0.3' dur='0.6s' repeatCount='indefinite' begin='0.075s' /> </circle> <circle cx='9' cy='5' r='1' style='opacity:0.3;'> <animate attributeType='CSS' attributeName='opacity' from='1' to='0.3' dur='0.6s' repeatCount='indefinite' begin='0.15s' /> </circle> <circle cx='7.8284' cy='7.8284' r='1' style='opacity:0.3;'> <animate attributeType='CSS' attributeName='opacity' from='1' to='0.3' dur='0.6s' repeatCount='indefinite' begin='0.225s' /> </circle> <circle cx='5' cy='9' r='1' style='opacity:0.3;'> <animate attributeType='CSS' attributeName='opacity' from='1' to='0.3' dur='0.6s' repeatCount='indefinite' begin='0.3s' /> </circle> <circle cx='2.1716' cy='7.8284' r='1' style='opacity:0.3;'> <animate attributeType='CSS' attributeName='opacity' from='1' to='0.3' dur='0.6s' repeatCount='indefinite' begin='0.375s' /> </circle> <circle cx='1' cy='5' r='1' style='opacity:0.3;'> <animate attributeType='CSS' attributeName='opacity' from='1' to='0.3' dur='0.6s' repeatCount='indefinite' begin='0.45s' /> </circle> <circle cx='2.1716' cy='2.1716' r='1' style='opacity:0.3;'> <animate attributeType='CSS' attributeName='opacity' from='1' to='0.3' dur='0.6s' repeatCount='indefinite' begin='0.525s' /> </circle> </g> </svg>
src/vs/base/parts/tree/browser/loading-dark.svg
0
https://github.com/microsoft/vscode/commit/bfef57fbab0a12949de803076577f9de4b8fec22
[ 0.00016833336849231273, 0.0001658633118495345, 0.00016400942695327103, 0.00016524718375876546, 0.0000018182118992626783 ]
{ "id": 0, "code_window": [ "\tpublic getId(): string {\n", "\t\treturn this.id;\n", "\t}\n", "\n", "\t/**\n", "\t * The label of the entry to identify it from others in the list\n", "\t */\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t/**\n", "\t * The prefix to show in front of the label if any\n", "\t */\n", "\tpublic getPrefix(): string {\n", "\t\treturn null;\n", "\t}\n", "\n" ], "file_path": "src/vs/base/parts/quickopen/browser/quickOpenModel.ts", "type": "add", "edit_start_line_idx": 50 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import WinJS = require('vs/base/common/winjs.base'); import {AbstractModeWorker} from 'vs/editor/common/modes/abstractModeWorker'; import URI from 'vs/base/common/uri'; import Types = require('vs/base/common/types'); import EditorCommon = require('vs/editor/common/editorCommon'); import Modes = require('vs/editor/common/modes'); import Strings = require('vs/base/common/strings'); import Paths = require('vs/base/common/paths'); import Marked = require('vs/languages/markdown/common/marked'); import ModesExtensions = require('vs/editor/common/modes/modesRegistry'); import {tokenizeToString} from 'vs/editor/common/modes/textToHtmlTokenizer'; import Platform = require('vs/platform/platform'); import {isMacintosh} from 'vs/base/common/platform'; import {IModeService} from 'vs/editor/common/services/modeService'; import {IResourceService} from 'vs/editor/common/services/resourceService'; import {IMarkerService} from 'vs/platform/markers/common/markers'; enum Theme { LIGHT, DARK, HC_BLACK } export class MarkdownWorker extends AbstractModeWorker { private static DEFAULT_MODE = 'text/plain'; private cssLinks: string[]; private theme: Theme = Theme.DARK; // Custom Scrollbar CSS (inlined because of pseudo elements that cannot be made theme aware) private static LIGHT_SCROLLBAR_CSS: string = [ '<style type="text/css">', ' ::-webkit-scrollbar {', ' width: 14px;', ' height: 14px;', ' }', '', ' ::-webkit-scrollbar-thumb {', ' background-color: rgba(100, 100, 100, 0.4);', ' }', '', ' ::-webkit-scrollbar-thumb:hover {', ' background-color: rgba(100, 100, 100, 0.7);', ' }', '', ' ::-webkit-scrollbar-thumb:active {', ' background-color: rgba(0, 0, 0, 0.6);', ' }', '</style>' ].join('\n'); private static DARK_SCROLLBAR_CSS: string = [ '<style type="text/css">', ' ::-webkit-scrollbar {', ' width: 14px;', ' height: 14px;', ' }', '', ' ::-webkit-scrollbar-thumb {', ' background-color: rgba(121, 121, 121, 0.4);', ' }', '', ' ::-webkit-scrollbar-thumb:hover {', ' background-color: rgba(100, 100, 100, 0.7);', ' }', '', ' ::-webkit-scrollbar-thumb:active {', ' background-color: rgba(85, 85, 85, 0.8);', ' }', '</style>' ].join('\n'); private static HC_BLACK_SCROLLBAR_CSS: string = [ '<style type="text/css">', ' ::-webkit-scrollbar {', ' width: 14px;', ' height: 14px;', ' }', '', ' ::-webkit-scrollbar-thumb {', ' background-color: rgba(111, 195, 223, 0.3);', ' }', '', ' ::-webkit-scrollbar-thumb:hover {', ' background-color: rgba(111, 195, 223, 0.4);', ' }', '', ' ::-webkit-scrollbar-thumb:active {', ' background-color: rgba(111, 195, 223, 0.4);', ' }', '</style>' ].join('\n'); private modeService: IModeService; constructor(mode: Modes.IMode, participants: Modes.IWorkerParticipant[], @IResourceService resourceService: IResourceService, @IMarkerService markerService: IMarkerService, @IModeService modeService: IModeService) { super(mode, participants, resourceService, markerService); this.modeService = modeService; } _doConfigure(options: any): WinJS.TPromise<boolean> { if (options && options.theme) { this.theme = (options.theme === 'vs-dark') ? Theme.DARK : (options.theme === 'vs') ? Theme.LIGHT : Theme.HC_BLACK; } if (options && Types.isArray(options.styles)) { this.cssLinks = options.styles; } return WinJS.TPromise.as(false); } public getEmitOutput(resource: URI, absoluteWorkersResourcePath: string): WinJS.TPromise<Modes.IEmitOutput> { // TODO@Ben technical debt: worker cannot resolve paths absolute let model = this.resourceService.get(resource); let cssLinks: string[] = this.cssLinks || []; // Custom Renderer to fix href in images let renderer = new Marked.marked.Renderer(); let $this = this; renderer.image = function(href: string, title: string, text: string): string { let out = '<img src="' + $this.fixHref(resource, href) + '" alt="' + text + '"'; if (title) { out += ' title="' + title + '"'; } out += (this.options && this.options.xhtml) ? '/>' : '>'; return out; }; // Custom Renderer to open links always in a new tab let superRenderLink = renderer.link; renderer.link = function(href: string, title: string, text: string): string { let link = superRenderLink.call(this, href, title, text); // We cannot support local anchor tags because the iframe editor does not have a src set if (href && href[0] === '#') { link = link.replace('href=', 'localhref='); } else { link = link.replace('<a', '<a target="_blank"'); } return link; }; let modeService = this.modeService; // Custom highlighter to use our modes to render code let highlighter = function(code: string, lang: string, callback?: (error: Error, result: string) => void) { // Lookup the mode and use the tokenizer to get the HTML let modesRegistry = <ModesExtensions.IEditorModesRegistry>Platform.Registry.as(ModesExtensions.Extensions.EditorModes); let mimeForLang = modesRegistry.getModeIdForLanguageName(lang) || lang || MarkdownWorker.DEFAULT_MODE; modeService.getOrCreateMode(mimeForLang).then((mode) => { callback(null, tokenizeToString(code, mode)); }); }; return new WinJS.Promise((c, e) => { // Render markdown file contents to HTML Marked.marked(model.getValue(), { gfm: true, // GitHub flavored markdown renderer: renderer, highlight: highlighter }, (error: Error, htmlResult: string) => { // Compute head let head = [ '<!DOCTYPE html>', '<html>', '<head>', '<meta http-equiv="Content-type" content="text/html;charset=UTF-8">', (cssLinks.length === 0) ? '<link rel="stylesheet" href="' + absoluteWorkersResourcePath + '/markdown.css" type="text/css" media="screen">' : '', (cssLinks.length === 0) ? '<link rel="stylesheet" href="' + absoluteWorkersResourcePath + '/tokens.css" type="text/css" media="screen">' : '', (this.theme === Theme.LIGHT) ? MarkdownWorker.LIGHT_SCROLLBAR_CSS : (this.theme === Theme.DARK) ? MarkdownWorker.DARK_SCROLLBAR_CSS : MarkdownWorker.HC_BLACK_SCROLLBAR_CSS, cssLinks.map((style) => { return '<link rel="stylesheet" href="' + this.fixHref(resource, style) + '" type="text/css" media="screen">'; }).join('\n'), '</head>', isMacintosh ? '<body class="mac">' : '<body>' ].join('\n'); // Compute body let body = [ (this.theme === Theme.LIGHT) ? '<div class="monaco-editor vs">' : (this.theme === Theme.DARK) ? '<div class="monaco-editor vs-dark">' : '<div class="monaco-editor hc-black">', htmlResult, '</div>', ].join('\n'); // Tail let tail = [ '</body>', '</html>' ].join('\n'); c({ head: head, body: body, tail: tail }); }); }); } private fixHref(resource: URI, href: string): string { if (href) { // Return early if href is already a URL if (URI.parse(href).scheme) { return href; } // Otherwise convert to a file URI by joining the href with the resource location return URI.file(Paths.join(Paths.dirname(resource.fsPath), href)).toString(); } return href; } }
src/vs/languages/markdown/common/markdownWorker.ts
0
https://github.com/microsoft/vscode/commit/bfef57fbab0a12949de803076577f9de4b8fec22
[ 0.00020291305554565042, 0.00017119872791226953, 0.0001654606603551656, 0.0001688525953795761, 0.000007460378128598677 ]
{ "id": 1, "code_window": [ "\tpublic setShowBorder(showBorder: boolean): void {\n", "\t\tthis.withBorder = showBorder;\n", "\t}\n", "\n", "\tpublic getLabel(): string {\n", "\t\treturn this.entry ? this.entry.getLabel() : super.getLabel();\n", "\t}\n", "\n", "\tpublic getMeta(): string {\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tpublic getPrefix(): string {\n", "\t\treturn this.entry ? this.entry.getPrefix() : super.getPrefix();\n", "\t}\n", "\n" ], "file_path": "src/vs/base/parts/quickopen/browser/quickOpenModel.ts", "type": "add", "edit_start_line_idx": 211 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import {Registry} from 'vs/platform/platform'; import filters = require('vs/base/common/filters'); import strings = require('vs/base/common/strings'); import types = require('vs/base/common/types'); import paths = require('vs/base/common/paths'); import URI from 'vs/base/common/uri'; import {EventType} from 'vs/base/common/events'; import comparers = require('vs/base/common/comparers'); import {Mode, IContext} from 'vs/base/parts/quickopen/browser/quickOpen'; import {QuickOpenEntry, QuickOpenModel, IHighlight} from 'vs/base/parts/quickopen/browser/quickOpenModel'; import {EditorInput, getUntitledOrFileResource} from 'vs/workbench/common/editor'; import {IEditorRegistry, Extensions} from 'vs/workbench/browser/parts/editor/baseEditor'; import {EditorQuickOpenEntry} from 'vs/workbench/browser/quickopen'; import {IWorkbenchEditorService} from 'vs/workbench/services/editor/common/editorService'; import {IInstantiationService} from 'vs/platform/instantiation/common/instantiation'; import {IWorkspaceContextService} from 'vs/platform/workspace/common/workspace'; const MAX_ENTRIES = 200; export class EditorHistoryEntry extends EditorQuickOpenEntry { private input: EditorInput; private model: EditorHistoryModel; private resource: URI; constructor( editorService: IWorkbenchEditorService, private contextService: IWorkspaceContextService, input: EditorInput, labelHighlights: IHighlight[], descriptionHighlights: IHighlight[], model: EditorHistoryModel ) { super(editorService); this.input = input; this.model = model; let resource = getUntitledOrFileResource(input); if (resource) { this.resource = resource; } else { let inputWithResource: { getResource(): URI } = <any>input; if (types.isFunction(inputWithResource.getResource)) { this.resource = inputWithResource.getResource(); } } this.setHighlights(labelHighlights, descriptionHighlights); } public clone(labelHighlights: IHighlight[], descriptionHighlights?: IHighlight[]): EditorHistoryEntry { return new EditorHistoryEntry(this.editorService, this.contextService, this.input, labelHighlights, descriptionHighlights, this.model); } public getLabel(): string { let status = this.input.getStatus(); if (status && status.decoration) { return status.decoration + ' ' + this.input.getName(); } return this.input.getName(); } public getDescription(): string { return this.input.getDescription(); } public getResource(): URI { return this.resource; } public getInput(): EditorInput { return this.input; } public matches(input: EditorInput): boolean { return this.input.matches(input); } public run(mode: Mode, context: IContext): boolean { if (mode === Mode.OPEN) { let event = context.event; let sideBySide = !context.quickNavigateConfiguration && (event && (event.ctrlKey || event.metaKey || (event.payload && event.payload.originalEvent && (event.payload.originalEvent.ctrlKey || event.payload.originalEvent.metaKey)))); this.editorService.openEditor(this.input, null, sideBySide).done(() => { // Automatically clean up stale history entries when the input can not be opened if (!this.input.matches(this.editorService.getActiveEditorInput())) { this.model.remove(this.input); } }); return true; } return false; } } interface ISerializedEditorInput { id: string; value: string; } export class EditorHistoryModel extends QuickOpenModel { constructor( private editorService: IWorkbenchEditorService, private instantiationService: IInstantiationService, private contextService: IWorkspaceContextService ) { super(); } public add(entry: EditorInput): void { // Ensure we have at least a name to show if (!entry.getName()) { return; } // Remove on Dispose let unbind = entry.addListener(EventType.DISPOSE, () => { this.remove(entry); unbind(); }); // Remove any existing entry and add to the beginning this.remove(entry); this.entries.unshift(new EditorHistoryEntry(this.editorService, this.contextService, entry, null, null, this)); // Respect max entries setting if (this.entries.length > MAX_ENTRIES) { this.entries = this.entries.slice(0, MAX_ENTRIES); } } public remove(entry: EditorInput): void { let index = this.indexOf(entry); if (index >= 0) { this.entries.splice(index, 1); } } private indexOf(entryToFind: EditorInput): number { for (let i = 0; i < this.entries.length; i++) { let entry = this.entries[i]; if ((<EditorHistoryEntry>entry).matches(entryToFind)) { return i; } } return -1; } public saveTo(memento: any): void { let registry = (<IEditorRegistry>Registry.as(Extensions.Editors)); let entries: ISerializedEditorInput[] = []; for (let i = this.entries.length - 1; i >= 0; i--) { let entry = this.entries[i]; let input = (<EditorHistoryEntry>entry).getInput(); let factory = registry.getEditorInputFactory(input.getId()); if (factory) { let value = factory.serialize(input); if (types.isString(value)) { entries.push({ id: input.getId(), value: value }); } } } if (entries.length > 0) { memento.entries = entries; } } public loadFrom(memento: any): void { let registry = (<IEditorRegistry>Registry.as(Extensions.Editors)); let entries: ISerializedEditorInput[] = memento.entries; if (entries && entries.length > 0) { for (let i = 0; i < entries.length; i++) { let entry = entries[i]; let factory = registry.getEditorInputFactory(entry.id); if (factory && types.isString(entry.value)) { let input = factory.deserialize(this.instantiationService, entry.value); if (input) { this.add(input); } } } } } public getEntries(): EditorHistoryEntry[] { return <EditorHistoryEntry[]>this.entries.slice(0); } public getResults(searchValue: string): QuickOpenEntry[] { searchValue = searchValue.trim(); let results: QuickOpenEntry[] = []; for (let i = 0; i < this.entries.length; i++) { let entry = <EditorHistoryEntry>this.entries[i]; if (!entry.getResource()) { continue; //For now, only support to match on inputs that provide resource information } let label = entry.getInput().getName(); let description = entry.getInput().getDescription(); let labelHighlights: IHighlight[] = []; let descriptionHighlights: IHighlight[] = []; // Search inside filename if (searchValue.indexOf(paths.nativeSep) < 0) { labelHighlights = filters.matchesFuzzy(searchValue, label); } // Search in full path else { descriptionHighlights = filters.matchesFuzzy(strings.trim(searchValue, paths.nativeSep), description); // If we have no highlights, assume that the match is split among name and parent folder if (!descriptionHighlights || !descriptionHighlights.length) { labelHighlights = filters.matchesFuzzy(paths.basename(searchValue), label); descriptionHighlights = filters.matchesFuzzy(strings.trim(paths.dirname(searchValue), paths.nativeSep), description); } } if ((labelHighlights && labelHighlights.length) || (descriptionHighlights && descriptionHighlights.length)) { results.push(entry.clone(labelHighlights, descriptionHighlights)); } } // If user is searching, use the same sorting that is used for other quick open handlers if (searchValue) { let normalizedSearchValue = strings.stripWildcards(searchValue.toLowerCase()); return results.sort((elementA: EditorHistoryEntry, elementB: EditorHistoryEntry) => QuickOpenEntry.compare(elementA, elementB, normalizedSearchValue)); } // Leave default "most recently used" order if user is not actually searching return results; } }
src/vs/workbench/browser/parts/quickopen/editorHistoryModel.ts
1
https://github.com/microsoft/vscode/commit/bfef57fbab0a12949de803076577f9de4b8fec22
[ 0.0017113139620050788, 0.00030434413929469883, 0.00016608848818577826, 0.00017405020480509847, 0.000315032055368647 ]
{ "id": 1, "code_window": [ "\tpublic setShowBorder(showBorder: boolean): void {\n", "\t\tthis.withBorder = showBorder;\n", "\t}\n", "\n", "\tpublic getLabel(): string {\n", "\t\treturn this.entry ? this.entry.getLabel() : super.getLabel();\n", "\t}\n", "\n", "\tpublic getMeta(): string {\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tpublic getPrefix(): string {\n", "\t\treturn this.entry ? this.entry.getPrefix() : super.getPrefix();\n", "\t}\n", "\n" ], "file_path": "src/vs/base/parts/quickopen/browser/quickOpenModel.ts", "type": "add", "edit_start_line_idx": 211 }
#!/bin/bash if [[ "$OSTYPE" == "darwin"* ]]; then realpath() { [[ $1 = /* ]] && echo "$1" || echo "$PWD/${1#./}"; } ROOT=$(dirname $(dirname $(realpath "$0"))) else ROOT=$(dirname $(dirname $(readlink -f $0))) fi function code() { cd $ROOT # Node modules test -d node_modules || ./scripts/npm.sh install # Get electron node node_modules/gulp/bin/gulp.js electron # Build test -d out || gulp compile # Configuration export NODE_ENV=development export VSCODE_DEV=1 export ELECTRON_ENABLE_LOGGING=1 export ELECTRON_ENABLE_STACK_DUMPING=1 # Launch Code if [[ "$OSTYPE" == "darwin"* ]]; then ./.build/electron/Electron.app/Contents/MacOS/Electron . $* else ./.build/electron/electron . $* fi } code $*
scripts/code.sh
0
https://github.com/microsoft/vscode/commit/bfef57fbab0a12949de803076577f9de4b8fec22
[ 0.00017399863281752914, 0.00017109193140640855, 0.00016570409934502095, 0.00017233251128345728, 0.0000031894553558231564 ]