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": 8, "code_window": [ "\t\tif (this.requiresTrailing) { // save\n", "\t\t\tif (stat && stat.isDirectory) {\n", "\t\t\t\t// Can't do this\n", "\t\t\t\treturn Promise.resolve(false);\n", "\t\t\t} else if (stat) {\n", "\t\t\t\t// This is replacing a file. Not supported yet.\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\tthis.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateFolder', 'The folder already exists. Please use a new file name.');\n" ], "file_path": "src/vs/workbench/services/dialogs/electron-browser/remoteFileDialog.ts", "type": "add", "edit_start_line_idx": 351 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Disposable } from 'vs/base/common/lifecycle'; import { join } from 'vs/base/common/path'; import { IEnvironmentService } from 'vs/platform/environment/common/environment'; import { IExtensionManagementService, DidInstallExtensionEvent, DidUninstallExtensionEvent } from 'vs/platform/extensionManagement/common/extensionManagement'; import { MANIFEST_CACHE_FOLDER, USER_MANIFEST_CACHE_FILE } from 'vs/platform/extensions/common/extensions'; import * as pfs from 'vs/base/node/pfs'; export class ExtensionsManifestCache extends Disposable { private extensionsManifestCache = join(this.environmentService.userDataPath, MANIFEST_CACHE_FOLDER, USER_MANIFEST_CACHE_FILE); constructor( private readonly environmentService: IEnvironmentService, extensionsManagementServuce: IExtensionManagementService ) { super(); this._register(extensionsManagementServuce.onDidInstallExtension(e => this.onDidInstallExtension(e))); this._register(extensionsManagementServuce.onDidUninstallExtension(e => this.onDidUnInstallExtension(e))); } private onDidInstallExtension(e: DidInstallExtensionEvent): void { if (!e.error) { this.invalidate(); } } private onDidUnInstallExtension(e: DidUninstallExtensionEvent): void { if (!e.error) { this.invalidate(); } } invalidate(): void { pfs.del(this.extensionsManifestCache).then(() => { }, () => { }); } }
src/vs/platform/extensionManagement/node/extensionsManifestCache.ts
0
https://github.com/microsoft/vscode/commit/f07c7d705629bea1c6f5af42b7d3f7d72e225f2a
[ 0.00017449325241614133, 0.0001704555907053873, 0.00016552220040466636, 0.00017053080955520272, 0.0000032715327051846543 ]
{ "id": 8, "code_window": [ "\t\tif (this.requiresTrailing) { // save\n", "\t\t\tif (stat && stat.isDirectory) {\n", "\t\t\t\t// Can't do this\n", "\t\t\t\treturn Promise.resolve(false);\n", "\t\t\t} else if (stat) {\n", "\t\t\t\t// This is replacing a file. Not supported yet.\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\tthis.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateFolder', 'The folder already exists. Please use a new file name.');\n" ], "file_path": "src/vs/workbench/services/dialogs/electron-browser/remoteFileDialog.ts", "type": "add", "edit_start_line_idx": 351 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { IEnvironmentService } from 'vs/platform/environment/common/environment'; import { join, dirname, basename } from 'vs/base/common/path'; import { readdir, rimraf } from 'vs/base/node/pfs'; import { onUnexpectedError } from 'vs/base/common/errors'; import { Disposable, toDisposable } from 'vs/base/common/lifecycle'; export class LogsDataCleaner extends Disposable { constructor( @IEnvironmentService private readonly environmentService: IEnvironmentService ) { super(); this.cleanUpOldLogsSoon(); } private cleanUpOldLogsSoon(): void { let handle: any = setTimeout(() => { handle = undefined; const currentLog = basename(this.environmentService.logsPath); const logsRoot = dirname(this.environmentService.logsPath); readdir(logsRoot).then(children => { const allSessions = children.filter(name => /^\d{8}T\d{6}$/.test(name)); const oldSessions = allSessions.sort().filter((d, i) => d !== currentLog); const toDelete = oldSessions.slice(0, Math.max(0, oldSessions.length - 9)); return Promise.all(toDelete.map(name => rimraf(join(logsRoot, name)))); }).then(null, onUnexpectedError); }, 10 * 1000); this._register(toDisposable(() => clearTimeout(handle))); } }
src/vs/code/electron-browser/sharedProcess/contrib/logsDataCleaner.ts
0
https://github.com/microsoft/vscode/commit/f07c7d705629bea1c6f5af42b7d3f7d72e225f2a
[ 0.0001738747232593596, 0.0001695567334536463, 0.0001676078245509416, 0.00016909830446820706, 0.0000022986794192547677 ]
{ "id": 9, "code_window": [ "\t\t\t\treturn Promise.resolve(false);\n", "\t\t\t} else if (stat) {\n", "\t\t\t\t// This is replacing a file. Not supported yet.\n", "\t\t\t\treturn Promise.resolve(false);\n", "\t\t\t} else if (!this.isValidBaseName(resources.basename(uri))) {\n", "\t\t\t\t// Filename not allowed\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\tthis.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateExisting', 'The file already exists. Please use a new file name.');\n" ], "file_path": "src/vs/workbench/services/dialogs/electron-browser/remoteFileDialog.ts", "type": "add", "edit_start_line_idx": 354 }
/*--------------------------------------------------------------------------------------------- * 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 resources from 'vs/base/common/resources'; import * as objects from 'vs/base/common/objects'; import { RemoteFileService } from 'vs/workbench/services/files/node/remoteFileService'; import { IFileService, IFileStat, FileKind } from 'vs/platform/files/common/files'; import { IQuickInputService, IQuickPickItem, IQuickPick } from 'vs/platform/quickinput/common/quickInput'; import { URI } from 'vs/base/common/uri'; import { isWindows } from 'vs/base/common/platform'; import { ISaveDialogOptions, IOpenDialogOptions, IFileDialogService } from 'vs/platform/dialogs/common/dialogs'; import { REMOTE_HOST_SCHEME } from 'vs/platform/remote/common/remoteHosts'; import { IWindowService, IURIToOpen } from 'vs/platform/windows/common/windows'; import { ILabelService } from 'vs/platform/label/common/label'; import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace'; import { INotificationService } from 'vs/platform/notification/common/notification'; import { IModelService } from 'vs/editor/common/services/modelService'; import { IModeService } from 'vs/editor/common/services/modeService'; import { getIconClasses } from 'vs/editor/common/services/getIconClasses'; import { Schemas } from 'vs/base/common/network'; interface FileQuickPickItem extends IQuickPickItem { uri: URI; isFolder: boolean; } // Reference: https://en.wikipedia.org/wiki/Filename const INVALID_FILE_CHARS = isWindows ? /[\\/:\*\?"<>\|]/g : /[\\/]/g; const WINDOWS_FORBIDDEN_NAMES = /^(con|prn|aux|clock\$|nul|lpt[0-9]|com[0-9])$/i; export class RemoteFileDialog { private fallbackPickerButton; private acceptButton; private currentFolder: URI; private filePickBox: IQuickPick<FileQuickPickItem>; private allowFileSelection: boolean; private allowFolderSelection: boolean; private remoteAuthority: string | undefined; private requiresTrailing: boolean; private userValue: string; private scheme: string = REMOTE_HOST_SCHEME; constructor( @IFileService private readonly remoteFileService: RemoteFileService, @IQuickInputService private readonly quickInputService: IQuickInputService, @IWindowService private readonly windowService: IWindowService, @ILabelService private readonly labelService: ILabelService, @IWorkspaceContextService private readonly workspaceContextService: IWorkspaceContextService, @INotificationService private readonly notificationService: INotificationService, @IFileDialogService private readonly fileDialogService: IFileDialogService, @IModelService private readonly modelService: IModelService, @IModeService private readonly modeService: IModeService, ) { this.remoteAuthority = this.windowService.getConfiguration().remoteAuthority; } public async showOpenDialog(options: IOpenDialogOptions = {}): Promise<IURIToOpen[] | undefined> { this.setScheme(options.defaultUri, options.availableFileSystems); const newOptions = this.getOptions(options); if (!newOptions) { return Promise.resolve(undefined); } const openFileString = nls.localize('remoteFileDialog.localFileFallback', 'Open Local File'); const openFolderString = nls.localize('remoteFileDialog.localFolderFallback', 'Open Local Folder'); const openFileFolderString = nls.localize('remoteFileDialog.localFileFolderFallback', 'Open Local File or Folder'); let tooltip = options.canSelectFiles ? (options.canSelectFolders ? openFileFolderString : openFileString) : openFolderString; this.fallbackPickerButton = { iconPath: this.getDialogIcons('folder'), tooltip }; return this.pickResource(newOptions).then(async fileFolderUri => { if (fileFolderUri) { const stat = await this.remoteFileService.resolveFile(fileFolderUri); return <IURIToOpen[]>[{ uri: fileFolderUri, typeHint: stat.isDirectory ? 'folder' : 'file' }]; } return Promise.resolve(undefined); }); } public showSaveDialog(options: ISaveDialogOptions): Promise<URI | undefined> { this.setScheme(options.defaultUri, options.availableFileSystems); this.requiresTrailing = true; const newOptions = this.getOptions(options); if (!newOptions) { return Promise.resolve(undefined); } this.fallbackPickerButton = { iconPath: this.getDialogIcons('folder'), tooltip: nls.localize('remoteFileDialog.localSaveFallback', 'Save Local File') }; newOptions.canSelectFolders = true; newOptions.canSelectFiles = true; return new Promise<URI | undefined>((resolve) => { this.pickResource(newOptions, true).then(folderUri => { resolve(folderUri); }); }); } private getOptions(options: ISaveDialogOptions | IOpenDialogOptions): IOpenDialogOptions | undefined { const defaultUri = options.defaultUri ? options.defaultUri : URI.from({ scheme: this.scheme, authority: this.remoteAuthority, path: '/' }); if ((this.scheme !== Schemas.file) && !this.remoteFileService.canHandleResource(defaultUri)) { this.notificationService.info(nls.localize('remoteFileDialog.notConnectedToRemote', 'File system provider for {0} is not available.', defaultUri.toString())); return undefined; } const newOptions: IOpenDialogOptions = objects.deepClone(options); newOptions.defaultUri = defaultUri; return newOptions; } private remoteUriFrom(path: string): URI { path = path.replace(/\\/g, '/'); return URI.from({ scheme: this.scheme, authority: this.remoteAuthority, path }); } private setScheme(defaultUri: URI | undefined, available: string[] | undefined) { this.scheme = defaultUri ? defaultUri.scheme : (available ? available[0] : Schemas.file); } private async pickResource(options: IOpenDialogOptions, isSave: boolean = false): Promise<URI | undefined> { this.allowFolderSelection = !!options.canSelectFolders; this.allowFileSelection = !!options.canSelectFiles; let homedir: URI = options.defaultUri ? options.defaultUri : this.workspaceContextService.getWorkspace().folders[0].uri; let trailing: string | undefined; let stat: IFileStat | undefined; let ext: string = resources.extname(homedir); if (options.defaultUri) { try { stat = await this.remoteFileService.resolveFile(options.defaultUri); } catch (e) { // The file or folder doesn't exist } if (!stat || !stat.isDirectory) { homedir = resources.dirname(options.defaultUri); trailing = resources.basename(options.defaultUri); } // append extension if (isSave && !ext && options.filters) { for (let i = 0; i < options.filters.length; i++) { if (options.filters[i].extensions[0] !== '*') { ext = '.' + options.filters[i].extensions[0]; trailing = trailing ? trailing + ext : ext; break; } } } } this.acceptButton = { iconPath: this.getDialogIcons('accept'), tooltip: options.title }; return new Promise<URI | undefined>((resolve) => { this.filePickBox = this.quickInputService.createQuickPick<FileQuickPickItem>(); this.filePickBox.matchOnLabel = false; this.filePickBox.autoFocusOnList = false; let isResolved = false; let isAcceptHandled = false; this.currentFolder = homedir; if (options.availableFileSystems && options.availableFileSystems.length > 1) { this.filePickBox.buttons = [this.fallbackPickerButton, this.acceptButton]; } else { this.filePickBox.buttons = [this.acceptButton]; } this.filePickBox.onDidTriggerButton(button => { if (button === this.fallbackPickerButton) { if (options.availableFileSystems) { options.availableFileSystems.shift(); } isResolved = true; if (this.requiresTrailing) { this.fileDialogService.showSaveDialog(options).then(result => { this.filePickBox.hide(); resolve(result); }); } else { this.fileDialogService.showOpenDialog(options).then(result => { this.filePickBox.hide(); resolve(result ? result[0] : undefined); }); } this.filePickBox.hide(); } else { // accept button const resolveValue = this.remoteUriFrom(this.filePickBox.value); this.validate(resolveValue).then(validated => { if (validated) { isResolved = true; this.filePickBox.hide(); resolve(resolveValue); } }); } }); this.filePickBox.title = options.title; this.filePickBox.value = this.pathFromUri(this.currentFolder); this.filePickBox.items = []; this.filePickBox.onDidAccept(_ => { if (isAcceptHandled || this.filePickBox.busy) { return; } isAcceptHandled = true; this.onDidAccept().then(resolveValue => { if (resolveValue) { isResolved = true; this.filePickBox.hide(); resolve(resolveValue); } }); }); this.filePickBox.onDidChangeActive(i => { isAcceptHandled = false; }); this.filePickBox.onDidChangeValue(async value => { if (value !== this.userValue) { const trimmedPickBoxValue = ((this.filePickBox.value.length > 1) && this.endsWithSlash(this.filePickBox.value)) ? this.filePickBox.value.substr(0, this.filePickBox.value.length - 1) : this.filePickBox.value; const valueUri = this.remoteUriFrom(trimmedPickBoxValue); if (!resources.isEqual(this.currentFolder, valueUri, true)) { await this.tryUpdateItems(value, valueUri); } this.setActiveItems(value); this.userValue = value; } else { this.filePickBox.activeItems = []; } }); this.filePickBox.onDidHide(() => { if (!isResolved) { resolve(undefined); } this.filePickBox.dispose(); }); this.filePickBox.show(); this.updateItems(homedir, trailing); if (trailing) { this.filePickBox.valueSelection = [this.filePickBox.value.length - trailing.length, this.filePickBox.value.length - ext.length]; } this.userValue = this.filePickBox.value; }); } private async onDidAccept(): Promise<URI | undefined> { let resolveValue: URI | undefined; let navigateValue: URI | undefined; const trimmedPickBoxValue = ((this.filePickBox.value.length > 1) && this.endsWithSlash(this.filePickBox.value)) ? this.filePickBox.value.substr(0, this.filePickBox.value.length - 1) : this.filePickBox.value; const inputUri = this.remoteUriFrom(trimmedPickBoxValue); const inputUriDirname = resources.dirname(inputUri); let stat: IFileStat | undefined; let statDirname: IFileStat | undefined; try { statDirname = await this.remoteFileService.resolveFile(inputUriDirname); stat = await this.remoteFileService.resolveFile(inputUri); } catch (e) { // do nothing } // Find resolve value if (this.filePickBox.activeItems.length === 0) { if (!this.requiresTrailing && resources.isEqual(this.currentFolder, inputUri, true)) { resolveValue = inputUri; } else if (this.requiresTrailing && statDirname && statDirname.isDirectory) { resolveValue = inputUri; } else if (stat && stat.isDirectory) { navigateValue = inputUri; } } else if (this.filePickBox.activeItems.length === 1) { const item = this.filePickBox.selectedItems[0]; if (item) { if (!item.isFolder) { resolveValue = item.uri; } else { navigateValue = item.uri; } } } if (resolveValue) { if (await this.validate(resolveValue)) { return Promise.resolve(resolveValue); } } else if (navigateValue) { // Try to navigate into the folder this.updateItems(navigateValue); } else { // validation error. Path does not exist. } return Promise.resolve(undefined); } private async tryUpdateItems(value: string, valueUri: URI) { if (this.endsWithSlash(value) || (!resources.isEqual(this.currentFolder, resources.dirname(valueUri), true) && resources.isEqualOrParent(this.currentFolder, resources.dirname(valueUri), true))) { let stat: IFileStat | undefined; try { stat = await this.remoteFileService.resolveFile(valueUri); } catch (e) { // do nothing } if (stat && stat.isDirectory && (resources.basename(valueUri) !== '.')) { this.updateItems(valueUri); } else { const inputUriDirname = resources.dirname(valueUri); if (!resources.isEqual(this.currentFolder, inputUriDirname, true)) { let statWithoutTrailing: IFileStat | undefined; try { statWithoutTrailing = await this.remoteFileService.resolveFile(inputUriDirname); } catch (e) { // do nothing } if (statWithoutTrailing && statWithoutTrailing.isDirectory && (resources.basename(valueUri) !== '.')) { this.updateItems(inputUriDirname, resources.basename(valueUri)); } } } } } private setActiveItems(value: string) { if (!this.userValue || (value !== this.userValue.substring(0, value.length))) { const inputBasename = resources.basename(this.remoteUriFrom(value)); let hasMatch = false; for (let i = 0; i < this.filePickBox.items.length; i++) { const item = <FileQuickPickItem>this.filePickBox.items[i]; const itemBasename = resources.basename(item.uri); if ((itemBasename.length >= inputBasename.length) && (itemBasename.substr(0, inputBasename.length).toLowerCase() === inputBasename.toLowerCase())) { this.filePickBox.activeItems = [item]; this.filePickBox.value = this.filePickBox.value + itemBasename.substr(inputBasename.length); this.filePickBox.valueSelection = [value.length, this.filePickBox.value.length]; hasMatch = true; break; } } if (!hasMatch) { this.filePickBox.activeItems = []; } } } private async validate(uri: URI): Promise<boolean> { let stat: IFileStat | undefined; let statDirname: IFileStat | undefined; try { statDirname = await this.remoteFileService.resolveFile(resources.dirname(uri)); stat = await this.remoteFileService.resolveFile(uri); } catch (e) { // do nothing } if (this.requiresTrailing) { // save if (stat && stat.isDirectory) { // Can't do this return Promise.resolve(false); } else if (stat) { // This is replacing a file. Not supported yet. return Promise.resolve(false); } else if (!this.isValidBaseName(resources.basename(uri))) { // Filename not allowed return Promise.resolve(false); } else if (!statDirname || !statDirname.isDirectory) { // Folder to save in doesn't exist return Promise.resolve(false); } } else { // open if (!stat) { // File or folder doesn't exist return Promise.resolve(false); } else if (stat.isDirectory && !this.allowFolderSelection) { // Folder selected when folder selection not permitted return Promise.resolve(false); } else if (!stat.isDirectory && !this.allowFileSelection) { // File selected when file selection not permitted return Promise.resolve(false); } } return Promise.resolve(true); } private updateItems(newFolder: URI, trailing?: string) { this.currentFolder = newFolder; this.filePickBox.value = trailing ? this.pathFromUri(resources.joinPath(newFolder, trailing)) : this.pathFromUri(newFolder, true); this.filePickBox.busy = true; this.createItems(this.currentFolder).then(items => { this.filePickBox.items = items; if (this.allowFolderSelection) { this.filePickBox.activeItems = []; } this.filePickBox.busy = false; }); } private pathFromUri(uri: URI, endWithSeparator: boolean = false): string { const sep = this.labelService.getSeparator(uri.scheme, uri.authority); let result: string; if (sep === '/') { result = uri.fsPath.replace(/\\/g, sep); } else { result = uri.fsPath.replace(/\//g, sep); } if (endWithSeparator && !this.endsWithSlash(result)) { result = result + sep; } return result; } private isValidBaseName(name: string): boolean { if (!name || name.length === 0 || /^\s+$/.test(name)) { return false; // require a name that is not just whitespace } INVALID_FILE_CHARS.lastIndex = 0; // the holy grail of software development if (INVALID_FILE_CHARS.test(name)) { return false; // check for certain invalid file characters } if (isWindows && WINDOWS_FORBIDDEN_NAMES.test(name)) { return false; // check for certain invalid file names } if (name === '.' || name === '..') { return false; // check for reserved values } if (isWindows && name[name.length - 1] === '.') { return false; // Windows: file cannot end with a "." } if (isWindows && name.length !== name.trim().length) { return false; // Windows: file cannot end with a whitespace } return true; } private endsWithSlash(s: string) { return /[\/\\]$/.test(s); } private basenameWithTrailingSlash(fullPath: URI): string { const child = this.pathFromUri(fullPath, true); const parent = this.pathFromUri(resources.dirname(fullPath), true); return child.substring(parent.length); } private createBackItem(currFolder: URI): FileQuickPickItem | null { const parentFolder = resources.dirname(currFolder)!; if (!resources.isEqual(currFolder, parentFolder, true)) { return { label: '..', uri: resources.dirname(currFolder), isFolder: true }; } return null; } private async createItems(currentFolder: URI): Promise<FileQuickPickItem[]> { const result: FileQuickPickItem[] = []; const backDir = this.createBackItem(currentFolder); try { const fileNames = await this.remoteFileService.readFolder(currentFolder); const items = await Promise.all(fileNames.map(fileName => this.createItem(fileName, currentFolder))); for (let item of items) { if (item) { result.push(item); } } } catch (e) { // ignore console.log(e); } const sorted = result.sort((i1, i2) => { if (i1.isFolder !== i2.isFolder) { return i1.isFolder ? -1 : 1; } const trimmed1 = this.endsWithSlash(i1.label) ? i1.label.substr(0, i1.label.length - 1) : i1.label; const trimmed2 = this.endsWithSlash(i2.label) ? i2.label.substr(0, i2.label.length - 1) : i2.label; return trimmed1.localeCompare(trimmed2); }); if (backDir) { sorted.unshift(backDir); } return sorted; } private async createItem(filename: string, parent: URI): Promise<FileQuickPickItem | null> { let fullPath = resources.joinPath(parent, filename); try { const stat = await this.remoteFileService.resolveFile(fullPath); if (stat.isDirectory) { filename = this.basenameWithTrailingSlash(fullPath); return { label: filename, uri: fullPath, isFolder: true, iconClasses: getIconClasses(this.modelService, this.modeService, fullPath || undefined, FileKind.FOLDER) }; } else if (!stat.isDirectory && this.allowFileSelection) { return { label: filename, uri: fullPath, isFolder: false, iconClasses: getIconClasses(this.modelService, this.modeService, fullPath || undefined) }; } return null; } catch (e) { return null; } } private getDialogIcons(name: string): { light: URI, dark: URI } { return { dark: URI.parse(require.toUrl(`vs/workbench/services/dialogs/electron-browser/media/dark/${name}.svg`)), light: URI.parse(require.toUrl(`vs/workbench/services/dialogs/electron-browser/media/light/${name}.svg`)) }; } }
src/vs/workbench/services/dialogs/electron-browser/remoteFileDialog.ts
1
https://github.com/microsoft/vscode/commit/f07c7d705629bea1c6f5af42b7d3f7d72e225f2a
[ 0.998236894607544, 0.020488187670707703, 0.00016183611296582967, 0.0001794222043827176, 0.1382838636636734 ]
{ "id": 9, "code_window": [ "\t\t\t\treturn Promise.resolve(false);\n", "\t\t\t} else if (stat) {\n", "\t\t\t\t// This is replacing a file. Not supported yet.\n", "\t\t\t\treturn Promise.resolve(false);\n", "\t\t\t} else if (!this.isValidBaseName(resources.basename(uri))) {\n", "\t\t\t\t// Filename not allowed\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\tthis.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateExisting', 'The file already exists. Please use a new file name.');\n" ], "file_path": "src/vs/workbench/services/dialogs/electron-browser/remoteFileDialog.ts", "type": "add", "edit_start_line_idx": 354 }
{ "name": "xml", "displayName": "%displayName%", "description": "%description%", "version": "1.0.0", "publisher": "vscode", "engines": { "vscode": "*" }, "contributes": { "languages": [{ "id": "xml", "extensions": [ ".xml", ".xsd", ".ascx", ".atom", ".axml", ".bpmn", ".cpt", ".csl", ".csproj", ".csproj.user", ".dita", ".ditamap", ".dtd", ".dtml", ".fsproj", ".fxml", ".iml", ".isml", ".jmx", ".launch", ".menu", ".mxml", ".nuspec", ".opml", ".owl", ".proj", ".props", ".pt", ".publishsettings", ".pubxml", ".pubxml.user", ".rdf", ".rng", ".rss", ".shproj", ".storyboard", ".svg", ".targets", ".tld", ".tmx", ".vbproj", ".vbproj.user", ".vcxproj", ".vcxproj.filters", ".wsdl", ".wxi", ".wxl", ".wxs", ".xaml", ".xbl", ".xib", ".xlf", ".xliff", ".xpdl", ".xul", ".xoml" ], "firstLine" : "(\\<\\?xml.*)|(\\<svg)|(\\<\\!doctype\\s+svg)", "aliases": [ "XML", "xml" ], "configuration": "./xml.language-configuration.json" }, { "id": "xsl", "extensions": [ ".xsl", ".xslt" ], "aliases": [ "XSL", "xsl" ], "configuration": "./xsl.language-configuration.json" }], "grammars": [{ "language": "xml", "scopeName": "text.xml", "path": "./syntaxes/xml.tmLanguage.json" }, { "language": "xsl", "scopeName": "text.xml.xsl", "path": "./syntaxes/xsl.tmLanguage.json" }] }, "scripts": { "update-grammar": "node ../../build/npm/update-grammar.js atom/language-xml grammars/xml.cson ./syntaxes/xml.tmLanguage.json grammars/xsl.cson ./syntaxes/xsl.tmLanguage.json" } }
extensions/xml/package.json
0
https://github.com/microsoft/vscode/commit/f07c7d705629bea1c6f5af42b7d3f7d72e225f2a
[ 0.0001761705643730238, 0.00017345693777315319, 0.00017147781909443438, 0.0001726166665321216, 0.00000175107254563045 ]
{ "id": 9, "code_window": [ "\t\t\t\treturn Promise.resolve(false);\n", "\t\t\t} else if (stat) {\n", "\t\t\t\t// This is replacing a file. Not supported yet.\n", "\t\t\t\treturn Promise.resolve(false);\n", "\t\t\t} else if (!this.isValidBaseName(resources.basename(uri))) {\n", "\t\t\t\t// Filename not allowed\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\tthis.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateExisting', 'The file already exists. Please use a new file name.');\n" ], "file_path": "src/vs/workbench/services/dialogs/electron-browser/remoteFileDialog.ts", "type": "add", "edit_start_line_idx": 354 }
/*--------------------------------------------------------------------------------------------- * 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!./keybindingLabel'; import { equals } from 'vs/base/common/objects'; import { OperatingSystem } from 'vs/base/common/platform'; import { ResolvedKeybinding, ResolvedKeybindingPart } from 'vs/base/common/keyCodes'; import { UILabelProvider } from 'vs/base/common/keybindingLabels'; import * as dom from 'vs/base/browser/dom'; import { localize } from 'vs/nls'; const $ = dom.$; export interface PartMatches { ctrlKey?: boolean; shiftKey?: boolean; altKey?: boolean; metaKey?: boolean; keyCode?: boolean; } export interface Matches { firstPart: PartMatches; chordPart: PartMatches; } export interface KeybindingLabelOptions { renderUnboundKeybindings: boolean; } export class KeybindingLabel { private domNode: HTMLElement; private keybinding: ResolvedKeybinding | undefined; private matches: Matches | undefined; private didEverRender: boolean; constructor(container: HTMLElement, private os: OperatingSystem, private options?: KeybindingLabelOptions) { this.domNode = dom.append(container, $('.monaco-keybinding')); this.didEverRender = false; container.appendChild(this.domNode); } get element(): HTMLElement { return this.domNode; } set(keybinding: ResolvedKeybinding | undefined, matches?: Matches) { if (this.didEverRender && this.keybinding === keybinding && KeybindingLabel.areSame(this.matches, matches)) { return; } this.keybinding = keybinding; this.matches = matches; this.render(); } private render() { dom.clearNode(this.domNode); if (this.keybinding) { let [firstPart, chordPart] = this.keybinding.getParts(); if (firstPart) { this.renderPart(this.domNode, firstPart, this.matches ? this.matches.firstPart : null); } if (chordPart) { dom.append(this.domNode, $('span.monaco-keybinding-key-chord-separator', undefined, ' ')); this.renderPart(this.domNode, chordPart, this.matches ? this.matches.chordPart : null); } this.domNode.title = this.keybinding.getAriaLabel() || ''; } else if (this.options && this.options.renderUnboundKeybindings) { this.renderUnbound(this.domNode); } this.didEverRender = true; } private renderPart(parent: HTMLElement, part: ResolvedKeybindingPart, match: PartMatches | null) { const modifierLabels = UILabelProvider.modifierLabels[this.os]; if (part.ctrlKey) { this.renderKey(parent, modifierLabels.ctrlKey, Boolean(match && match.ctrlKey), modifierLabels.separator); } if (part.shiftKey) { this.renderKey(parent, modifierLabels.shiftKey, Boolean(match && match.shiftKey), modifierLabels.separator); } if (part.altKey) { this.renderKey(parent, modifierLabels.altKey, Boolean(match && match.altKey), modifierLabels.separator); } if (part.metaKey) { this.renderKey(parent, modifierLabels.metaKey, Boolean(match && match.metaKey), modifierLabels.separator); } const keyLabel = part.keyLabel; if (keyLabel) { this.renderKey(parent, keyLabel, Boolean(match && match.keyCode), ''); } } private renderKey(parent: HTMLElement, label: string, highlight: boolean, separator: string): void { dom.append(parent, $('span.monaco-keybinding-key' + (highlight ? '.highlight' : ''), undefined, label)); if (separator) { dom.append(parent, $('span.monaco-keybinding-key-separator', undefined, separator)); } } private renderUnbound(parent: HTMLElement): void { dom.append(parent, $('span.monaco-keybinding-key', undefined, localize('unbound', "Unbound"))); } private static areSame(a: Matches | undefined, b: Matches | undefined): boolean { if (a === b || (!a && !b)) { return true; } return !!a && !!b && equals(a.firstPart, b.firstPart) && equals(a.chordPart, b.chordPart); } }
src/vs/base/browser/ui/keybindingLabel/keybindingLabel.ts
0
https://github.com/microsoft/vscode/commit/f07c7d705629bea1c6f5af42b7d3f7d72e225f2a
[ 0.00017696789291221648, 0.00017222373571712524, 0.00016556955233681947, 0.00017249997472390532, 0.0000032927921438385965 ]
{ "id": 9, "code_window": [ "\t\t\t\treturn Promise.resolve(false);\n", "\t\t\t} else if (stat) {\n", "\t\t\t\t// This is replacing a file. Not supported yet.\n", "\t\t\t\treturn Promise.resolve(false);\n", "\t\t\t} else if (!this.isValidBaseName(resources.basename(uri))) {\n", "\t\t\t\t// Filename not allowed\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\tthis.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateExisting', 'The file already exists. Please use a new file name.');\n" ], "file_path": "src/vs/workbench/services/dialogs/electron-browser/remoteFileDialog.ts", "type": "add", "edit_start_line_idx": 354 }
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><defs><style>.icon-canvas-transparent,.icon-vs-out{fill:#f6f6f6;}.icon-canvas-transparent{opacity:0;}.icon-vs-bg{fill:#424242;}</style></defs><title>add</title><g id="canvas"><path class="icon-canvas-transparent" d="M16,16H0V0H16Z"/></g><g id="outline" style="display: none;"><path class="icon-vs-out" d="M14,6v4H10v4H6V10H2V6H6V2h4V6Z"/></g><g id="iconBg"><path class="icon-vs-bg" d="M13,7V9H9v4H7V9H3V7H7V3H9V7Z"/></g></svg>
src/vs/workbench/contrib/debug/browser/media/add.svg
0
https://github.com/microsoft/vscode/commit/f07c7d705629bea1c6f5af42b7d3f7d72e225f2a
[ 0.00017455648048780859, 0.00017455648048780859, 0.00017455648048780859, 0.00017455648048780859, 0 ]
{ "id": 10, "code_window": [ "\t\t\t\treturn Promise.resolve(false);\n", "\t\t\t} else if (!this.isValidBaseName(resources.basename(uri))) {\n", "\t\t\t\t// Filename not allowed\n", "\t\t\t\treturn Promise.resolve(false);\n", "\t\t\t} else if (!statDirname || !statDirname.isDirectory) {\n", "\t\t\t\t// Folder to save in doesn't exist\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\tthis.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateBadFilename', 'Please enter a valid file name.');\n" ], "file_path": "src/vs/workbench/services/dialogs/electron-browser/remoteFileDialog.ts", "type": "add", "edit_start_line_idx": 357 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { createDecorator } from 'vs/platform/instantiation/common/instantiation'; import { CancellationToken } from 'vs/base/common/cancellation'; import { ResolvedKeybinding } from 'vs/base/common/keyCodes'; import { URI } from 'vs/base/common/uri'; import { Event } from 'vs/base/common/event'; export interface IQuickPickItem { type?: 'item'; id?: string; label: string; description?: string; detail?: string; iconClasses?: string[]; buttons?: IQuickInputButton[]; picked?: boolean; alwaysShow?: boolean; } export interface IQuickPickSeparator { type: 'separator'; label?: string; } export interface IKeyMods { readonly ctrlCmd: boolean; readonly alt: boolean; } export interface IQuickNavigateConfiguration { keybindings: ResolvedKeybinding[]; } export interface IPickOptions<T extends IQuickPickItem> { /** * an optional string to show as place holder in the input box to guide the user what she picks on */ placeHolder?: string; /** * an optional flag to include the description when filtering the picks */ matchOnDescription?: boolean; /** * an optional flag to include the detail when filtering the picks */ matchOnDetail?: boolean; /** * an optional flag to filter the picks based on label. Defaults to true. */ matchOnLabel?: boolean; /** * an option flag to control whether focus is always automatically brought to a list item. Defaults to true. */ autoFocusOnList?: boolean; /** * an optional flag to not close the picker on focus lost */ ignoreFocusLost?: boolean; /** * an optional flag to make this picker multi-select */ canPickMany?: boolean; /** * enables quick navigate in the picker to open an element without typing */ quickNavigate?: IQuickNavigateConfiguration; /** * a context key to set when this picker is active */ contextKey?: string; /** * an optional property for the item to focus initially. */ activeItem?: Promise<T> | T; onKeyMods?: (keyMods: IKeyMods) => void; onDidFocus?: (entry: T) => void; onDidTriggerItemButton?: (context: IQuickPickItemButtonContext<T>) => void; } export interface IInputOptions { /** * the value to prefill in the input box */ value?: string; /** * the selection of value, default to the whole word */ valueSelection?: [number, number]; /** * 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; ignoreFocusLost?: boolean; /** * an optional function that is used to validate user input. */ validateInput?: (input: string) => Promise<string | null | undefined>; } export interface IQuickInput { title: string | undefined; step: number | undefined; totalSteps: number | undefined; enabled: boolean; contextKey: string | undefined; busy: boolean; ignoreFocusOut: boolean; show(): void; hide(): void; onDidHide: Event<void>; dispose(): void; } export interface IQuickPick<T extends IQuickPickItem> extends IQuickInput { value: string; placeholder: string | undefined; readonly onDidChangeValue: Event<string>; readonly onDidAccept: Event<void>; buttons: ReadonlyArray<IQuickInputButton>; readonly onDidTriggerButton: Event<IQuickInputButton>; readonly onDidTriggerItemButton: Event<IQuickPickItemButtonEvent<T>>; items: ReadonlyArray<T | IQuickPickSeparator>; canSelectMany: boolean; matchOnDescription: boolean; matchOnDetail: boolean; matchOnLabel: boolean; autoFocusOnList: boolean; quickNavigate: IQuickNavigateConfiguration | undefined; activeItems: ReadonlyArray<T>; readonly onDidChangeActive: Event<T[]>; selectedItems: ReadonlyArray<T>; readonly onDidChangeSelection: Event<T[]>; readonly keyMods: IKeyMods; valueSelection: Readonly<[number, number]> | undefined; } export interface IInputBox extends IQuickInput { value: string; valueSelection: Readonly<[number, number]> | undefined; placeholder: string | undefined; password: boolean; readonly onDidChangeValue: Event<string>; readonly onDidAccept: Event<void>; buttons: ReadonlyArray<IQuickInputButton>; readonly onDidTriggerButton: Event<IQuickInputButton>; prompt: string | undefined; validationMessage: string | undefined; } export interface IQuickInputButton { /** iconPath or iconClass required */ iconPath?: { dark: URI; light?: URI; }; /** iconPath or iconClass required */ iconClass?: string; tooltip?: string; } export interface IQuickPickItemButtonEvent<T extends IQuickPickItem> { button: IQuickInputButton; item: T; } export interface IQuickPickItemButtonContext<T extends IQuickPickItem> extends IQuickPickItemButtonEvent<T> { removeItem(): void; } export const IQuickInputService = createDecorator<IQuickInputService>('quickInputService'); export type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>; export type QuickPickInput<T = IQuickPickItem> = T | IQuickPickSeparator; export interface IQuickInputService { _serviceBrand: any; /** * Opens the quick input box for selecting items and returns a promise with the user selected item(s) if any. */ pick<T extends IQuickPickItem>(picks: Promise<QuickPickInput<T>[]> | QuickPickInput<T>[], options?: IPickOptions<T> & { canPickMany: true }, token?: CancellationToken): Promise<T[]>; pick<T extends IQuickPickItem>(picks: Promise<QuickPickInput<T>[]> | QuickPickInput<T>[], options?: IPickOptions<T> & { canPickMany: false }, token?: CancellationToken): Promise<T>; pick<T extends IQuickPickItem>(picks: Promise<QuickPickInput<T>[]> | QuickPickInput<T>[], options?: Omit<IPickOptions<T>, 'canPickMany'>, token?: CancellationToken): Promise<T>; /** * Opens the quick input box for text input and returns a promise with the user typed value if any. */ input(options?: IInputOptions, token?: CancellationToken): Promise<string>; backButton: IQuickInputButton; createQuickPick<T extends IQuickPickItem>(): IQuickPick<T>; createInputBox(): IInputBox; focus(): void; toggle(): void; navigate(next: boolean, quickNavigate?: IQuickNavigateConfiguration): void; accept(): Promise<void>; back(): Promise<void>; cancel(): Promise<void>; }
src/vs/platform/quickinput/common/quickInput.ts
1
https://github.com/microsoft/vscode/commit/f07c7d705629bea1c6f5af42b7d3f7d72e225f2a
[ 0.00020566924649756402, 0.00017185854085255414, 0.00016433974087703973, 0.00017017190111801028, 0.000007409818863379769 ]
{ "id": 10, "code_window": [ "\t\t\t\treturn Promise.resolve(false);\n", "\t\t\t} else if (!this.isValidBaseName(resources.basename(uri))) {\n", "\t\t\t\t// Filename not allowed\n", "\t\t\t\treturn Promise.resolve(false);\n", "\t\t\t} else if (!statDirname || !statDirname.isDirectory) {\n", "\t\t\t\t// Folder to save in doesn't exist\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\tthis.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateBadFilename', 'Please enter a valid file name.');\n" ], "file_path": "src/vs/workbench/services/dialogs/electron-browser/remoteFileDialog.ts", "type": "add", "edit_start_line_idx": 357 }
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="3 3 16 16" enable-background="new 3 3 16 16"><polygon fill="#e8e8e8" points="12.597,11.042 15.4,13.845 13.844,15.4 11.042,12.598 8.239,15.4 6.683,13.845 9.485,11.042 6.683,8.239 8.238,6.683 11.042,9.486 13.845,6.683 15.4,8.239"/></svg>
src/vs/editor/contrib/suggest/media/close-dark.svg
0
https://github.com/microsoft/vscode/commit/f07c7d705629bea1c6f5af42b7d3f7d72e225f2a
[ 0.00017228710930794477, 0.00017228710930794477, 0.00017228710930794477, 0.00017228710930794477, 0 ]
{ "id": 10, "code_window": [ "\t\t\t\treturn Promise.resolve(false);\n", "\t\t\t} else if (!this.isValidBaseName(resources.basename(uri))) {\n", "\t\t\t\t// Filename not allowed\n", "\t\t\t\treturn Promise.resolve(false);\n", "\t\t\t} else if (!statDirname || !statDirname.isDirectory) {\n", "\t\t\t\t// Folder to save in doesn't exist\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\tthis.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateBadFilename', 'Please enter a valid file name.');\n" ], "file_path": "src/vs/workbench/services/dialogs/electron-browser/remoteFileDialog.ts", "type": "add", "edit_start_line_idx": 357 }
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><style>.icon-canvas-transparent{opacity:0;fill:#2d2d30}.icon-vs-out{fill:#2d2d30}.icon-vs-bg{fill:#c5c5c5}.icon-vs-fg{fill:#2b282e}</style><path class="icon-canvas-transparent" d="M16 16H0V0h16v16z" id="canvas"/><path class="icon-vs-out" d="M16 5V2H9V1H0v14h13v-3h3V9h-1V6H9V5h7zm-8 7V9h1v3H8z" id="outline"/><path class="icon-vs-fg" d="M2 3h5v1H2V3z" id="iconFg"/><path class="icon-vs-bg" d="M15 4h-5V3h5v1zm-1 3h-2v1h2V7zm-4 0H1v1h9V7zm2 6H1v1h11v-1zm-5-3H1v1h6v-1zm8 0h-5v1h5v-1zM8 2v3H1V2h7zM7 3H2v1h5V3z" id="iconBg"/></svg>
src/vs/editor/contrib/suggest/media/IntelliSenseKeyword_inverse_16x.svg
0
https://github.com/microsoft/vscode/commit/f07c7d705629bea1c6f5af42b7d3f7d72e225f2a
[ 0.00016484585648868233, 0.00016484585648868233, 0.00016484585648868233, 0.00016484585648868233, 0 ]
{ "id": 10, "code_window": [ "\t\t\t\treturn Promise.resolve(false);\n", "\t\t\t} else if (!this.isValidBaseName(resources.basename(uri))) {\n", "\t\t\t\t// Filename not allowed\n", "\t\t\t\treturn Promise.resolve(false);\n", "\t\t\t} else if (!statDirname || !statDirname.isDirectory) {\n", "\t\t\t\t// Folder to save in doesn't exist\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\tthis.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateBadFilename', 'Please enter a valid file name.');\n" ], "file_path": "src/vs/workbench/services/dialogs/electron-browser/remoteFileDialog.ts", "type": "add", "edit_start_line_idx": 357 }
"use strict"; /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ Object.defineProperty(exports, "__esModule", { value: true }); const https = require("https"); const fs = require("fs"); const path = require("path"); const cp = require("child_process"); function ensureDir(filepath) { if (!fs.existsSync(filepath)) { ensureDir(path.dirname(filepath)); fs.mkdirSync(filepath); } } function download(options, destination) { ensureDir(path.dirname(destination)); return new Promise((c, e) => { const fd = fs.openSync(destination, 'w'); const req = https.get(options, (res) => { res.on('data', (chunk) => { fs.writeSync(fd, chunk); }); res.on('end', () => { fs.closeSync(fd); c(); }); }); req.on('error', (reqErr) => { console.error(`request to ${options.host}${options.path} failed.`); console.error(reqErr); e(reqErr); }); }); } const MARKER_ARGUMENT = `_download_fork_`; function base64encode(str) { return Buffer.from(str, 'utf8').toString('base64'); } function base64decode(str) { return Buffer.from(str, 'base64').toString('utf8'); } function downloadInExternalProcess(options) { const url = `https://${options.requestOptions.host}${options.requestOptions.path}`; console.log(`Downloading ${url}...`); return new Promise((c, e) => { const child = cp.fork(__filename, [MARKER_ARGUMENT, base64encode(JSON.stringify(options))], { stdio: ['pipe', 'pipe', 'pipe', 'ipc'] }); let stderr = []; child.stderr.on('data', (chunk) => { stderr.push(typeof chunk === 'string' ? Buffer.from(chunk) : chunk); }); child.on('exit', (code) => { if (code === 0) { // normal termination console.log(`Finished downloading ${url}.`); c(); } else { // abnormal termination console.error(Buffer.concat(stderr).toString()); e(new Error(`Download of ${url} failed.`)); } }); }); } exports.downloadInExternalProcess = downloadInExternalProcess; function _downloadInExternalProcess() { let options; try { options = JSON.parse(base64decode(process.argv[3])); } catch (err) { console.error(`Cannot read arguments`); console.error(err); process.exit(-1); return; } download(options.requestOptions, options.destinationPath).then(() => { process.exit(0); }, (err) => { console.error(err); process.exit(-2); }); } if (process.argv.length >= 4 && process.argv[2] === MARKER_ARGUMENT) { // running as forked download script _downloadInExternalProcess(); }
build/download/download.js
0
https://github.com/microsoft/vscode/commit/f07c7d705629bea1c6f5af42b7d3f7d72e225f2a
[ 0.00021746230777353048, 0.00017754180589690804, 0.0001676079846220091, 0.0001741599990054965, 0.000013578873222286347 ]
{ "id": 11, "code_window": [ "\t\t\t\treturn Promise.resolve(false);\n", "\t\t\t} else if (!statDirname || !statDirname.isDirectory) {\n", "\t\t\t\t// Folder to save in doesn't exist\n", "\t\t\t\treturn Promise.resolve(false);\n", "\t\t\t}\n", "\t\t} else { // open\n", "\t\t\tif (!stat) {\n", "\t\t\t\t// File or folder doesn't exist\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\tthis.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateNonexistentDir', 'Please enter a path that exists.');\n" ], "file_path": "src/vs/workbench/services/dialogs/electron-browser/remoteFileDialog.ts", "type": "add", "edit_start_line_idx": 360 }
/*--------------------------------------------------------------------------------------------- * 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 resources from 'vs/base/common/resources'; import * as objects from 'vs/base/common/objects'; import { RemoteFileService } from 'vs/workbench/services/files/node/remoteFileService'; import { IFileService, IFileStat, FileKind } from 'vs/platform/files/common/files'; import { IQuickInputService, IQuickPickItem, IQuickPick } from 'vs/platform/quickinput/common/quickInput'; import { URI } from 'vs/base/common/uri'; import { isWindows } from 'vs/base/common/platform'; import { ISaveDialogOptions, IOpenDialogOptions, IFileDialogService } from 'vs/platform/dialogs/common/dialogs'; import { REMOTE_HOST_SCHEME } from 'vs/platform/remote/common/remoteHosts'; import { IWindowService, IURIToOpen } from 'vs/platform/windows/common/windows'; import { ILabelService } from 'vs/platform/label/common/label'; import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace'; import { INotificationService } from 'vs/platform/notification/common/notification'; import { IModelService } from 'vs/editor/common/services/modelService'; import { IModeService } from 'vs/editor/common/services/modeService'; import { getIconClasses } from 'vs/editor/common/services/getIconClasses'; import { Schemas } from 'vs/base/common/network'; interface FileQuickPickItem extends IQuickPickItem { uri: URI; isFolder: boolean; } // Reference: https://en.wikipedia.org/wiki/Filename const INVALID_FILE_CHARS = isWindows ? /[\\/:\*\?"<>\|]/g : /[\\/]/g; const WINDOWS_FORBIDDEN_NAMES = /^(con|prn|aux|clock\$|nul|lpt[0-9]|com[0-9])$/i; export class RemoteFileDialog { private fallbackPickerButton; private acceptButton; private currentFolder: URI; private filePickBox: IQuickPick<FileQuickPickItem>; private allowFileSelection: boolean; private allowFolderSelection: boolean; private remoteAuthority: string | undefined; private requiresTrailing: boolean; private userValue: string; private scheme: string = REMOTE_HOST_SCHEME; constructor( @IFileService private readonly remoteFileService: RemoteFileService, @IQuickInputService private readonly quickInputService: IQuickInputService, @IWindowService private readonly windowService: IWindowService, @ILabelService private readonly labelService: ILabelService, @IWorkspaceContextService private readonly workspaceContextService: IWorkspaceContextService, @INotificationService private readonly notificationService: INotificationService, @IFileDialogService private readonly fileDialogService: IFileDialogService, @IModelService private readonly modelService: IModelService, @IModeService private readonly modeService: IModeService, ) { this.remoteAuthority = this.windowService.getConfiguration().remoteAuthority; } public async showOpenDialog(options: IOpenDialogOptions = {}): Promise<IURIToOpen[] | undefined> { this.setScheme(options.defaultUri, options.availableFileSystems); const newOptions = this.getOptions(options); if (!newOptions) { return Promise.resolve(undefined); } const openFileString = nls.localize('remoteFileDialog.localFileFallback', 'Open Local File'); const openFolderString = nls.localize('remoteFileDialog.localFolderFallback', 'Open Local Folder'); const openFileFolderString = nls.localize('remoteFileDialog.localFileFolderFallback', 'Open Local File or Folder'); let tooltip = options.canSelectFiles ? (options.canSelectFolders ? openFileFolderString : openFileString) : openFolderString; this.fallbackPickerButton = { iconPath: this.getDialogIcons('folder'), tooltip }; return this.pickResource(newOptions).then(async fileFolderUri => { if (fileFolderUri) { const stat = await this.remoteFileService.resolveFile(fileFolderUri); return <IURIToOpen[]>[{ uri: fileFolderUri, typeHint: stat.isDirectory ? 'folder' : 'file' }]; } return Promise.resolve(undefined); }); } public showSaveDialog(options: ISaveDialogOptions): Promise<URI | undefined> { this.setScheme(options.defaultUri, options.availableFileSystems); this.requiresTrailing = true; const newOptions = this.getOptions(options); if (!newOptions) { return Promise.resolve(undefined); } this.fallbackPickerButton = { iconPath: this.getDialogIcons('folder'), tooltip: nls.localize('remoteFileDialog.localSaveFallback', 'Save Local File') }; newOptions.canSelectFolders = true; newOptions.canSelectFiles = true; return new Promise<URI | undefined>((resolve) => { this.pickResource(newOptions, true).then(folderUri => { resolve(folderUri); }); }); } private getOptions(options: ISaveDialogOptions | IOpenDialogOptions): IOpenDialogOptions | undefined { const defaultUri = options.defaultUri ? options.defaultUri : URI.from({ scheme: this.scheme, authority: this.remoteAuthority, path: '/' }); if ((this.scheme !== Schemas.file) && !this.remoteFileService.canHandleResource(defaultUri)) { this.notificationService.info(nls.localize('remoteFileDialog.notConnectedToRemote', 'File system provider for {0} is not available.', defaultUri.toString())); return undefined; } const newOptions: IOpenDialogOptions = objects.deepClone(options); newOptions.defaultUri = defaultUri; return newOptions; } private remoteUriFrom(path: string): URI { path = path.replace(/\\/g, '/'); return URI.from({ scheme: this.scheme, authority: this.remoteAuthority, path }); } private setScheme(defaultUri: URI | undefined, available: string[] | undefined) { this.scheme = defaultUri ? defaultUri.scheme : (available ? available[0] : Schemas.file); } private async pickResource(options: IOpenDialogOptions, isSave: boolean = false): Promise<URI | undefined> { this.allowFolderSelection = !!options.canSelectFolders; this.allowFileSelection = !!options.canSelectFiles; let homedir: URI = options.defaultUri ? options.defaultUri : this.workspaceContextService.getWorkspace().folders[0].uri; let trailing: string | undefined; let stat: IFileStat | undefined; let ext: string = resources.extname(homedir); if (options.defaultUri) { try { stat = await this.remoteFileService.resolveFile(options.defaultUri); } catch (e) { // The file or folder doesn't exist } if (!stat || !stat.isDirectory) { homedir = resources.dirname(options.defaultUri); trailing = resources.basename(options.defaultUri); } // append extension if (isSave && !ext && options.filters) { for (let i = 0; i < options.filters.length; i++) { if (options.filters[i].extensions[0] !== '*') { ext = '.' + options.filters[i].extensions[0]; trailing = trailing ? trailing + ext : ext; break; } } } } this.acceptButton = { iconPath: this.getDialogIcons('accept'), tooltip: options.title }; return new Promise<URI | undefined>((resolve) => { this.filePickBox = this.quickInputService.createQuickPick<FileQuickPickItem>(); this.filePickBox.matchOnLabel = false; this.filePickBox.autoFocusOnList = false; let isResolved = false; let isAcceptHandled = false; this.currentFolder = homedir; if (options.availableFileSystems && options.availableFileSystems.length > 1) { this.filePickBox.buttons = [this.fallbackPickerButton, this.acceptButton]; } else { this.filePickBox.buttons = [this.acceptButton]; } this.filePickBox.onDidTriggerButton(button => { if (button === this.fallbackPickerButton) { if (options.availableFileSystems) { options.availableFileSystems.shift(); } isResolved = true; if (this.requiresTrailing) { this.fileDialogService.showSaveDialog(options).then(result => { this.filePickBox.hide(); resolve(result); }); } else { this.fileDialogService.showOpenDialog(options).then(result => { this.filePickBox.hide(); resolve(result ? result[0] : undefined); }); } this.filePickBox.hide(); } else { // accept button const resolveValue = this.remoteUriFrom(this.filePickBox.value); this.validate(resolveValue).then(validated => { if (validated) { isResolved = true; this.filePickBox.hide(); resolve(resolveValue); } }); } }); this.filePickBox.title = options.title; this.filePickBox.value = this.pathFromUri(this.currentFolder); this.filePickBox.items = []; this.filePickBox.onDidAccept(_ => { if (isAcceptHandled || this.filePickBox.busy) { return; } isAcceptHandled = true; this.onDidAccept().then(resolveValue => { if (resolveValue) { isResolved = true; this.filePickBox.hide(); resolve(resolveValue); } }); }); this.filePickBox.onDidChangeActive(i => { isAcceptHandled = false; }); this.filePickBox.onDidChangeValue(async value => { if (value !== this.userValue) { const trimmedPickBoxValue = ((this.filePickBox.value.length > 1) && this.endsWithSlash(this.filePickBox.value)) ? this.filePickBox.value.substr(0, this.filePickBox.value.length - 1) : this.filePickBox.value; const valueUri = this.remoteUriFrom(trimmedPickBoxValue); if (!resources.isEqual(this.currentFolder, valueUri, true)) { await this.tryUpdateItems(value, valueUri); } this.setActiveItems(value); this.userValue = value; } else { this.filePickBox.activeItems = []; } }); this.filePickBox.onDidHide(() => { if (!isResolved) { resolve(undefined); } this.filePickBox.dispose(); }); this.filePickBox.show(); this.updateItems(homedir, trailing); if (trailing) { this.filePickBox.valueSelection = [this.filePickBox.value.length - trailing.length, this.filePickBox.value.length - ext.length]; } this.userValue = this.filePickBox.value; }); } private async onDidAccept(): Promise<URI | undefined> { let resolveValue: URI | undefined; let navigateValue: URI | undefined; const trimmedPickBoxValue = ((this.filePickBox.value.length > 1) && this.endsWithSlash(this.filePickBox.value)) ? this.filePickBox.value.substr(0, this.filePickBox.value.length - 1) : this.filePickBox.value; const inputUri = this.remoteUriFrom(trimmedPickBoxValue); const inputUriDirname = resources.dirname(inputUri); let stat: IFileStat | undefined; let statDirname: IFileStat | undefined; try { statDirname = await this.remoteFileService.resolveFile(inputUriDirname); stat = await this.remoteFileService.resolveFile(inputUri); } catch (e) { // do nothing } // Find resolve value if (this.filePickBox.activeItems.length === 0) { if (!this.requiresTrailing && resources.isEqual(this.currentFolder, inputUri, true)) { resolveValue = inputUri; } else if (this.requiresTrailing && statDirname && statDirname.isDirectory) { resolveValue = inputUri; } else if (stat && stat.isDirectory) { navigateValue = inputUri; } } else if (this.filePickBox.activeItems.length === 1) { const item = this.filePickBox.selectedItems[0]; if (item) { if (!item.isFolder) { resolveValue = item.uri; } else { navigateValue = item.uri; } } } if (resolveValue) { if (await this.validate(resolveValue)) { return Promise.resolve(resolveValue); } } else if (navigateValue) { // Try to navigate into the folder this.updateItems(navigateValue); } else { // validation error. Path does not exist. } return Promise.resolve(undefined); } private async tryUpdateItems(value: string, valueUri: URI) { if (this.endsWithSlash(value) || (!resources.isEqual(this.currentFolder, resources.dirname(valueUri), true) && resources.isEqualOrParent(this.currentFolder, resources.dirname(valueUri), true))) { let stat: IFileStat | undefined; try { stat = await this.remoteFileService.resolveFile(valueUri); } catch (e) { // do nothing } if (stat && stat.isDirectory && (resources.basename(valueUri) !== '.')) { this.updateItems(valueUri); } else { const inputUriDirname = resources.dirname(valueUri); if (!resources.isEqual(this.currentFolder, inputUriDirname, true)) { let statWithoutTrailing: IFileStat | undefined; try { statWithoutTrailing = await this.remoteFileService.resolveFile(inputUriDirname); } catch (e) { // do nothing } if (statWithoutTrailing && statWithoutTrailing.isDirectory && (resources.basename(valueUri) !== '.')) { this.updateItems(inputUriDirname, resources.basename(valueUri)); } } } } } private setActiveItems(value: string) { if (!this.userValue || (value !== this.userValue.substring(0, value.length))) { const inputBasename = resources.basename(this.remoteUriFrom(value)); let hasMatch = false; for (let i = 0; i < this.filePickBox.items.length; i++) { const item = <FileQuickPickItem>this.filePickBox.items[i]; const itemBasename = resources.basename(item.uri); if ((itemBasename.length >= inputBasename.length) && (itemBasename.substr(0, inputBasename.length).toLowerCase() === inputBasename.toLowerCase())) { this.filePickBox.activeItems = [item]; this.filePickBox.value = this.filePickBox.value + itemBasename.substr(inputBasename.length); this.filePickBox.valueSelection = [value.length, this.filePickBox.value.length]; hasMatch = true; break; } } if (!hasMatch) { this.filePickBox.activeItems = []; } } } private async validate(uri: URI): Promise<boolean> { let stat: IFileStat | undefined; let statDirname: IFileStat | undefined; try { statDirname = await this.remoteFileService.resolveFile(resources.dirname(uri)); stat = await this.remoteFileService.resolveFile(uri); } catch (e) { // do nothing } if (this.requiresTrailing) { // save if (stat && stat.isDirectory) { // Can't do this return Promise.resolve(false); } else if (stat) { // This is replacing a file. Not supported yet. return Promise.resolve(false); } else if (!this.isValidBaseName(resources.basename(uri))) { // Filename not allowed return Promise.resolve(false); } else if (!statDirname || !statDirname.isDirectory) { // Folder to save in doesn't exist return Promise.resolve(false); } } else { // open if (!stat) { // File or folder doesn't exist return Promise.resolve(false); } else if (stat.isDirectory && !this.allowFolderSelection) { // Folder selected when folder selection not permitted return Promise.resolve(false); } else if (!stat.isDirectory && !this.allowFileSelection) { // File selected when file selection not permitted return Promise.resolve(false); } } return Promise.resolve(true); } private updateItems(newFolder: URI, trailing?: string) { this.currentFolder = newFolder; this.filePickBox.value = trailing ? this.pathFromUri(resources.joinPath(newFolder, trailing)) : this.pathFromUri(newFolder, true); this.filePickBox.busy = true; this.createItems(this.currentFolder).then(items => { this.filePickBox.items = items; if (this.allowFolderSelection) { this.filePickBox.activeItems = []; } this.filePickBox.busy = false; }); } private pathFromUri(uri: URI, endWithSeparator: boolean = false): string { const sep = this.labelService.getSeparator(uri.scheme, uri.authority); let result: string; if (sep === '/') { result = uri.fsPath.replace(/\\/g, sep); } else { result = uri.fsPath.replace(/\//g, sep); } if (endWithSeparator && !this.endsWithSlash(result)) { result = result + sep; } return result; } private isValidBaseName(name: string): boolean { if (!name || name.length === 0 || /^\s+$/.test(name)) { return false; // require a name that is not just whitespace } INVALID_FILE_CHARS.lastIndex = 0; // the holy grail of software development if (INVALID_FILE_CHARS.test(name)) { return false; // check for certain invalid file characters } if (isWindows && WINDOWS_FORBIDDEN_NAMES.test(name)) { return false; // check for certain invalid file names } if (name === '.' || name === '..') { return false; // check for reserved values } if (isWindows && name[name.length - 1] === '.') { return false; // Windows: file cannot end with a "." } if (isWindows && name.length !== name.trim().length) { return false; // Windows: file cannot end with a whitespace } return true; } private endsWithSlash(s: string) { return /[\/\\]$/.test(s); } private basenameWithTrailingSlash(fullPath: URI): string { const child = this.pathFromUri(fullPath, true); const parent = this.pathFromUri(resources.dirname(fullPath), true); return child.substring(parent.length); } private createBackItem(currFolder: URI): FileQuickPickItem | null { const parentFolder = resources.dirname(currFolder)!; if (!resources.isEqual(currFolder, parentFolder, true)) { return { label: '..', uri: resources.dirname(currFolder), isFolder: true }; } return null; } private async createItems(currentFolder: URI): Promise<FileQuickPickItem[]> { const result: FileQuickPickItem[] = []; const backDir = this.createBackItem(currentFolder); try { const fileNames = await this.remoteFileService.readFolder(currentFolder); const items = await Promise.all(fileNames.map(fileName => this.createItem(fileName, currentFolder))); for (let item of items) { if (item) { result.push(item); } } } catch (e) { // ignore console.log(e); } const sorted = result.sort((i1, i2) => { if (i1.isFolder !== i2.isFolder) { return i1.isFolder ? -1 : 1; } const trimmed1 = this.endsWithSlash(i1.label) ? i1.label.substr(0, i1.label.length - 1) : i1.label; const trimmed2 = this.endsWithSlash(i2.label) ? i2.label.substr(0, i2.label.length - 1) : i2.label; return trimmed1.localeCompare(trimmed2); }); if (backDir) { sorted.unshift(backDir); } return sorted; } private async createItem(filename: string, parent: URI): Promise<FileQuickPickItem | null> { let fullPath = resources.joinPath(parent, filename); try { const stat = await this.remoteFileService.resolveFile(fullPath); if (stat.isDirectory) { filename = this.basenameWithTrailingSlash(fullPath); return { label: filename, uri: fullPath, isFolder: true, iconClasses: getIconClasses(this.modelService, this.modeService, fullPath || undefined, FileKind.FOLDER) }; } else if (!stat.isDirectory && this.allowFileSelection) { return { label: filename, uri: fullPath, isFolder: false, iconClasses: getIconClasses(this.modelService, this.modeService, fullPath || undefined) }; } return null; } catch (e) { return null; } } private getDialogIcons(name: string): { light: URI, dark: URI } { return { dark: URI.parse(require.toUrl(`vs/workbench/services/dialogs/electron-browser/media/dark/${name}.svg`)), light: URI.parse(require.toUrl(`vs/workbench/services/dialogs/electron-browser/media/light/${name}.svg`)) }; } }
src/vs/workbench/services/dialogs/electron-browser/remoteFileDialog.ts
1
https://github.com/microsoft/vscode/commit/f07c7d705629bea1c6f5af42b7d3f7d72e225f2a
[ 0.9979109168052673, 0.03634565323591232, 0.00016415491700172424, 0.00017832043522503227, 0.17618168890476227 ]
{ "id": 11, "code_window": [ "\t\t\t\treturn Promise.resolve(false);\n", "\t\t\t} else if (!statDirname || !statDirname.isDirectory) {\n", "\t\t\t\t// Folder to save in doesn't exist\n", "\t\t\t\treturn Promise.resolve(false);\n", "\t\t\t}\n", "\t\t} else { // open\n", "\t\t\tif (!stat) {\n", "\t\t\t\t// File or folder doesn't exist\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\tthis.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateNonexistentDir', 'Please enter a path that exists.');\n" ], "file_path": "src/vs/workbench/services/dialogs/electron-browser/remoteFileDialog.ts", "type": "add", "edit_start_line_idx": 360 }
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="3 3 16 16" enable-background="new 3 3 16 16"><polygon fill="#424242" points="12.597,11.042 15.4,13.845 13.844,15.4 11.042,12.598 8.239,15.4 6.683,13.845 9.485,11.042 6.683,8.239 8.238,6.683 11.042,9.486 13.845,6.683 15.4,8.239"/></svg>
src/vs/workbench/contrib/files/browser/media/action-close.svg
0
https://github.com/microsoft/vscode/commit/f07c7d705629bea1c6f5af42b7d3f7d72e225f2a
[ 0.00017078839300666004, 0.00017078839300666004, 0.00017078839300666004, 0.00017078839300666004, 0 ]
{ "id": 11, "code_window": [ "\t\t\t\treturn Promise.resolve(false);\n", "\t\t\t} else if (!statDirname || !statDirname.isDirectory) {\n", "\t\t\t\t// Folder to save in doesn't exist\n", "\t\t\t\treturn Promise.resolve(false);\n", "\t\t\t}\n", "\t\t} else { // open\n", "\t\t\tif (!stat) {\n", "\t\t\t\t// File or folder doesn't exist\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\tthis.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateNonexistentDir', 'Please enter a path that exists.');\n" ], "file_path": "src/vs/workbench/services/dialogs/electron-browser/remoteFileDialog.ts", "type": "add", "edit_start_line_idx": 360 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { validateConstraint } from 'vs/base/common/types'; import { ICommandHandlerDescription } from 'vs/platform/commands/common/commands'; import * as extHostTypes from 'vs/workbench/api/node/extHostTypes'; import * as extHostTypeConverter from 'vs/workbench/api/node/extHostTypeConverters'; import { cloneAndChange } from 'vs/base/common/objects'; import { MainContext, MainThreadCommandsShape, ExtHostCommandsShape, ObjectIdentifier, IMainContext, CommandDto } from './extHost.protocol'; import { ExtHostHeapService } from 'vs/workbench/api/node/extHostHeapService'; import { isNonEmptyArray } from 'vs/base/common/arrays'; import * as modes from 'vs/editor/common/modes'; import * as vscode from 'vscode'; import { ILogService } from 'vs/platform/log/common/log'; import { revive } from 'vs/base/common/marshalling'; import { Range } from 'vs/editor/common/core/range'; import { Position } from 'vs/editor/common/core/position'; import { URI } from 'vs/base/common/uri'; interface CommandHandler { callback: Function; thisArg: any; description?: ICommandHandlerDescription; } export interface ArgumentProcessor { processArgument(arg: any): any; } export class ExtHostCommands implements ExtHostCommandsShape { private readonly _commands = new Map<string, CommandHandler>(); private readonly _proxy: MainThreadCommandsShape; private readonly _converter: CommandsConverter; private readonly _logService: ILogService; private readonly _argumentProcessors: ArgumentProcessor[]; constructor( mainContext: IMainContext, heapService: ExtHostHeapService, logService: ILogService ) { this._proxy = mainContext.getProxy(MainContext.MainThreadCommands); this._logService = logService; this._converter = new CommandsConverter(this, heapService); this._argumentProcessors = [ { processArgument(a) { // URI, Regex return revive(a, 0); } }, { processArgument(arg) { return cloneAndChange(arg, function (obj) { // Reverse of https://github.com/Microsoft/vscode/blob/1f28c5fc681f4c01226460b6d1c7e91b8acb4a5b/src/vs/workbench/api/node/extHostCommands.ts#L112-L127 if (Range.isIRange(obj)) { return extHostTypeConverter.Range.to(obj); } if (Position.isIPosition(obj)) { return extHostTypeConverter.Position.to(obj); } if (Range.isIRange((obj as modes.Location).range) && URI.isUri((obj as modes.Location).uri)) { return extHostTypeConverter.location.to(obj); } if (!Array.isArray(obj)) { return obj; } }); } } ]; } get converter(): CommandsConverter { return this._converter; } registerArgumentProcessor(processor: ArgumentProcessor): void { this._argumentProcessors.push(processor); } registerCommand(global: boolean, id: string, callback: <T>(...args: any[]) => T | Thenable<T>, thisArg?: any, description?: ICommandHandlerDescription): extHostTypes.Disposable { this._logService.trace('ExtHostCommands#registerCommand', id); if (!id.trim().length) { throw new Error('invalid id'); } if (this._commands.has(id)) { throw new Error(`command '${id}' already exists`); } this._commands.set(id, { callback, thisArg, description }); if (global) { this._proxy.$registerCommand(id); } return new extHostTypes.Disposable(() => { if (this._commands.delete(id)) { if (global) { this._proxy.$unregisterCommand(id); } } }); } executeCommand<T>(id: string, ...args: any[]): Promise<T> { this._logService.trace('ExtHostCommands#executeCommand', id); if (this._commands.has(id)) { // we stay inside the extension host and support // to pass any kind of parameters around return this._executeContributedCommand<T>(id, args); } else { // automagically convert some argument types args = cloneAndChange(args, function (value) { if (value instanceof extHostTypes.Position) { return extHostTypeConverter.Position.from(value); } if (value instanceof extHostTypes.Range) { return extHostTypeConverter.Range.from(value); } if (value instanceof extHostTypes.Location) { return extHostTypeConverter.location.from(value); } if (!Array.isArray(value)) { return value; } }); return this._proxy.$executeCommand<T>(id, args).then(result => revive(result, 0)); } } private _executeContributedCommand<T>(id: string, args: any[]): Promise<T> { const command = this._commands.get(id); if (!command) { throw new Error('Unknown command'); } let { callback, thisArg, description } = command; if (description) { for (let i = 0; i < description.args.length; i++) { try { validateConstraint(args[i], description.args[i].constraint); } catch (err) { return Promise.reject(new Error(`Running the contributed command:'${id}' failed. Illegal argument '${description.args[i].name}' - ${description.args[i].description}`)); } } } try { const result = callback.apply(thisArg, args); return Promise.resolve(result); } catch (err) { this._logService.error(err, id); return Promise.reject(new Error(`Running the contributed command:'${id}' failed.`)); } } $executeContributedCommand<T>(id: string, ...args: any[]): Promise<T> { this._logService.trace('ExtHostCommands#$executeContributedCommand', id); if (!this._commands.has(id)) { return Promise.reject(new Error(`Contributed command '${id}' does not exist.`)); } else { args = args.map(arg => this._argumentProcessors.reduce((r, p) => p.processArgument(r), arg)); return this._executeContributedCommand(id, args); } } getCommands(filterUnderscoreCommands: boolean = false): Promise<string[]> { this._logService.trace('ExtHostCommands#getCommands', filterUnderscoreCommands); return this._proxy.$getCommands().then(result => { if (filterUnderscoreCommands) { result = result.filter(command => command[0] !== '_'); } return result; }); } $getContributedCommandHandlerDescriptions(): Promise<{ [id: string]: string | ICommandHandlerDescription }> { const result: { [id: string]: string | ICommandHandlerDescription } = Object.create(null); this._commands.forEach((command, id) => { let { description } = command; if (description) { result[id] = description; } }); return Promise.resolve(result); } } export class CommandsConverter { private readonly _delegatingCommandId: string; private _commands: ExtHostCommands; private _heap: ExtHostHeapService; // --- conversion between internal and api commands constructor(commands: ExtHostCommands, heap: ExtHostHeapService) { this._delegatingCommandId = `_internal_command_delegation_${Date.now()}`; this._commands = commands; this._heap = heap; this._commands.registerCommand(true, this._delegatingCommandId, this._executeConvertedCommand, this); } toInternal(command: vscode.Command | undefined): CommandDto | undefined { if (!command) { return undefined; } const result: CommandDto = { $ident: undefined, id: command.command, title: command.title, }; if (command.command && isNonEmptyArray(command.arguments)) { // we have a contributed command with arguments. that // means we don't want to send the arguments around const id = this._heap.keep(command); result.$ident = id; result.id = this._delegatingCommandId; result.arguments = [id]; } if (command.tooltip) { result.tooltip = command.tooltip; } return result; } fromInternal(command: modes.Command | undefined): vscode.Command | undefined { if (!command) { return undefined; } const id = ObjectIdentifier.of(command); if (typeof id === 'number') { return this._heap.get<vscode.Command>(id); } else { return { command: command.id, title: command.title, arguments: command.arguments }; } } private _executeConvertedCommand<R>(...args: any[]): Promise<R> { const actualCmd = this._heap.get<vscode.Command>(args[0]); return this._commands.executeCommand(actualCmd.command, ...(actualCmd.arguments || [])); } }
src/vs/workbench/api/node/extHostCommands.ts
0
https://github.com/microsoft/vscode/commit/f07c7d705629bea1c6f5af42b7d3f7d72e225f2a
[ 0.00023585725284647197, 0.00017474980268161744, 0.00016431231051683426, 0.0001696409162832424, 0.000015877771147643216 ]
{ "id": 11, "code_window": [ "\t\t\t\treturn Promise.resolve(false);\n", "\t\t\t} else if (!statDirname || !statDirname.isDirectory) {\n", "\t\t\t\t// Folder to save in doesn't exist\n", "\t\t\t\treturn Promise.resolve(false);\n", "\t\t\t}\n", "\t\t} else { // open\n", "\t\t\tif (!stat) {\n", "\t\t\t\t// File or folder doesn't exist\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\tthis.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateNonexistentDir', 'Please enter a path that exists.');\n" ], "file_path": "src/vs/workbench/services/dialogs/electron-browser/remoteFileDialog.ts", "type": "add", "edit_start_line_idx": 360 }
/*--------------------------------------------------------------------------------------------- * 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 path from 'vs/base/common/path'; import { createWriteStream, WriteStream } from 'fs'; import { Readable } from 'stream'; import { nfcall, ninvoke, Sequencer, createCancelablePromise } from 'vs/base/common/async'; import { mkdirp, rimraf } from 'vs/base/node/pfs'; import { open as _openZip, Entry, ZipFile } from 'yauzl'; import * as yazl from 'yazl'; import { CancellationToken } from 'vs/base/common/cancellation'; import { Event } from 'vs/base/common/event'; export interface IExtractOptions { overwrite?: boolean; /** * Source path within the ZIP archive. Only the files contained in this * path will be extracted. */ sourcePath?: string; } interface IOptions { sourcePathRegex: RegExp; } export type ExtractErrorType = 'CorruptZip' | 'Incomplete'; export class ExtractError extends Error { readonly type?: ExtractErrorType; readonly cause: Error; constructor(type: ExtractErrorType | undefined, cause: Error) { let message = cause.message; switch (type) { case 'CorruptZip': message = `Corrupt ZIP: ${message}`; break; } super(message); this.type = type; this.cause = cause; } } function modeFromEntry(entry: Entry) { const attr = entry.externalFileAttributes >> 16 || 33188; return [448 /* S_IRWXU */, 56 /* S_IRWXG */, 7 /* S_IRWXO */] .map(mask => attr & mask) .reduce((a, b) => a + b, attr & 61440 /* S_IFMT */); } function toExtractError(err: Error): ExtractError { if (err instanceof ExtractError) { return err; } let type: ExtractErrorType | undefined = undefined; if (/end of central directory record signature not found/.test(err.message)) { type = 'CorruptZip'; } return new ExtractError(type, err); } function extractEntry(stream: Readable, fileName: string, mode: number, targetPath: string, options: IOptions, token: CancellationToken): Promise<void> { const dirName = path.dirname(fileName); const targetDirName = path.join(targetPath, dirName); if (targetDirName.indexOf(targetPath) !== 0) { return Promise.reject(new Error(nls.localize('invalid file', "Error extracting {0}. Invalid file.", fileName))); } const targetFileName = path.join(targetPath, fileName); let istream: WriteStream; Event.once(token.onCancellationRequested)(() => { if (istream) { istream.destroy(); } }); return Promise.resolve(mkdirp(targetDirName, undefined, token)).then(() => new Promise<void>((c, e) => { if (token.isCancellationRequested) { return; } try { istream = createWriteStream(targetFileName, { mode }); istream.once('close', () => c()); istream.once('error', e); stream.once('error', e); stream.pipe(istream); } catch (error) { e(error); } })); } function extractZip(zipfile: ZipFile, targetPath: string, options: IOptions, token: CancellationToken): Promise<void> { let last = createCancelablePromise<void>(() => Promise.resolve()); let extractedEntriesCount = 0; Event.once(token.onCancellationRequested)(() => { last.cancel(); zipfile.close(); }); return new Promise((c, e) => { const throttler = new Sequencer(); const readNextEntry = (token: CancellationToken) => { if (token.isCancellationRequested) { return; } extractedEntriesCount++; zipfile.readEntry(); }; zipfile.once('error', e); zipfile.once('close', () => last.then(() => { if (token.isCancellationRequested || zipfile.entryCount === extractedEntriesCount) { c(); } else { e(new ExtractError('Incomplete', new Error(nls.localize('incompleteExtract', "Incomplete. Found {0} of {1} entries", extractedEntriesCount, zipfile.entryCount)))); } }, e)); zipfile.readEntry(); zipfile.on('entry', (entry: Entry) => { if (token.isCancellationRequested) { return; } if (!options.sourcePathRegex.test(entry.fileName)) { readNextEntry(token); return; } const fileName = entry.fileName.replace(options.sourcePathRegex, ''); // directory file names end with '/' if (/\/$/.test(fileName)) { const targetFileName = path.join(targetPath, fileName); last = createCancelablePromise(token => mkdirp(targetFileName, undefined, token).then(() => readNextEntry(token)).then(undefined, e)); return; } const stream = ninvoke(zipfile, zipfile.openReadStream, entry); const mode = modeFromEntry(entry); last = createCancelablePromise(token => throttler.queue(() => stream.then(stream => extractEntry(stream, fileName, mode, targetPath, options, token).then(() => readNextEntry(token)))).then(null!, e)); }); }); } function openZip(zipFile: string, lazy: boolean = false): Promise<ZipFile> { return nfcall<ZipFile>(_openZip, zipFile, lazy ? { lazyEntries: true } : undefined) .then(undefined, err => Promise.reject(toExtractError(err))); } export interface IFile { path: string; contents?: Buffer | string; localPath?: string; } export function zip(zipPath: string, files: IFile[]): Promise<string> { return new Promise<string>((c, e) => { const zip = new yazl.ZipFile(); files.forEach(f => { if (f.contents) { zip.addBuffer(typeof f.contents === 'string' ? Buffer.from(f.contents, 'utf8') : f.contents, f.path); } else if (f.localPath) { zip.addFile(f.localPath, f.path); } }); zip.end(); const zipStream = createWriteStream(zipPath); zip.outputStream.pipe(zipStream); zip.outputStream.once('error', e); zipStream.once('error', e); zipStream.once('finish', () => c(zipPath)); }); } export function extract(zipPath: string, targetPath: string, options: IExtractOptions = {}, token: CancellationToken): Promise<void> { const sourcePathRegex = new RegExp(options.sourcePath ? `^${options.sourcePath}` : ''); let promise = openZip(zipPath, true); if (options.overwrite) { promise = promise.then(zipfile => rimraf(targetPath).then(() => zipfile)); } return promise.then(zipfile => extractZip(zipfile, targetPath, { sourcePathRegex }, token)); } function read(zipPath: string, filePath: string): Promise<Readable> { return openZip(zipPath).then(zipfile => { return new Promise<Readable>((c, e) => { zipfile.on('entry', (entry: Entry) => { if (entry.fileName === filePath) { ninvoke<Readable>(zipfile, zipfile.openReadStream, entry).then(stream => c(stream), err => e(err)); } }); zipfile.once('close', () => e(new Error(nls.localize('notFound', "{0} not found inside zip.", filePath)))); }); }); } export function buffer(zipPath: string, filePath: string): Promise<Buffer> { return read(zipPath, filePath).then(stream => { return new Promise<Buffer>((c, e) => { const buffers: Buffer[] = []; stream.once('error', e); stream.on('data', b => buffers.push(b as Buffer)); stream.on('end', () => c(Buffer.concat(buffers))); }); }); }
src/vs/base/node/zip.ts
0
https://github.com/microsoft/vscode/commit/f07c7d705629bea1c6f5af42b7d3f7d72e225f2a
[ 0.0034875799901783466, 0.00031869180384092033, 0.00016471357957925647, 0.00017121339624281973, 0.0006620772765018046 ]
{ "id": 12, "code_window": [ "\t\t\t\treturn Promise.resolve(false);\n", "\t\t\t}\n", "\t\t} else { // open\n", "\t\t\tif (!stat) {\n", "\t\t\t\t// File or folder doesn't exist\n", "\t\t\t\treturn Promise.resolve(false);\n", "\t\t\t} else if (stat.isDirectory && !this.allowFolderSelection) {\n", "\t\t\t\t// Folder selected when folder selection not permitted\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\tthis.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateNonexistentDir', 'Please enter a path that exists.');\n" ], "file_path": "src/vs/workbench/services/dialogs/electron-browser/remoteFileDialog.ts", "type": "add", "edit_start_line_idx": 365 }
/*--------------------------------------------------------------------------------------------- * 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 resources from 'vs/base/common/resources'; import * as objects from 'vs/base/common/objects'; import { RemoteFileService } from 'vs/workbench/services/files/node/remoteFileService'; import { IFileService, IFileStat, FileKind } from 'vs/platform/files/common/files'; import { IQuickInputService, IQuickPickItem, IQuickPick } from 'vs/platform/quickinput/common/quickInput'; import { URI } from 'vs/base/common/uri'; import { isWindows } from 'vs/base/common/platform'; import { ISaveDialogOptions, IOpenDialogOptions, IFileDialogService } from 'vs/platform/dialogs/common/dialogs'; import { REMOTE_HOST_SCHEME } from 'vs/platform/remote/common/remoteHosts'; import { IWindowService, IURIToOpen } from 'vs/platform/windows/common/windows'; import { ILabelService } from 'vs/platform/label/common/label'; import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace'; import { INotificationService } from 'vs/platform/notification/common/notification'; import { IModelService } from 'vs/editor/common/services/modelService'; import { IModeService } from 'vs/editor/common/services/modeService'; import { getIconClasses } from 'vs/editor/common/services/getIconClasses'; import { Schemas } from 'vs/base/common/network'; interface FileQuickPickItem extends IQuickPickItem { uri: URI; isFolder: boolean; } // Reference: https://en.wikipedia.org/wiki/Filename const INVALID_FILE_CHARS = isWindows ? /[\\/:\*\?"<>\|]/g : /[\\/]/g; const WINDOWS_FORBIDDEN_NAMES = /^(con|prn|aux|clock\$|nul|lpt[0-9]|com[0-9])$/i; export class RemoteFileDialog { private fallbackPickerButton; private acceptButton; private currentFolder: URI; private filePickBox: IQuickPick<FileQuickPickItem>; private allowFileSelection: boolean; private allowFolderSelection: boolean; private remoteAuthority: string | undefined; private requiresTrailing: boolean; private userValue: string; private scheme: string = REMOTE_HOST_SCHEME; constructor( @IFileService private readonly remoteFileService: RemoteFileService, @IQuickInputService private readonly quickInputService: IQuickInputService, @IWindowService private readonly windowService: IWindowService, @ILabelService private readonly labelService: ILabelService, @IWorkspaceContextService private readonly workspaceContextService: IWorkspaceContextService, @INotificationService private readonly notificationService: INotificationService, @IFileDialogService private readonly fileDialogService: IFileDialogService, @IModelService private readonly modelService: IModelService, @IModeService private readonly modeService: IModeService, ) { this.remoteAuthority = this.windowService.getConfiguration().remoteAuthority; } public async showOpenDialog(options: IOpenDialogOptions = {}): Promise<IURIToOpen[] | undefined> { this.setScheme(options.defaultUri, options.availableFileSystems); const newOptions = this.getOptions(options); if (!newOptions) { return Promise.resolve(undefined); } const openFileString = nls.localize('remoteFileDialog.localFileFallback', 'Open Local File'); const openFolderString = nls.localize('remoteFileDialog.localFolderFallback', 'Open Local Folder'); const openFileFolderString = nls.localize('remoteFileDialog.localFileFolderFallback', 'Open Local File or Folder'); let tooltip = options.canSelectFiles ? (options.canSelectFolders ? openFileFolderString : openFileString) : openFolderString; this.fallbackPickerButton = { iconPath: this.getDialogIcons('folder'), tooltip }; return this.pickResource(newOptions).then(async fileFolderUri => { if (fileFolderUri) { const stat = await this.remoteFileService.resolveFile(fileFolderUri); return <IURIToOpen[]>[{ uri: fileFolderUri, typeHint: stat.isDirectory ? 'folder' : 'file' }]; } return Promise.resolve(undefined); }); } public showSaveDialog(options: ISaveDialogOptions): Promise<URI | undefined> { this.setScheme(options.defaultUri, options.availableFileSystems); this.requiresTrailing = true; const newOptions = this.getOptions(options); if (!newOptions) { return Promise.resolve(undefined); } this.fallbackPickerButton = { iconPath: this.getDialogIcons('folder'), tooltip: nls.localize('remoteFileDialog.localSaveFallback', 'Save Local File') }; newOptions.canSelectFolders = true; newOptions.canSelectFiles = true; return new Promise<URI | undefined>((resolve) => { this.pickResource(newOptions, true).then(folderUri => { resolve(folderUri); }); }); } private getOptions(options: ISaveDialogOptions | IOpenDialogOptions): IOpenDialogOptions | undefined { const defaultUri = options.defaultUri ? options.defaultUri : URI.from({ scheme: this.scheme, authority: this.remoteAuthority, path: '/' }); if ((this.scheme !== Schemas.file) && !this.remoteFileService.canHandleResource(defaultUri)) { this.notificationService.info(nls.localize('remoteFileDialog.notConnectedToRemote', 'File system provider for {0} is not available.', defaultUri.toString())); return undefined; } const newOptions: IOpenDialogOptions = objects.deepClone(options); newOptions.defaultUri = defaultUri; return newOptions; } private remoteUriFrom(path: string): URI { path = path.replace(/\\/g, '/'); return URI.from({ scheme: this.scheme, authority: this.remoteAuthority, path }); } private setScheme(defaultUri: URI | undefined, available: string[] | undefined) { this.scheme = defaultUri ? defaultUri.scheme : (available ? available[0] : Schemas.file); } private async pickResource(options: IOpenDialogOptions, isSave: boolean = false): Promise<URI | undefined> { this.allowFolderSelection = !!options.canSelectFolders; this.allowFileSelection = !!options.canSelectFiles; let homedir: URI = options.defaultUri ? options.defaultUri : this.workspaceContextService.getWorkspace().folders[0].uri; let trailing: string | undefined; let stat: IFileStat | undefined; let ext: string = resources.extname(homedir); if (options.defaultUri) { try { stat = await this.remoteFileService.resolveFile(options.defaultUri); } catch (e) { // The file or folder doesn't exist } if (!stat || !stat.isDirectory) { homedir = resources.dirname(options.defaultUri); trailing = resources.basename(options.defaultUri); } // append extension if (isSave && !ext && options.filters) { for (let i = 0; i < options.filters.length; i++) { if (options.filters[i].extensions[0] !== '*') { ext = '.' + options.filters[i].extensions[0]; trailing = trailing ? trailing + ext : ext; break; } } } } this.acceptButton = { iconPath: this.getDialogIcons('accept'), tooltip: options.title }; return new Promise<URI | undefined>((resolve) => { this.filePickBox = this.quickInputService.createQuickPick<FileQuickPickItem>(); this.filePickBox.matchOnLabel = false; this.filePickBox.autoFocusOnList = false; let isResolved = false; let isAcceptHandled = false; this.currentFolder = homedir; if (options.availableFileSystems && options.availableFileSystems.length > 1) { this.filePickBox.buttons = [this.fallbackPickerButton, this.acceptButton]; } else { this.filePickBox.buttons = [this.acceptButton]; } this.filePickBox.onDidTriggerButton(button => { if (button === this.fallbackPickerButton) { if (options.availableFileSystems) { options.availableFileSystems.shift(); } isResolved = true; if (this.requiresTrailing) { this.fileDialogService.showSaveDialog(options).then(result => { this.filePickBox.hide(); resolve(result); }); } else { this.fileDialogService.showOpenDialog(options).then(result => { this.filePickBox.hide(); resolve(result ? result[0] : undefined); }); } this.filePickBox.hide(); } else { // accept button const resolveValue = this.remoteUriFrom(this.filePickBox.value); this.validate(resolveValue).then(validated => { if (validated) { isResolved = true; this.filePickBox.hide(); resolve(resolveValue); } }); } }); this.filePickBox.title = options.title; this.filePickBox.value = this.pathFromUri(this.currentFolder); this.filePickBox.items = []; this.filePickBox.onDidAccept(_ => { if (isAcceptHandled || this.filePickBox.busy) { return; } isAcceptHandled = true; this.onDidAccept().then(resolveValue => { if (resolveValue) { isResolved = true; this.filePickBox.hide(); resolve(resolveValue); } }); }); this.filePickBox.onDidChangeActive(i => { isAcceptHandled = false; }); this.filePickBox.onDidChangeValue(async value => { if (value !== this.userValue) { const trimmedPickBoxValue = ((this.filePickBox.value.length > 1) && this.endsWithSlash(this.filePickBox.value)) ? this.filePickBox.value.substr(0, this.filePickBox.value.length - 1) : this.filePickBox.value; const valueUri = this.remoteUriFrom(trimmedPickBoxValue); if (!resources.isEqual(this.currentFolder, valueUri, true)) { await this.tryUpdateItems(value, valueUri); } this.setActiveItems(value); this.userValue = value; } else { this.filePickBox.activeItems = []; } }); this.filePickBox.onDidHide(() => { if (!isResolved) { resolve(undefined); } this.filePickBox.dispose(); }); this.filePickBox.show(); this.updateItems(homedir, trailing); if (trailing) { this.filePickBox.valueSelection = [this.filePickBox.value.length - trailing.length, this.filePickBox.value.length - ext.length]; } this.userValue = this.filePickBox.value; }); } private async onDidAccept(): Promise<URI | undefined> { let resolveValue: URI | undefined; let navigateValue: URI | undefined; const trimmedPickBoxValue = ((this.filePickBox.value.length > 1) && this.endsWithSlash(this.filePickBox.value)) ? this.filePickBox.value.substr(0, this.filePickBox.value.length - 1) : this.filePickBox.value; const inputUri = this.remoteUriFrom(trimmedPickBoxValue); const inputUriDirname = resources.dirname(inputUri); let stat: IFileStat | undefined; let statDirname: IFileStat | undefined; try { statDirname = await this.remoteFileService.resolveFile(inputUriDirname); stat = await this.remoteFileService.resolveFile(inputUri); } catch (e) { // do nothing } // Find resolve value if (this.filePickBox.activeItems.length === 0) { if (!this.requiresTrailing && resources.isEqual(this.currentFolder, inputUri, true)) { resolveValue = inputUri; } else if (this.requiresTrailing && statDirname && statDirname.isDirectory) { resolveValue = inputUri; } else if (stat && stat.isDirectory) { navigateValue = inputUri; } } else if (this.filePickBox.activeItems.length === 1) { const item = this.filePickBox.selectedItems[0]; if (item) { if (!item.isFolder) { resolveValue = item.uri; } else { navigateValue = item.uri; } } } if (resolveValue) { if (await this.validate(resolveValue)) { return Promise.resolve(resolveValue); } } else if (navigateValue) { // Try to navigate into the folder this.updateItems(navigateValue); } else { // validation error. Path does not exist. } return Promise.resolve(undefined); } private async tryUpdateItems(value: string, valueUri: URI) { if (this.endsWithSlash(value) || (!resources.isEqual(this.currentFolder, resources.dirname(valueUri), true) && resources.isEqualOrParent(this.currentFolder, resources.dirname(valueUri), true))) { let stat: IFileStat | undefined; try { stat = await this.remoteFileService.resolveFile(valueUri); } catch (e) { // do nothing } if (stat && stat.isDirectory && (resources.basename(valueUri) !== '.')) { this.updateItems(valueUri); } else { const inputUriDirname = resources.dirname(valueUri); if (!resources.isEqual(this.currentFolder, inputUriDirname, true)) { let statWithoutTrailing: IFileStat | undefined; try { statWithoutTrailing = await this.remoteFileService.resolveFile(inputUriDirname); } catch (e) { // do nothing } if (statWithoutTrailing && statWithoutTrailing.isDirectory && (resources.basename(valueUri) !== '.')) { this.updateItems(inputUriDirname, resources.basename(valueUri)); } } } } } private setActiveItems(value: string) { if (!this.userValue || (value !== this.userValue.substring(0, value.length))) { const inputBasename = resources.basename(this.remoteUriFrom(value)); let hasMatch = false; for (let i = 0; i < this.filePickBox.items.length; i++) { const item = <FileQuickPickItem>this.filePickBox.items[i]; const itemBasename = resources.basename(item.uri); if ((itemBasename.length >= inputBasename.length) && (itemBasename.substr(0, inputBasename.length).toLowerCase() === inputBasename.toLowerCase())) { this.filePickBox.activeItems = [item]; this.filePickBox.value = this.filePickBox.value + itemBasename.substr(inputBasename.length); this.filePickBox.valueSelection = [value.length, this.filePickBox.value.length]; hasMatch = true; break; } } if (!hasMatch) { this.filePickBox.activeItems = []; } } } private async validate(uri: URI): Promise<boolean> { let stat: IFileStat | undefined; let statDirname: IFileStat | undefined; try { statDirname = await this.remoteFileService.resolveFile(resources.dirname(uri)); stat = await this.remoteFileService.resolveFile(uri); } catch (e) { // do nothing } if (this.requiresTrailing) { // save if (stat && stat.isDirectory) { // Can't do this return Promise.resolve(false); } else if (stat) { // This is replacing a file. Not supported yet. return Promise.resolve(false); } else if (!this.isValidBaseName(resources.basename(uri))) { // Filename not allowed return Promise.resolve(false); } else if (!statDirname || !statDirname.isDirectory) { // Folder to save in doesn't exist return Promise.resolve(false); } } else { // open if (!stat) { // File or folder doesn't exist return Promise.resolve(false); } else if (stat.isDirectory && !this.allowFolderSelection) { // Folder selected when folder selection not permitted return Promise.resolve(false); } else if (!stat.isDirectory && !this.allowFileSelection) { // File selected when file selection not permitted return Promise.resolve(false); } } return Promise.resolve(true); } private updateItems(newFolder: URI, trailing?: string) { this.currentFolder = newFolder; this.filePickBox.value = trailing ? this.pathFromUri(resources.joinPath(newFolder, trailing)) : this.pathFromUri(newFolder, true); this.filePickBox.busy = true; this.createItems(this.currentFolder).then(items => { this.filePickBox.items = items; if (this.allowFolderSelection) { this.filePickBox.activeItems = []; } this.filePickBox.busy = false; }); } private pathFromUri(uri: URI, endWithSeparator: boolean = false): string { const sep = this.labelService.getSeparator(uri.scheme, uri.authority); let result: string; if (sep === '/') { result = uri.fsPath.replace(/\\/g, sep); } else { result = uri.fsPath.replace(/\//g, sep); } if (endWithSeparator && !this.endsWithSlash(result)) { result = result + sep; } return result; } private isValidBaseName(name: string): boolean { if (!name || name.length === 0 || /^\s+$/.test(name)) { return false; // require a name that is not just whitespace } INVALID_FILE_CHARS.lastIndex = 0; // the holy grail of software development if (INVALID_FILE_CHARS.test(name)) { return false; // check for certain invalid file characters } if (isWindows && WINDOWS_FORBIDDEN_NAMES.test(name)) { return false; // check for certain invalid file names } if (name === '.' || name === '..') { return false; // check for reserved values } if (isWindows && name[name.length - 1] === '.') { return false; // Windows: file cannot end with a "." } if (isWindows && name.length !== name.trim().length) { return false; // Windows: file cannot end with a whitespace } return true; } private endsWithSlash(s: string) { return /[\/\\]$/.test(s); } private basenameWithTrailingSlash(fullPath: URI): string { const child = this.pathFromUri(fullPath, true); const parent = this.pathFromUri(resources.dirname(fullPath), true); return child.substring(parent.length); } private createBackItem(currFolder: URI): FileQuickPickItem | null { const parentFolder = resources.dirname(currFolder)!; if (!resources.isEqual(currFolder, parentFolder, true)) { return { label: '..', uri: resources.dirname(currFolder), isFolder: true }; } return null; } private async createItems(currentFolder: URI): Promise<FileQuickPickItem[]> { const result: FileQuickPickItem[] = []; const backDir = this.createBackItem(currentFolder); try { const fileNames = await this.remoteFileService.readFolder(currentFolder); const items = await Promise.all(fileNames.map(fileName => this.createItem(fileName, currentFolder))); for (let item of items) { if (item) { result.push(item); } } } catch (e) { // ignore console.log(e); } const sorted = result.sort((i1, i2) => { if (i1.isFolder !== i2.isFolder) { return i1.isFolder ? -1 : 1; } const trimmed1 = this.endsWithSlash(i1.label) ? i1.label.substr(0, i1.label.length - 1) : i1.label; const trimmed2 = this.endsWithSlash(i2.label) ? i2.label.substr(0, i2.label.length - 1) : i2.label; return trimmed1.localeCompare(trimmed2); }); if (backDir) { sorted.unshift(backDir); } return sorted; } private async createItem(filename: string, parent: URI): Promise<FileQuickPickItem | null> { let fullPath = resources.joinPath(parent, filename); try { const stat = await this.remoteFileService.resolveFile(fullPath); if (stat.isDirectory) { filename = this.basenameWithTrailingSlash(fullPath); return { label: filename, uri: fullPath, isFolder: true, iconClasses: getIconClasses(this.modelService, this.modeService, fullPath || undefined, FileKind.FOLDER) }; } else if (!stat.isDirectory && this.allowFileSelection) { return { label: filename, uri: fullPath, isFolder: false, iconClasses: getIconClasses(this.modelService, this.modeService, fullPath || undefined) }; } return null; } catch (e) { return null; } } private getDialogIcons(name: string): { light: URI, dark: URI } { return { dark: URI.parse(require.toUrl(`vs/workbench/services/dialogs/electron-browser/media/dark/${name}.svg`)), light: URI.parse(require.toUrl(`vs/workbench/services/dialogs/electron-browser/media/light/${name}.svg`)) }; } }
src/vs/workbench/services/dialogs/electron-browser/remoteFileDialog.ts
1
https://github.com/microsoft/vscode/commit/f07c7d705629bea1c6f5af42b7d3f7d72e225f2a
[ 0.99847012758255, 0.02432188391685486, 0.00016408089140895754, 0.00017982537974603474, 0.13951173424720764 ]
{ "id": 12, "code_window": [ "\t\t\t\treturn Promise.resolve(false);\n", "\t\t\t}\n", "\t\t} else { // open\n", "\t\t\tif (!stat) {\n", "\t\t\t\t// File or folder doesn't exist\n", "\t\t\t\treturn Promise.resolve(false);\n", "\t\t\t} else if (stat.isDirectory && !this.allowFolderSelection) {\n", "\t\t\t\t// Folder selected when folder selection not permitted\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\tthis.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateNonexistentDir', 'Please enter a path that exists.');\n" ], "file_path": "src/vs/workbench/services/dialogs/electron-browser/remoteFileDialog.ts", "type": "add", "edit_start_line_idx": 365 }
[ { "c": "<?", "t": "text.xml meta.tag.preprocessor.xml punctuation.definition.tag.xml", "r": { "dark_plus": "punctuation.definition.tag: #808080", "light_plus": "punctuation.definition.tag: #800000", "dark_vs": "punctuation.definition.tag: #808080", "light_vs": "punctuation.definition.tag: #800000", "hc_black": "punctuation.definition.tag: #808080" } }, { "c": "xml", "t": "text.xml meta.tag.preprocessor.xml entity.name.tag.xml", "r": { "dark_plus": "entity.name.tag: #569CD6", "light_plus": "entity.name.tag: #800000", "dark_vs": "entity.name.tag: #569CD6", "light_vs": "entity.name.tag: #800000", "hc_black": "entity.name.tag: #569CD6" } }, { "c": " version", "t": "text.xml meta.tag.preprocessor.xml entity.other.attribute-name.xml", "r": { "dark_plus": "entity.other.attribute-name: #9CDCFE", "light_plus": "entity.other.attribute-name: #FF0000", "dark_vs": "entity.other.attribute-name: #9CDCFE", "light_vs": "entity.other.attribute-name: #FF0000", "hc_black": "entity.other.attribute-name: #9CDCFE" } }, { "c": "=", "t": "text.xml meta.tag.preprocessor.xml", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "\"", "t": "text.xml meta.tag.preprocessor.xml string.quoted.double.xml punctuation.definition.string.begin.xml", "r": { "dark_plus": "string: #CE9178", "light_plus": "string.quoted.double.xml: #0000FF", "dark_vs": "string: #CE9178", "light_vs": "string.quoted.double.xml: #0000FF", "hc_black": "string: #CE9178" } }, { "c": "1.0", "t": "text.xml meta.tag.preprocessor.xml string.quoted.double.xml", "r": { "dark_plus": "string: #CE9178", "light_plus": "string.quoted.double.xml: #0000FF", "dark_vs": "string: #CE9178", "light_vs": "string.quoted.double.xml: #0000FF", "hc_black": "string: #CE9178" } }, { "c": "\"", "t": "text.xml meta.tag.preprocessor.xml string.quoted.double.xml punctuation.definition.string.end.xml", "r": { "dark_plus": "string: #CE9178", "light_plus": "string.quoted.double.xml: #0000FF", "dark_vs": "string: #CE9178", "light_vs": "string.quoted.double.xml: #0000FF", "hc_black": "string: #CE9178" } }, { "c": " encoding", "t": "text.xml meta.tag.preprocessor.xml entity.other.attribute-name.xml", "r": { "dark_plus": "entity.other.attribute-name: #9CDCFE", "light_plus": "entity.other.attribute-name: #FF0000", "dark_vs": "entity.other.attribute-name: #9CDCFE", "light_vs": "entity.other.attribute-name: #FF0000", "hc_black": "entity.other.attribute-name: #9CDCFE" } }, { "c": "=", "t": "text.xml meta.tag.preprocessor.xml", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "\"", "t": "text.xml meta.tag.preprocessor.xml string.quoted.double.xml punctuation.definition.string.begin.xml", "r": { "dark_plus": "string: #CE9178", "light_plus": "string.quoted.double.xml: #0000FF", "dark_vs": "string: #CE9178", "light_vs": "string.quoted.double.xml: #0000FF", "hc_black": "string: #CE9178" } }, { "c": "utf-8", "t": "text.xml meta.tag.preprocessor.xml string.quoted.double.xml", "r": { "dark_plus": "string: #CE9178", "light_plus": "string.quoted.double.xml: #0000FF", "dark_vs": "string: #CE9178", "light_vs": "string.quoted.double.xml: #0000FF", "hc_black": "string: #CE9178" } }, { "c": "\"", "t": "text.xml meta.tag.preprocessor.xml string.quoted.double.xml punctuation.definition.string.end.xml", "r": { "dark_plus": "string: #CE9178", "light_plus": "string.quoted.double.xml: #0000FF", "dark_vs": "string: #CE9178", "light_vs": "string.quoted.double.xml: #0000FF", "hc_black": "string: #CE9178" } }, { "c": " standalone", "t": "text.xml meta.tag.preprocessor.xml entity.other.attribute-name.xml", "r": { "dark_plus": "entity.other.attribute-name: #9CDCFE", "light_plus": "entity.other.attribute-name: #FF0000", "dark_vs": "entity.other.attribute-name: #9CDCFE", "light_vs": "entity.other.attribute-name: #FF0000", "hc_black": "entity.other.attribute-name: #9CDCFE" } }, { "c": "=", "t": "text.xml meta.tag.preprocessor.xml", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "\"", "t": "text.xml meta.tag.preprocessor.xml string.quoted.double.xml punctuation.definition.string.begin.xml", "r": { "dark_plus": "string: #CE9178", "light_plus": "string.quoted.double.xml: #0000FF", "dark_vs": "string: #CE9178", "light_vs": "string.quoted.double.xml: #0000FF", "hc_black": "string: #CE9178" } }, { "c": "no", "t": "text.xml meta.tag.preprocessor.xml string.quoted.double.xml", "r": { "dark_plus": "string: #CE9178", "light_plus": "string.quoted.double.xml: #0000FF", "dark_vs": "string: #CE9178", "light_vs": "string.quoted.double.xml: #0000FF", "hc_black": "string: #CE9178" } }, { "c": "\"", "t": "text.xml meta.tag.preprocessor.xml string.quoted.double.xml punctuation.definition.string.end.xml", "r": { "dark_plus": "string: #CE9178", "light_plus": "string.quoted.double.xml: #0000FF", "dark_vs": "string: #CE9178", "light_vs": "string.quoted.double.xml: #0000FF", "hc_black": "string: #CE9178" } }, { "c": " ", "t": "text.xml meta.tag.preprocessor.xml", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "?>", "t": "text.xml meta.tag.preprocessor.xml punctuation.definition.tag.xml", "r": { "dark_plus": "punctuation.definition.tag: #808080", "light_plus": "punctuation.definition.tag: #800000", "dark_vs": "punctuation.definition.tag: #808080", "light_vs": "punctuation.definition.tag: #800000", "hc_black": "punctuation.definition.tag: #808080" } }, { "c": "<", "t": "text.xml meta.tag.xml punctuation.definition.tag.xml", "r": { "dark_plus": "punctuation.definition.tag: #808080", "light_plus": "punctuation.definition.tag: #800000", "dark_vs": "punctuation.definition.tag: #808080", "light_vs": "punctuation.definition.tag: #800000", "hc_black": "punctuation.definition.tag: #808080" } }, { "c": "WorkFine", "t": "text.xml meta.tag.xml entity.name.tag.localname.xml", "r": { "dark_plus": "entity.name.tag: #569CD6", "light_plus": "entity.name.tag: #800000", "dark_vs": "entity.name.tag: #569CD6", "light_vs": "entity.name.tag: #800000", "hc_black": "entity.name.tag: #569CD6" } }, { "c": ">", "t": "text.xml meta.tag.xml punctuation.definition.tag.xml", "r": { "dark_plus": "punctuation.definition.tag: #808080", "light_plus": "punctuation.definition.tag: #800000", "dark_vs": "punctuation.definition.tag: #808080", "light_vs": "punctuation.definition.tag: #800000", "hc_black": "punctuation.definition.tag: #808080" } }, { "c": " ", "t": "text.xml", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "<", "t": "text.xml meta.tag.xml punctuation.definition.tag.xml", "r": { "dark_plus": "punctuation.definition.tag: #808080", "light_plus": "punctuation.definition.tag: #800000", "dark_vs": "punctuation.definition.tag: #808080", "light_vs": "punctuation.definition.tag: #800000", "hc_black": "punctuation.definition.tag: #808080" } }, { "c": "NoColorWithNonLatinCharacters_АБВ", "t": "text.xml meta.tag.xml entity.name.tag.localname.xml", "r": { "dark_plus": "entity.name.tag: #569CD6", "light_plus": "entity.name.tag: #800000", "dark_vs": "entity.name.tag: #569CD6", "light_vs": "entity.name.tag: #800000", "hc_black": "entity.name.tag: #569CD6" } }, { "c": " ", "t": "text.xml meta.tag.xml", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "NextTagnotWork", "t": "text.xml meta.tag.xml entity.other.attribute-name.localname.xml", "r": { "dark_plus": "entity.other.attribute-name: #9CDCFE", "light_plus": "entity.other.attribute-name: #FF0000", "dark_vs": "entity.other.attribute-name: #9CDCFE", "light_vs": "entity.other.attribute-name: #FF0000", "hc_black": "entity.other.attribute-name: #9CDCFE" } }, { "c": "=", "t": "text.xml meta.tag.xml", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "\"", "t": "text.xml meta.tag.xml string.quoted.double.xml punctuation.definition.string.begin.xml", "r": { "dark_plus": "string: #CE9178", "light_plus": "string.quoted.double.xml: #0000FF", "dark_vs": "string: #CE9178", "light_vs": "string.quoted.double.xml: #0000FF", "hc_black": "string: #CE9178" } }, { "c": "something", "t": "text.xml meta.tag.xml string.quoted.double.xml", "r": { "dark_plus": "string: #CE9178", "light_plus": "string.quoted.double.xml: #0000FF", "dark_vs": "string: #CE9178", "light_vs": "string.quoted.double.xml: #0000FF", "hc_black": "string: #CE9178" } }, { "c": "\"", "t": "text.xml meta.tag.xml string.quoted.double.xml punctuation.definition.string.end.xml", "r": { "dark_plus": "string: #CE9178", "light_plus": "string.quoted.double.xml: #0000FF", "dark_vs": "string: #CE9178", "light_vs": "string.quoted.double.xml: #0000FF", "hc_black": "string: #CE9178" } }, { "c": " ", "t": "text.xml meta.tag.xml", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "Поле", "t": "text.xml meta.tag.xml entity.other.attribute-name.localname.xml", "r": { "dark_plus": "entity.other.attribute-name: #9CDCFE", "light_plus": "entity.other.attribute-name: #FF0000", "dark_vs": "entity.other.attribute-name: #9CDCFE", "light_vs": "entity.other.attribute-name: #FF0000", "hc_black": "entity.other.attribute-name: #9CDCFE" } }, { "c": "=", "t": "text.xml meta.tag.xml", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "\"", "t": "text.xml meta.tag.xml string.quoted.double.xml punctuation.definition.string.begin.xml", "r": { "dark_plus": "string: #CE9178", "light_plus": "string.quoted.double.xml: #0000FF", "dark_vs": "string: #CE9178", "light_vs": "string.quoted.double.xml: #0000FF", "hc_black": "string: #CE9178" } }, { "c": "tagnotwork", "t": "text.xml meta.tag.xml string.quoted.double.xml", "r": { "dark_plus": "string: #CE9178", "light_plus": "string.quoted.double.xml: #0000FF", "dark_vs": "string: #CE9178", "light_vs": "string.quoted.double.xml: #0000FF", "hc_black": "string: #CE9178" } }, { "c": "\"", "t": "text.xml meta.tag.xml string.quoted.double.xml punctuation.definition.string.end.xml", "r": { "dark_plus": "string: #CE9178", "light_plus": "string.quoted.double.xml: #0000FF", "dark_vs": "string: #CE9178", "light_vs": "string.quoted.double.xml: #0000FF", "hc_black": "string: #CE9178" } }, { "c": ">", "t": "text.xml meta.tag.xml punctuation.definition.tag.xml", "r": { "dark_plus": "punctuation.definition.tag: #808080", "light_plus": "punctuation.definition.tag: #800000", "dark_vs": "punctuation.definition.tag: #808080", "light_vs": "punctuation.definition.tag: #800000", "hc_black": "punctuation.definition.tag: #808080" } }, { "c": " ", "t": "text.xml", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "<", "t": "text.xml meta.tag.xml punctuation.definition.tag.xml", "r": { "dark_plus": "punctuation.definition.tag: #808080", "light_plus": "punctuation.definition.tag: #800000", "dark_vs": "punctuation.definition.tag: #808080", "light_vs": "punctuation.definition.tag: #800000", "hc_black": "punctuation.definition.tag: #808080" } }, { "c": "WorkFine", "t": "text.xml meta.tag.xml entity.name.tag.localname.xml", "r": { "dark_plus": "entity.name.tag: #569CD6", "light_plus": "entity.name.tag: #800000", "dark_vs": "entity.name.tag: #569CD6", "light_vs": "entity.name.tag: #800000", "hc_black": "entity.name.tag: #569CD6" } }, { "c": "/>", "t": "text.xml meta.tag.xml punctuation.definition.tag.xml", "r": { "dark_plus": "punctuation.definition.tag: #808080", "light_plus": "punctuation.definition.tag: #800000", "dark_vs": "punctuation.definition.tag: #808080", "light_vs": "punctuation.definition.tag: #800000", "hc_black": "punctuation.definition.tag: #808080" } }, { "c": " ", "t": "text.xml", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "<", "t": "text.xml meta.tag.xml punctuation.definition.tag.xml", "r": { "dark_plus": "punctuation.definition.tag: #808080", "light_plus": "punctuation.definition.tag: #800000", "dark_vs": "punctuation.definition.tag: #808080", "light_vs": "punctuation.definition.tag: #800000", "hc_black": "punctuation.definition.tag: #808080" } }, { "c": "Error_АБВГД", "t": "text.xml meta.tag.xml entity.name.tag.localname.xml", "r": { "dark_plus": "entity.name.tag: #569CD6", "light_plus": "entity.name.tag: #800000", "dark_vs": "entity.name.tag: #569CD6", "light_vs": "entity.name.tag: #800000", "hc_black": "entity.name.tag: #569CD6" } }, { "c": "/>", "t": "text.xml meta.tag.xml punctuation.definition.tag.xml", "r": { "dark_plus": "punctuation.definition.tag: #808080", "light_plus": "punctuation.definition.tag: #800000", "dark_vs": "punctuation.definition.tag: #808080", "light_vs": "punctuation.definition.tag: #800000", "hc_black": "punctuation.definition.tag: #808080" } }, { "c": " ", "t": "text.xml", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "</", "t": "text.xml meta.tag.xml punctuation.definition.tag.xml", "r": { "dark_plus": "punctuation.definition.tag: #808080", "light_plus": "punctuation.definition.tag: #800000", "dark_vs": "punctuation.definition.tag: #808080", "light_vs": "punctuation.definition.tag: #800000", "hc_black": "punctuation.definition.tag: #808080" } }, { "c": "NoColorWithNonLatinCharacters_АБВ", "t": "text.xml meta.tag.xml entity.name.tag.localname.xml", "r": { "dark_plus": "entity.name.tag: #569CD6", "light_plus": "entity.name.tag: #800000", "dark_vs": "entity.name.tag: #569CD6", "light_vs": "entity.name.tag: #800000", "hc_black": "entity.name.tag: #569CD6" } }, { "c": ">", "t": "text.xml meta.tag.xml punctuation.definition.tag.xml", "r": { "dark_plus": "punctuation.definition.tag: #808080", "light_plus": "punctuation.definition.tag: #800000", "dark_vs": "punctuation.definition.tag: #808080", "light_vs": "punctuation.definition.tag: #800000", "hc_black": "punctuation.definition.tag: #808080" } }, { "c": "</", "t": "text.xml meta.tag.xml punctuation.definition.tag.xml", "r": { "dark_plus": "punctuation.definition.tag: #808080", "light_plus": "punctuation.definition.tag: #800000", "dark_vs": "punctuation.definition.tag: #808080", "light_vs": "punctuation.definition.tag: #800000", "hc_black": "punctuation.definition.tag: #808080" } }, { "c": "WorkFine", "t": "text.xml meta.tag.xml entity.name.tag.localname.xml", "r": { "dark_plus": "entity.name.tag: #569CD6", "light_plus": "entity.name.tag: #800000", "dark_vs": "entity.name.tag: #569CD6", "light_vs": "entity.name.tag: #800000", "hc_black": "entity.name.tag: #569CD6" } }, { "c": ">", "t": "text.xml meta.tag.xml punctuation.definition.tag.xml", "r": { "dark_plus": "punctuation.definition.tag: #808080", "light_plus": "punctuation.definition.tag: #800000", "dark_vs": "punctuation.definition.tag: #808080", "light_vs": "punctuation.definition.tag: #800000", "hc_black": "punctuation.definition.tag: #808080" } } ]
extensions/xml/test/colorize-results/test-7115_xml.json
0
https://github.com/microsoft/vscode/commit/f07c7d705629bea1c6f5af42b7d3f7d72e225f2a
[ 0.00017677109281066805, 0.00017433940956834704, 0.0001719961001072079, 0.0001743149769026786, 0.000001005513013296877 ]
{ "id": 12, "code_window": [ "\t\t\t\treturn Promise.resolve(false);\n", "\t\t\t}\n", "\t\t} else { // open\n", "\t\t\tif (!stat) {\n", "\t\t\t\t// File or folder doesn't exist\n", "\t\t\t\treturn Promise.resolve(false);\n", "\t\t\t} else if (stat.isDirectory && !this.allowFolderSelection) {\n", "\t\t\t\t// Folder selected when folder selection not permitted\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\tthis.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateNonexistentDir', 'Please enter a path that exists.');\n" ], "file_path": "src/vs/workbench/services/dialogs/electron-browser/remoteFileDialog.ts", "type": "add", "edit_start_line_idx": 365 }
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><defs><style>.icon-canvas-transparent,.icon-vs-out{fill:#f6f6f6;}.icon-canvas-transparent{opacity:0;}.icon-vs-bg{fill:#424242;}</style></defs><title>add</title><g id="canvas"><path class="icon-canvas-transparent" d="M16,16H0V0H16Z"/></g><g id="outline" style="display: none;"><path class="icon-vs-out" d="M14,6v4H10v4H6V10H2V6H6V2h4V6Z"/></g><g id="iconBg"><path class="icon-vs-bg" d="M13,7V9H9v4H7V9H3V7H7V3H9V7Z"/></g></svg>
src/vs/workbench/contrib/debug/browser/media/add.svg
0
https://github.com/microsoft/vscode/commit/f07c7d705629bea1c6f5af42b7d3f7d72e225f2a
[ 0.00017427476996090263, 0.00017427476996090263, 0.00017427476996090263, 0.00017427476996090263, 0 ]
{ "id": 12, "code_window": [ "\t\t\t\treturn Promise.resolve(false);\n", "\t\t\t}\n", "\t\t} else { // open\n", "\t\t\tif (!stat) {\n", "\t\t\t\t// File or folder doesn't exist\n", "\t\t\t\treturn Promise.resolve(false);\n", "\t\t\t} else if (stat.isDirectory && !this.allowFolderSelection) {\n", "\t\t\t\t// Folder selected when folder selection not permitted\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\tthis.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateNonexistentDir', 'Please enter a path that exists.');\n" ], "file_path": "src/vs/workbench/services/dialogs/electron-browser/remoteFileDialog.ts", "type": "add", "edit_start_line_idx": 365 }
build/** cgmanifest.json
extensions/theme-seti/.vscodeignore
0
https://github.com/microsoft/vscode/commit/f07c7d705629bea1c6f5af42b7d3f7d72e225f2a
[ 0.00017419250798411667, 0.00017419250798411667, 0.00017419250798411667, 0.00017419250798411667, 0 ]
{ "id": 13, "code_window": [ "\t\t\t\treturn Promise.resolve(false);\n", "\t\t\t} else if (stat.isDirectory && !this.allowFolderSelection) {\n", "\t\t\t\t// Folder selected when folder selection not permitted\n", "\t\t\t\treturn Promise.resolve(false);\n", "\t\t\t} else if (!stat.isDirectory && !this.allowFileSelection) {\n", "\t\t\t\t// File selected when file selection not permitted\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\tthis.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateFileOnly', 'Please select a file.');\n" ], "file_path": "src/vs/workbench/services/dialogs/electron-browser/remoteFileDialog.ts", "type": "add", "edit_start_line_idx": 368 }
/*--------------------------------------------------------------------------------------------- * 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!./quickInput'; import { Component } from 'vs/workbench/common/component'; import { IQuickInputService, IQuickPickItem, IPickOptions, IInputOptions, IQuickNavigateConfiguration, IQuickPick, IQuickInput, IQuickInputButton, IInputBox, IQuickPickItemButtonEvent, QuickPickInput, IQuickPickSeparator, IKeyMods } from 'vs/platform/quickinput/common/quickInput'; import { IWorkbenchLayoutService } from 'vs/workbench/services/layout/browser/layoutService'; import * as dom from 'vs/base/browser/dom'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IThemeService } from 'vs/platform/theme/common/themeService'; import { contrastBorder, widgetShadow } from 'vs/platform/theme/common/colorRegistry'; import { SIDE_BAR_BACKGROUND, SIDE_BAR_FOREGROUND } from 'vs/workbench/common/theme'; import { IQuickOpenService } from 'vs/platform/quickOpen/common/quickOpen'; import { CancellationToken } from 'vs/base/common/cancellation'; import { QuickInputList } from './quickInputList'; import { QuickInputBox } from './quickInputBox'; import { KeyCode } from 'vs/base/common/keyCodes'; import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent'; import { localize } from 'vs/nls'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { CLOSE_ON_FOCUS_LOST_CONFIG } from 'vs/workbench/browser/quickopen'; import { CountBadge } from 'vs/base/browser/ui/countBadge/countBadge'; import { attachBadgeStyler, attachProgressBarStyler, attachButtonStyler } from 'vs/platform/theme/common/styler'; import { IEnvironmentService } from 'vs/platform/environment/common/environment'; import { ProgressBar } from 'vs/base/browser/ui/progressbar/progressbar'; import { Emitter, Event } from 'vs/base/common/event'; import { Button } from 'vs/base/browser/ui/button/button'; import { dispose, IDisposable } from 'vs/base/common/lifecycle'; import Severity from 'vs/base/common/severity'; import { IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService'; import { IContextKeyService, RawContextKey, IContextKey } from 'vs/platform/contextkey/common/contextkey'; import { ICommandAndKeybindingRule, KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry'; import { inQuickOpenContext, InQuickOpenContextKey } from 'vs/workbench/browser/parts/quickopen/quickopen'; import { ActionBar, ActionItem } from 'vs/base/browser/ui/actionbar/actionbar'; import { Action } from 'vs/base/common/actions'; import { URI } from 'vs/base/common/uri'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; import { equals } from 'vs/base/common/arrays'; import { TimeoutTimer } from 'vs/base/common/async'; import { getIconClass } from 'vs/workbench/browser/parts/quickinput/quickInputUtils'; import { IEditorOptions } from 'vs/editor/common/config/editorOptions'; import { IStorageService } from 'vs/platform/storage/common/storage'; import { IAccessibilityService, AccessibilitySupport } from 'vs/platform/accessibility/common/accessibility'; import { registerSingleton } from 'vs/platform/instantiation/common/extensions'; const $ = dom.$; type Writeable<T> = { -readonly [P in keyof T]: T[P] }; const backButton = { iconPath: { dark: URI.parse(require.toUrl('vs/workbench/browser/parts/quickinput/media/dark/arrow-left.svg')), light: URI.parse(require.toUrl('vs/workbench/browser/parts/quickinput/media/light/arrow-left.svg')) }, tooltip: localize('quickInput.back', "Back"), handle: -1 // TODO }; interface QuickInputUI { container: HTMLElement; leftActionBar: ActionBar; title: HTMLElement; rightActionBar: ActionBar; checkAll: HTMLInputElement; inputBox: QuickInputBox; visibleCount: CountBadge; count: CountBadge; message: HTMLElement; progressBar: ProgressBar; list: QuickInputList; onDidAccept: Event<void>; onDidTriggerButton: Event<IQuickInputButton>; ignoreFocusOut: boolean; keyMods: Writeable<IKeyMods>; isScreenReaderOptimized(): boolean; show(controller: QuickInput): void; setVisibilities(visibilities: Visibilities): void; setComboboxAccessibility(enabled: boolean): void; setEnabled(enabled: boolean): void; setContextKey(contextKey?: string): void; hide(): void; } type Visibilities = { title?: boolean; checkAll?: boolean; inputBox?: boolean; visibleCount?: boolean; count?: boolean; message?: boolean; list?: boolean; ok?: boolean; }; class QuickInput implements IQuickInput { private _title: string; private _steps: number; private _totalSteps: number; protected visible = false; private _enabled = true; private _contextKey: string; private _busy = false; private _ignoreFocusOut = false; private _buttons: IQuickInputButton[] = []; private buttonsUpdated = false; private onDidTriggerButtonEmitter = new Emitter<IQuickInputButton>(); private onDidHideEmitter = new Emitter<void>(); protected visibleDisposables: IDisposable[] = []; protected disposables: IDisposable[] = [ this.onDidTriggerButtonEmitter, this.onDidHideEmitter, ]; private busyDelay: TimeoutTimer | null; constructor(protected ui: QuickInputUI) { } get title() { return this._title; } set title(title: string) { this._title = title; this.update(); } get step() { return this._steps; } set step(step: number) { this._steps = step; this.update(); } get totalSteps() { return this._totalSteps; } set totalSteps(totalSteps: number) { this._totalSteps = totalSteps; this.update(); } get enabled() { return this._enabled; } set enabled(enabled: boolean) { this._enabled = enabled; this.update(); } get contextKey() { return this._contextKey; } set contextKey(contextKey: string) { this._contextKey = contextKey; this.update(); } get busy() { return this._busy; } set busy(busy: boolean) { this._busy = busy; this.update(); } get ignoreFocusOut() { return this._ignoreFocusOut; } set ignoreFocusOut(ignoreFocusOut: boolean) { this._ignoreFocusOut = ignoreFocusOut; this.update(); } get buttons() { return this._buttons; } set buttons(buttons: IQuickInputButton[]) { this._buttons = buttons; this.buttonsUpdated = true; this.update(); } onDidTriggerButton = this.onDidTriggerButtonEmitter.event; show(): void { if (this.visible) { return; } this.visibleDisposables.push( this.ui.onDidTriggerButton(button => { if (this.buttons.indexOf(button) !== -1) { this.onDidTriggerButtonEmitter.fire(button); } }), ); this.ui.show(this); this.visible = true; this.update(); } hide(): void { if (!this.visible) { return; } this.ui.hide(); } didHide(): void { this.visible = false; this.visibleDisposables = dispose(this.visibleDisposables); this.onDidHideEmitter.fire(); } onDidHide = this.onDidHideEmitter.event; protected update() { if (!this.visible) { return; } const title = this.getTitle(); if (this.ui.title.textContent !== title) { this.ui.title.textContent = title; } if (this.busy && !this.busyDelay) { this.busyDelay = new TimeoutTimer(); this.busyDelay.setIfNotSet(() => { if (this.visible) { this.ui.progressBar.infinite(); } }, 800); } if (!this.busy && this.busyDelay) { this.ui.progressBar.stop(); this.busyDelay.cancel(); this.busyDelay = null; } if (this.buttonsUpdated) { this.buttonsUpdated = false; this.ui.leftActionBar.clear(); const leftButtons = this.buttons.filter(button => button === backButton); this.ui.leftActionBar.push(leftButtons.map((button, index) => { const action = new Action(`id-${index}`, '', button.iconClass || getIconClass(button.iconPath!), true, () => { this.onDidTriggerButtonEmitter.fire(button); return Promise.resolve(null); }); action.tooltip = button.tooltip || ''; return action; }), { icon: true, label: false }); this.ui.rightActionBar.clear(); const rightButtons = this.buttons.filter(button => button !== backButton); this.ui.rightActionBar.push(rightButtons.map((button, index) => { const action = new Action(`id-${index}`, '', button.iconClass || getIconClass(button.iconPath!), true, () => { this.onDidTriggerButtonEmitter.fire(button); return Promise.resolve(null); }); action.tooltip = button.tooltip || ''; return action; }), { icon: true, label: false }); } this.ui.ignoreFocusOut = this.ignoreFocusOut; this.ui.setEnabled(this.enabled); this.ui.setContextKey(this.contextKey); } private getTitle() { if (this.title && this.step) { return `${this.title} (${this.getSteps()})`; } if (this.title) { return this.title; } if (this.step) { return this.getSteps(); } return ''; } private getSteps() { if (this.step && this.totalSteps) { return localize('quickInput.steps', "{0}/{1}", this.step, this.totalSteps); } if (this.step) { return String(this.step); } return ''; } public dispose(): void { this.hide(); this.disposables = dispose(this.disposables); } } class QuickPick<T extends IQuickPickItem> extends QuickInput implements IQuickPick<T> { private static INPUT_BOX_ARIA_LABEL = localize('quickInputBox.ariaLabel', "Type to narrow down results."); private _value = ''; private _placeholder; private onDidChangeValueEmitter = new Emitter<string>(); private onDidAcceptEmitter = new Emitter<void>(); private _items: Array<T | IQuickPickSeparator> = []; private itemsUpdated = false; private _canSelectMany = false; private _matchOnDescription = false; private _matchOnDetail = false; private _matchOnLabel = true; private _autoFocusOnList = true; private _activeItems: T[] = []; private activeItemsUpdated = false; private activeItemsToConfirm: T[] | null = []; private onDidChangeActiveEmitter = new Emitter<T[]>(); private _selectedItems: T[] = []; private selectedItemsUpdated = false; private selectedItemsToConfirm: T[] | null = []; private onDidChangeSelectionEmitter = new Emitter<T[]>(); private onDidTriggerItemButtonEmitter = new Emitter<IQuickPickItemButtonEvent<T>>(); private _valueSelection: Readonly<[number, number]>; private valueSelectionUpdated = true; quickNavigate: IQuickNavigateConfiguration; constructor(ui: QuickInputUI) { super(ui); this.disposables.push( this.onDidChangeValueEmitter, this.onDidAcceptEmitter, this.onDidChangeActiveEmitter, this.onDidChangeSelectionEmitter, this.onDidTriggerItemButtonEmitter, ); } get value() { return this._value; } set value(value: string) { this._value = value || ''; this.update(); } get placeholder() { return this._placeholder; } set placeholder(placeholder: string) { this._placeholder = placeholder; this.update(); } onDidChangeValue = this.onDidChangeValueEmitter.event; onDidAccept = this.onDidAcceptEmitter.event; get items() { return this._items; } set items(items: Array<T | IQuickPickSeparator>) { this._items = items; this.itemsUpdated = true; this.update(); } get canSelectMany() { return this._canSelectMany; } set canSelectMany(canSelectMany: boolean) { this._canSelectMany = canSelectMany; this.update(); } get matchOnDescription() { return this._matchOnDescription; } set matchOnDescription(matchOnDescription: boolean) { this._matchOnDescription = matchOnDescription; this.update(); } get matchOnDetail() { return this._matchOnDetail; } set matchOnDetail(matchOnDetail: boolean) { this._matchOnDetail = matchOnDetail; this.update(); } get matchOnLabel() { return this._matchOnLabel; } set matchOnLabel(matchOnLabel: boolean) { this._matchOnLabel = matchOnLabel; this.update(); } get autoFocusOnList() { return this._autoFocusOnList; } set autoFocusOnList(autoFocusOnList: boolean) { this._autoFocusOnList = autoFocusOnList; this.update(); } get activeItems() { return this._activeItems; } set activeItems(activeItems: T[]) { this._activeItems = activeItems; this.activeItemsUpdated = true; this.update(); } onDidChangeActive = this.onDidChangeActiveEmitter.event; get selectedItems() { return this._selectedItems; } set selectedItems(selectedItems: T[]) { this._selectedItems = selectedItems; this.selectedItemsUpdated = true; this.update(); } get keyMods() { return this.ui.keyMods; } set valueSelection(valueSelection: Readonly<[number, number]>) { this._valueSelection = valueSelection; this.valueSelectionUpdated = true; this.update(); } onDidChangeSelection = this.onDidChangeSelectionEmitter.event; onDidTriggerItemButton = this.onDidTriggerItemButtonEmitter.event; private trySelectFirst() { if (this.autoFocusOnList) { if (!this.ui.isScreenReaderOptimized() && !this.canSelectMany) { this.ui.list.focus('First'); } } } show() { if (!this.visible) { this.visibleDisposables.push( this.ui.inputBox.onDidChange(value => { if (value === this.value) { return; } this._value = value; this.ui.list.filter(this.ui.inputBox.value); this.trySelectFirst(); this.onDidChangeValueEmitter.fire(value); }), this.ui.inputBox.onMouseDown(event => { if (!this.autoFocusOnList) { this.ui.list.clearFocus(); } }), this.ui.inputBox.onKeyDown(event => { switch (event.keyCode) { case KeyCode.DownArrow: this.ui.list.focus('Next'); if (this.canSelectMany) { this.ui.list.domFocus(); } break; case KeyCode.UpArrow: if (this.ui.list.getFocusedElements().length) { this.ui.list.focus('Previous'); } else { this.ui.list.focus('Last'); } if (this.canSelectMany) { this.ui.list.domFocus(); } break; case KeyCode.PageDown: if (this.ui.list.getFocusedElements().length) { this.ui.list.focus('NextPage'); } else { this.ui.list.focus('First'); } if (this.canSelectMany) { this.ui.list.domFocus(); } break; case KeyCode.PageUp: if (this.ui.list.getFocusedElements().length) { this.ui.list.focus('PreviousPage'); } else { this.ui.list.focus('Last'); } if (this.canSelectMany) { this.ui.list.domFocus(); } break; } }), this.ui.onDidAccept(() => { if (!this.canSelectMany && this.activeItems[0]) { this._selectedItems = [this.activeItems[0]]; this.onDidChangeSelectionEmitter.fire(this.selectedItems); } this.onDidAcceptEmitter.fire(undefined); }), this.ui.list.onDidChangeFocus(focusedItems => { if (this.activeItemsUpdated) { return; // Expect another event. } if (this.activeItemsToConfirm !== this._activeItems && equals(focusedItems, this._activeItems, (a, b) => a === b)) { return; } this._activeItems = focusedItems as T[]; this.onDidChangeActiveEmitter.fire(focusedItems as T[]); }), this.ui.list.onDidChangeSelection(selectedItems => { if (this.canSelectMany) { if (selectedItems.length) { this.ui.list.setSelectedElements([]); } return; } if (this.selectedItemsToConfirm !== this._selectedItems && equals(selectedItems, this._selectedItems, (a, b) => a === b)) { return; } this._selectedItems = selectedItems as T[]; this.onDidChangeSelectionEmitter.fire(selectedItems as T[]); if (selectedItems.length) { this.onDidAcceptEmitter.fire(undefined); } }), this.ui.list.onChangedCheckedElements(checkedItems => { if (!this.canSelectMany) { return; } if (this.selectedItemsToConfirm !== this._selectedItems && equals(checkedItems, this._selectedItems, (a, b) => a === b)) { return; } this._selectedItems = checkedItems as T[]; this.onDidChangeSelectionEmitter.fire(checkedItems as T[]); }), this.ui.list.onButtonTriggered(event => this.onDidTriggerItemButtonEmitter.fire(event as IQuickPickItemButtonEvent<T>)), this.registerQuickNavigation() ); this.valueSelectionUpdated = true; } super.show(); // TODO: Why have show() bubble up while update() trickles down? (Could move setComboboxAccessibility() here.) } private registerQuickNavigation() { return dom.addDisposableListener(this.ui.container, dom.EventType.KEY_UP, e => { if (this.canSelectMany || !this.quickNavigate) { return; } const keyboardEvent: StandardKeyboardEvent = new StandardKeyboardEvent(e); const keyCode = keyboardEvent.keyCode; // Select element when keys are pressed that signal it const quickNavKeys = this.quickNavigate.keybindings; const wasTriggerKeyPressed = keyCode === KeyCode.Enter || quickNavKeys.some(k => { const [firstPart, chordPart] = k.getParts(); if (chordPart) { return false; } if (firstPart.shiftKey && keyCode === KeyCode.Shift) { if (keyboardEvent.ctrlKey || keyboardEvent.altKey || keyboardEvent.metaKey) { return false; // this is an optimistic check for the shift key being used to navigate back in quick open } return true; } if (firstPart.altKey && keyCode === KeyCode.Alt) { return true; } if (firstPart.ctrlKey && keyCode === KeyCode.Ctrl) { return true; } if (firstPart.metaKey && keyCode === KeyCode.Meta) { return true; } return false; }); if (wasTriggerKeyPressed && this.activeItems[0]) { this._selectedItems = [this.activeItems[0]]; this.onDidChangeSelectionEmitter.fire(this.selectedItems); this.onDidAcceptEmitter.fire(undefined); } }); } protected update() { super.update(); if (!this.visible) { return; } if (this.ui.inputBox.value !== this.value) { this.ui.inputBox.value = this.value; } if (this.valueSelectionUpdated) { this.valueSelectionUpdated = false; this.ui.inputBox.select(this._valueSelection && { start: this._valueSelection[0], end: this._valueSelection[1] }); } if (this.ui.inputBox.placeholder !== (this.placeholder || '')) { this.ui.inputBox.placeholder = (this.placeholder || ''); } if (this.itemsUpdated) { this.itemsUpdated = false; this.ui.list.setElements(this.items); this.ui.list.filter(this.ui.inputBox.value); this.ui.checkAll.checked = this.ui.list.getAllVisibleChecked(); this.ui.visibleCount.setCount(this.ui.list.getVisibleCount()); this.ui.count.setCount(this.ui.list.getCheckedCount()); this.trySelectFirst(); } if (this.ui.container.classList.contains('show-checkboxes') !== !!this.canSelectMany) { if (this.canSelectMany) { this.ui.list.clearFocus(); } else { this.trySelectFirst(); } } if (this.activeItemsUpdated) { this.activeItemsUpdated = false; this.activeItemsToConfirm = this._activeItems; this.ui.list.setFocusedElements(this.activeItems); if (this.activeItemsToConfirm === this._activeItems) { this.activeItemsToConfirm = null; } } if (this.selectedItemsUpdated) { this.selectedItemsUpdated = false; this.selectedItemsToConfirm = this._selectedItems; if (this.canSelectMany) { this.ui.list.setCheckedElements(this.selectedItems); } else { this.ui.list.setSelectedElements(this.selectedItems); } if (this.selectedItemsToConfirm === this._selectedItems) { this.selectedItemsToConfirm = null; } } this.ui.list.matchOnDescription = this.matchOnDescription; this.ui.list.matchOnDetail = this.matchOnDetail; this.ui.list.matchOnLabel = this.matchOnLabel; this.ui.setComboboxAccessibility(true); this.ui.inputBox.setAttribute('aria-label', QuickPick.INPUT_BOX_ARIA_LABEL); this.ui.setVisibilities(this.canSelectMany ? { title: !!this.title || !!this.step, checkAll: true, inputBox: true, visibleCount: true, count: true, ok: true, list: true } : { title: !!this.title || !!this.step, inputBox: true, visibleCount: true, list: true }); } } class InputBox extends QuickInput implements IInputBox { private static noPromptMessage = localize('inputModeEntry', "Press 'Enter' to confirm your input or 'Escape' to cancel"); private _value = ''; private _valueSelection: Readonly<[number, number]>; private valueSelectionUpdated = true; private _placeholder: string; private _password = false; private _prompt: string; private noValidationMessage = InputBox.noPromptMessage; private _validationMessage: string; private onDidValueChangeEmitter = new Emitter<string>(); private onDidAcceptEmitter = new Emitter<void>(); constructor(ui: QuickInputUI) { super(ui); this.disposables.push( this.onDidValueChangeEmitter, this.onDidAcceptEmitter, ); } get value() { return this._value; } set value(value: string) { this._value = value || ''; this.update(); } set valueSelection(valueSelection: Readonly<[number, number]>) { this._valueSelection = valueSelection; this.valueSelectionUpdated = true; this.update(); } get placeholder() { return this._placeholder; } set placeholder(placeholder: string) { this._placeholder = placeholder; this.update(); } get password() { return this._password; } set password(password: boolean) { this._password = password; this.update(); } get prompt() { return this._prompt; } set prompt(prompt: string) { this._prompt = prompt; this.noValidationMessage = prompt ? localize('inputModeEntryDescription', "{0} (Press 'Enter' to confirm or 'Escape' to cancel)", prompt) : InputBox.noPromptMessage; this.update(); } get validationMessage() { return this._validationMessage; } set validationMessage(validationMessage: string) { this._validationMessage = validationMessage; this.update(); } onDidChangeValue = this.onDidValueChangeEmitter.event; onDidAccept = this.onDidAcceptEmitter.event; show() { if (!this.visible) { this.visibleDisposables.push( this.ui.inputBox.onDidChange(value => { if (value === this.value) { return; } this._value = value; this.onDidValueChangeEmitter.fire(value); }), this.ui.onDidAccept(() => this.onDidAcceptEmitter.fire(undefined)), ); this.valueSelectionUpdated = true; } super.show(); } protected update() { super.update(); if (!this.visible) { return; } if (this.ui.inputBox.value !== this.value) { this.ui.inputBox.value = this.value; } if (this.valueSelectionUpdated) { this.valueSelectionUpdated = false; this.ui.inputBox.select(this._valueSelection && { start: this._valueSelection[0], end: this._valueSelection[1] }); } if (this.ui.inputBox.placeholder !== (this.placeholder || '')) { this.ui.inputBox.placeholder = (this.placeholder || ''); } if (this.ui.inputBox.password !== this.password) { this.ui.inputBox.password = this.password; } if (!this.validationMessage && this.ui.message.textContent !== this.noValidationMessage) { this.ui.message.textContent = this.noValidationMessage; this.ui.inputBox.showDecoration(Severity.Ignore); } if (this.validationMessage && this.ui.message.textContent !== this.validationMessage) { this.ui.message.textContent = this.validationMessage; this.ui.inputBox.showDecoration(Severity.Error); } this.ui.setVisibilities({ title: !!this.title || !!this.step, inputBox: true, message: true }); } } export class QuickInputService extends Component implements IQuickInputService { public _serviceBrand: any; private static readonly ID = 'workbench.component.quickinput'; private static readonly MAX_WIDTH = 600; // Max total width of quick open widget private idPrefix = 'quickInput_'; // Constant since there is still only one. private titleBar: HTMLElement; private filterContainer: HTMLElement; private visibleCountContainer: HTMLElement; private countContainer: HTMLElement; private okContainer: HTMLElement; private ok: Button; private ui: QuickInputUI; private comboboxAccessibility = false; private enabled = true; private inQuickOpenWidgets: Record<string, boolean> = {}; private inQuickOpenContext: IContextKey<boolean>; private contexts: { [id: string]: IContextKey<boolean>; } = Object.create(null); private onDidAcceptEmitter = this._register(new Emitter<void>()); private onDidTriggerButtonEmitter = this._register(new Emitter<IQuickInputButton>()); private keyMods: Writeable<IKeyMods> = { ctrlCmd: false, alt: false }; private controller: QuickInput | null = null; constructor( @IEnvironmentService private readonly environmentService: IEnvironmentService, @IConfigurationService private readonly configurationService: IConfigurationService, @IInstantiationService private readonly instantiationService: IInstantiationService, @IQuickOpenService private readonly quickOpenService: IQuickOpenService, @IEditorGroupsService private readonly editorGroupService: IEditorGroupsService, @IKeybindingService private readonly keybindingService: IKeybindingService, @IContextKeyService private readonly contextKeyService: IContextKeyService, @IThemeService themeService: IThemeService, @IStorageService storageService: IStorageService, @IAccessibilityService private readonly accessibilityService: IAccessibilityService, @IWorkbenchLayoutService private readonly layoutService: IWorkbenchLayoutService ) { super(QuickInputService.ID, themeService, storageService); this.inQuickOpenContext = InQuickOpenContextKey.bindTo(contextKeyService); this._register(this.quickOpenService.onShow(() => this.inQuickOpen('quickOpen', true))); this._register(this.quickOpenService.onHide(() => this.inQuickOpen('quickOpen', false))); this._register(this.layoutService.onLayout(dimension => this.layout(dimension))); this.registerKeyModsListeners(); } private inQuickOpen(widget: 'quickInput' | 'quickOpen', open: boolean) { if (open) { this.inQuickOpenWidgets[widget] = true; } else { delete this.inQuickOpenWidgets[widget]; } if (Object.keys(this.inQuickOpenWidgets).length) { if (!this.inQuickOpenContext.get()) { this.inQuickOpenContext.set(true); } } else { if (this.inQuickOpenContext.get()) { this.inQuickOpenContext.reset(); } } } private setContextKey(id?: string) { let key: IContextKey<boolean> | undefined; if (id) { key = this.contexts[id]; if (!key) { key = new RawContextKey<boolean>(id, false) .bindTo(this.contextKeyService); this.contexts[id] = key; } } if (key && key.get()) { return; // already active context } this.resetContextKeys(); if (key) { key.set(true); } } private resetContextKeys() { for (const key in this.contexts) { if (this.contexts[key].get()) { this.contexts[key].reset(); } } } private registerKeyModsListeners() { const workbench = this.layoutService.getWorkbenchElement(); this._register(dom.addDisposableListener(workbench, dom.EventType.KEY_DOWN, (e: KeyboardEvent) => { const event = new StandardKeyboardEvent(e); switch (event.keyCode) { case KeyCode.Ctrl: case KeyCode.Meta: this.keyMods.ctrlCmd = true; break; case KeyCode.Alt: this.keyMods.alt = true; break; } })); this._register(dom.addDisposableListener(workbench, dom.EventType.KEY_UP, (e: KeyboardEvent) => { const event = new StandardKeyboardEvent(e); switch (event.keyCode) { case KeyCode.Ctrl: case KeyCode.Meta: this.keyMods.ctrlCmd = false; break; case KeyCode.Alt: this.keyMods.alt = false; break; } })); } private create() { if (this.ui) { return; } const workbench = this.layoutService.getWorkbenchElement(); const container = dom.append(workbench, $('.quick-input-widget.show-file-icons')); container.tabIndex = -1; container.style.display = 'none'; this.titleBar = dom.append(container, $('.quick-input-titlebar')); const leftActionBar = this._register(new ActionBar(this.titleBar)); leftActionBar.domNode.classList.add('quick-input-left-action-bar'); const title = dom.append(this.titleBar, $('.quick-input-title')); const rightActionBar = this._register(new ActionBar(this.titleBar)); rightActionBar.domNode.classList.add('quick-input-right-action-bar'); const headerContainer = dom.append(container, $('.quick-input-header')); const checkAll = <HTMLInputElement>dom.append(headerContainer, $('input.quick-input-check-all')); checkAll.type = 'checkbox'; this._register(dom.addStandardDisposableListener(checkAll, dom.EventType.CHANGE, e => { const checked = checkAll.checked; list.setAllVisibleChecked(checked); })); this._register(dom.addDisposableListener(checkAll, dom.EventType.CLICK, e => { if (e.x || e.y) { // Avoid 'click' triggered by 'space'... inputBox.setFocus(); } })); this.filterContainer = dom.append(headerContainer, $('.quick-input-filter')); const inputBox = this._register(new QuickInputBox(this.filterContainer)); inputBox.setAttribute('aria-describedby', `${this.idPrefix}message`); this.visibleCountContainer = dom.append(this.filterContainer, $('.quick-input-visible-count')); this.visibleCountContainer.setAttribute('aria-live', 'polite'); this.visibleCountContainer.setAttribute('aria-atomic', 'true'); const visibleCount = new CountBadge(this.visibleCountContainer, { countFormat: localize({ key: 'quickInput.visibleCount', comment: ['This tells the user how many items are shown in a list of items to select from. The items can be anything. Currently not visible, but read by screen readers.'] }, "{0} Results") }); this.countContainer = dom.append(this.filterContainer, $('.quick-input-count')); this.countContainer.setAttribute('aria-live', 'polite'); const count = new CountBadge(this.countContainer, { countFormat: localize({ key: 'quickInput.countSelected', comment: ['This tells the user how many items are selected in a list of items to select from. The items can be anything.'] }, "{0} Selected") }); this._register(attachBadgeStyler(count, this.themeService)); this.okContainer = dom.append(headerContainer, $('.quick-input-action')); this.ok = new Button(this.okContainer); attachButtonStyler(this.ok, this.themeService); this.ok.label = localize('ok', "OK"); this._register(this.ok.onDidClick(e => { this.onDidAcceptEmitter.fire(); })); const message = dom.append(container, $(`#${this.idPrefix}message.quick-input-message`)); const progressBar = new ProgressBar(container); dom.addClass(progressBar.getContainer(), 'quick-input-progress'); this._register(attachProgressBarStyler(progressBar, this.themeService)); const list = this._register(this.instantiationService.createInstance(QuickInputList, container, this.idPrefix + 'list')); this._register(list.onChangedAllVisibleChecked(checked => { checkAll.checked = checked; })); this._register(list.onChangedVisibleCount(c => { visibleCount.setCount(c); })); this._register(list.onChangedCheckedCount(c => { count.setCount(c); })); this._register(list.onLeave(() => { // Defer to avoid the input field reacting to the triggering key. setTimeout(() => { inputBox.setFocus(); if (this.controller instanceof QuickPick && this.controller.canSelectMany) { list.clearFocus(); } }, 0); })); this._register(list.onDidChangeFocus(() => { if (this.comboboxAccessibility) { this.ui.inputBox.setAttribute('aria-activedescendant', this.ui.list.getActiveDescendant() || ''); } })); const focusTracker = dom.trackFocus(container); this._register(focusTracker); this._register(focusTracker.onDidBlur(() => { if (!this.ui.ignoreFocusOut && !this.environmentService.args['sticky-quickopen'] && this.configurationService.getValue(CLOSE_ON_FOCUS_LOST_CONFIG)) { this.hide(true); } })); this._register(dom.addDisposableListener(container, dom.EventType.KEY_DOWN, (e: KeyboardEvent) => { const event = new StandardKeyboardEvent(e); switch (event.keyCode) { case KeyCode.Enter: dom.EventHelper.stop(e, true); this.onDidAcceptEmitter.fire(); break; case KeyCode.Escape: dom.EventHelper.stop(e, true); this.hide(); break; case KeyCode.Tab: if (!event.altKey && !event.ctrlKey && !event.metaKey) { const selectors = ['.action-label.icon']; if (container.classList.contains('show-checkboxes')) { selectors.push('input'); } else { selectors.push('input[type=text]'); } if (this.ui.list.isDisplayed()) { selectors.push('.monaco-list'); } const stops = container.querySelectorAll<HTMLElement>(selectors.join(', ')); if (event.shiftKey && event.target === stops[0]) { dom.EventHelper.stop(e, true); stops[stops.length - 1].focus(); } else if (!event.shiftKey && event.target === stops[stops.length - 1]) { dom.EventHelper.stop(e, true); stops[0].focus(); } } break; } })); this._register(this.quickOpenService.onShow(() => this.hide(true))); this.ui = { container, leftActionBar, title, rightActionBar, checkAll, inputBox, visibleCount, count, message, progressBar, list, onDidAccept: this.onDidAcceptEmitter.event, onDidTriggerButton: this.onDidTriggerButtonEmitter.event, ignoreFocusOut: false, keyMods: this.keyMods, isScreenReaderOptimized: () => this.isScreenReaderOptimized(), show: controller => this.show(controller), hide: () => this.hide(), setVisibilities: visibilities => this.setVisibilities(visibilities), setComboboxAccessibility: enabled => this.setComboboxAccessibility(enabled), setEnabled: enabled => this.setEnabled(enabled), setContextKey: contextKey => this.setContextKey(contextKey), }; this.updateStyles(); } pick<T extends IQuickPickItem, O extends IPickOptions<T>>(picks: Promise<QuickPickInput<T>[]> | QuickPickInput<T>[], options: O = <O>{}, token: CancellationToken = CancellationToken.None): Promise<O extends { canPickMany: true } ? T[] : T> { return new Promise<O extends { canPickMany: true } ? T[] : T>((doResolve, reject) => { let resolve = (result: any) => { resolve = doResolve; if (options.onKeyMods) { options.onKeyMods(input.keyMods); } doResolve(result); }; if (token.isCancellationRequested) { resolve(undefined); return; } const input = this.createQuickPick<T>(); let activeItem: T | undefined; const disposables = [ input, input.onDidAccept(() => { if (input.canSelectMany) { resolve(<any>input.selectedItems.slice()); input.hide(); } else { const result = input.activeItems[0]; if (result) { resolve(<any>result); input.hide(); } } }), input.onDidChangeActive(items => { const focused = items[0]; if (focused && options.onDidFocus) { options.onDidFocus(focused); } }), input.onDidChangeSelection(items => { if (!input.canSelectMany) { const result = items[0]; if (result) { resolve(<any>result); input.hide(); } } }), input.onDidTriggerItemButton(event => options.onDidTriggerItemButton && options.onDidTriggerItemButton({ ...event, removeItem: () => { const index = input.items.indexOf(event.item); if (index !== -1) { const items = input.items.slice(); items.splice(index, 1); input.items = items; } } })), input.onDidChangeValue(value => { if (activeItem && !value && (input.activeItems.length !== 1 || input.activeItems[0] !== activeItem)) { input.activeItems = [activeItem]; } }), token.onCancellationRequested(() => { input.hide(); }), input.onDidHide(() => { dispose(disposables); resolve(undefined); }), ]; input.canSelectMany = !!options.canPickMany; input.placeholder = options.placeHolder; input.ignoreFocusOut = !!options.ignoreFocusLost; input.matchOnDescription = !!options.matchOnDescription; input.matchOnDetail = !!options.matchOnDetail; input.matchOnLabel = (options.matchOnLabel === undefined) || options.matchOnLabel; // default to true input.autoFocusOnList = (options.autoFocusOnList === undefined) || options.autoFocusOnList; // default to true input.quickNavigate = options.quickNavigate; input.contextKey = options.contextKey; input.busy = true; Promise.all<QuickPickInput<T>[], T | undefined>([picks, options.activeItem]) .then(([items, _activeItem]) => { activeItem = _activeItem; input.busy = false; input.items = items; if (input.canSelectMany) { input.selectedItems = items.filter(item => item.type !== 'separator' && item.picked) as T[]; } if (activeItem) { input.activeItems = [activeItem]; } }); input.show(); Promise.resolve(picks).then(undefined, err => { reject(err); input.hide(); }); }); } input(options: IInputOptions = {}, token: CancellationToken = CancellationToken.None): Promise<string> { return new Promise<string>((resolve, reject) => { if (token.isCancellationRequested) { resolve(undefined); return; } const input = this.createInputBox(); const validateInput = options.validateInput || (() => <Promise<undefined>>Promise.resolve(undefined)); const onDidValueChange = Event.debounce(input.onDidChangeValue, (last, cur) => cur, 100); let validationValue = options.value || ''; let validation = Promise.resolve(validateInput(validationValue)); const disposables = [ input, onDidValueChange(value => { if (value !== validationValue) { validation = Promise.resolve(validateInput(value)); validationValue = value; } validation.then(result => { if (value === validationValue) { input.validationMessage = result || undefined; } }); }), input.onDidAccept(() => { const value = input.value; if (value !== validationValue) { validation = Promise.resolve(validateInput(value)); validationValue = value; } validation.then(result => { if (!result) { resolve(value); input.hide(); } else if (value === validationValue) { input.validationMessage = result; } }); }), token.onCancellationRequested(() => { input.hide(); }), input.onDidHide(() => { dispose(disposables); resolve(undefined); }), ]; input.value = options.value || ''; input.valueSelection = options.valueSelection; input.prompt = options.prompt; input.placeholder = options.placeHolder; input.password = !!options.password; input.ignoreFocusOut = !!options.ignoreFocusLost; input.show(); }); } backButton = backButton; createQuickPick<T extends IQuickPickItem>(): IQuickPick<T> { this.create(); return new QuickPick<T>(this.ui); } createInputBox(): IInputBox { this.create(); return new InputBox(this.ui); } private show(controller: QuickInput) { this.create(); this.quickOpenService.close(); const oldController = this.controller; this.controller = controller; if (oldController) { oldController.didHide(); } this.setEnabled(true); this.ui.leftActionBar.clear(); this.ui.title.textContent = ''; this.ui.rightActionBar.clear(); this.ui.checkAll.checked = false; // this.ui.inputBox.value = ''; Avoid triggering an event. this.ui.inputBox.placeholder = ''; this.ui.inputBox.password = false; this.ui.inputBox.showDecoration(Severity.Ignore); this.ui.visibleCount.setCount(0); this.ui.count.setCount(0); this.ui.message.textContent = ''; this.ui.progressBar.stop(); this.ui.list.setElements([]); this.ui.list.matchOnDescription = false; this.ui.list.matchOnDetail = false; this.ui.list.matchOnLabel = true; this.ui.ignoreFocusOut = false; this.setComboboxAccessibility(false); this.ui.inputBox.removeAttribute('aria-label'); const keybinding = this.keybindingService.lookupKeybinding(BackAction.ID); backButton.tooltip = keybinding ? localize('quickInput.backWithKeybinding', "Back ({0})", keybinding.getLabel()) : localize('quickInput.back', "Back"); this.inQuickOpen('quickInput', true); this.resetContextKeys(); this.ui.container.style.display = ''; this.updateLayout(); this.ui.inputBox.setFocus(); } private setVisibilities(visibilities: Visibilities) { this.ui.title.style.display = visibilities.title ? '' : 'none'; this.ui.checkAll.style.display = visibilities.checkAll ? '' : 'none'; this.filterContainer.style.display = visibilities.inputBox ? '' : 'none'; this.visibleCountContainer.style.display = visibilities.visibleCount ? '' : 'none'; this.countContainer.style.display = visibilities.count ? '' : 'none'; this.okContainer.style.display = visibilities.ok ? '' : 'none'; this.ui.message.style.display = visibilities.message ? '' : 'none'; this.ui.list.display(!!visibilities.list); this.ui.container.classList[visibilities.checkAll ? 'add' : 'remove']('show-checkboxes'); this.updateLayout(); // TODO } private setComboboxAccessibility(enabled: boolean) { if (enabled !== this.comboboxAccessibility) { this.comboboxAccessibility = enabled; if (this.comboboxAccessibility) { this.ui.inputBox.setAttribute('role', 'combobox'); this.ui.inputBox.setAttribute('aria-haspopup', 'true'); this.ui.inputBox.setAttribute('aria-autocomplete', 'list'); this.ui.inputBox.setAttribute('aria-activedescendant', this.ui.list.getActiveDescendant() || ''); } else { this.ui.inputBox.removeAttribute('role'); this.ui.inputBox.removeAttribute('aria-haspopup'); this.ui.inputBox.removeAttribute('aria-autocomplete'); this.ui.inputBox.removeAttribute('aria-activedescendant'); } } } private isScreenReaderOptimized() { const detected = this.accessibilityService.getAccessibilitySupport() === AccessibilitySupport.Enabled; const config = this.configurationService.getValue<IEditorOptions>('editor').accessibilitySupport; return config === 'on' || (config === 'auto' && detected); } private setEnabled(enabled: boolean) { if (enabled !== this.enabled) { this.enabled = enabled; for (const item of this.ui.leftActionBar.items) { (item as ActionItem).getAction().enabled = enabled; } for (const item of this.ui.rightActionBar.items) { (item as ActionItem).getAction().enabled = enabled; } this.ui.checkAll.disabled = !enabled; // this.ui.inputBox.enabled = enabled; Avoid loosing focus. this.ok.enabled = enabled; this.ui.list.enabled = enabled; } } private hide(focusLost?: boolean) { const controller = this.controller; if (controller) { this.controller = null; this.inQuickOpen('quickInput', false); this.resetContextKeys(); this.ui.container.style.display = 'none'; if (!focusLost) { this.editorGroupService.activeGroup.focus(); } controller.didHide(); } } focus() { if (this.isDisplayed()) { this.ui.inputBox.setFocus(); } } toggle() { if (this.isDisplayed() && this.controller instanceof QuickPick && this.controller.canSelectMany) { this.ui.list.toggleCheckbox(); } } navigate(next: boolean, quickNavigate?: IQuickNavigateConfiguration) { if (this.isDisplayed() && this.ui.list.isDisplayed()) { this.ui.list.focus(next ? 'Next' : 'Previous'); if (quickNavigate && this.controller instanceof QuickPick) { this.controller.quickNavigate = quickNavigate; } } } accept() { this.onDidAcceptEmitter.fire(); return Promise.resolve(undefined); } back() { this.onDidTriggerButtonEmitter.fire(this.backButton); return Promise.resolve(undefined); } cancel() { this.hide(); return Promise.resolve(undefined); } layout(dimension: dom.Dimension): void { this.updateLayout(); } private updateLayout() { if (this.ui) { const titlebarOffset = this.layoutService.getTitleBarOffset(); this.ui.container.style.top = `${titlebarOffset}px`; const style = this.ui.container.style; const width = Math.min(this.layoutService.dimension.width * 0.62 /* golden cut */, QuickInputService.MAX_WIDTH); style.width = width + 'px'; style.marginLeft = '-' + (width / 2) + 'px'; this.ui.inputBox.layout(); this.ui.list.layout(); } } protected updateStyles() { const theme = this.themeService.getTheme(); if (this.ui) { // TODO const titleColor = { dark: 'rgba(255, 255, 255, 0.105)', light: 'rgba(0,0,0,.06)', hc: 'black' }[theme.type]; this.titleBar.style.backgroundColor = titleColor ? titleColor.toString() : null; this.ui.inputBox.style(theme); const sideBarBackground = theme.getColor(SIDE_BAR_BACKGROUND); this.ui.container.style.backgroundColor = sideBarBackground ? sideBarBackground.toString() : null; const sideBarForeground = theme.getColor(SIDE_BAR_FOREGROUND); this.ui.container.style.color = sideBarForeground ? sideBarForeground.toString() : null; const contrastBorderColor = theme.getColor(contrastBorder); this.ui.container.style.border = contrastBorderColor ? `1px solid ${contrastBorderColor}` : null; const widgetShadowColor = theme.getColor(widgetShadow); this.ui.container.style.boxShadow = widgetShadowColor ? `0 5px 8px ${widgetShadowColor}` : null; } } private isDisplayed() { return this.ui && this.ui.container.style.display !== 'none'; } } export const QuickPickManyToggle: ICommandAndKeybindingRule = { id: 'workbench.action.quickPickManyToggle', weight: KeybindingWeight.WorkbenchContrib, when: inQuickOpenContext, primary: 0, handler: accessor => { const quickInputService = accessor.get(IQuickInputService); quickInputService.toggle(); } }; export class BackAction extends Action { public static readonly ID = 'workbench.action.quickInputBack'; public static readonly LABEL = localize('back', "Back"); constructor(id: string, label: string, @IQuickInputService private readonly quickInputService: IQuickInputService) { super(id, label); } public run(): Promise<any> { this.quickInputService.back(); return Promise.resolve(); } } registerSingleton(IQuickInputService, QuickInputService, true);
src/vs/workbench/browser/parts/quickinput/quickInput.ts
1
https://github.com/microsoft/vscode/commit/f07c7d705629bea1c6f5af42b7d3f7d72e225f2a
[ 0.0001940051297424361, 0.00017225596820935607, 0.00016399957530666143, 0.0001723567838780582, 0.0000037068557503516786 ]
{ "id": 13, "code_window": [ "\t\t\t\treturn Promise.resolve(false);\n", "\t\t\t} else if (stat.isDirectory && !this.allowFolderSelection) {\n", "\t\t\t\t// Folder selected when folder selection not permitted\n", "\t\t\t\treturn Promise.resolve(false);\n", "\t\t\t} else if (!stat.isDirectory && !this.allowFileSelection) {\n", "\t\t\t\t// File selected when file selection not permitted\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\tthis.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateFileOnly', 'Please select a file.');\n" ], "file_path": "src/vs/workbench/services/dialogs/electron-browser/remoteFileDialog.ts", "type": "add", "edit_start_line_idx": 368 }
{ // a comment "options": { "myBool": true, "myInteger": 1, "myString": "String\u0056", "myNumber": 1.24, "myNull": null, "myArray": [ 1, "Hello", true, null, [], {}], "myObject" : { "foo": "bar" } } }
extensions/json/test/colorize-fixtures/test.json
0
https://github.com/microsoft/vscode/commit/f07c7d705629bea1c6f5af42b7d3f7d72e225f2a
[ 0.00017435438348911703, 0.00017429181025363505, 0.00017422923701815307, 0.00017429181025363505, 6.257323548197746e-8 ]
{ "id": 13, "code_window": [ "\t\t\t\treturn Promise.resolve(false);\n", "\t\t\t} else if (stat.isDirectory && !this.allowFolderSelection) {\n", "\t\t\t\t// Folder selected when folder selection not permitted\n", "\t\t\t\treturn Promise.resolve(false);\n", "\t\t\t} else if (!stat.isDirectory && !this.allowFileSelection) {\n", "\t\t\t\t// File selected when file selection not permitted\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\tthis.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateFileOnly', 'Please select a file.');\n" ], "file_path": "src/vs/workbench/services/dialogs/electron-browser/remoteFileDialog.ts", "type": "add", "edit_start_line_idx": 368 }
{ "Insert bold text": { "prefix": "bold", "body": "**${1:${TM_SELECTED_TEXT}}**$0", "description": "Insert bold text" }, "Insert italic text": { "prefix": "italic", "body": "*${1:${TM_SELECTED_TEXT}}*$0", "description": "Insert italic text" }, "Insert quoted text": { "prefix": "quote", "body": "> ${1:${TM_SELECTED_TEXT}}", "description": "Insert quoted text" }, "Insert code": { "prefix": "code", "body": "`${1:${TM_SELECTED_TEXT}}`$0", "description": "Insert code" }, "Insert fenced code block": { "prefix": "fenced codeblock", "body": [ "```${1:language}", "${TM_SELECTED_TEXT}$0", "```" ], "description": "Insert fenced code block" }, "Insert heading": { "prefix": "heading", "body": "# ${1:${TM_SELECTED_TEXT}}", "description": "Insert heading" }, "Insert unordered list": { "prefix": "unordered list", "body": [ "- ${1:first}", "- ${2:second}", "- ${3:third}", "$0" ], "description": "Insert unordered list" }, "Insert ordered list": { "prefix": "ordered list", "body": [ "1. ${1:first}", "2. ${2:second}", "3. ${3:third}", "$0" ], "description": "Insert ordered list" }, "Insert horizontal rule": { "prefix": "horizontal rule", "body": "----------\n", "description": "Insert horizontal rule" }, "Insert link": { "prefix": "link", "body": "[${TM_SELECTED_TEXT:${1:text}}](https://${2:link})$0", "description": "Insert link" }, "Insert image": { "prefix": "image", "body": "![${TM_SELECTED_TEXT:${1:alt}}](https://${2:link})$0", "description": "Insert image" } }
extensions/markdown-basics/snippets/markdown.json
0
https://github.com/microsoft/vscode/commit/f07c7d705629bea1c6f5af42b7d3f7d72e225f2a
[ 0.0001757873105816543, 0.00017433793982490897, 0.00017197479610331357, 0.00017474842024967074, 0.0000012707039331871783 ]
{ "id": 13, "code_window": [ "\t\t\t\treturn Promise.resolve(false);\n", "\t\t\t} else if (stat.isDirectory && !this.allowFolderSelection) {\n", "\t\t\t\t// Folder selected when folder selection not permitted\n", "\t\t\t\treturn Promise.resolve(false);\n", "\t\t\t} else if (!stat.isDirectory && !this.allowFileSelection) {\n", "\t\t\t\t// File selected when file selection not permitted\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\tthis.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateFileOnly', 'Please select a file.');\n" ], "file_path": "src/vs/workbench/services/dialogs/electron-browser/remoteFileDialog.ts", "type": "add", "edit_start_line_idx": 368 }
/*--------------------------------------------------------------------------------------------- * 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 { ITextModel } from 'vs/editor/common/model'; import { URI } from 'vs/base/common/uri'; import { ResourceEditorInput } from 'vs/workbench/common/editor/resourceEditorInput'; import { ResourceEditorModel } from 'vs/workbench/common/editor/resourceEditorModel'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { workbenchInstantiationService, TestTextFileService } from 'vs/workbench/test/workbenchTestServices'; import { toResource } from 'vs/base/test/common/utils'; import { ITextModelService } from 'vs/editor/common/services/resolverService'; import { IModelService } from 'vs/editor/common/services/modelService'; import { IModeService } from 'vs/editor/common/services/modeService'; import { TextFileEditorModel } from 'vs/workbench/services/textfile/common/textFileEditorModel'; import { ITextFileService } from 'vs/workbench/services/textfile/common/textfiles'; import { IUntitledEditorService } from 'vs/workbench/services/untitled/common/untitledEditorService'; import { TextFileEditorModelManager } from 'vs/workbench/services/textfile/common/textFileEditorModelManager'; import { Event } from 'vs/base/common/event'; import { snapshotToString } from 'vs/platform/files/common/files'; import { timeout } from 'vs/base/common/async'; class ServiceAccessor { constructor( @ITextModelService public textModelResolverService: ITextModelService, @IModelService public modelService: IModelService, @IModeService public modeService: IModeService, @ITextFileService public textFileService: TestTextFileService, @IUntitledEditorService public untitledEditorService: IUntitledEditorService ) { } } suite('Workbench - TextModelResolverService', () => { let instantiationService: IInstantiationService; let accessor: ServiceAccessor; let model: TextFileEditorModel; setup(() => { instantiationService = workbenchInstantiationService(); accessor = instantiationService.createInstance(ServiceAccessor); }); teardown(() => { if (model) { model.dispose(); model = (undefined)!; } (<TextFileEditorModelManager>accessor.textFileService.models).clear(); (<TextFileEditorModelManager>accessor.textFileService.models).dispose(); accessor.untitledEditorService.revertAll(); }); test('resolve resource', function () { const dispose = accessor.textModelResolverService.registerTextModelContentProvider('test', { provideTextContent: function (resource: URI): Promise<ITextModel> { if (resource.scheme === 'test') { let modelContent = 'Hello Test'; let languageSelection = accessor.modeService.create('json'); return Promise.resolve(accessor.modelService.createModel(modelContent, languageSelection, resource)); } return Promise.resolve(null!); } }); let resource = URI.from({ scheme: 'test', authority: null!, path: 'thePath' }); let input: ResourceEditorInput = instantiationService.createInstance(ResourceEditorInput, 'The Name', 'The Description', resource); return input.resolve().then(async model => { assert.ok(model); assert.equal(snapshotToString((model as ResourceEditorModel).createSnapshot()!), 'Hello Test'); let disposed = false; let disposedPromise = new Promise(resolve => { Event.once(model.onDispose)(() => { disposed = true; resolve(); }); }); input.dispose(); await disposedPromise; assert.equal(disposed, true); dispose.dispose(); }); }); test('resolve file', function () { model = instantiationService.createInstance(TextFileEditorModel, toResource.call(this, '/path/file_resolver.txt'), 'utf8'); (<TextFileEditorModelManager>accessor.textFileService.models).add(model.getResource(), model); return model.load().then(() => { return accessor.textModelResolverService.createModelReference(model.getResource()).then(ref => { const model = ref.object; const editorModel = model.textEditorModel; assert.ok(editorModel); assert.equal(editorModel.getValue(), 'Hello Html'); let disposed = false; Event.once(model.onDispose)(() => { disposed = true; }); ref.dispose(); return timeout(0).then(() => { // due to the reference resolving the model first which is async assert.equal(disposed, true); }); }); }); }); test('resolve untitled', function () { const service = accessor.untitledEditorService; const input = service.createOrGet(); return input.resolve().then(() => { return accessor.textModelResolverService.createModelReference(input.getResource()).then(ref => { const model = ref.object; const editorModel = model.textEditorModel; assert.ok(editorModel); ref.dispose(); input.dispose(); }); }); }); test('even loading documents should be refcounted', async () => { let resolveModel!: Function; let waitForIt = new Promise(c => resolveModel = c); const disposable = accessor.textModelResolverService.registerTextModelContentProvider('test', { provideTextContent: (resource: URI): Promise<ITextModel> => { return waitForIt.then(_ => { let modelContent = 'Hello Test'; let languageSelection = accessor.modeService.create('json'); return accessor.modelService.createModel(modelContent, languageSelection, resource); }); } }); const uri = URI.from({ scheme: 'test', authority: null!, path: 'thePath' }); const modelRefPromise1 = accessor.textModelResolverService.createModelReference(uri); const modelRefPromise2 = accessor.textModelResolverService.createModelReference(uri); resolveModel(); const modelRef1 = await modelRefPromise1; const model1 = modelRef1.object; const modelRef2 = await modelRefPromise2; const model2 = modelRef2.object; const textModel = model1.textEditorModel; assert.equal(model1, model2, 'they are the same model'); assert(!textModel.isDisposed(), 'the text model should not be disposed'); modelRef1.dispose(); assert(!textModel.isDisposed(), 'the text model should still not be disposed'); let p1 = new Promise(resolve => textModel.onWillDispose(resolve)); modelRef2.dispose(); await p1; assert(textModel.isDisposed(), 'the text model should finally be disposed'); disposable.dispose(); }); });
src/vs/workbench/services/textmodelResolver/test/textModelResolverService.test.ts
0
https://github.com/microsoft/vscode/commit/f07c7d705629bea1c6f5af42b7d3f7d72e225f2a
[ 0.00017888718866743147, 0.00017339125042781234, 0.00016465751104988158, 0.0001744713808875531, 0.00000360087278750143 ]
{ "id": 14, "code_window": [ "\t\t\t\treturn Promise.resolve(false);\n", "\t\t\t} else if (!stat.isDirectory && !this.allowFileSelection) {\n", "\t\t\t\t// File selected when file selection not permitted\n", "\t\t\t\treturn Promise.resolve(false);\n", "\t\t\t}\n", "\t\t}\n", "\t\treturn Promise.resolve(true);\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\tthis.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateFolderOnly', 'Please select a folder.');\n" ], "file_path": "src/vs/workbench/services/dialogs/electron-browser/remoteFileDialog.ts", "type": "add", "edit_start_line_idx": 371 }
/*--------------------------------------------------------------------------------------------- * 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 resources from 'vs/base/common/resources'; import * as objects from 'vs/base/common/objects'; import { RemoteFileService } from 'vs/workbench/services/files/node/remoteFileService'; import { IFileService, IFileStat, FileKind } from 'vs/platform/files/common/files'; import { IQuickInputService, IQuickPickItem, IQuickPick } from 'vs/platform/quickinput/common/quickInput'; import { URI } from 'vs/base/common/uri'; import { isWindows } from 'vs/base/common/platform'; import { ISaveDialogOptions, IOpenDialogOptions, IFileDialogService } from 'vs/platform/dialogs/common/dialogs'; import { REMOTE_HOST_SCHEME } from 'vs/platform/remote/common/remoteHosts'; import { IWindowService, IURIToOpen } from 'vs/platform/windows/common/windows'; import { ILabelService } from 'vs/platform/label/common/label'; import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace'; import { INotificationService } from 'vs/platform/notification/common/notification'; import { IModelService } from 'vs/editor/common/services/modelService'; import { IModeService } from 'vs/editor/common/services/modeService'; import { getIconClasses } from 'vs/editor/common/services/getIconClasses'; import { Schemas } from 'vs/base/common/network'; interface FileQuickPickItem extends IQuickPickItem { uri: URI; isFolder: boolean; } // Reference: https://en.wikipedia.org/wiki/Filename const INVALID_FILE_CHARS = isWindows ? /[\\/:\*\?"<>\|]/g : /[\\/]/g; const WINDOWS_FORBIDDEN_NAMES = /^(con|prn|aux|clock\$|nul|lpt[0-9]|com[0-9])$/i; export class RemoteFileDialog { private fallbackPickerButton; private acceptButton; private currentFolder: URI; private filePickBox: IQuickPick<FileQuickPickItem>; private allowFileSelection: boolean; private allowFolderSelection: boolean; private remoteAuthority: string | undefined; private requiresTrailing: boolean; private userValue: string; private scheme: string = REMOTE_HOST_SCHEME; constructor( @IFileService private readonly remoteFileService: RemoteFileService, @IQuickInputService private readonly quickInputService: IQuickInputService, @IWindowService private readonly windowService: IWindowService, @ILabelService private readonly labelService: ILabelService, @IWorkspaceContextService private readonly workspaceContextService: IWorkspaceContextService, @INotificationService private readonly notificationService: INotificationService, @IFileDialogService private readonly fileDialogService: IFileDialogService, @IModelService private readonly modelService: IModelService, @IModeService private readonly modeService: IModeService, ) { this.remoteAuthority = this.windowService.getConfiguration().remoteAuthority; } public async showOpenDialog(options: IOpenDialogOptions = {}): Promise<IURIToOpen[] | undefined> { this.setScheme(options.defaultUri, options.availableFileSystems); const newOptions = this.getOptions(options); if (!newOptions) { return Promise.resolve(undefined); } const openFileString = nls.localize('remoteFileDialog.localFileFallback', 'Open Local File'); const openFolderString = nls.localize('remoteFileDialog.localFolderFallback', 'Open Local Folder'); const openFileFolderString = nls.localize('remoteFileDialog.localFileFolderFallback', 'Open Local File or Folder'); let tooltip = options.canSelectFiles ? (options.canSelectFolders ? openFileFolderString : openFileString) : openFolderString; this.fallbackPickerButton = { iconPath: this.getDialogIcons('folder'), tooltip }; return this.pickResource(newOptions).then(async fileFolderUri => { if (fileFolderUri) { const stat = await this.remoteFileService.resolveFile(fileFolderUri); return <IURIToOpen[]>[{ uri: fileFolderUri, typeHint: stat.isDirectory ? 'folder' : 'file' }]; } return Promise.resolve(undefined); }); } public showSaveDialog(options: ISaveDialogOptions): Promise<URI | undefined> { this.setScheme(options.defaultUri, options.availableFileSystems); this.requiresTrailing = true; const newOptions = this.getOptions(options); if (!newOptions) { return Promise.resolve(undefined); } this.fallbackPickerButton = { iconPath: this.getDialogIcons('folder'), tooltip: nls.localize('remoteFileDialog.localSaveFallback', 'Save Local File') }; newOptions.canSelectFolders = true; newOptions.canSelectFiles = true; return new Promise<URI | undefined>((resolve) => { this.pickResource(newOptions, true).then(folderUri => { resolve(folderUri); }); }); } private getOptions(options: ISaveDialogOptions | IOpenDialogOptions): IOpenDialogOptions | undefined { const defaultUri = options.defaultUri ? options.defaultUri : URI.from({ scheme: this.scheme, authority: this.remoteAuthority, path: '/' }); if ((this.scheme !== Schemas.file) && !this.remoteFileService.canHandleResource(defaultUri)) { this.notificationService.info(nls.localize('remoteFileDialog.notConnectedToRemote', 'File system provider for {0} is not available.', defaultUri.toString())); return undefined; } const newOptions: IOpenDialogOptions = objects.deepClone(options); newOptions.defaultUri = defaultUri; return newOptions; } private remoteUriFrom(path: string): URI { path = path.replace(/\\/g, '/'); return URI.from({ scheme: this.scheme, authority: this.remoteAuthority, path }); } private setScheme(defaultUri: URI | undefined, available: string[] | undefined) { this.scheme = defaultUri ? defaultUri.scheme : (available ? available[0] : Schemas.file); } private async pickResource(options: IOpenDialogOptions, isSave: boolean = false): Promise<URI | undefined> { this.allowFolderSelection = !!options.canSelectFolders; this.allowFileSelection = !!options.canSelectFiles; let homedir: URI = options.defaultUri ? options.defaultUri : this.workspaceContextService.getWorkspace().folders[0].uri; let trailing: string | undefined; let stat: IFileStat | undefined; let ext: string = resources.extname(homedir); if (options.defaultUri) { try { stat = await this.remoteFileService.resolveFile(options.defaultUri); } catch (e) { // The file or folder doesn't exist } if (!stat || !stat.isDirectory) { homedir = resources.dirname(options.defaultUri); trailing = resources.basename(options.defaultUri); } // append extension if (isSave && !ext && options.filters) { for (let i = 0; i < options.filters.length; i++) { if (options.filters[i].extensions[0] !== '*') { ext = '.' + options.filters[i].extensions[0]; trailing = trailing ? trailing + ext : ext; break; } } } } this.acceptButton = { iconPath: this.getDialogIcons('accept'), tooltip: options.title }; return new Promise<URI | undefined>((resolve) => { this.filePickBox = this.quickInputService.createQuickPick<FileQuickPickItem>(); this.filePickBox.matchOnLabel = false; this.filePickBox.autoFocusOnList = false; let isResolved = false; let isAcceptHandled = false; this.currentFolder = homedir; if (options.availableFileSystems && options.availableFileSystems.length > 1) { this.filePickBox.buttons = [this.fallbackPickerButton, this.acceptButton]; } else { this.filePickBox.buttons = [this.acceptButton]; } this.filePickBox.onDidTriggerButton(button => { if (button === this.fallbackPickerButton) { if (options.availableFileSystems) { options.availableFileSystems.shift(); } isResolved = true; if (this.requiresTrailing) { this.fileDialogService.showSaveDialog(options).then(result => { this.filePickBox.hide(); resolve(result); }); } else { this.fileDialogService.showOpenDialog(options).then(result => { this.filePickBox.hide(); resolve(result ? result[0] : undefined); }); } this.filePickBox.hide(); } else { // accept button const resolveValue = this.remoteUriFrom(this.filePickBox.value); this.validate(resolveValue).then(validated => { if (validated) { isResolved = true; this.filePickBox.hide(); resolve(resolveValue); } }); } }); this.filePickBox.title = options.title; this.filePickBox.value = this.pathFromUri(this.currentFolder); this.filePickBox.items = []; this.filePickBox.onDidAccept(_ => { if (isAcceptHandled || this.filePickBox.busy) { return; } isAcceptHandled = true; this.onDidAccept().then(resolveValue => { if (resolveValue) { isResolved = true; this.filePickBox.hide(); resolve(resolveValue); } }); }); this.filePickBox.onDidChangeActive(i => { isAcceptHandled = false; }); this.filePickBox.onDidChangeValue(async value => { if (value !== this.userValue) { const trimmedPickBoxValue = ((this.filePickBox.value.length > 1) && this.endsWithSlash(this.filePickBox.value)) ? this.filePickBox.value.substr(0, this.filePickBox.value.length - 1) : this.filePickBox.value; const valueUri = this.remoteUriFrom(trimmedPickBoxValue); if (!resources.isEqual(this.currentFolder, valueUri, true)) { await this.tryUpdateItems(value, valueUri); } this.setActiveItems(value); this.userValue = value; } else { this.filePickBox.activeItems = []; } }); this.filePickBox.onDidHide(() => { if (!isResolved) { resolve(undefined); } this.filePickBox.dispose(); }); this.filePickBox.show(); this.updateItems(homedir, trailing); if (trailing) { this.filePickBox.valueSelection = [this.filePickBox.value.length - trailing.length, this.filePickBox.value.length - ext.length]; } this.userValue = this.filePickBox.value; }); } private async onDidAccept(): Promise<URI | undefined> { let resolveValue: URI | undefined; let navigateValue: URI | undefined; const trimmedPickBoxValue = ((this.filePickBox.value.length > 1) && this.endsWithSlash(this.filePickBox.value)) ? this.filePickBox.value.substr(0, this.filePickBox.value.length - 1) : this.filePickBox.value; const inputUri = this.remoteUriFrom(trimmedPickBoxValue); const inputUriDirname = resources.dirname(inputUri); let stat: IFileStat | undefined; let statDirname: IFileStat | undefined; try { statDirname = await this.remoteFileService.resolveFile(inputUriDirname); stat = await this.remoteFileService.resolveFile(inputUri); } catch (e) { // do nothing } // Find resolve value if (this.filePickBox.activeItems.length === 0) { if (!this.requiresTrailing && resources.isEqual(this.currentFolder, inputUri, true)) { resolveValue = inputUri; } else if (this.requiresTrailing && statDirname && statDirname.isDirectory) { resolveValue = inputUri; } else if (stat && stat.isDirectory) { navigateValue = inputUri; } } else if (this.filePickBox.activeItems.length === 1) { const item = this.filePickBox.selectedItems[0]; if (item) { if (!item.isFolder) { resolveValue = item.uri; } else { navigateValue = item.uri; } } } if (resolveValue) { if (await this.validate(resolveValue)) { return Promise.resolve(resolveValue); } } else if (navigateValue) { // Try to navigate into the folder this.updateItems(navigateValue); } else { // validation error. Path does not exist. } return Promise.resolve(undefined); } private async tryUpdateItems(value: string, valueUri: URI) { if (this.endsWithSlash(value) || (!resources.isEqual(this.currentFolder, resources.dirname(valueUri), true) && resources.isEqualOrParent(this.currentFolder, resources.dirname(valueUri), true))) { let stat: IFileStat | undefined; try { stat = await this.remoteFileService.resolveFile(valueUri); } catch (e) { // do nothing } if (stat && stat.isDirectory && (resources.basename(valueUri) !== '.')) { this.updateItems(valueUri); } else { const inputUriDirname = resources.dirname(valueUri); if (!resources.isEqual(this.currentFolder, inputUriDirname, true)) { let statWithoutTrailing: IFileStat | undefined; try { statWithoutTrailing = await this.remoteFileService.resolveFile(inputUriDirname); } catch (e) { // do nothing } if (statWithoutTrailing && statWithoutTrailing.isDirectory && (resources.basename(valueUri) !== '.')) { this.updateItems(inputUriDirname, resources.basename(valueUri)); } } } } } private setActiveItems(value: string) { if (!this.userValue || (value !== this.userValue.substring(0, value.length))) { const inputBasename = resources.basename(this.remoteUriFrom(value)); let hasMatch = false; for (let i = 0; i < this.filePickBox.items.length; i++) { const item = <FileQuickPickItem>this.filePickBox.items[i]; const itemBasename = resources.basename(item.uri); if ((itemBasename.length >= inputBasename.length) && (itemBasename.substr(0, inputBasename.length).toLowerCase() === inputBasename.toLowerCase())) { this.filePickBox.activeItems = [item]; this.filePickBox.value = this.filePickBox.value + itemBasename.substr(inputBasename.length); this.filePickBox.valueSelection = [value.length, this.filePickBox.value.length]; hasMatch = true; break; } } if (!hasMatch) { this.filePickBox.activeItems = []; } } } private async validate(uri: URI): Promise<boolean> { let stat: IFileStat | undefined; let statDirname: IFileStat | undefined; try { statDirname = await this.remoteFileService.resolveFile(resources.dirname(uri)); stat = await this.remoteFileService.resolveFile(uri); } catch (e) { // do nothing } if (this.requiresTrailing) { // save if (stat && stat.isDirectory) { // Can't do this return Promise.resolve(false); } else if (stat) { // This is replacing a file. Not supported yet. return Promise.resolve(false); } else if (!this.isValidBaseName(resources.basename(uri))) { // Filename not allowed return Promise.resolve(false); } else if (!statDirname || !statDirname.isDirectory) { // Folder to save in doesn't exist return Promise.resolve(false); } } else { // open if (!stat) { // File or folder doesn't exist return Promise.resolve(false); } else if (stat.isDirectory && !this.allowFolderSelection) { // Folder selected when folder selection not permitted return Promise.resolve(false); } else if (!stat.isDirectory && !this.allowFileSelection) { // File selected when file selection not permitted return Promise.resolve(false); } } return Promise.resolve(true); } private updateItems(newFolder: URI, trailing?: string) { this.currentFolder = newFolder; this.filePickBox.value = trailing ? this.pathFromUri(resources.joinPath(newFolder, trailing)) : this.pathFromUri(newFolder, true); this.filePickBox.busy = true; this.createItems(this.currentFolder).then(items => { this.filePickBox.items = items; if (this.allowFolderSelection) { this.filePickBox.activeItems = []; } this.filePickBox.busy = false; }); } private pathFromUri(uri: URI, endWithSeparator: boolean = false): string { const sep = this.labelService.getSeparator(uri.scheme, uri.authority); let result: string; if (sep === '/') { result = uri.fsPath.replace(/\\/g, sep); } else { result = uri.fsPath.replace(/\//g, sep); } if (endWithSeparator && !this.endsWithSlash(result)) { result = result + sep; } return result; } private isValidBaseName(name: string): boolean { if (!name || name.length === 0 || /^\s+$/.test(name)) { return false; // require a name that is not just whitespace } INVALID_FILE_CHARS.lastIndex = 0; // the holy grail of software development if (INVALID_FILE_CHARS.test(name)) { return false; // check for certain invalid file characters } if (isWindows && WINDOWS_FORBIDDEN_NAMES.test(name)) { return false; // check for certain invalid file names } if (name === '.' || name === '..') { return false; // check for reserved values } if (isWindows && name[name.length - 1] === '.') { return false; // Windows: file cannot end with a "." } if (isWindows && name.length !== name.trim().length) { return false; // Windows: file cannot end with a whitespace } return true; } private endsWithSlash(s: string) { return /[\/\\]$/.test(s); } private basenameWithTrailingSlash(fullPath: URI): string { const child = this.pathFromUri(fullPath, true); const parent = this.pathFromUri(resources.dirname(fullPath), true); return child.substring(parent.length); } private createBackItem(currFolder: URI): FileQuickPickItem | null { const parentFolder = resources.dirname(currFolder)!; if (!resources.isEqual(currFolder, parentFolder, true)) { return { label: '..', uri: resources.dirname(currFolder), isFolder: true }; } return null; } private async createItems(currentFolder: URI): Promise<FileQuickPickItem[]> { const result: FileQuickPickItem[] = []; const backDir = this.createBackItem(currentFolder); try { const fileNames = await this.remoteFileService.readFolder(currentFolder); const items = await Promise.all(fileNames.map(fileName => this.createItem(fileName, currentFolder))); for (let item of items) { if (item) { result.push(item); } } } catch (e) { // ignore console.log(e); } const sorted = result.sort((i1, i2) => { if (i1.isFolder !== i2.isFolder) { return i1.isFolder ? -1 : 1; } const trimmed1 = this.endsWithSlash(i1.label) ? i1.label.substr(0, i1.label.length - 1) : i1.label; const trimmed2 = this.endsWithSlash(i2.label) ? i2.label.substr(0, i2.label.length - 1) : i2.label; return trimmed1.localeCompare(trimmed2); }); if (backDir) { sorted.unshift(backDir); } return sorted; } private async createItem(filename: string, parent: URI): Promise<FileQuickPickItem | null> { let fullPath = resources.joinPath(parent, filename); try { const stat = await this.remoteFileService.resolveFile(fullPath); if (stat.isDirectory) { filename = this.basenameWithTrailingSlash(fullPath); return { label: filename, uri: fullPath, isFolder: true, iconClasses: getIconClasses(this.modelService, this.modeService, fullPath || undefined, FileKind.FOLDER) }; } else if (!stat.isDirectory && this.allowFileSelection) { return { label: filename, uri: fullPath, isFolder: false, iconClasses: getIconClasses(this.modelService, this.modeService, fullPath || undefined) }; } return null; } catch (e) { return null; } } private getDialogIcons(name: string): { light: URI, dark: URI } { return { dark: URI.parse(require.toUrl(`vs/workbench/services/dialogs/electron-browser/media/dark/${name}.svg`)), light: URI.parse(require.toUrl(`vs/workbench/services/dialogs/electron-browser/media/light/${name}.svg`)) }; } }
src/vs/workbench/services/dialogs/electron-browser/remoteFileDialog.ts
1
https://github.com/microsoft/vscode/commit/f07c7d705629bea1c6f5af42b7d3f7d72e225f2a
[ 0.9982485771179199, 0.02121027745306492, 0.00016420861356891692, 0.0001743418979458511, 0.13822847604751587 ]
{ "id": 14, "code_window": [ "\t\t\t\treturn Promise.resolve(false);\n", "\t\t\t} else if (!stat.isDirectory && !this.allowFileSelection) {\n", "\t\t\t\t// File selected when file selection not permitted\n", "\t\t\t\treturn Promise.resolve(false);\n", "\t\t\t}\n", "\t\t}\n", "\t\treturn Promise.resolve(true);\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\tthis.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateFolderOnly', 'Please select a folder.');\n" ], "file_path": "src/vs/workbench/services/dialogs/electron-browser/remoteFileDialog.ts", "type": "add", "edit_start_line_idx": 371 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { FormattingOptions, Edit } from 'vs/base/common/jsonFormatter'; import { setProperty, removeProperty } from 'vs/base/common/jsonEdit'; import * as assert from 'assert'; suite('JSON - edits', () => { function assertEdit(content: string, edits: Edit[], expected: string) { assert(edits); let lastEditOffset = content.length; for (let i = edits.length - 1; i >= 0; i--) { let edit = edits[i]; assert(edit.offset >= 0 && edit.length >= 0 && edit.offset + edit.length <= content.length); assert(typeof edit.content === 'string'); assert(lastEditOffset >= edit.offset + edit.length); // make sure all edits are ordered lastEditOffset = edit.offset; content = content.substring(0, edit.offset) + edit.content + content.substring(edit.offset + edit.length); } assert.equal(content, expected); } let formatterOptions: FormattingOptions = { insertSpaces: true, tabSize: 2, eol: '\n' }; test('set property', () => { let content = '{\n "x": "y"\n}'; let edits = setProperty(content, ['x'], 'bar', formatterOptions); assertEdit(content, edits, '{\n "x": "bar"\n}'); content = 'true'; edits = setProperty(content, [], 'bar', formatterOptions); assertEdit(content, edits, '"bar"'); content = '{\n "x": "y"\n}'; edits = setProperty(content, ['x'], { key: true }, formatterOptions); assertEdit(content, edits, '{\n "x": {\n "key": true\n }\n}'); content = '{\n "a": "b", "x": "y"\n}'; edits = setProperty(content, ['a'], null, formatterOptions); assertEdit(content, edits, '{\n "a": null, "x": "y"\n}'); }); test('insert property', () => { let content = '{}'; let edits = setProperty(content, ['foo'], 'bar', formatterOptions); assertEdit(content, edits, '{\n "foo": "bar"\n}'); edits = setProperty(content, ['foo', 'foo2'], 'bar', formatterOptions); assertEdit(content, edits, '{\n "foo": {\n "foo2": "bar"\n }\n}'); content = '{\n}'; edits = setProperty(content, ['foo'], 'bar', formatterOptions); assertEdit(content, edits, '{\n "foo": "bar"\n}'); content = ' {\n }'; edits = setProperty(content, ['foo'], 'bar', formatterOptions); assertEdit(content, edits, ' {\n "foo": "bar"\n }'); content = '{\n "x": "y"\n}'; edits = setProperty(content, ['foo'], 'bar', formatterOptions); assertEdit(content, edits, '{\n "x": "y",\n "foo": "bar"\n}'); content = '{\n "x": "y"\n}'; edits = setProperty(content, ['e'], 'null', formatterOptions); assertEdit(content, edits, '{\n "x": "y",\n "e": "null"\n}'); edits = setProperty(content, ['x'], 'bar', formatterOptions); assertEdit(content, edits, '{\n "x": "bar"\n}'); content = '{\n "x": {\n "a": 1,\n "b": true\n }\n}\n'; edits = setProperty(content, ['x'], 'bar', formatterOptions); assertEdit(content, edits, '{\n "x": "bar"\n}\n'); edits = setProperty(content, ['x', 'b'], 'bar', formatterOptions); assertEdit(content, edits, '{\n "x": {\n "a": 1,\n "b": "bar"\n }\n}\n'); edits = setProperty(content, ['x', 'c'], 'bar', formatterOptions, () => 0); assertEdit(content, edits, '{\n "x": {\n "c": "bar",\n "a": 1,\n "b": true\n }\n}\n'); edits = setProperty(content, ['x', 'c'], 'bar', formatterOptions, () => 1); assertEdit(content, edits, '{\n "x": {\n "a": 1,\n "c": "bar",\n "b": true\n }\n}\n'); edits = setProperty(content, ['x', 'c'], 'bar', formatterOptions, () => 2); assertEdit(content, edits, '{\n "x": {\n "a": 1,\n "b": true,\n "c": "bar"\n }\n}\n'); edits = setProperty(content, ['c'], 'bar', formatterOptions); assertEdit(content, edits, '{\n "x": {\n "a": 1,\n "b": true\n },\n "c": "bar"\n}\n'); content = '{\n "a": [\n {\n } \n ] \n}'; edits = setProperty(content, ['foo'], 'bar', formatterOptions); assertEdit(content, edits, '{\n "a": [\n {\n } \n ],\n "foo": "bar"\n}'); content = ''; edits = setProperty(content, ['foo', 0], 'bar', formatterOptions); assertEdit(content, edits, '{\n "foo": [\n "bar"\n ]\n}'); content = '//comment'; edits = setProperty(content, ['foo', 0], 'bar', formatterOptions); assertEdit(content, edits, '{\n "foo": [\n "bar"\n ]\n} //comment'); }); test('remove property', () => { let content = '{\n "x": "y"\n}'; let edits = removeProperty(content, ['x'], formatterOptions); assertEdit(content, edits, '{\n}'); content = '{\n "x": "y", "a": []\n}'; edits = removeProperty(content, ['x'], formatterOptions); assertEdit(content, edits, '{\n "a": []\n}'); content = '{\n "x": "y", "a": []\n}'; edits = removeProperty(content, ['a'], formatterOptions); assertEdit(content, edits, '{\n "x": "y"\n}'); }); test('insert item to empty array', () => { let content = '[\n]'; let edits = setProperty(content, [-1], 'bar', formatterOptions); assertEdit(content, edits, '[\n "bar"\n]'); }); test('insert item', () => { let content = '[\n 1,\n 2\n]'; let edits = setProperty(content, [-1], 'bar', formatterOptions); assertEdit(content, edits, '[\n 1,\n 2,\n "bar"\n]'); }); test('remove item in array with one item', () => { let content = '[\n 1\n]'; let edits = setProperty(content, [0], undefined, formatterOptions); assertEdit(content, edits, '[]'); }); test('remove item in the middle of the array', () => { let content = '[\n 1,\n 2,\n 3\n]'; let edits = setProperty(content, [1], undefined, formatterOptions); assertEdit(content, edits, '[\n 1,\n 3\n]'); }); test('remove last item in the array', () => { let content = '[\n 1,\n 2,\n "bar"\n]'; let edits = setProperty(content, [2], undefined, formatterOptions); assertEdit(content, edits, '[\n 1,\n 2\n]'); }); test('remove last item in the array if ends with comma', () => { let content = '[\n 1,\n "foo",\n "bar",\n]'; let edits = setProperty(content, [2], undefined, formatterOptions); assertEdit(content, edits, '[\n 1,\n "foo"\n]'); }); test('remove last item in the array if there is a comment in the beginning', () => { let content = '// This is a comment\n[\n 1,\n "foo",\n "bar"\n]'; let edits = setProperty(content, [2], undefined, formatterOptions); assertEdit(content, edits, '// This is a comment\n[\n 1,\n "foo"\n]'); }); });
src/vs/base/test/common/jsonEdit.test.ts
0
https://github.com/microsoft/vscode/commit/f07c7d705629bea1c6f5af42b7d3f7d72e225f2a
[ 0.00031970060081221163, 0.00018240342615172267, 0.00016947068797890097, 0.00017428604769520462, 0.00003440757063799538 ]
{ "id": 14, "code_window": [ "\t\t\t\treturn Promise.resolve(false);\n", "\t\t\t} else if (!stat.isDirectory && !this.allowFileSelection) {\n", "\t\t\t\t// File selected when file selection not permitted\n", "\t\t\t\treturn Promise.resolve(false);\n", "\t\t\t}\n", "\t\t}\n", "\t\treturn Promise.resolve(true);\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\tthis.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateFolderOnly', 'Please select a folder.');\n" ], "file_path": "src/vs/workbench/services/dialogs/electron-browser/remoteFileDialog.ts", "type": "add", "edit_start_line_idx": 371 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Registry } from 'vs/platform/registry/common/platform'; import { Action, IAction } from 'vs/base/common/actions'; import { BaseActionItem, Separator } from 'vs/base/browser/ui/actionbar/actionbar'; import { ITree, IActionProvider } from 'vs/base/parts/tree/browser/tree'; import { IInstantiationService, IConstructorSignature0, ServicesAccessor } from 'vs/platform/instantiation/common/instantiation'; /** * The action bar contributor allows to add actions to an actionbar in a given context. */ export class ActionBarContributor { /** * Returns true if this contributor has actions for the given context. */ hasActions(context: any): boolean { return false; } /** * Returns an array of primary actions in the given context. */ getActions(context: any): IAction[] { return []; } /** * Returns true if this contributor has secondary actions for the given context. */ hasSecondaryActions(context: any): boolean { return false; } /** * Returns an array of secondary actions in the given context. */ getSecondaryActions(context: any): IAction[] { return []; } /** * Can return a specific IActionItem to render the given action. */ getActionItem(context: any, action: Action): BaseActionItem | null { return null; } } /** * Some predefined scopes to contribute actions to */ export const Scope = { /** * Actions inside tree widgets. */ VIEWER: 'viewer' }; /** * The ContributableActionProvider leverages the actionbar contribution model to find actions. */ export class ContributableActionProvider implements IActionProvider { private registry: IActionBarRegistry; constructor() { this.registry = Registry.as<IActionBarRegistry>(Extensions.Actionbar); } private toContext(tree: ITree, element: any): any { return { viewer: tree, element: element }; } hasActions(tree: ITree, element: any): boolean { const context = this.toContext(tree, element); const contributors = this.registry.getActionBarContributors(Scope.VIEWER); for (const contributor of contributors) { if (contributor.hasActions(context)) { return true; } } return false; } getActions(tree: ITree, element: any): IAction[] { const actions: IAction[] = []; const context = this.toContext(tree, element); // Collect Actions const contributors = this.registry.getActionBarContributors(Scope.VIEWER); for (const contributor of contributors) { if (contributor.hasActions(context)) { actions.push(...contributor.getActions(context)); } } return prepareActions(actions); } hasSecondaryActions(tree: ITree, element: any): boolean { const context = this.toContext(tree, element); const contributors = this.registry.getActionBarContributors(Scope.VIEWER); for (const contributor of contributors) { if (contributor.hasSecondaryActions(context)) { return true; } } return false; } getSecondaryActions(tree: ITree, element: any): IAction[] { const actions: IAction[] = []; const context = this.toContext(tree, element); // Collect Actions const contributors = this.registry.getActionBarContributors(Scope.VIEWER); for (const contributor of contributors) { if (contributor.hasSecondaryActions(context)) { actions.push(...contributor.getSecondaryActions(context)); } } return prepareActions(actions); } getActionItem(tree: ITree, element: any, action: Action): BaseActionItem | null { const contributors = this.registry.getActionBarContributors(Scope.VIEWER); const context = this.toContext(tree, element); for (let i = contributors.length - 1; i >= 0; i--) { const contributor = contributors[i]; const itemProvider = contributor.getActionItem(context, action); if (itemProvider) { return itemProvider; } } return null; } } // Helper function used in parts to massage actions before showing in action areas export function prepareActions(actions: IAction[]): IAction[] { if (!actions.length) { return actions; } // Clean up leading separators let firstIndexOfAction = -1; for (let i = 0; i < actions.length; i++) { if (actions[i].id === Separator.ID) { continue; } firstIndexOfAction = i; break; } if (firstIndexOfAction === -1) { return []; } actions = actions.slice(firstIndexOfAction); // Clean up trailing separators for (let h = actions.length - 1; h >= 0; h--) { const isSeparator = actions[h].id === Separator.ID; if (isSeparator) { actions.splice(h, 1); } else { break; } } // Clean up separator duplicates let foundAction = false; for (let k = actions.length - 1; k >= 0; k--) { const isSeparator = actions[k].id === Separator.ID; if (isSeparator && !foundAction) { actions.splice(k, 1); } else if (!isSeparator) { foundAction = true; } else if (isSeparator) { foundAction = false; } } return actions; } export const Extensions = { Actionbar: 'workbench.contributions.actionbar' }; export interface IActionBarRegistry { /** * Goes through all action bar contributors and asks them for contributed actions for * the provided scope and context. Supports primary actions. */ getActionBarActionsForContext(scope: string, context: any): IAction[]; /** * Goes through all action bar contributors and asks them for contributed actions for * the provided scope and context. Supports secondary actions. */ getSecondaryActionBarActionsForContext(scope: string, context: any): IAction[]; /** * Goes through all action bar contributors and asks them for contributed action item for * the provided scope and context. */ getActionItemForContext(scope: string, context: any, action: Action): BaseActionItem | null; /** * Registers an Actionbar contributor. It will be called to contribute actions to all the action bars * that are used in the Workbench in the given scope. */ registerActionBarContributor(scope: string, ctor: IConstructorSignature0<ActionBarContributor>): void; /** * Returns an array of registered action bar contributors known to the workbench for the given scope. */ getActionBarContributors(scope: string): ActionBarContributor[]; /** * Starts the registry by providing the required services. */ start(accessor: ServicesAccessor): void; } class ActionBarRegistry implements IActionBarRegistry { private actionBarContributorConstructors: { scope: string; ctor: IConstructorSignature0<ActionBarContributor>; }[] = []; private actionBarContributorInstances: { [scope: string]: ActionBarContributor[] } = Object.create(null); private instantiationService: IInstantiationService; start(accessor: ServicesAccessor): void { this.instantiationService = accessor.get(IInstantiationService); while (this.actionBarContributorConstructors.length > 0) { const entry = this.actionBarContributorConstructors.shift()!; this.createActionBarContributor(entry.scope, entry.ctor); } } private createActionBarContributor(scope: string, ctor: IConstructorSignature0<ActionBarContributor>): void { const instance = this.instantiationService.createInstance(ctor); let target = this.actionBarContributorInstances[scope]; if (!target) { target = this.actionBarContributorInstances[scope] = []; } target.push(instance); } private getContributors(scope: string): ActionBarContributor[] { return this.actionBarContributorInstances[scope] || []; } getActionBarActionsForContext(scope: string, context: any): IAction[] { const actions: IAction[] = []; // Go through contributors for scope this.getContributors(scope).forEach((contributor: ActionBarContributor) => { // Primary Actions if (contributor.hasActions(context)) { actions.push(...contributor.getActions(context)); } }); return actions; } getSecondaryActionBarActionsForContext(scope: string, context: any): IAction[] { const actions: IAction[] = []; // Go through contributors this.getContributors(scope).forEach((contributor: ActionBarContributor) => { // Secondary Actions if (contributor.hasSecondaryActions(context)) { actions.push(...contributor.getSecondaryActions(context)); } }); return actions; } getActionItemForContext(scope: string, context: any, action: Action): BaseActionItem | null { const contributors = this.getContributors(scope); for (const contributor of contributors) { const item = contributor.getActionItem(context, action); if (item) { return item; } } return null; } registerActionBarContributor(scope: string, ctor: IConstructorSignature0<ActionBarContributor>): void { if (!this.instantiationService) { this.actionBarContributorConstructors.push({ scope: scope, ctor: ctor }); } else { this.createActionBarContributor(scope, ctor); } } getActionBarContributors(scope: string): ActionBarContributor[] { return this.getContributors(scope).slice(0); } } Registry.add(Extensions.Actionbar, new ActionBarRegistry());
src/vs/workbench/browser/actions.ts
0
https://github.com/microsoft/vscode/commit/f07c7d705629bea1c6f5af42b7d3f7d72e225f2a
[ 0.00017640303121879697, 0.00017127665341831744, 0.00016514981689397246, 0.00017182889860123396, 0.00000294603319161979 ]
{ "id": 14, "code_window": [ "\t\t\t\treturn Promise.resolve(false);\n", "\t\t\t} else if (!stat.isDirectory && !this.allowFileSelection) {\n", "\t\t\t\t// File selected when file selection not permitted\n", "\t\t\t\treturn Promise.resolve(false);\n", "\t\t\t}\n", "\t\t}\n", "\t\treturn Promise.resolve(true);\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\tthis.filePickBox.validationMessage = nls.localize('remoteFileDialog.validateFolderOnly', 'Please select a folder.');\n" ], "file_path": "src/vs/workbench/services/dialogs/electron-browser/remoteFileDialog.ts", "type": "add", "edit_start_line_idx": 371 }
[ { "c": "var", "t": "source.swift keyword.other.declaration-specifier.swift", "r": { "dark_plus": "keyword: #569CD6", "light_plus": "keyword: #0000FF", "dark_vs": "keyword: #569CD6", "light_vs": "keyword: #0000FF", "hc_black": "keyword: #569CD6" } }, { "c": " teamScore ", "t": "source.swift", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "=", "t": "source.swift keyword.operator.custom.infix.swift", "r": { "dark_plus": "keyword.operator: #D4D4D4", "light_plus": "keyword.operator: #000000", "dark_vs": "keyword.operator: #D4D4D4", "light_vs": "keyword.operator: #000000", "hc_black": "keyword.operator: #D4D4D4" } }, { "c": " ", "t": "source.swift", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "0", "t": "source.swift constant.numeric.integer.decimal.swift", "r": { "dark_plus": "constant.numeric: #B5CEA8", "light_plus": "constant.numeric: #09885A", "dark_vs": "constant.numeric: #B5CEA8", "light_vs": "constant.numeric: #09885A", "hc_black": "constant.numeric: #B5CEA8" } }, { "c": "var", "t": "source.swift keyword.other.declaration-specifier.swift", "r": { "dark_plus": "keyword: #569CD6", "light_plus": "keyword: #0000FF", "dark_vs": "keyword: #569CD6", "light_vs": "keyword: #0000FF", "hc_black": "keyword: #569CD6" } }, { "c": " greeting ", "t": "source.swift", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "=", "t": "source.swift keyword.operator.custom.infix.swift", "r": { "dark_plus": "keyword.operator: #D4D4D4", "light_plus": "keyword.operator: #000000", "dark_vs": "keyword.operator: #D4D4D4", "light_vs": "keyword.operator: #000000", "hc_black": "keyword.operator: #D4D4D4" } }, { "c": " ", "t": "source.swift", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "\"", "t": "source.swift string.quoted.double.single-line.swift punctuation.definition.string.begin.swift", "r": { "dark_plus": "string: #CE9178", "light_plus": "string: #A31515", "dark_vs": "string: #CE9178", "light_vs": "string: #A31515", "hc_black": "string: #CE9178" } }, { "c": "Hello!", "t": "source.swift string.quoted.double.single-line.swift", "r": { "dark_plus": "string: #CE9178", "light_plus": "string: #A31515", "dark_vs": "string: #CE9178", "light_vs": "string: #A31515", "hc_black": "string: #CE9178" } }, { "c": "\"", "t": "source.swift string.quoted.double.single-line.swift punctuation.definition.string.end.swift", "r": { "dark_plus": "string: #CE9178", "light_plus": "string: #A31515", "dark_vs": "string: #CE9178", "light_vs": "string: #A31515", "hc_black": "string: #CE9178" } }, { "c": "var", "t": "source.swift keyword.other.declaration-specifier.swift", "r": { "dark_plus": "keyword: #569CD6", "light_plus": "keyword: #0000FF", "dark_vs": "keyword: #569CD6", "light_vs": "keyword: #0000FF", "hc_black": "keyword: #569CD6" } }, { "c": " multiLineString ", "t": "source.swift", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "=", "t": "source.swift keyword.operator.custom.infix.swift", "r": { "dark_plus": "keyword.operator: #D4D4D4", "light_plus": "keyword.operator: #000000", "dark_vs": "keyword.operator: #D4D4D4", "light_vs": "keyword.operator: #000000", "hc_black": "keyword.operator: #D4D4D4" } }, { "c": " ", "t": "source.swift", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "\"\"\"", "t": "source.swift string.quoted.double.block.swift punctuation.definition.string.begin.swift", "r": { "dark_plus": "string: #CE9178", "light_plus": "string: #A31515", "dark_vs": "string: #CE9178", "light_vs": "string: #A31515", "hc_black": "string: #CE9178" } }, { "c": " This is a multi-line string!", "t": "source.swift string.quoted.double.block.swift", "r": { "dark_plus": "string: #CE9178", "light_plus": "string: #A31515", "dark_vs": "string: #CE9178", "light_vs": "string: #A31515", "hc_black": "string: #CE9178" } }, { "c": "\"\"\"", "t": "source.swift string.quoted.double.block.swift punctuation.definition.string.end.swift", "r": { "dark_plus": "string: #CE9178", "light_plus": "string: #A31515", "dark_vs": "string: #CE9178", "light_vs": "string: #A31515", "hc_black": "string: #CE9178" } }, { "c": "func", "t": "source.swift meta.definition.function.swift storage.type.function.swift", "r": { "dark_plus": "storage.type: #569CD6", "light_plus": "storage.type: #0000FF", "dark_vs": "storage.type: #569CD6", "light_vs": "storage.type: #0000FF", "hc_black": "storage.type: #569CD6" } }, { "c": " ", "t": "source.swift meta.definition.function.swift", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "hasAnyMatches", "t": "source.swift meta.definition.function.swift entity.name.function.swift", "r": { "dark_plus": "entity.name.function: #DCDCAA", "light_plus": "entity.name.function: #795E26", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "entity.name.function: #DCDCAA" } }, { "c": "(", "t": "source.swift meta.definition.function.swift meta.parameter-clause.swift punctuation.definition.parameters.begin.swift", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "list", "t": "source.swift meta.definition.function.swift meta.parameter-clause.swift variable.parameter.function.swift entity.name.function.swift", "r": { "dark_plus": "entity.name.function: #DCDCAA", "light_plus": "entity.name.function: #795E26", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "entity.name.function: #DCDCAA" } }, { "c": ": ", "t": "source.swift meta.definition.function.swift meta.parameter-clause.swift", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "[", "t": "source.swift meta.definition.function.swift meta.parameter-clause.swift punctuation.section.collection-type.begin.swift", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "Int", "t": "source.swift meta.definition.function.swift meta.parameter-clause.swift support.type.swift", "r": { "dark_plus": "support.type: #4EC9B0", "light_plus": "support.type: #267F99", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "support.type: #4EC9B0" } }, { "c": "]", "t": "source.swift meta.definition.function.swift meta.parameter-clause.swift punctuation.section.collection-type.end.swift", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": ", ", "t": "source.swift meta.definition.function.swift meta.parameter-clause.swift", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "condition", "t": "source.swift meta.definition.function.swift meta.parameter-clause.swift variable.parameter.function.swift entity.name.function.swift", "r": { "dark_plus": "entity.name.function: #DCDCAA", "light_plus": "entity.name.function: #795E26", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "entity.name.function: #DCDCAA" } }, { "c": ": ", "t": "source.swift meta.definition.function.swift meta.parameter-clause.swift", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "(", "t": "source.swift meta.definition.function.swift meta.parameter-clause.swift punctuation.section.tuple-type.begin.swift", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "Int", "t": "source.swift meta.definition.function.swift meta.parameter-clause.swift support.type.swift", "r": { "dark_plus": "support.type: #4EC9B0", "light_plus": "support.type: #267F99", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "support.type: #4EC9B0" } }, { "c": ")", "t": "source.swift meta.definition.function.swift meta.parameter-clause.swift punctuation.section.tuple-type.end.swift", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": " ", "t": "source.swift meta.definition.function.swift meta.parameter-clause.swift", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "->", "t": "source.swift meta.definition.function.swift meta.parameter-clause.swift keyword.operator.type.function.swift", "r": { "dark_plus": "keyword.operator: #D4D4D4", "light_plus": "keyword.operator: #000000", "dark_vs": "keyword.operator: #D4D4D4", "light_vs": "keyword.operator: #000000", "hc_black": "keyword.operator: #D4D4D4" } }, { "c": " ", "t": "source.swift meta.definition.function.swift meta.parameter-clause.swift", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "Bool", "t": "source.swift meta.definition.function.swift meta.parameter-clause.swift support.type.swift", "r": { "dark_plus": "support.type: #4EC9B0", "light_plus": "support.type: #267F99", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "support.type: #4EC9B0" } }, { "c": ")", "t": "source.swift meta.definition.function.swift meta.parameter-clause.swift punctuation.definition.parameters.end.swift", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": " ", "t": "source.swift meta.definition.function.swift", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "->", "t": "source.swift meta.definition.function.swift meta.function-result.swift keyword.operator.function-result.swift", "r": { "dark_plus": "keyword.operator: #D4D4D4", "light_plus": "keyword.operator: #000000", "dark_vs": "keyword.operator: #D4D4D4", "light_vs": "keyword.operator: #000000", "hc_black": "keyword.operator: #D4D4D4" } }, { "c": " ", "t": "source.swift meta.definition.function.swift meta.function-result.swift", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "Bool", "t": "source.swift meta.definition.function.swift meta.function-result.swift support.type.swift", "r": { "dark_plus": "support.type: #4EC9B0", "light_plus": "support.type: #267F99", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "support.type: #4EC9B0" } }, { "c": " ", "t": "source.swift meta.definition.function.swift meta.function-result.swift", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "{", "t": "source.swift meta.definition.function.swift meta.definition.function.body.swift punctuation.section.function.begin.swift", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": " ", "t": "source.swift meta.definition.function.swift meta.definition.function.body.swift", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "for", "t": "source.swift meta.definition.function.swift meta.definition.function.body.swift keyword.control.loop.swift", "r": { "dark_plus": "keyword.control: #C586C0", "light_plus": "keyword.control: #AF00DB", "dark_vs": "keyword.control: #569CD6", "light_vs": "keyword.control: #0000FF", "hc_black": "keyword.control: #C586C0" } }, { "c": " item ", "t": "source.swift meta.definition.function.swift meta.definition.function.body.swift", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "in", "t": "source.swift meta.definition.function.swift meta.definition.function.body.swift keyword.control.loop.swift", "r": { "dark_plus": "keyword.control: #C586C0", "light_plus": "keyword.control: #AF00DB", "dark_vs": "keyword.control: #569CD6", "light_vs": "keyword.control: #0000FF", "hc_black": "keyword.control: #C586C0" } }, { "c": " list ", "t": "source.swift meta.definition.function.swift meta.definition.function.body.swift", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "{", "t": "source.swift meta.definition.function.swift meta.definition.function.body.swift punctuation.section.scope.begin.swift", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": " ", "t": "source.swift meta.definition.function.swift meta.definition.function.body.swift", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "if", "t": "source.swift meta.definition.function.swift meta.definition.function.body.swift keyword.control.branch.swift", "r": { "dark_plus": "keyword.control: #C586C0", "light_plus": "keyword.control: #AF00DB", "dark_vs": "keyword.control: #569CD6", "light_vs": "keyword.control: #0000FF", "hc_black": "keyword.control: #C586C0" } }, { "c": " ", "t": "source.swift meta.definition.function.swift meta.definition.function.body.swift", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "condition", "t": "source.swift meta.definition.function.swift meta.definition.function.body.swift meta.function-call.swift support.function.any-method.swift", "r": { "dark_plus": "support.function: #DCDCAA", "light_plus": "support.function: #795E26", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "support.function: #DCDCAA" } }, { "c": "(", "t": "source.swift meta.definition.function.swift meta.definition.function.body.swift meta.function-call.swift punctuation.definition.arguments.begin.swift", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "item", "t": "source.swift meta.definition.function.swift meta.definition.function.body.swift meta.function-call.swift", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": ")", "t": "source.swift meta.definition.function.swift meta.definition.function.body.swift meta.function-call.swift punctuation.definition.arguments.end.swift", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": " ", "t": "source.swift meta.definition.function.swift meta.definition.function.body.swift", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "{", "t": "source.swift meta.definition.function.swift meta.definition.function.body.swift punctuation.section.scope.begin.swift", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": " ", "t": "source.swift meta.definition.function.swift meta.definition.function.body.swift", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "return", "t": "source.swift meta.definition.function.swift meta.definition.function.body.swift keyword.control.transfer.swift", "r": { "dark_plus": "keyword.control: #C586C0", "light_plus": "keyword.control: #AF00DB", "dark_vs": "keyword.control: #569CD6", "light_vs": "keyword.control: #0000FF", "hc_black": "keyword.control: #C586C0" } }, { "c": " ", "t": "source.swift meta.definition.function.swift meta.definition.function.body.swift", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "true", "t": "source.swift meta.definition.function.swift meta.definition.function.body.swift constant.language.boolean.swift", "r": { "dark_plus": "constant.language: #569CD6", "light_plus": "constant.language: #0000FF", "dark_vs": "constant.language: #569CD6", "light_vs": "constant.language: #0000FF", "hc_black": "constant.language: #569CD6" } }, { "c": " ", "t": "source.swift meta.definition.function.swift meta.definition.function.body.swift", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "}", "t": "source.swift meta.definition.function.swift meta.definition.function.body.swift punctuation.section.scope.end.swift", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": " ", "t": "source.swift meta.definition.function.swift meta.definition.function.body.swift", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "}", "t": "source.swift meta.definition.function.swift meta.definition.function.body.swift punctuation.section.scope.end.swift", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": " ", "t": "source.swift meta.definition.function.swift meta.definition.function.body.swift", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "return", "t": "source.swift meta.definition.function.swift meta.definition.function.body.swift keyword.control.transfer.swift", "r": { "dark_plus": "keyword.control: #C586C0", "light_plus": "keyword.control: #AF00DB", "dark_vs": "keyword.control: #569CD6", "light_vs": "keyword.control: #0000FF", "hc_black": "keyword.control: #C586C0" } }, { "c": " ", "t": "source.swift meta.definition.function.swift meta.definition.function.body.swift", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } }, { "c": "false", "t": "source.swift meta.definition.function.swift meta.definition.function.body.swift constant.language.boolean.swift", "r": { "dark_plus": "constant.language: #569CD6", "light_plus": "constant.language: #0000FF", "dark_vs": "constant.language: #569CD6", "light_vs": "constant.language: #0000FF", "hc_black": "constant.language: #569CD6" } }, { "c": "}", "t": "source.swift meta.definition.function.swift meta.definition.function.body.swift punctuation.section.function.end.swift", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF" } } ]
extensions/swift/test/colorize-results/test_swift.json
0
https://github.com/microsoft/vscode/commit/f07c7d705629bea1c6f5af42b7d3f7d72e225f2a
[ 0.000176411762367934, 0.00017334539734292775, 0.0001704844762571156, 0.00017349830886814743, 0.000001360033024866425 ]
{ "id": 0, "code_window": [ "\t) {\n", "\t\tsuper();\n", "\t\tthis._proxy = extHostContext.getProxy(ExtHostContext.ExtHostTreeViews);\n", "\t}\n", "\n", "\t$registerTreeViewDataProvider(treeViewId: string, options: { showCollapseAll: boolean, canSelectMany: boolean }): void {\n", "\t\tthis.logService.trace('MainThreadTreeViews#$registerTreeViewDataProvider', treeViewId, options);\n", "\n", "\t\tthis.extensionService.whenInstalledExtensionsRegistered().then(() => {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\tasync $registerTreeViewDataProvider(treeViewId: string, options: { showCollapseAll: boolean, canSelectMany: boolean }): Promise<void> {\n" ], "file_path": "src/vs/workbench/api/browser/mainThreadTreeViews.ts", "type": "replace", "edit_start_line_idx": 33 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as performance from 'vs/base/common/performance'; import { VSBuffer } from 'vs/base/common/buffer'; import { CancellationToken } from 'vs/base/common/cancellation'; import { IRemoteConsoleLog } from 'vs/base/common/console'; import { SerializedError } from 'vs/base/common/errors'; import { IRelativePattern } from 'vs/base/common/glob'; import { IMarkdownString } from 'vs/base/common/htmlContent'; import { IDisposable } from 'vs/base/common/lifecycle'; import Severity from 'vs/base/common/severity'; import { URI, UriComponents } from 'vs/base/common/uri'; import { RenderLineNumbersType, TextEditorCursorStyle } from 'vs/editor/common/config/editorOptions'; import { IPosition } from 'vs/editor/common/core/position'; import { IRange } from 'vs/editor/common/core/range'; import { ISelection, Selection } from 'vs/editor/common/core/selection'; import * as editorCommon from 'vs/editor/common/editorCommon'; import { EndOfLineSequence, ISingleEditOperation } from 'vs/editor/common/model'; import { IModelChangedEvent } from 'vs/editor/common/model/mirrorTextModel'; import * as modes from 'vs/editor/common/modes'; import { CharacterPair, CommentRule, EnterAction } from 'vs/editor/common/modes/languageConfiguration'; import { ICommandHandlerDescription } from 'vs/platform/commands/common/commands'; import { ConfigurationTarget, IConfigurationData, IConfigurationChange, IConfigurationOverrides } from 'vs/platform/configuration/common/configuration'; import { ConfigurationScope } from 'vs/platform/configuration/common/configurationRegistry'; import { ExtensionIdentifier, IExtensionDescription } from 'vs/platform/extensions/common/extensions'; import * as files from 'vs/platform/files/common/files'; import { ResourceLabelFormatter } from 'vs/platform/label/common/label'; import { LogLevel } from 'vs/platform/log/common/log'; import { IMarkerData } from 'vs/platform/markers/common/markers'; import { IProgressOptions, IProgressStep } from 'vs/platform/progress/common/progress'; import * as quickInput from 'vs/platform/quickinput/common/quickInput'; import { RemoteAuthorityResolverErrorCode, ResolverResult, TunnelDescription, IRemoteConnectionData } from 'vs/platform/remote/common/remoteAuthorityResolver'; import * as statusbar from 'vs/workbench/services/statusbar/common/statusbar'; import { ClassifiedEvent, GDPRClassification, StrictPropertyCheck } from 'vs/platform/telemetry/common/gdprTypings'; import { ITelemetryInfo } from 'vs/platform/telemetry/common/telemetry'; import { ThemeColor } from 'vs/platform/theme/common/themeService'; import * as tasks from 'vs/workbench/api/common/shared/tasks'; import { IRevealOptions, ITreeItem } from 'vs/workbench/common/views'; import { IAdapterDescriptor, IConfig, IDebugSessionReplMode } from 'vs/workbench/contrib/debug/common/debug'; import { ITextQueryBuilderOptions } from 'vs/workbench/contrib/search/common/queryBuilder'; import { ITerminalDimensions, IShellLaunchConfig, ITerminalLaunchError } from 'vs/workbench/contrib/terminal/common/terminal'; import { ActivationKind, ExtensionActivationError, ExtensionHostKind } from 'vs/workbench/services/extensions/common/extensions'; import { createExtHostContextProxyIdentifier as createExtId, createMainContextProxyIdentifier as createMainId, IRPCProtocol } from 'vs/workbench/services/extensions/common/proxyIdentifier'; import * as search from 'vs/workbench/services/search/common/search'; import { EditorGroupColumn, SaveReason } from 'vs/workbench/common/editor'; import { ExtensionActivationReason } from 'vs/workbench/api/common/extHostExtensionActivator'; import { TunnelDto } from 'vs/workbench/api/common/extHostTunnelService'; import { TunnelCreationOptions, TunnelProviderFeatures, TunnelOptions } from 'vs/platform/remote/common/tunnel'; import { Timeline, TimelineChangeEvent, TimelineOptions, TimelineProviderDescriptor, InternalTimelineOptions } from 'vs/workbench/contrib/timeline/common/timeline'; import { revive } from 'vs/base/common/marshalling'; import { INotebookDisplayOrder, NotebookCellMetadata, NotebookDocumentMetadata, ICellEditOperation, NotebookCellsChangedEventDto, NotebookDataDto, IMainCellDto, INotebookDocumentFilter, TransientMetadata, INotebookCellStatusBarEntry, ICellRange, INotebookDecorationRenderOptions, INotebookExclusiveDocumentFilter, IOutputDto } from 'vs/workbench/contrib/notebook/common/notebookCommon'; import { CallHierarchyItem } from 'vs/workbench/contrib/callHierarchy/common/callHierarchy'; import { Dto } from 'vs/base/common/types'; import { ISerializableEnvironmentVariableCollection } from 'vs/workbench/contrib/terminal/common/environmentVariable'; import { DebugConfigurationProviderTriggerKind, WorkspaceTrustState } from 'vs/workbench/api/common/extHostTypes'; import { IAccessibilityInformation } from 'vs/platform/accessibility/common/accessibility'; import { IExtensionIdWithVersion } from 'vs/platform/userDataSync/common/extensionsStorageSync'; import { InternalTestItem, InternalTestResults, ITestState, RunTestForProviderRequest, RunTestsRequest, TestIdWithProvider, TestsDiff } from 'vs/workbench/contrib/testing/common/testCollection'; import { CandidatePort } from 'vs/workbench/services/remote/common/remoteExplorerService'; import { WorkspaceTrustStateChangeEvent } from 'vs/platform/workspace/common/workspaceTrust'; export interface IEnvironment { isExtensionDevelopmentDebug: boolean; appName: string; appRoot?: URI; appLanguage: string; appUriScheme: string; extensionDevelopmentLocationURI?: URI[]; extensionTestsLocationURI?: URI; globalStorageHome: URI; workspaceStorageHome: URI; webviewResourceRoot: string; webviewCspSource: string; useHostProxy?: boolean; } export interface IStaticWorkspaceData { id: string; name: string; configuration?: UriComponents | null; isUntitled?: boolean | null; } export interface IWorkspaceData extends IStaticWorkspaceData { folders: { uri: UriComponents, name: string, index: number; }[]; } export interface IInitData { version: string; commit?: string; parentPid: number; environment: IEnvironment; workspace?: IStaticWorkspaceData | null; resolvedExtensions: ExtensionIdentifier[]; hostExtensions: ExtensionIdentifier[]; extensions: IExtensionDescription[]; telemetryInfo: ITelemetryInfo; logLevel: LogLevel; logsLocation: URI; logFile: URI; autoStart: boolean; remote: { isRemote: boolean; authority: string | undefined; connectionData: IRemoteConnectionData | null; }; uiKind: UIKind; } export interface IConfigurationInitData extends IConfigurationData { configurationScopes: [string, ConfigurationScope | undefined][]; } export interface IExtHostContext extends IRPCProtocol { readonly remoteAuthority: string | null; readonly extensionHostKind: ExtensionHostKind; } export interface IMainContext extends IRPCProtocol { } export enum UIKind { Desktop = 1, Web = 2 } // --- main thread export interface MainThreadClipboardShape extends IDisposable { $readText(): Promise<string>; $writeText(value: string): Promise<void>; } export interface MainThreadCommandsShape extends IDisposable { $registerCommand(id: string): void; $unregisterCommand(id: string): void; $executeCommand<T>(id: string, args: any[], retry: boolean): Promise<T | undefined>; $getCommands(): Promise<string[]>; } export interface CommentProviderFeatures { reactionGroup?: modes.CommentReaction[]; reactionHandler?: boolean; options?: modes.CommentOptions; } export type CommentThreadChanges = Partial<{ range: IRange, label: string, contextValue: string, comments: modes.Comment[], collapseState: modes.CommentThreadCollapsibleState; canReply: boolean; }>; export interface MainThreadCommentsShape extends IDisposable { $registerCommentController(handle: number, id: string, label: string): void; $unregisterCommentController(handle: number): void; $updateCommentControllerFeatures(handle: number, features: CommentProviderFeatures): void; $createCommentThread(handle: number, commentThreadHandle: number, threadId: string, resource: UriComponents, range: IRange, extensionId: ExtensionIdentifier): modes.CommentThread | undefined; $updateCommentThread(handle: number, commentThreadHandle: number, threadId: string, resource: UriComponents, changes: CommentThreadChanges): void; $deleteCommentThread(handle: number, commentThreadHandle: number): void; $onDidCommentThreadsChange(handle: number, event: modes.CommentThreadChangedEvent): void; } export interface MainThreadAuthenticationShape extends IDisposable { $registerAuthenticationProvider(id: string, label: string, supportsMultipleAccounts: boolean): void; $unregisterAuthenticationProvider(id: string): void; $ensureProvider(id: string): Promise<void>; $sendDidChangeSessions(providerId: string, event: modes.AuthenticationSessionsChangeEvent): void; $getSession(providerId: string, scopes: string[], extensionId: string, extensionName: string, options: { createIfNone?: boolean, clearSessionPreference?: boolean }): Promise<modes.AuthenticationSession | undefined>; $removeSession(providerId: string, sessionId: string): Promise<void>; } export interface MainThreadSecretStateShape extends IDisposable { $getPassword(extensionId: string, key: string): Promise<string | undefined>; $setPassword(extensionId: string, key: string, value: string): Promise<void>; $deletePassword(extensionId: string, key: string): Promise<void>; } export interface MainThreadConfigurationShape extends IDisposable { $updateConfigurationOption(target: ConfigurationTarget | null, key: string, value: any, overrides: IConfigurationOverrides | undefined, scopeToLanguage: boolean | undefined): Promise<void>; $removeConfigurationOption(target: ConfigurationTarget | null, key: string, overrides: IConfigurationOverrides | undefined, scopeToLanguage: boolean | undefined): Promise<void>; } export interface MainThreadDiagnosticsShape extends IDisposable { $changeMany(owner: string, entries: [UriComponents, IMarkerData[] | undefined][]): void; $clear(owner: string): void; } export interface MainThreadDialogOpenOptions { defaultUri?: UriComponents; openLabel?: string; canSelectFiles?: boolean; canSelectFolders?: boolean; canSelectMany?: boolean; filters?: { [name: string]: string[]; }; title?: string; } export interface MainThreadDialogSaveOptions { defaultUri?: UriComponents; saveLabel?: string; filters?: { [name: string]: string[]; }; title?: string; } export interface MainThreadDiaglogsShape extends IDisposable { $showOpenDialog(options?: MainThreadDialogOpenOptions): Promise<UriComponents[] | undefined>; $showSaveDialog(options?: MainThreadDialogSaveOptions): Promise<UriComponents | undefined>; } export interface MainThreadDecorationsShape extends IDisposable { $registerDecorationProvider(handle: number, label: string): void; $unregisterDecorationProvider(handle: number): void; $onDidChange(handle: number, resources: UriComponents[] | null): void; } export interface MainThreadDocumentContentProvidersShape extends IDisposable { $registerTextContentProvider(handle: number, scheme: string): void; $unregisterTextContentProvider(handle: number): void; $onVirtualDocumentChange(uri: UriComponents, value: string): void; } export interface MainThreadDocumentsShape extends IDisposable { $tryCreateDocument(options?: { language?: string; content?: string; }): Promise<UriComponents>; $tryOpenDocument(uri: UriComponents): Promise<UriComponents>; $trySaveDocument(uri: UriComponents): Promise<boolean>; } export interface ITextEditorConfigurationUpdate { tabSize?: number | 'auto'; insertSpaces?: boolean | 'auto'; cursorStyle?: TextEditorCursorStyle; lineNumbers?: RenderLineNumbersType; } export interface IResolvedTextEditorConfiguration { tabSize: number; insertSpaces: boolean; cursorStyle: TextEditorCursorStyle; lineNumbers: RenderLineNumbersType; } export enum TextEditorRevealType { Default = 0, InCenter = 1, InCenterIfOutsideViewport = 2, AtTop = 3 } export interface IUndoStopOptions { undoStopBefore: boolean; undoStopAfter: boolean; } export interface IApplyEditsOptions extends IUndoStopOptions { setEndOfLine?: EndOfLineSequence; } export interface ITextDocumentShowOptions { position?: EditorGroupColumn; preserveFocus?: boolean; pinned?: boolean; selection?: IRange; } export interface MainThreadBulkEditsShape extends IDisposable { $tryApplyWorkspaceEdit(workspaceEditDto: IWorkspaceEditDto, undoRedoGroupId?: number): Promise<boolean>; } export interface MainThreadTextEditorsShape extends IDisposable { $tryShowTextDocument(resource: UriComponents, options: ITextDocumentShowOptions): Promise<string | undefined>; $registerTextEditorDecorationType(key: string, options: editorCommon.IDecorationRenderOptions): void; $removeTextEditorDecorationType(key: string): void; $tryShowEditor(id: string, position: EditorGroupColumn): Promise<void>; $tryHideEditor(id: string): Promise<void>; $trySetOptions(id: string, options: ITextEditorConfigurationUpdate): Promise<void>; $trySetDecorations(id: string, key: string, ranges: editorCommon.IDecorationOptions[]): Promise<void>; $trySetDecorationsFast(id: string, key: string, ranges: number[]): Promise<void>; $tryRevealRange(id: string, range: IRange, revealType: TextEditorRevealType): Promise<void>; $trySetSelections(id: string, selections: ISelection[]): Promise<void>; $tryApplyEdits(id: string, modelVersionId: number, edits: ISingleEditOperation[], opts: IApplyEditsOptions): Promise<boolean>; $tryInsertSnippet(id: string, template: string, selections: readonly IRange[], opts: IUndoStopOptions): Promise<boolean>; $getDiffInformation(id: string): Promise<editorCommon.ILineChange[]>; } export interface MainThreadTreeViewsShape extends IDisposable { $registerTreeViewDataProvider(treeViewId: string, options: { showCollapseAll: boolean, canSelectMany: boolean; }): void; $refresh(treeViewId: string, itemsToRefresh?: { [treeItemHandle: string]: ITreeItem; }): Promise<void>; $reveal(treeViewId: string, itemInfo: { item: ITreeItem, parentChain: ITreeItem[] } | undefined, options: IRevealOptions): Promise<void>; $setMessage(treeViewId: string, message: string): void; $setTitle(treeViewId: string, title: string, description: string | undefined): void; } export interface MainThreadDownloadServiceShape extends IDisposable { $download(uri: UriComponents, to: UriComponents): Promise<void>; } export interface MainThreadErrorsShape extends IDisposable { $onUnexpectedError(err: any | SerializedError): void; } export interface MainThreadConsoleShape extends IDisposable { $logExtensionHostMessage(msg: IRemoteConsoleLog): void; } export interface MainThreadKeytarShape extends IDisposable { $getPassword(service: string, account: string): Promise<string | null>; $setPassword(service: string, account: string, password: string): Promise<void>; $deletePassword(service: string, account: string): Promise<boolean>; $findPassword(service: string): Promise<string | null>; $findCredentials(service: string): Promise<Array<{ account: string, password: string; }>>; } export interface IRegExpDto { pattern: string; flags?: string; } export interface IIndentationRuleDto { decreaseIndentPattern: IRegExpDto; increaseIndentPattern: IRegExpDto; indentNextLinePattern?: IRegExpDto; unIndentedLinePattern?: IRegExpDto; } export interface IOnEnterRuleDto { beforeText: IRegExpDto; afterText?: IRegExpDto; previousLineText?: IRegExpDto; action: EnterAction; } export interface ILanguageConfigurationDto { comments?: CommentRule; brackets?: CharacterPair[]; wordPattern?: IRegExpDto; indentationRules?: IIndentationRuleDto; onEnterRules?: IOnEnterRuleDto[]; __electricCharacterSupport?: { brackets?: any; docComment?: { scope: string; open: string; lineStart: string; close?: string; }; }; __characterPairSupport?: { autoClosingPairs: { open: string; close: string; notIn?: string[]; }[]; }; } export type GlobPattern = string | { base: string; pattern: string; }; export interface IDocumentFilterDto { $serialized: true; language?: string; scheme?: string; pattern?: string | IRelativePattern; exclusive?: boolean; } export interface ISignatureHelpProviderMetadataDto { readonly triggerCharacters: readonly string[]; readonly retriggerCharacters: readonly string[]; } export interface MainThreadLanguageFeaturesShape extends IDisposable { $unregister(handle: number): void; $registerDocumentSymbolProvider(handle: number, selector: IDocumentFilterDto[], label: string): void; $registerCodeLensSupport(handle: number, selector: IDocumentFilterDto[], eventHandle: number | undefined): void; $emitCodeLensEvent(eventHandle: number, event?: any): void; $registerDefinitionSupport(handle: number, selector: IDocumentFilterDto[]): void; $registerDeclarationSupport(handle: number, selector: IDocumentFilterDto[]): void; $registerImplementationSupport(handle: number, selector: IDocumentFilterDto[]): void; $registerTypeDefinitionSupport(handle: number, selector: IDocumentFilterDto[]): void; $registerHoverProvider(handle: number, selector: IDocumentFilterDto[]): void; $registerEvaluatableExpressionProvider(handle: number, selector: IDocumentFilterDto[]): void; $registerInlineValuesProvider(handle: number, selector: IDocumentFilterDto[], eventHandle: number | undefined): void; $emitInlineValuesEvent(eventHandle: number, event?: any): void; $registerDocumentHighlightProvider(handle: number, selector: IDocumentFilterDto[]): void; $registerLinkedEditingRangeProvider(handle: number, selector: IDocumentFilterDto[]): void; $registerReferenceSupport(handle: number, selector: IDocumentFilterDto[]): void; $registerQuickFixSupport(handle: number, selector: IDocumentFilterDto[], metadata: ICodeActionProviderMetadataDto, displayName: string, supportsResolve: boolean): void; $registerDocumentFormattingSupport(handle: number, selector: IDocumentFilterDto[], extensionId: ExtensionIdentifier, displayName: string): void; $registerRangeFormattingSupport(handle: number, selector: IDocumentFilterDto[], extensionId: ExtensionIdentifier, displayName: string): void; $registerOnTypeFormattingSupport(handle: number, selector: IDocumentFilterDto[], autoFormatTriggerCharacters: string[], extensionId: ExtensionIdentifier): void; $registerNavigateTypeSupport(handle: number): void; $registerRenameSupport(handle: number, selector: IDocumentFilterDto[], supportsResolveInitialValues: boolean): void; $registerDocumentSemanticTokensProvider(handle: number, selector: IDocumentFilterDto[], legend: modes.SemanticTokensLegend, eventHandle: number | undefined): void; $emitDocumentSemanticTokensEvent(eventHandle: number): void; $registerDocumentRangeSemanticTokensProvider(handle: number, selector: IDocumentFilterDto[], legend: modes.SemanticTokensLegend): void; $registerSuggestSupport(handle: number, selector: IDocumentFilterDto[], triggerCharacters: string[], supportsResolveDetails: boolean, displayName: string): void; $registerSignatureHelpProvider(handle: number, selector: IDocumentFilterDto[], metadata: ISignatureHelpProviderMetadataDto): void; $registerInlineHintsProvider(handle: number, selector: IDocumentFilterDto[], eventHandle: number | undefined): void; $emitInlineHintsEvent(eventHandle: number, event?: any): void; $registerDocumentLinkProvider(handle: number, selector: IDocumentFilterDto[], supportsResolve: boolean): void; $registerDocumentColorProvider(handle: number, selector: IDocumentFilterDto[]): void; $registerFoldingRangeProvider(handle: number, selector: IDocumentFilterDto[], eventHandle: number | undefined): void; $emitFoldingRangeEvent(eventHandle: number, event?: any): void; $registerSelectionRangeProvider(handle: number, selector: IDocumentFilterDto[]): void; $registerCallHierarchyProvider(handle: number, selector: IDocumentFilterDto[]): void; $setLanguageConfiguration(handle: number, languageId: string, configuration: ILanguageConfigurationDto): void; } export interface MainThreadLanguagesShape extends IDisposable { $getLanguages(): Promise<string[]>; $changeLanguage(resource: UriComponents, languageId: string): Promise<void>; $tokensAtPosition(resource: UriComponents, position: IPosition): Promise<undefined | { type: modes.StandardTokenType, range: IRange }>; } export interface MainThreadMessageOptions { extension?: IExtensionDescription; modal?: boolean; useCustom?: boolean; } export interface MainThreadMessageServiceShape extends IDisposable { $showMessage(severity: Severity, message: string, options: MainThreadMessageOptions, commands: { title: string; isCloseAffordance: boolean; handle: number; }[]): Promise<number | undefined>; } export interface MainThreadOutputServiceShape extends IDisposable { $register(label: string, log: boolean, file?: UriComponents): Promise<string>; $append(channelId: string, value: string): Promise<void> | undefined; $update(channelId: string): Promise<void> | undefined; $clear(channelId: string, till: number): Promise<void> | undefined; $reveal(channelId: string, preserveFocus: boolean): Promise<void> | undefined; $close(channelId: string): Promise<void> | undefined; $dispose(channelId: string): Promise<void> | undefined; } export interface MainThreadProgressShape extends IDisposable { $startProgress(handle: number, options: IProgressOptions, extension?: IExtensionDescription): void; $progressReport(handle: number, message: IProgressStep): void; $progressEnd(handle: number): void; } /** * A terminal that is created on the extension host side is temporarily assigned * a UUID by the extension host that created it. Once the renderer side has assigned * a real numeric id, the numeric id will be used. * * All other terminals (that are not created on the extension host side) always * use the numeric id. */ export type TerminalIdentifier = number | string; export interface TerminalLaunchConfig { name?: string; shellPath?: string; shellArgs?: string[] | string; cwd?: string | UriComponents; env?: { [key: string]: string | null; }; waitOnExit?: boolean; strictEnv?: boolean; hideFromUser?: boolean; isExtensionTerminal?: boolean; isFeatureTerminal?: boolean; } export interface MainThreadTerminalServiceShape extends IDisposable { $createTerminal(extHostTerminalId: string, config: TerminalLaunchConfig): Promise<void>; $dispose(id: TerminalIdentifier): void; $hide(id: TerminalIdentifier): void; $sendText(id: TerminalIdentifier, text: string, addNewLine: boolean): void; $show(id: TerminalIdentifier, preserveFocus: boolean): void; $startSendingDataEvents(): void; $stopSendingDataEvents(): void; $startLinkProvider(): void; $stopLinkProvider(): void; $registerProcessSupport(isSupported: boolean): void; $setEnvironmentVariableCollection(extensionIdentifier: string, persistent: boolean, collection: ISerializableEnvironmentVariableCollection | undefined): void; // Process $sendProcessTitle(terminalId: number, title: string): void; $sendProcessData(terminalId: number, data: string): void; $sendProcessReady(terminalId: number, pid: number, cwd: string): void; $sendProcessExit(terminalId: number, exitCode: number | undefined): void; $sendProcessInitialCwd(terminalId: number, cwd: string): void; $sendProcessCwd(terminalId: number, initialCwd: string): void; $sendOverrideDimensions(terminalId: number, dimensions: ITerminalDimensions | undefined): void; $sendResolvedLaunchConfig(terminalId: number, shellLaunchConfig: IShellLaunchConfig): void; } export interface TransferQuickPickItems extends quickInput.IQuickPickItem { handle: number; } export interface TransferQuickInputButton { handle: number; iconPath: { dark: URI; light?: URI; } | { id: string; }; tooltip?: string; } export type TransferQuickInput = TransferQuickPick | TransferInputBox; export interface BaseTransferQuickInput { [key: string]: any; id: number; type?: 'quickPick' | 'inputBox'; enabled?: boolean; busy?: boolean; visible?: boolean; } export interface TransferQuickPick extends BaseTransferQuickInput { type?: 'quickPick'; value?: string; placeholder?: string; buttons?: TransferQuickInputButton[]; items?: TransferQuickPickItems[]; activeItems?: number[]; selectedItems?: number[]; canSelectMany?: boolean; ignoreFocusOut?: boolean; matchOnDescription?: boolean; matchOnDetail?: boolean; sortByLabel?: boolean; } export interface TransferInputBox extends BaseTransferQuickInput { type?: 'inputBox'; value?: string; placeholder?: string; password?: boolean; buttons?: TransferQuickInputButton[]; prompt?: string; validationMessage?: string; } export interface IInputBoxOptions { value?: string; valueSelection?: [number, number]; prompt?: string; placeHolder?: string; password?: boolean; ignoreFocusOut?: boolean; } export interface MainThreadQuickOpenShape extends IDisposable { $show(instance: number, options: quickInput.IPickOptions<TransferQuickPickItems>, token: CancellationToken): Promise<number | number[] | undefined>; $setItems(instance: number, items: TransferQuickPickItems[]): Promise<void>; $setError(instance: number, error: Error): Promise<void>; $input(options: IInputBoxOptions | undefined, validateInput: boolean, token: CancellationToken): Promise<string | undefined>; $createOrUpdate(params: TransferQuickInput): Promise<void>; $dispose(id: number): Promise<void>; } export interface MainThreadStatusBarShape extends IDisposable { $setEntry(id: number, statusId: string, statusName: string, text: string, tooltip: string | undefined, command: ICommandDto | undefined, color: string | ThemeColor | undefined, backgroundColor: string | ThemeColor | undefined, alignment: statusbar.StatusbarAlignment, priority: number | undefined, accessibilityInformation: IAccessibilityInformation | undefined): void; $dispose(id: number): void; } export interface MainThreadStorageShape extends IDisposable { $getValue<T>(shared: boolean, key: string): Promise<T | undefined>; $setValue(shared: boolean, key: string, value: object): Promise<void>; $registerExtensionStorageKeysToSync(extension: IExtensionIdWithVersion, keys: string[]): void; } export interface MainThreadTelemetryShape extends IDisposable { $publicLog(eventName: string, data?: any): void; $publicLog2<E extends ClassifiedEvent<T> = never, T extends GDPRClassification<T> = never>(eventName: string, data?: StrictPropertyCheck<T, E>): void; } export interface MainThreadEditorInsetsShape extends IDisposable { $createEditorInset(handle: number, id: string, uri: UriComponents, line: number, height: number, options: modes.IWebviewOptions, extensionId: ExtensionIdentifier, extensionLocation: UriComponents): Promise<void>; $disposeEditorInset(handle: number): void; $setHtml(handle: number, value: string): void; $setOptions(handle: number, options: modes.IWebviewOptions): void; $postMessage(handle: number, value: any): Promise<boolean>; } export interface ExtHostEditorInsetsShape { $onDidDispose(handle: number): void; $onDidReceiveMessage(handle: number, message: any): void; } //#region --- open editors model export interface MainThreadEditorTabsShape extends IDisposable { // manage tabs: move, close, rearrange etc } export interface IEditorTabDto { group: number; name: string; resource: UriComponents } export interface IExtHostEditorTabsShape { $acceptEditorTabs(tabs: IEditorTabDto[]): void; } //#endregion export type WebviewHandle = string; export interface WebviewPanelShowOptions { readonly viewColumn?: EditorGroupColumn; readonly preserveFocus?: boolean; } export interface WebviewExtensionDescription { readonly id: ExtensionIdentifier; readonly location: UriComponents; } export interface NotebookExtensionDescription { readonly id: ExtensionIdentifier; readonly location: UriComponents; readonly description?: string; } export enum WebviewEditorCapabilities { Editable, SupportsHotExit, } export interface CustomTextEditorCapabilities { readonly supportsMove?: boolean; } export interface MainThreadWebviewsShape extends IDisposable { $setHtml(handle: WebviewHandle, value: string): void; $setOptions(handle: WebviewHandle, options: modes.IWebviewOptions): void; $postMessage(handle: WebviewHandle, value: any): Promise<boolean> } export interface MainThreadWebviewPanelsShape extends IDisposable { $createWebviewPanel(extension: WebviewExtensionDescription, handle: WebviewHandle, viewType: string, title: string, showOptions: WebviewPanelShowOptions, options: modes.IWebviewPanelOptions & modes.IWebviewOptions): void; $disposeWebview(handle: WebviewHandle): void; $reveal(handle: WebviewHandle, showOptions: WebviewPanelShowOptions): void; $setTitle(handle: WebviewHandle, value: string): void; $setIconPath(handle: WebviewHandle, value: { light: UriComponents, dark: UriComponents; } | undefined): void; $registerSerializer(viewType: string): void; $unregisterSerializer(viewType: string): void; } export interface MainThreadCustomEditorsShape extends IDisposable { $registerTextEditorProvider(extension: WebviewExtensionDescription, viewType: string, options: modes.IWebviewPanelOptions, capabilities: CustomTextEditorCapabilities): void; $registerCustomEditorProvider(extension: WebviewExtensionDescription, viewType: string, options: modes.IWebviewPanelOptions, supportsMultipleEditorsPerDocument: boolean): void; $unregisterEditorProvider(viewType: string): void; $onDidEdit(resource: UriComponents, viewType: string, editId: number, label: string | undefined): void; $onContentChange(resource: UriComponents, viewType: string): void; } export interface MainThreadWebviewViewsShape extends IDisposable { $registerWebviewViewProvider(extension: WebviewExtensionDescription, viewType: string, options?: { retainContextWhenHidden?: boolean }): void; $unregisterWebviewViewProvider(viewType: string): void; $setWebviewViewTitle(handle: WebviewHandle, value: string | undefined): void; $setWebviewViewDescription(handle: WebviewHandle, value: string | undefined): void; $show(handle: WebviewHandle, preserveFocus: boolean): void; } export interface WebviewPanelViewStateData { [handle: string]: { readonly active: boolean; readonly visible: boolean; readonly position: EditorGroupColumn; }; } export interface ExtHostWebviewsShape { $onMessage(handle: WebviewHandle, message: any): void; $onMissingCsp(handle: WebviewHandle, extensionId: string): void; } export interface ExtHostWebviewPanelsShape { $onDidChangeWebviewPanelViewStates(newState: WebviewPanelViewStateData): void; $onDidDisposeWebviewPanel(handle: WebviewHandle): Promise<void>; $deserializeWebviewPanel(newWebviewHandle: WebviewHandle, viewType: string, title: string, state: any, position: EditorGroupColumn, options: modes.IWebviewOptions & modes.IWebviewPanelOptions): Promise<void>; } export interface ExtHostCustomEditorsShape { $resolveWebviewEditor(resource: UriComponents, newWebviewHandle: WebviewHandle, viewType: string, title: string, position: EditorGroupColumn, options: modes.IWebviewOptions & modes.IWebviewPanelOptions, cancellation: CancellationToken): Promise<void>; $createCustomDocument(resource: UriComponents, viewType: string, backupId: string | undefined, cancellation: CancellationToken): Promise<{ editable: boolean }>; $disposeCustomDocument(resource: UriComponents, viewType: string): Promise<void>; $undo(resource: UriComponents, viewType: string, editId: number, isDirty: boolean): Promise<void>; $redo(resource: UriComponents, viewType: string, editId: number, isDirty: boolean): Promise<void>; $revert(resource: UriComponents, viewType: string, cancellation: CancellationToken): Promise<void>; $disposeEdits(resourceComponents: UriComponents, viewType: string, editIds: number[]): void; $onSave(resource: UriComponents, viewType: string, cancellation: CancellationToken): Promise<void>; $onSaveAs(resource: UriComponents, viewType: string, targetResource: UriComponents, cancellation: CancellationToken): Promise<void>; $backup(resource: UriComponents, viewType: string, cancellation: CancellationToken): Promise<string>; $onMoveCustomEditor(handle: WebviewHandle, newResource: UriComponents, viewType: string): Promise<void>; } export interface ExtHostWebviewViewsShape { $resolveWebviewView(webviewHandle: WebviewHandle, viewType: string, title: string | undefined, state: any, cancellation: CancellationToken): Promise<void>; $onDidChangeWebviewViewVisibility(webviewHandle: WebviewHandle, visible: boolean): void; $disposeWebviewView(webviewHandle: WebviewHandle): void; } export enum CellKind { Markdown = 1, Code = 2 } export enum CellOutputKind { Text = 1, Error = 2, Rich = 3 } export interface ICellDto { handle: number; uri: UriComponents, source: string[]; language: string; cellKind: CellKind; outputs: IOutputDto[]; metadata?: NotebookCellMetadata; } export type NotebookCellsSplice = [ number /* start */, number /* delete count */, ICellDto[] ]; export type NotebookCellOutputsSplice = [ number /* start */, number /* delete count */, IOutputDto[] ]; export enum NotebookEditorRevealType { Default = 0, InCenter = 1, InCenterIfOutsideViewport = 2, AtTop = 3 } export interface INotebookDocumentShowOptions { position?: EditorGroupColumn; preserveFocus?: boolean; pinned?: boolean; selection?: ICellRange; } export type INotebookCellStatusBarEntryDto = Dto<INotebookCellStatusBarEntry>; export interface MainThreadNotebookShape extends IDisposable { $registerNotebookProvider(extension: NotebookExtensionDescription, viewType: string, supportBackup: boolean, options: { transientOutputs: boolean; transientMetadata: TransientMetadata; viewOptions?: { displayName: string; filenamePattern: (string | IRelativePattern | INotebookExclusiveDocumentFilter)[]; exclusive: boolean; }; }): Promise<void>; $updateNotebookProviderOptions(viewType: string, options?: { transientOutputs: boolean; transientMetadata: TransientMetadata; }): Promise<void>; $unregisterNotebookProvider(viewType: string): Promise<void>; $registerNotebookKernelProvider(extension: NotebookExtensionDescription, handle: number, documentFilter: INotebookDocumentFilter): Promise<void>; $unregisterNotebookKernelProvider(handle: number): Promise<void>; $onNotebookKernelChange(handle: number, uri: UriComponents | undefined): void; $tryApplyEdits(viewType: string, resource: UriComponents, modelVersionId: number, edits: ICellEditOperation[]): Promise<boolean>; $postMessage(editorId: string, forRendererId: string | undefined, value: any): Promise<boolean>; $setStatusBarEntry(id: number, statusBarEntry: INotebookCellStatusBarEntryDto): Promise<void>; $tryOpenDocument(uriComponents: UriComponents, viewType?: string): Promise<URI>; $tryShowNotebookDocument(uriComponents: UriComponents, viewType: string, options: INotebookDocumentShowOptions): Promise<string>; $tryRevealRange(id: string, range: ICellRange, revealType: NotebookEditorRevealType): Promise<void>; $registerNotebookEditorDecorationType(key: string, options: INotebookDecorationRenderOptions): void; $removeNotebookEditorDecorationType(key: string): void; $trySetDecorations(id: string, range: ICellRange, decorationKey: string): void; } export interface MainThreadUrlsShape extends IDisposable { $registerUriHandler(handle: number, extensionId: ExtensionIdentifier): Promise<void>; $unregisterUriHandler(handle: number): Promise<void>; $createAppUri(uri: UriComponents): Promise<UriComponents>; } export interface ExtHostUrlsShape { $handleExternalUri(handle: number, uri: UriComponents): Promise<void>; } export interface MainThreadUriOpenersShape extends IDisposable { $registerUriOpener(id: string, schemes: readonly string[], extensionId: ExtensionIdentifier, label: string): Promise<void>; $unregisterUriOpener(id: string): Promise<void>; } export interface ExtHostUriOpenersShape { $canOpenUri(id: string, uri: UriComponents, token: CancellationToken): Promise<modes.ExternalUriOpenerPriority>; $openUri(id: string, context: { resolvedUri: UriComponents, sourceUri: UriComponents }, token: CancellationToken): Promise<void>; } export interface ITextSearchComplete { limitHit?: boolean; } export interface MainThreadWorkspaceShape extends IDisposable { $startFileSearch(includePattern: string | null, includeFolder: UriComponents | null, excludePatternOrDisregardExcludes: string | false | null, maxResults: number | null, token: CancellationToken): Promise<UriComponents[] | null>; $startTextSearch(query: search.IPatternInfo, folder: UriComponents | null, options: ITextQueryBuilderOptions, requestId: number, token: CancellationToken): Promise<ITextSearchComplete | null>; $checkExists(folders: readonly UriComponents[], includes: string[], token: CancellationToken): Promise<boolean>; $saveAll(includeUntitled?: boolean): Promise<boolean>; $updateWorkspaceFolders(extensionName: string, index: number, deleteCount: number, workspaceFoldersToAdd: { uri: UriComponents, name?: string; }[]): Promise<void>; $resolveProxy(url: string): Promise<string | undefined>; $requireWorkspaceTrust(message?: string): Promise<WorkspaceTrustState> } export interface IFileChangeDto { resource: UriComponents; type: files.FileChangeType; } export interface MainThreadFileSystemShape extends IDisposable { $registerFileSystemProvider(handle: number, scheme: string, capabilities: files.FileSystemProviderCapabilities): Promise<void>; $unregisterProvider(handle: number): void; $onFileSystemChange(handle: number, resource: IFileChangeDto[]): void; $stat(uri: UriComponents): Promise<files.IStat>; $readdir(resource: UriComponents): Promise<[string, files.FileType][]>; $readFile(resource: UriComponents): Promise<VSBuffer>; $writeFile(resource: UriComponents, content: VSBuffer): Promise<void>; $rename(resource: UriComponents, target: UriComponents, opts: files.FileOverwriteOptions): Promise<void>; $copy(resource: UriComponents, target: UriComponents, opts: files.FileOverwriteOptions): Promise<void>; $mkdir(resource: UriComponents): Promise<void>; $delete(resource: UriComponents, opts: files.FileDeleteOptions): Promise<void>; } export interface MainThreadLabelServiceShape extends IDisposable { $registerResourceLabelFormatter(handle: number, formatter: ResourceLabelFormatter): void; $unregisterResourceLabelFormatter(handle: number): void; } export interface MainThreadSearchShape extends IDisposable { $registerFileSearchProvider(handle: number, scheme: string): void; $registerTextSearchProvider(handle: number, scheme: string): void; $unregisterProvider(handle: number): void; $handleFileMatch(handle: number, session: number, data: UriComponents[]): void; $handleTextMatch(handle: number, session: number, data: search.IRawFileMatch2[]): void; $handleTelemetry(eventName: string, data: any): void; } export interface MainThreadTaskShape extends IDisposable { $createTaskId(task: tasks.TaskDTO): Promise<string>; $registerTaskProvider(handle: number, type: string): Promise<void>; $unregisterTaskProvider(handle: number): Promise<void>; $fetchTasks(filter?: tasks.TaskFilterDTO): Promise<tasks.TaskDTO[]>; $getTaskExecution(value: tasks.TaskHandleDTO | tasks.TaskDTO): Promise<tasks.TaskExecutionDTO>; $executeTask(task: tasks.TaskHandleDTO | tasks.TaskDTO): Promise<tasks.TaskExecutionDTO>; $terminateTask(id: string): Promise<void>; $registerTaskSystem(scheme: string, info: tasks.TaskSystemInfoDTO): void; $customExecutionComplete(id: string, result?: number): Promise<void>; $registerSupportedExecutions(custom?: boolean, shell?: boolean, process?: boolean): Promise<void>; } export interface MainThreadExtensionServiceShape extends IDisposable { $activateExtension(extensionId: ExtensionIdentifier, reason: ExtensionActivationReason): Promise<void>; $onWillActivateExtension(extensionId: ExtensionIdentifier): Promise<void>; $onDidActivateExtension(extensionId: ExtensionIdentifier, codeLoadingTime: number, activateCallTime: number, activateResolvedTime: number, activationReason: ExtensionActivationReason): void; $onExtensionActivationError(extensionId: ExtensionIdentifier, error: ExtensionActivationError): Promise<void>; $onExtensionRuntimeError(extensionId: ExtensionIdentifier, error: SerializedError): void; $onExtensionHostExit(code: number): Promise<void>; $setPerformanceMarks(marks: performance.PerformanceMark[]): Promise<void>; } export interface SCMProviderFeatures { hasQuickDiffProvider?: boolean; count?: number; commitTemplate?: string; acceptInputCommand?: modes.Command; statusBarCommands?: ICommandDto[]; } export interface SCMGroupFeatures { hideWhenEmpty?: boolean; } export type SCMRawResource = [ number /*handle*/, UriComponents /*resourceUri*/, UriComponents[] /*icons: light, dark*/, string /*tooltip*/, boolean /*strike through*/, boolean /*faded*/, string /*context value*/, ICommandDto | undefined /*command*/ ]; export type SCMRawResourceSplice = [ number /* start */, number /* delete count */, SCMRawResource[] ]; export type SCMRawResourceSplices = [ number, /*handle*/ SCMRawResourceSplice[] ]; export interface MainThreadSCMShape extends IDisposable { $registerSourceControl(handle: number, id: string, label: string, rootUri: UriComponents | undefined): void; $updateSourceControl(handle: number, features: SCMProviderFeatures): void; $unregisterSourceControl(handle: number): void; $registerGroups(sourceControlHandle: number, groups: [number /*handle*/, string /*id*/, string /*label*/, SCMGroupFeatures][], splices: SCMRawResourceSplices[]): void; $updateGroup(sourceControlHandle: number, handle: number, features: SCMGroupFeatures): void; $updateGroupLabel(sourceControlHandle: number, handle: number, label: string): void; $unregisterGroup(sourceControlHandle: number, handle: number): void; $spliceResourceStates(sourceControlHandle: number, splices: SCMRawResourceSplices[]): void; $setInputBoxValue(sourceControlHandle: number, value: string): void; $setInputBoxPlaceholder(sourceControlHandle: number, placeholder: string): void; $setInputBoxVisibility(sourceControlHandle: number, visible: boolean): void; $setValidationProviderIsEnabled(sourceControlHandle: number, enabled: boolean): void; } export type DebugSessionUUID = string; export interface IDebugConfiguration { type: string; name: string; request: string; [key: string]: any; } export interface IStartDebuggingOptions { parentSessionID?: DebugSessionUUID; repl?: IDebugSessionReplMode; noDebug?: boolean; compact?: boolean; } export interface MainThreadDebugServiceShape extends IDisposable { $registerDebugTypes(debugTypes: string[]): void; $sessionCached(sessionID: string): void; $acceptDAMessage(handle: number, message: DebugProtocol.ProtocolMessage): void; $acceptDAError(handle: number, name: string, message: string, stack: string | undefined): void; $acceptDAExit(handle: number, code: number | undefined, signal: string | undefined): void; $registerDebugConfigurationProvider(type: string, triggerKind: DebugConfigurationProviderTriggerKind, hasProvideMethod: boolean, hasResolveMethod: boolean, hasResolve2Method: boolean, handle: number): Promise<void>; $registerDebugAdapterDescriptorFactory(type: string, handle: number): Promise<void>; $unregisterDebugConfigurationProvider(handle: number): void; $unregisterDebugAdapterDescriptorFactory(handle: number): void; $startDebugging(folder: UriComponents | undefined, nameOrConfig: string | IDebugConfiguration, options: IStartDebuggingOptions): Promise<boolean>; $stopDebugging(sessionId: DebugSessionUUID | undefined): Promise<void>; $setDebugSessionName(id: DebugSessionUUID, name: string): void; $customDebugAdapterRequest(id: DebugSessionUUID, command: string, args: any): Promise<any>; $getDebugProtocolBreakpoint(id: DebugSessionUUID, breakpoinId: string): Promise<DebugProtocol.Breakpoint | undefined>; $appendDebugConsole(value: string): void; $startBreakpointEvents(): void; $registerBreakpoints(breakpoints: Array<ISourceMultiBreakpointDto | IFunctionBreakpointDto | IDataBreakpointDto>): Promise<void>; $unregisterBreakpoints(breakpointIds: string[], functionBreakpointIds: string[], dataBreakpointIds: string[]): Promise<void>; } export interface IOpenUriOptions { readonly allowTunneling?: boolean; readonly allowContributedOpeners?: boolean | string; } export interface MainThreadWindowShape extends IDisposable { $getWindowVisibility(): Promise<boolean>; $openUri(uri: UriComponents, uriString: string | undefined, options: IOpenUriOptions): Promise<boolean>; $asExternalUri(uri: UriComponents, options: IOpenUriOptions): Promise<UriComponents>; } export enum CandidatePortSource { None = 0, Process = 1, Output = 2 } export interface MainThreadTunnelServiceShape extends IDisposable { $openTunnel(tunnelOptions: TunnelOptions, source: string | undefined): Promise<TunnelDto | undefined>; $closeTunnel(remote: { host: string, port: number }): Promise<void>; $getTunnels(): Promise<TunnelDescription[]>; $setTunnelProvider(features: TunnelProviderFeatures): Promise<void>; $setRemoteTunnelService(processId: number): Promise<void>; $setCandidateFilter(): Promise<void>; $onFoundNewCandidates(candidates: { host: string, port: number, detail: string }[]): Promise<void>; $setCandidatePortSource(source: CandidatePortSource): Promise<void>; } export interface MainThreadTimelineShape extends IDisposable { $registerTimelineProvider(provider: TimelineProviderDescriptor): void; $unregisterTimelineProvider(source: string): void; $emitTimelineChangeEvent(e: TimelineChangeEvent | undefined): void; } // -- extension host export interface ExtHostCommandsShape { $executeContributedCommand<T>(id: string, ...args: any[]): Promise<T>; $getContributedCommandHandlerDescriptions(): Promise<{ [id: string]: string | ICommandHandlerDescription; }>; } export interface ExtHostConfigurationShape { $initializeConfiguration(data: IConfigurationInitData): void; $acceptConfigurationChanged(data: IConfigurationInitData, change: IConfigurationChange): void; } export interface ExtHostDiagnosticsShape { $acceptMarkersChange(data: [UriComponents, IMarkerData[]][]): void; } export interface ExtHostDocumentContentProvidersShape { $provideTextDocumentContent(handle: number, uri: UriComponents): Promise<string | null | undefined>; } export interface IModelAddedData { uri: UriComponents; versionId: number; lines: string[]; EOL: string; modeId: string; isDirty: boolean; } export interface ExtHostDocumentsShape { $acceptModelModeChanged(strURL: UriComponents, oldModeId: string, newModeId: string): void; $acceptModelSaved(strURL: UriComponents): void; $acceptDirtyStateChanged(strURL: UriComponents, isDirty: boolean): void; $acceptModelChanged(strURL: UriComponents, e: IModelChangedEvent, isDirty: boolean): void; } export interface ExtHostDocumentSaveParticipantShape { $participateInSave(resource: UriComponents, reason: SaveReason): Promise<boolean[]>; } export interface ITextEditorAddData { id: string; documentUri: UriComponents; options: IResolvedTextEditorConfiguration; selections: ISelection[]; visibleRanges: IRange[]; editorPosition: EditorGroupColumn | undefined; } export interface ITextEditorPositionData { [id: string]: EditorGroupColumn; } export interface IEditorPropertiesChangeData { options: IResolvedTextEditorConfiguration | null; selections: ISelectionChangeEvent | null; visibleRanges: IRange[] | null; } export interface ISelectionChangeEvent { selections: Selection[]; source?: string; } export interface ExtHostEditorsShape { $acceptEditorPropertiesChanged(id: string, props: IEditorPropertiesChangeData): void; $acceptEditorPositionData(data: ITextEditorPositionData): void; } export interface IDocumentsAndEditorsDelta { removedDocuments?: UriComponents[]; addedDocuments?: IModelAddedData[]; removedEditors?: string[]; addedEditors?: ITextEditorAddData[]; newActiveEditor?: string | null; } export interface ExtHostDocumentsAndEditorsShape { $acceptDocumentsAndEditorsDelta(delta: IDocumentsAndEditorsDelta): void; } export interface ExtHostTreeViewsShape { $getChildren(treeViewId: string, treeItemHandle?: string): Promise<ITreeItem[]>; $setExpanded(treeViewId: string, treeItemHandle: string, expanded: boolean): void; $setSelection(treeViewId: string, treeItemHandles: string[]): void; $setVisible(treeViewId: string, visible: boolean): void; $hasResolve(treeViewId: string): Promise<boolean>; $resolve(treeViewId: string, treeItemHandle: string, token: CancellationToken): Promise<ITreeItem | undefined>; } export interface ExtHostWorkspaceShape { $initializeWorkspace(workspace: IWorkspaceData | null, trustState: WorkspaceTrustState): void; $acceptWorkspaceData(workspace: IWorkspaceData | null): void; $handleTextSearchResult(result: search.IRawFileMatch2, requestId: number): void; $onDidChangeWorkspaceTrustState(state: WorkspaceTrustStateChangeEvent): void; } export interface ExtHostFileSystemInfoShape { $acceptProviderInfos(scheme: string, capabilities: number | null): void; } export interface ExtHostFileSystemShape { $stat(handle: number, resource: UriComponents): Promise<files.IStat>; $readdir(handle: number, resource: UriComponents): Promise<[string, files.FileType][]>; $readFile(handle: number, resource: UriComponents): Promise<VSBuffer>; $writeFile(handle: number, resource: UriComponents, content: VSBuffer, opts: files.FileWriteOptions): Promise<void>; $rename(handle: number, resource: UriComponents, target: UriComponents, opts: files.FileOverwriteOptions): Promise<void>; $copy(handle: number, resource: UriComponents, target: UriComponents, opts: files.FileOverwriteOptions): Promise<void>; $mkdir(handle: number, resource: UriComponents): Promise<void>; $delete(handle: number, resource: UriComponents, opts: files.FileDeleteOptions): Promise<void>; $watch(handle: number, session: number, resource: UriComponents, opts: files.IWatchOptions): void; $unwatch(handle: number, session: number): void; $open(handle: number, resource: UriComponents, opts: files.FileOpenOptions): Promise<number>; $close(handle: number, fd: number): Promise<void>; $read(handle: number, fd: number, pos: number, length: number): Promise<VSBuffer>; $write(handle: number, fd: number, pos: number, data: VSBuffer): Promise<number>; } export interface ExtHostLabelServiceShape { $registerResourceLabelFormatter(formatter: ResourceLabelFormatter): IDisposable; } export interface ExtHostAuthenticationShape { $getSessions(id: string, scopes?: string[]): Promise<ReadonlyArray<modes.AuthenticationSession>>; $createSession(id: string, scopes: string[]): Promise<modes.AuthenticationSession>; $removeSession(id: string, sessionId: string): Promise<void>; $onDidChangeAuthenticationSessions(id: string, label: string, event: modes.AuthenticationSessionsChangeEvent): Promise<void>; $onDidChangeAuthenticationProviders(added: modes.AuthenticationProviderInformation[], removed: modes.AuthenticationProviderInformation[]): Promise<void>; $setProviders(providers: modes.AuthenticationProviderInformation[]): Promise<void>; } export interface ExtHostSecretStateShape { $onDidChangePassword(e: { extensionId: string, key: string }): Promise<void>; } export interface ExtHostSearchShape { $provideFileSearchResults(handle: number, session: number, query: search.IRawQuery, token: CancellationToken): Promise<search.ISearchCompleteStats>; $provideTextSearchResults(handle: number, session: number, query: search.IRawTextQuery, token: CancellationToken): Promise<search.ISearchCompleteStats>; $clearCache(cacheKey: string): Promise<void>; } export interface IResolveAuthorityErrorResult { type: 'error'; error: { message: string | undefined; code: RemoteAuthorityResolverErrorCode; detail: any; }; } export interface IResolveAuthorityOKResult { type: 'ok'; value: ResolverResult; } export type IResolveAuthorityResult = IResolveAuthorityErrorResult | IResolveAuthorityOKResult; export interface ExtHostExtensionServiceShape { $resolveAuthority(remoteAuthority: string, resolveAttempt: number): Promise<IResolveAuthorityResult>; $startExtensionHost(enabledExtensionIds: ExtensionIdentifier[]): Promise<void>; $activateByEvent(activationEvent: string, activationKind: ActivationKind): Promise<void>; $activate(extensionId: ExtensionIdentifier, reason: ExtensionActivationReason): Promise<boolean>; $setRemoteEnvironment(env: { [key: string]: string | null; }): Promise<void>; $updateRemoteConnectionData(connectionData: IRemoteConnectionData): Promise<void>; $deltaExtensions(toAdd: IExtensionDescription[], toRemove: ExtensionIdentifier[]): Promise<void>; $test_latency(n: number): Promise<number>; $test_up(b: VSBuffer): Promise<number>; $test_down(size: number): Promise<VSBuffer>; } export interface FileSystemEvents { created: UriComponents[]; changed: UriComponents[]; deleted: UriComponents[]; } export interface SourceTargetPair { source?: UriComponents; target: UriComponents; } export interface IWillRunFileOperationParticipation { edit: IWorkspaceEditDto; extensionNames: string[] } export interface ExtHostFileSystemEventServiceShape { $onFileEvent(events: FileSystemEvents): void; $onWillRunFileOperation(operation: files.FileOperation, files: SourceTargetPair[], timeout: number, token: CancellationToken): Promise<IWillRunFileOperationParticipation | undefined>; $onDidRunFileOperation(operation: files.FileOperation, files: SourceTargetPair[]): void; } export interface ObjectIdentifier { $ident?: number; } export namespace ObjectIdentifier { export const name = '$ident'; export function mixin<T>(obj: T, id: number): T & ObjectIdentifier { Object.defineProperty(obj, name, { value: id, enumerable: true }); return <T & ObjectIdentifier>obj; } export function of(obj: any): number { return obj[name]; } } export interface ExtHostHeapServiceShape { $onGarbageCollection(ids: number[]): void; } export interface IRawColorInfo { color: [number, number, number, number]; range: IRange; } export class IdObject { _id?: number; private static _n = 0; static mixin<T extends object>(object: T): T & IdObject { (<any>object)._id = IdObject._n++; return <any>object; } } export const enum ISuggestDataDtoField { label = 'a', kind = 'b', detail = 'c', documentation = 'd', sortText = 'e', filterText = 'f', preselect = 'g', insertText = 'h', insertTextRules = 'i', range = 'j', commitCharacters = 'k', additionalTextEdits = 'l', command = 'm', kindModifier = 'n', // to merge into label label2 = 'o', } export interface ISuggestDataDto { [ISuggestDataDtoField.label]: string; [ISuggestDataDtoField.label2]?: string | modes.CompletionItemLabel; [ISuggestDataDtoField.kind]?: modes.CompletionItemKind; [ISuggestDataDtoField.detail]?: string; [ISuggestDataDtoField.documentation]?: string | IMarkdownString; [ISuggestDataDtoField.sortText]?: string; [ISuggestDataDtoField.filterText]?: string; [ISuggestDataDtoField.preselect]?: true; [ISuggestDataDtoField.insertText]?: string; [ISuggestDataDtoField.insertTextRules]?: modes.CompletionItemInsertTextRule; [ISuggestDataDtoField.range]?: IRange | { insert: IRange, replace: IRange; }; [ISuggestDataDtoField.commitCharacters]?: string[]; [ISuggestDataDtoField.additionalTextEdits]?: ISingleEditOperation[]; [ISuggestDataDtoField.command]?: modes.Command; [ISuggestDataDtoField.kindModifier]?: modes.CompletionItemTag[]; // not-standard x?: ChainedCacheId; } export const enum ISuggestResultDtoField { defaultRanges = 'a', completions = 'b', isIncomplete = 'c', duration = 'd', } export interface ISuggestResultDto { [ISuggestResultDtoField.defaultRanges]: { insert: IRange, replace: IRange; }; [ISuggestResultDtoField.completions]: ISuggestDataDto[]; [ISuggestResultDtoField.isIncomplete]: undefined | true; [ISuggestResultDtoField.duration]: number; x?: number; } export interface ISignatureHelpDto { id: CacheId; signatures: modes.SignatureInformation[]; activeSignature: number; activeParameter: number; } export interface ISignatureHelpContextDto { readonly triggerKind: modes.SignatureHelpTriggerKind; readonly triggerCharacter?: string; readonly isRetrigger: boolean; readonly activeSignatureHelp?: ISignatureHelpDto; } export interface IInlineHintDto { text: string; range: IRange; kind: modes.InlineHintKind; whitespaceBefore?: boolean; whitespaceAfter?: boolean; hoverMessage?: string; } export interface IInlineHintsDto { hints: IInlineHintDto[] } export interface ILocationDto { uri: UriComponents; range: IRange; } export interface IDefinitionLinkDto { originSelectionRange?: IRange; uri: UriComponents; range: IRange; targetSelectionRange?: IRange; } export interface IWorkspaceSymbolDto extends IdObject { name: string; containerName?: string; kind: modes.SymbolKind; location: ILocationDto; } export interface IWorkspaceSymbolsDto extends IdObject { symbols: IWorkspaceSymbolDto[]; } export interface IWorkspaceEditEntryMetadataDto { needsConfirmation: boolean; label: string; description?: string; iconPath?: { id: string } | UriComponents | { light: UriComponents, dark: UriComponents }; } export const enum WorkspaceEditType { File = 1, Text = 2, Cell = 3, } export interface IWorkspaceFileEditDto { _type: WorkspaceEditType.File; oldUri?: UriComponents; newUri?: UriComponents; options?: modes.WorkspaceFileEditOptions metadata?: IWorkspaceEditEntryMetadataDto; } export interface IWorkspaceTextEditDto { _type: WorkspaceEditType.Text; resource: UriComponents; edit: modes.TextEdit; modelVersionId?: number; metadata?: IWorkspaceEditEntryMetadataDto; } export interface IWorkspaceCellEditDto { _type: WorkspaceEditType.Cell; resource: UriComponents; edit: ICellEditOperation; notebookVersionId?: number; metadata?: IWorkspaceEditEntryMetadataDto; } export interface IWorkspaceEditDto { edits: Array<IWorkspaceFileEditDto | IWorkspaceTextEditDto | IWorkspaceCellEditDto>; // todo@jrieken reject should go into rename rejectReason?: string; } export function reviveWorkspaceEditDto(data: IWorkspaceEditDto | undefined): modes.WorkspaceEdit { if (data && data.edits) { for (const edit of data.edits) { if (typeof (<IWorkspaceTextEditDto>edit).resource === 'object') { (<IWorkspaceTextEditDto>edit).resource = URI.revive((<IWorkspaceTextEditDto>edit).resource); } else { (<IWorkspaceFileEditDto>edit).newUri = URI.revive((<IWorkspaceFileEditDto>edit).newUri); (<IWorkspaceFileEditDto>edit).oldUri = URI.revive((<IWorkspaceFileEditDto>edit).oldUri); } if (edit.metadata && edit.metadata.iconPath) { edit.metadata = revive(edit.metadata); } } } return <modes.WorkspaceEdit>data; } export type ICommandDto = ObjectIdentifier & modes.Command; export interface ICodeActionDto { cacheId?: ChainedCacheId; title: string; edit?: IWorkspaceEditDto; diagnostics?: IMarkerData[]; command?: ICommandDto; kind?: string; isPreferred?: boolean; disabled?: string; } export interface ICodeActionListDto { cacheId: CacheId; actions: ReadonlyArray<ICodeActionDto>; } export interface ICodeActionProviderMetadataDto { readonly providedKinds?: readonly string[]; readonly documentation?: ReadonlyArray<{ readonly kind: string, readonly command: ICommandDto }>; } export type CacheId = number; export type ChainedCacheId = [CacheId, CacheId]; export interface ILinksListDto { id?: CacheId; links: ILinkDto[]; } export interface ILinkDto { cacheId?: ChainedCacheId; range: IRange; url?: string | UriComponents; tooltip?: string; } export interface ICodeLensListDto { cacheId?: number; lenses: ICodeLensDto[]; } export interface ICodeLensDto { cacheId?: ChainedCacheId; range: IRange; command?: ICommandDto; } export type ICallHierarchyItemDto = Dto<CallHierarchyItem>; export interface IIncomingCallDto { from: ICallHierarchyItemDto; fromRanges: IRange[]; } export interface IOutgoingCallDto { fromRanges: IRange[]; to: ICallHierarchyItemDto; } export interface ILanguageWordDefinitionDto { languageId: string; regexSource: string; regexFlags: string } export interface ILinkedEditingRangesDto { ranges: IRange[]; wordPattern?: IRegExpDto; } export interface IInlineValueContextDto { stoppedLocation: IRange; } export interface ExtHostLanguageFeaturesShape { $provideDocumentSymbols(handle: number, resource: UriComponents, token: CancellationToken): Promise<modes.DocumentSymbol[] | undefined>; $provideCodeLenses(handle: number, resource: UriComponents, token: CancellationToken): Promise<ICodeLensListDto | undefined>; $resolveCodeLens(handle: number, symbol: ICodeLensDto, token: CancellationToken): Promise<ICodeLensDto | undefined>; $releaseCodeLenses(handle: number, id: number): void; $provideDefinition(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<IDefinitionLinkDto[]>; $provideDeclaration(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<IDefinitionLinkDto[]>; $provideImplementation(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<IDefinitionLinkDto[]>; $provideTypeDefinition(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<IDefinitionLinkDto[]>; $provideHover(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<modes.Hover | undefined>; $provideEvaluatableExpression(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<modes.EvaluatableExpression | undefined>; $provideInlineValues(handle: number, resource: UriComponents, range: IRange, context: modes.InlineValueContext, token: CancellationToken): Promise<modes.InlineValue[] | undefined>; $provideDocumentHighlights(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<modes.DocumentHighlight[] | undefined>; $provideLinkedEditingRanges(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<ILinkedEditingRangesDto | undefined>; $provideReferences(handle: number, resource: UriComponents, position: IPosition, context: modes.ReferenceContext, token: CancellationToken): Promise<ILocationDto[] | undefined>; $provideCodeActions(handle: number, resource: UriComponents, rangeOrSelection: IRange | ISelection, context: modes.CodeActionContext, token: CancellationToken): Promise<ICodeActionListDto | undefined>; $resolveCodeAction(handle: number, id: ChainedCacheId, token: CancellationToken): Promise<IWorkspaceEditDto | undefined>; $releaseCodeActions(handle: number, cacheId: number): void; $provideDocumentFormattingEdits(handle: number, resource: UriComponents, options: modes.FormattingOptions, token: CancellationToken): Promise<ISingleEditOperation[] | undefined>; $provideDocumentRangeFormattingEdits(handle: number, resource: UriComponents, range: IRange, options: modes.FormattingOptions, token: CancellationToken): Promise<ISingleEditOperation[] | undefined>; $provideOnTypeFormattingEdits(handle: number, resource: UriComponents, position: IPosition, ch: string, options: modes.FormattingOptions, token: CancellationToken): Promise<ISingleEditOperation[] | undefined>; $provideWorkspaceSymbols(handle: number, search: string, token: CancellationToken): Promise<IWorkspaceSymbolsDto>; $resolveWorkspaceSymbol(handle: number, symbol: IWorkspaceSymbolDto, token: CancellationToken): Promise<IWorkspaceSymbolDto | undefined>; $releaseWorkspaceSymbols(handle: number, id: number): void; $provideRenameEdits(handle: number, resource: UriComponents, position: IPosition, newName: string, token: CancellationToken): Promise<IWorkspaceEditDto | undefined>; $resolveRenameLocation(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<modes.RenameLocation | undefined>; $provideDocumentSemanticTokens(handle: number, resource: UriComponents, previousResultId: number, token: CancellationToken): Promise<VSBuffer | null>; $releaseDocumentSemanticTokens(handle: number, semanticColoringResultId: number): void; $provideDocumentRangeSemanticTokens(handle: number, resource: UriComponents, range: IRange, token: CancellationToken): Promise<VSBuffer | null>; $provideCompletionItems(handle: number, resource: UriComponents, position: IPosition, context: modes.CompletionContext, token: CancellationToken): Promise<ISuggestResultDto | undefined>; $resolveCompletionItem(handle: number, id: ChainedCacheId, token: CancellationToken): Promise<ISuggestDataDto | undefined>; $releaseCompletionItems(handle: number, id: number): void; $provideSignatureHelp(handle: number, resource: UriComponents, position: IPosition, context: modes.SignatureHelpContext, token: CancellationToken): Promise<ISignatureHelpDto | undefined>; $releaseSignatureHelp(handle: number, id: number): void; $provideInlineHints(handle: number, resource: UriComponents, range: IRange, token: CancellationToken): Promise<IInlineHintsDto | undefined> $provideDocumentLinks(handle: number, resource: UriComponents, token: CancellationToken): Promise<ILinksListDto | undefined>; $resolveDocumentLink(handle: number, id: ChainedCacheId, token: CancellationToken): Promise<ILinkDto | undefined>; $releaseDocumentLinks(handle: number, id: number): void; $provideDocumentColors(handle: number, resource: UriComponents, token: CancellationToken): Promise<IRawColorInfo[]>; $provideColorPresentations(handle: number, resource: UriComponents, colorInfo: IRawColorInfo, token: CancellationToken): Promise<modes.IColorPresentation[] | undefined>; $provideFoldingRanges(handle: number, resource: UriComponents, context: modes.FoldingContext, token: CancellationToken): Promise<modes.FoldingRange[] | undefined>; $provideSelectionRanges(handle: number, resource: UriComponents, positions: IPosition[], token: CancellationToken): Promise<modes.SelectionRange[][]>; $prepareCallHierarchy(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<ICallHierarchyItemDto[] | undefined>; $provideCallHierarchyIncomingCalls(handle: number, sessionId: string, itemId: string, token: CancellationToken): Promise<IIncomingCallDto[] | undefined>; $provideCallHierarchyOutgoingCalls(handle: number, sessionId: string, itemId: string, token: CancellationToken): Promise<IOutgoingCallDto[] | undefined>; $releaseCallHierarchy(handle: number, sessionId: string): void; $setWordDefinitions(wordDefinitions: ILanguageWordDefinitionDto[]): void; } export interface ExtHostQuickOpenShape { $onItemSelected(handle: number): void; $validateInput(input: string): Promise<string | null | undefined>; $onDidChangeActive(sessionId: number, handles: number[]): void; $onDidChangeSelection(sessionId: number, handles: number[]): void; $onDidAccept(sessionId: number): void; $onDidChangeValue(sessionId: number, value: string): void; $onDidTriggerButton(sessionId: number, handle: number): void; $onDidHide(sessionId: number): void; } export interface IShellLaunchConfigDto { name?: string; executable?: string; args?: string[] | string; cwd?: string | UriComponents; env?: { [key: string]: string | null; }; hideFromUser?: boolean; flowControl?: boolean; } export interface IShellDefinitionDto { label: string; path: string; } export interface IShellAndArgsDto { shell: string; args: string[] | string | undefined; } export interface ITerminalLinkDto { /** The ID of the link to enable activation and disposal. */ id: number; /** The startIndex of the link in the line. */ startIndex: number; /** The length of the link in the line. */ length: number; /** The descriptive label for what the link does when activated. */ label?: string; } export interface ITerminalDimensionsDto { columns: number; rows: number; } export interface ExtHostTerminalServiceShape { $acceptTerminalClosed(id: number, exitCode: number | undefined): void; $acceptTerminalOpened(id: number, extHostTerminalId: string | undefined, name: string, shellLaunchConfig: IShellLaunchConfigDto): void; $acceptActiveTerminalChanged(id: number | null): void; $acceptTerminalProcessId(id: number, processId: number): void; $acceptTerminalProcessData(id: number, data: string): void; $acceptTerminalTitleChange(id: number, name: string): void; $acceptTerminalDimensions(id: number, cols: number, rows: number): void; $acceptTerminalMaximumDimensions(id: number, cols: number, rows: number): void; $spawnExtHostProcess(id: number, shellLaunchConfig: IShellLaunchConfigDto, activeWorkspaceRootUri: UriComponents | undefined, cols: number, rows: number, isWorkspaceShellAllowed: boolean): Promise<ITerminalLaunchError | undefined>; $startExtensionTerminal(id: number, initialDimensions: ITerminalDimensionsDto | undefined): Promise<ITerminalLaunchError | undefined>; $acceptProcessAckDataEvent(id: number, charCount: number): void; $acceptProcessInput(id: number, data: string): void; $acceptProcessResize(id: number, cols: number, rows: number): void; $acceptProcessShutdown(id: number, immediate: boolean): void; $acceptProcessRequestInitialCwd(id: number): void; $acceptProcessRequestCwd(id: number): void; $acceptProcessRequestLatency(id: number): number; $acceptWorkspacePermissionsChanged(isAllowed: boolean): void; $getAvailableShells(): Promise<IShellDefinitionDto[]>; $getDefaultShellAndArgs(useAutomationShell: boolean): Promise<IShellAndArgsDto>; $provideLinks(id: number, line: string): Promise<ITerminalLinkDto[]>; $activateLink(id: number, linkId: number): void; $initEnvironmentVariableCollections(collections: [string, ISerializableEnvironmentVariableCollection][]): void; } export interface ExtHostSCMShape { $provideOriginalResource(sourceControlHandle: number, uri: UriComponents, token: CancellationToken): Promise<UriComponents | null>; $onInputBoxValueChange(sourceControlHandle: number, value: string): void; $executeResourceCommand(sourceControlHandle: number, groupHandle: number, handle: number, preserveFocus: boolean): Promise<void>; $validateInput(sourceControlHandle: number, value: string, cursorPosition: number): Promise<[string, number] | undefined>; $setSelectedSourceControl(selectedSourceControlHandle: number | undefined): Promise<void>; } export interface ExtHostTaskShape { $provideTasks(handle: number, validTypes: { [key: string]: boolean; }): Thenable<tasks.TaskSetDTO>; $resolveTask(handle: number, taskDTO: tasks.TaskDTO): Thenable<tasks.TaskDTO | undefined>; $onDidStartTask(execution: tasks.TaskExecutionDTO, terminalId: number, resolvedDefinition: tasks.TaskDefinitionDTO): void; $onDidStartTaskProcess(value: tasks.TaskProcessStartedDTO): void; $onDidEndTaskProcess(value: tasks.TaskProcessEndedDTO): void; $OnDidEndTask(execution: tasks.TaskExecutionDTO): void; $resolveVariables(workspaceFolder: UriComponents, toResolve: { process?: { name: string; cwd?: string; }, variables: string[]; }): Promise<{ process?: string; variables: { [key: string]: string; }; }>; $getDefaultShellAndArgs(): Thenable<{ shell: string, args: string[] | string | undefined; }>; $jsonTasksSupported(): Thenable<boolean>; $findExecutable(command: string, cwd?: string, paths?: string[]): Promise<string | undefined>; } export interface IBreakpointDto { type: string; id?: string; enabled: boolean; condition?: string; hitCondition?: string; logMessage?: string; } export interface IFunctionBreakpointDto extends IBreakpointDto { type: 'function'; functionName: string; } export interface IDataBreakpointDto extends IBreakpointDto { type: 'data'; dataId: string; canPersist: boolean; label: string; accessTypes?: DebugProtocol.DataBreakpointAccessType[]; } export interface ISourceBreakpointDto extends IBreakpointDto { type: 'source'; uri: UriComponents; line: number; character: number; } export interface IBreakpointsDeltaDto { added?: Array<ISourceBreakpointDto | IFunctionBreakpointDto | IDataBreakpointDto>; removed?: string[]; changed?: Array<ISourceBreakpointDto | IFunctionBreakpointDto | IDataBreakpointDto>; } export interface ISourceMultiBreakpointDto { type: 'sourceMulti'; uri: UriComponents; lines: { id: string; enabled: boolean; condition?: string; hitCondition?: string; logMessage?: string; line: number; character: number; }[]; } export interface IDebugSessionFullDto { id: DebugSessionUUID; type: string; name: string; folderUri: UriComponents | undefined; configuration: IConfig; } export type IDebugSessionDto = IDebugSessionFullDto | DebugSessionUUID; export interface ExtHostDebugServiceShape { $substituteVariables(folder: UriComponents | undefined, config: IConfig): Promise<IConfig>; $runInTerminal(args: DebugProtocol.RunInTerminalRequestArguments, sessionId: string): Promise<number | undefined>; $startDASession(handle: number, session: IDebugSessionDto): Promise<void>; $stopDASession(handle: number): Promise<void>; $sendDAMessage(handle: number, message: DebugProtocol.ProtocolMessage): void; $resolveDebugConfiguration(handle: number, folder: UriComponents | undefined, debugConfiguration: IConfig, token: CancellationToken): Promise<IConfig | null | undefined>; $resolveDebugConfigurationWithSubstitutedVariables(handle: number, folder: UriComponents | undefined, debugConfiguration: IConfig, token: CancellationToken): Promise<IConfig | null | undefined>; $provideDebugConfigurations(handle: number, folder: UriComponents | undefined, token: CancellationToken): Promise<IConfig[]>; $provideDebugAdapter(handle: number, session: IDebugSessionDto): Promise<IAdapterDescriptor>; $acceptDebugSessionStarted(session: IDebugSessionDto): void; $acceptDebugSessionTerminated(session: IDebugSessionDto): void; $acceptDebugSessionActiveChanged(session: IDebugSessionDto | undefined): void; $acceptDebugSessionCustomEvent(session: IDebugSessionDto, event: any): void; $acceptBreakpointsDelta(delta: IBreakpointsDeltaDto): void; $acceptDebugSessionNameChanged(session: IDebugSessionDto, name: string): void; } export interface DecorationRequest { readonly id: number; readonly uri: UriComponents; } export type DecorationData = [boolean, string, string, ThemeColor]; export type DecorationReply = { [id: number]: DecorationData; }; export interface ExtHostDecorationsShape { $provideDecorations(handle: number, requests: DecorationRequest[], token: CancellationToken): Promise<DecorationReply>; } export interface ExtHostWindowShape { $onDidChangeWindowFocus(value: boolean): void; } export interface ExtHostLogServiceShape { $setLevel(level: LogLevel): void; } export interface MainThreadLogShape { $log(file: UriComponents, level: LogLevel, args: any[]): void; } export interface ExtHostOutputServiceShape { $setVisibleChannel(channelId: string | null): void; } export interface ExtHostProgressShape { $acceptProgressCanceled(handle: number): void; } export interface ExtHostCommentsShape { $createCommentThreadTemplate(commentControllerHandle: number, uriComponents: UriComponents, range: IRange): void; $updateCommentThreadTemplate(commentControllerHandle: number, threadHandle: number, range: IRange): Promise<void>; $deleteCommentThread(commentControllerHandle: number, commentThreadHandle: number): void; $provideCommentingRanges(commentControllerHandle: number, uriComponents: UriComponents, token: CancellationToken): Promise<IRange[] | undefined>; $toggleReaction(commentControllerHandle: number, threadHandle: number, uri: UriComponents, comment: modes.Comment, reaction: modes.CommentReaction): Promise<void>; } export interface INotebookSelectionChangeEvent { // handles selections: number[]; } export interface INotebookVisibleRangesEvent { ranges: ICellRange[]; } export interface INotebookEditorPropertiesChangeData { visibleRanges: INotebookVisibleRangesEvent | null; selections: INotebookSelectionChangeEvent | null; } export interface INotebookDocumentPropertiesChangeData { metadata: NotebookDocumentMetadata | null; } export interface INotebookModelAddedData { uri: UriComponents; versionId: number; cells: IMainCellDto[], viewType: string; metadata?: NotebookDocumentMetadata; attachedEditor?: { id: string; selections: number[]; visibleRanges: ICellRange[] } contentOptions: { transientOutputs: boolean; transientMetadata: TransientMetadata; } } export interface INotebookEditorAddData { id: string; documentUri: UriComponents; selections: number[]; visibleRanges: ICellRange[]; } export interface INotebookDocumentsAndEditorsDelta { removedDocuments?: UriComponents[]; addedDocuments?: INotebookModelAddedData[]; removedEditors?: string[]; addedEditors?: INotebookEditorAddData[]; newActiveEditor?: string | null; visibleEditors?: string[]; } export interface INotebookKernelInfoDto2 { id?: string; friendlyId: string; label: string; extension: ExtensionIdentifier; extensionLocation: UriComponents; providerHandle?: number; description?: string; detail?: string; isPreferred?: boolean; preloads?: UriComponents[]; supportedLanguages?: string[] } export interface ExtHostNotebookShape { $openNotebook(viewType: string, uri: UriComponents, backupId?: string): Promise<NotebookDataDto>; $resolveNotebookEditor(viewType: string, uri: UriComponents, editorId: string): Promise<void>; $provideNotebookKernels(handle: number, uri: UriComponents, token: CancellationToken): Promise<INotebookKernelInfoDto2[]>; $resolveNotebookKernel(handle: number, editorId: string, uri: UriComponents, kernelId: string, token: CancellationToken): Promise<void>; $executeNotebookKernelFromProvider(handle: number, uri: UriComponents, kernelId: string, cellHandle: number | undefined): Promise<void>; $cancelNotebookKernelFromProvider(handle: number, uri: UriComponents, kernelId: string, cellHandle: number | undefined): Promise<void>; $saveNotebook(viewType: string, uri: UriComponents, token: CancellationToken): Promise<boolean>; $saveNotebookAs(viewType: string, uri: UriComponents, target: UriComponents, token: CancellationToken): Promise<boolean>; $backup(viewType: string, uri: UriComponents, cancellation: CancellationToken): Promise<string | undefined>; $acceptDisplayOrder(displayOrder: INotebookDisplayOrder): void; $acceptNotebookActiveKernelChange(event: { uri: UriComponents, providerHandle: number | undefined, kernelFriendlyId: string | undefined }): void; $onDidReceiveMessage(editorId: string, rendererId: string | undefined, message: unknown): void; $acceptModelChanged(uriComponents: UriComponents, event: NotebookCellsChangedEventDto, isDirty: boolean): void; $acceptDirtyStateChanged(uriComponents: UriComponents, isDirty: boolean): void; $acceptModelSaved(uriComponents: UriComponents): void; $acceptEditorPropertiesChanged(id: string, data: INotebookEditorPropertiesChangeData): void; $acceptDocumentPropertiesChanged(uriComponents: UriComponents, data: INotebookDocumentPropertiesChangeData): void; $acceptDocumentAndEditorsDelta(delta: INotebookDocumentsAndEditorsDelta): void; } export interface ExtHostStorageShape { $acceptValue(shared: boolean, key: string, value: object | undefined): void; } export interface ExtHostThemingShape { $onColorThemeChange(themeType: string): void; } export interface MainThreadThemingShape extends IDisposable { } export interface ExtHostTunnelServiceShape { $forwardPort(tunnelOptions: TunnelOptions, tunnelCreationOptions: TunnelCreationOptions): Promise<TunnelDto | undefined>; $closeTunnel(remote: { host: string, port: number }, silent?: boolean): Promise<void>; $onDidTunnelsChange(): Promise<void>; $registerCandidateFinder(enable: boolean): Promise<void>; $applyCandidateFilter(candidates: CandidatePort[]): Promise<CandidatePort[]>; } export interface ExtHostTimelineShape { $getTimeline(source: string, uri: UriComponents, options: TimelineOptions, token: CancellationToken, internalOptions?: InternalTimelineOptions): Promise<Timeline | undefined>; } export const enum ExtHostTestingResource { Workspace, TextDocument } export interface ExtHostTestingShape { $runTestsForProvider(req: RunTestForProviderRequest, token: CancellationToken): Promise<void>; $subscribeToTests(resource: ExtHostTestingResource, uri: UriComponents): void; $unsubscribeFromTests(resource: ExtHostTestingResource, uri: UriComponents): void; $lookupTest(test: TestIdWithProvider): Promise<InternalTestItem | undefined>; $acceptDiff(resource: ExtHostTestingResource, uri: UriComponents, diff: TestsDiff): void; $publishTestResults(results: InternalTestResults): void; } export interface MainThreadTestingShape { $registerTestProvider(id: string): void; $unregisterTestProvider(id: string): void; $subscribeToDiffs(resource: ExtHostTestingResource, uri: UriComponents): void; $unsubscribeFromDiffs(resource: ExtHostTestingResource, uri: UriComponents): void; $publishDiff(resource: ExtHostTestingResource, uri: UriComponents, diff: TestsDiff): void; $updateTestStateInRun(runId: string, testId: string, state: ITestState): void; $runTests(req: RunTestsRequest, token: CancellationToken): Promise<string>; $retireTest(extId: string): void; } // --- proxy identifiers export const MainContext = { MainThreadAuthentication: createMainId<MainThreadAuthenticationShape>('MainThreadAuthentication'), MainThreadBulkEdits: createMainId<MainThreadBulkEditsShape>('MainThreadBulkEdits'), MainThreadClipboard: createMainId<MainThreadClipboardShape>('MainThreadClipboard'), MainThreadCommands: createMainId<MainThreadCommandsShape>('MainThreadCommands'), MainThreadComments: createMainId<MainThreadCommentsShape>('MainThreadComments'), MainThreadConfiguration: createMainId<MainThreadConfigurationShape>('MainThreadConfiguration'), MainThreadConsole: createMainId<MainThreadConsoleShape>('MainThreadConsole'), MainThreadDebugService: createMainId<MainThreadDebugServiceShape>('MainThreadDebugService'), MainThreadDecorations: createMainId<MainThreadDecorationsShape>('MainThreadDecorations'), MainThreadDiagnostics: createMainId<MainThreadDiagnosticsShape>('MainThreadDiagnostics'), MainThreadDialogs: createMainId<MainThreadDiaglogsShape>('MainThreadDiaglogs'), MainThreadDocuments: createMainId<MainThreadDocumentsShape>('MainThreadDocuments'), MainThreadDocumentContentProviders: createMainId<MainThreadDocumentContentProvidersShape>('MainThreadDocumentContentProviders'), MainThreadTextEditors: createMainId<MainThreadTextEditorsShape>('MainThreadTextEditors'), MainThreadEditorInsets: createMainId<MainThreadEditorInsetsShape>('MainThreadEditorInsets'), MainThreadEditorTabs: createMainId<MainThreadEditorTabsShape>('MainThreadEditorTabs'), MainThreadErrors: createMainId<MainThreadErrorsShape>('MainThreadErrors'), MainThreadTreeViews: createMainId<MainThreadTreeViewsShape>('MainThreadTreeViews'), MainThreadDownloadService: createMainId<MainThreadDownloadServiceShape>('MainThreadDownloadService'), MainThreadKeytar: createMainId<MainThreadKeytarShape>('MainThreadKeytar'), MainThreadLanguageFeatures: createMainId<MainThreadLanguageFeaturesShape>('MainThreadLanguageFeatures'), MainThreadLanguages: createMainId<MainThreadLanguagesShape>('MainThreadLanguages'), MainThreadLog: createMainId<MainThreadLogShape>('MainThread'), MainThreadMessageService: createMainId<MainThreadMessageServiceShape>('MainThreadMessageService'), MainThreadOutputService: createMainId<MainThreadOutputServiceShape>('MainThreadOutputService'), MainThreadProgress: createMainId<MainThreadProgressShape>('MainThreadProgress'), MainThreadQuickOpen: createMainId<MainThreadQuickOpenShape>('MainThreadQuickOpen'), MainThreadStatusBar: createMainId<MainThreadStatusBarShape>('MainThreadStatusBar'), MainThreadSecretState: createMainId<MainThreadSecretStateShape>('MainThreadSecretState'), MainThreadStorage: createMainId<MainThreadStorageShape>('MainThreadStorage'), MainThreadTelemetry: createMainId<MainThreadTelemetryShape>('MainThreadTelemetry'), MainThreadTerminalService: createMainId<MainThreadTerminalServiceShape>('MainThreadTerminalService'), MainThreadWebviews: createMainId<MainThreadWebviewsShape>('MainThreadWebviews'), MainThreadWebviewPanels: createMainId<MainThreadWebviewPanelsShape>('MainThreadWebviewPanels'), MainThreadWebviewViews: createMainId<MainThreadWebviewViewsShape>('MainThreadWebviewViews'), MainThreadCustomEditors: createMainId<MainThreadCustomEditorsShape>('MainThreadCustomEditors'), MainThreadUrls: createMainId<MainThreadUrlsShape>('MainThreadUrls'), MainThreadUriOpeners: createMainId<MainThreadUriOpenersShape>('MainThreadUriOpeners'), MainThreadWorkspace: createMainId<MainThreadWorkspaceShape>('MainThreadWorkspace'), MainThreadFileSystem: createMainId<MainThreadFileSystemShape>('MainThreadFileSystem'), MainThreadExtensionService: createMainId<MainThreadExtensionServiceShape>('MainThreadExtensionService'), MainThreadSCM: createMainId<MainThreadSCMShape>('MainThreadSCM'), MainThreadSearch: createMainId<MainThreadSearchShape>('MainThreadSearch'), MainThreadTask: createMainId<MainThreadTaskShape>('MainThreadTask'), MainThreadWindow: createMainId<MainThreadWindowShape>('MainThreadWindow'), MainThreadLabelService: createMainId<MainThreadLabelServiceShape>('MainThreadLabelService'), MainThreadNotebook: createMainId<MainThreadNotebookShape>('MainThreadNotebook'), MainThreadTheming: createMainId<MainThreadThemingShape>('MainThreadTheming'), MainThreadTunnelService: createMainId<MainThreadTunnelServiceShape>('MainThreadTunnelService'), MainThreadTimeline: createMainId<MainThreadTimelineShape>('MainThreadTimeline'), MainThreadTesting: createMainId<MainThreadTestingShape>('MainThreadTesting'), }; export const ExtHostContext = { ExtHostCommands: createExtId<ExtHostCommandsShape>('ExtHostCommands'), ExtHostConfiguration: createExtId<ExtHostConfigurationShape>('ExtHostConfiguration'), ExtHostDiagnostics: createExtId<ExtHostDiagnosticsShape>('ExtHostDiagnostics'), ExtHostDebugService: createExtId<ExtHostDebugServiceShape>('ExtHostDebugService'), ExtHostDecorations: createExtId<ExtHostDecorationsShape>('ExtHostDecorations'), ExtHostDocumentsAndEditors: createExtId<ExtHostDocumentsAndEditorsShape>('ExtHostDocumentsAndEditors'), ExtHostDocuments: createExtId<ExtHostDocumentsShape>('ExtHostDocuments'), ExtHostDocumentContentProviders: createExtId<ExtHostDocumentContentProvidersShape>('ExtHostDocumentContentProviders'), ExtHostDocumentSaveParticipant: createExtId<ExtHostDocumentSaveParticipantShape>('ExtHostDocumentSaveParticipant'), ExtHostEditors: createExtId<ExtHostEditorsShape>('ExtHostEditors'), ExtHostTreeViews: createExtId<ExtHostTreeViewsShape>('ExtHostTreeViews'), ExtHostFileSystem: createExtId<ExtHostFileSystemShape>('ExtHostFileSystem'), ExtHostFileSystemInfo: createExtId<ExtHostFileSystemInfoShape>('ExtHostFileSystemInfo'), ExtHostFileSystemEventService: createExtId<ExtHostFileSystemEventServiceShape>('ExtHostFileSystemEventService'), ExtHostLanguageFeatures: createExtId<ExtHostLanguageFeaturesShape>('ExtHostLanguageFeatures'), ExtHostQuickOpen: createExtId<ExtHostQuickOpenShape>('ExtHostQuickOpen'), ExtHostExtensionService: createExtId<ExtHostExtensionServiceShape>('ExtHostExtensionService'), ExtHostLogService: createExtId<ExtHostLogServiceShape>('ExtHostLogService'), ExtHostTerminalService: createExtId<ExtHostTerminalServiceShape>('ExtHostTerminalService'), ExtHostSCM: createExtId<ExtHostSCMShape>('ExtHostSCM'), ExtHostSearch: createExtId<ExtHostSearchShape>('ExtHostSearch'), ExtHostTask: createExtId<ExtHostTaskShape>('ExtHostTask'), ExtHostWorkspace: createExtId<ExtHostWorkspaceShape>('ExtHostWorkspace'), ExtHostWindow: createExtId<ExtHostWindowShape>('ExtHostWindow'), ExtHostWebviews: createExtId<ExtHostWebviewsShape>('ExtHostWebviews'), ExtHostWebviewPanels: createExtId<ExtHostWebviewPanelsShape>('ExtHostWebviewPanels'), ExtHostCustomEditors: createExtId<ExtHostCustomEditorsShape>('ExtHostCustomEditors'), ExtHostWebviewViews: createExtId<ExtHostWebviewViewsShape>('ExtHostWebviewViews'), ExtHostEditorInsets: createExtId<ExtHostEditorInsetsShape>('ExtHostEditorInsets'), ExtHostEditorTabs: createExtId<IExtHostEditorTabsShape>('ExtHostEditorTabs'), ExtHostProgress: createMainId<ExtHostProgressShape>('ExtHostProgress'), ExtHostComments: createMainId<ExtHostCommentsShape>('ExtHostComments'), ExtHostSecretState: createMainId<ExtHostSecretStateShape>('ExtHostSecretState'), ExtHostStorage: createMainId<ExtHostStorageShape>('ExtHostStorage'), ExtHostUrls: createExtId<ExtHostUrlsShape>('ExtHostUrls'), ExtHostUriOpeners: createExtId<ExtHostUriOpenersShape>('ExtHostUriOpeners'), ExtHostOutputService: createMainId<ExtHostOutputServiceShape>('ExtHostOutputService'), ExtHosLabelService: createMainId<ExtHostLabelServiceShape>('ExtHostLabelService'), ExtHostNotebook: createMainId<ExtHostNotebookShape>('ExtHostNotebook'), ExtHostTheming: createMainId<ExtHostThemingShape>('ExtHostTheming'), ExtHostTunnelService: createMainId<ExtHostTunnelServiceShape>('ExtHostTunnelService'), ExtHostAuthentication: createMainId<ExtHostAuthenticationShape>('ExtHostAuthentication'), ExtHostTimeline: createMainId<ExtHostTimelineShape>('ExtHostTimeline'), ExtHostTesting: createMainId<ExtHostTestingShape>('ExtHostTesting'), };
src/vs/workbench/api/common/extHost.protocol.ts
1
https://github.com/microsoft/vscode/commit/44dbd182557ee8c164f3917a2f9dc09a37ff623c
[ 0.9984277486801147, 0.005910865031182766, 0.00016346095071639866, 0.0001747811329551041, 0.07077069580554962 ]
{ "id": 0, "code_window": [ "\t) {\n", "\t\tsuper();\n", "\t\tthis._proxy = extHostContext.getProxy(ExtHostContext.ExtHostTreeViews);\n", "\t}\n", "\n", "\t$registerTreeViewDataProvider(treeViewId: string, options: { showCollapseAll: boolean, canSelectMany: boolean }): void {\n", "\t\tthis.logService.trace('MainThreadTreeViews#$registerTreeViewDataProvider', treeViewId, options);\n", "\n", "\t\tthis.extensionService.whenInstalledExtensionsRegistered().then(() => {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\tasync $registerTreeViewDataProvider(treeViewId: string, options: { showCollapseAll: boolean, canSelectMany: boolean }): Promise<void> {\n" ], "file_path": "src/vs/workbench/api/browser/mainThreadTreeViews.ts", "type": "replace", "edit_start_line_idx": 33 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { ChildProcess, fork, ForkOptions } from 'child_process'; import { IDisposable, toDisposable, dispose } from 'vs/base/common/lifecycle'; import { Delayer, createCancelablePromise } from 'vs/base/common/async'; import { deepClone } from 'vs/base/common/objects'; import { Emitter, Event } from 'vs/base/common/event'; import { createQueuedSender } from 'vs/base/node/processes'; import { IChannel, ChannelServer as IPCServer, ChannelClient as IPCClient, IChannelClient } from 'vs/base/parts/ipc/common/ipc'; import { isRemoteConsoleLog, log } from 'vs/base/common/console'; import { CancellationToken } from 'vs/base/common/cancellation'; import * as errors from 'vs/base/common/errors'; import { VSBuffer } from 'vs/base/common/buffer'; import { isMacintosh } from 'vs/base/common/platform'; /** * This implementation doesn't perform well since it uses base64 encoding for buffers. * We should move all implementations to use named ipc.net, so we stop depending on cp.fork. */ export class Server<TContext extends string> extends IPCServer<TContext> { constructor(ctx: TContext) { super({ send: r => { try { if (process.send) { process.send((<Buffer>r.buffer).toString('base64')); } } catch (e) { /* not much to do */ } }, onMessage: Event.fromNodeEventEmitter(process, 'message', msg => VSBuffer.wrap(Buffer.from(msg, 'base64'))) }, ctx); process.once('disconnect', () => this.dispose()); } } export interface IIPCOptions { /** * A descriptive name for the server this connection is to. Used in logging. */ serverName: string; /** * Time in millies before killing the ipc process. The next request after killing will start it again. */ timeout?: number; /** * Arguments to the module to execute. */ args?: string[]; /** * Environment key-value pairs to be passed to the process that gets spawned for the ipc. */ env?: any; /** * Allows to assign a debug port for debugging the application executed. */ debug?: number; /** * Allows to assign a debug port for debugging the application and breaking it on the first line. */ debugBrk?: number; /** * If set, starts the fork with empty execArgv. If not set, execArgv from the parent proces are inherited, * except --inspect= and --inspect-brk= which are filtered as they would result in a port conflict. */ freshExecArgv?: boolean; /** * Enables our createQueuedSender helper for this Client. Uses a queue when the internal Node.js queue is * full of messages - see notes on that method. */ useQueue?: boolean; } export class Client implements IChannelClient, IDisposable { private disposeDelayer: Delayer<void> | undefined; private activeRequests = new Set<IDisposable>(); private child: ChildProcess | null; private _client: IPCClient | null; private channels = new Map<string, IChannel>(); private readonly _onDidProcessExit = new Emitter<{ code: number, signal: string }>(); readonly onDidProcessExit = this._onDidProcessExit.event; constructor(private modulePath: string, private options: IIPCOptions) { const timeout = options && options.timeout ? options.timeout : 60000; this.disposeDelayer = new Delayer<void>(timeout); this.child = null; this._client = null; } getChannel<T extends IChannel>(channelName: string): T { const that = this; return { call<T>(command: string, arg?: any, cancellationToken?: CancellationToken): Promise<T> { return that.requestPromise<T>(channelName, command, arg, cancellationToken); }, listen(event: string, arg?: any) { return that.requestEvent(channelName, event, arg); } } as T; } protected requestPromise<T>(channelName: string, name: string, arg?: any, cancellationToken = CancellationToken.None): Promise<T> { if (!this.disposeDelayer) { return Promise.reject(new Error('disposed')); } if (cancellationToken.isCancellationRequested) { return Promise.reject(errors.canceled()); } this.disposeDelayer.cancel(); const channel = this.getCachedChannel(channelName); const result = createCancelablePromise(token => channel.call<T>(name, arg, token)); const cancellationTokenListener = cancellationToken.onCancellationRequested(() => result.cancel()); const disposable = toDisposable(() => result.cancel()); this.activeRequests.add(disposable); result.finally(() => { cancellationTokenListener.dispose(); this.activeRequests.delete(disposable); if (this.activeRequests.size === 0 && this.disposeDelayer) { this.disposeDelayer.trigger(() => this.disposeClient()); } }); return result; } protected requestEvent<T>(channelName: string, name: string, arg?: any): Event<T> { if (!this.disposeDelayer) { return Event.None; } this.disposeDelayer.cancel(); let listener: IDisposable; const emitter = new Emitter<any>({ onFirstListenerAdd: () => { const channel = this.getCachedChannel(channelName); const event: Event<T> = channel.listen(name, arg); listener = event(emitter.fire, emitter); this.activeRequests.add(listener); }, onLastListenerRemove: () => { this.activeRequests.delete(listener); listener.dispose(); if (this.activeRequests.size === 0 && this.disposeDelayer) { this.disposeDelayer.trigger(() => this.disposeClient()); } } }); return emitter.event; } private get client(): IPCClient { if (!this._client) { const args = this.options && this.options.args ? this.options.args : []; const forkOpts: ForkOptions = Object.create(null); forkOpts.env = { ...deepClone(process.env), 'VSCODE_PARENT_PID': String(process.pid) }; if (this.options && this.options.env) { forkOpts.env = { ...forkOpts.env, ...this.options.env }; } if (this.options && this.options.freshExecArgv) { forkOpts.execArgv = []; } if (this.options && typeof this.options.debug === 'number') { forkOpts.execArgv = ['--nolazy', '--inspect=' + this.options.debug]; } if (this.options && typeof this.options.debugBrk === 'number') { forkOpts.execArgv = ['--nolazy', '--inspect-brk=' + this.options.debugBrk]; } if (forkOpts.execArgv === undefined) { // if not set, the forked process inherits the execArgv of the parent process // --inspect and --inspect-brk can not be inherited as the port would conflict forkOpts.execArgv = process.execArgv.filter(a => !/^--inspect(-brk)?=/.test(a)); // remove } if (isMacintosh && forkOpts.env) { // Unset `DYLD_LIBRARY_PATH`, as it leads to process crashes // See https://github.com/microsoft/vscode/issues/105848 delete forkOpts.env['DYLD_LIBRARY_PATH']; } this.child = fork(this.modulePath, args, forkOpts); const onMessageEmitter = new Emitter<VSBuffer>(); const onRawMessage = Event.fromNodeEventEmitter(this.child, 'message', msg => msg); onRawMessage(msg => { // Handle remote console logs specially if (isRemoteConsoleLog(msg)) { log(msg, `IPC Library: ${this.options.serverName}`); return; } // Anything else goes to the outside onMessageEmitter.fire(VSBuffer.wrap(Buffer.from(msg, 'base64'))); }); const sender = this.options.useQueue ? createQueuedSender(this.child) : this.child; const send = (r: VSBuffer) => this.child && this.child.connected && sender.send((<Buffer>r.buffer).toString('base64')); const onMessage = onMessageEmitter.event; const protocol = { send, onMessage }; this._client = new IPCClient(protocol); const onExit = () => this.disposeClient(); process.once('exit', onExit); this.child.on('error', err => console.warn('IPC "' + this.options.serverName + '" errored with ' + err)); this.child.on('exit', (code: any, signal: any) => { process.removeListener('exit' as 'loaded', onExit); // https://github.com/electron/electron/issues/21475 this.activeRequests.forEach(r => dispose(r)); this.activeRequests.clear(); if (code !== 0 && signal !== 'SIGTERM') { console.warn('IPC "' + this.options.serverName + '" crashed with exit code ' + code + ' and signal ' + signal); } if (this.disposeDelayer) { this.disposeDelayer.cancel(); } this.disposeClient(); this._onDidProcessExit.fire({ code, signal }); }); } return this._client; } private getCachedChannel(name: string): IChannel { let channel = this.channels.get(name); if (!channel) { channel = this.client.getChannel(name); this.channels.set(name, channel); } return channel; } private disposeClient() { if (this._client) { if (this.child) { this.child.kill(); this.child = null; } this._client = null; this.channels.clear(); } } dispose() { this._onDidProcessExit.dispose(); if (this.disposeDelayer) { this.disposeDelayer.cancel(); this.disposeDelayer = undefined; } this.disposeClient(); this.activeRequests.clear(); } }
src/vs/base/parts/ipc/node/ipc.cp.ts
0
https://github.com/microsoft/vscode/commit/44dbd182557ee8c164f3917a2f9dc09a37ff623c
[ 0.0002356866461923346, 0.00017209794896189123, 0.00016408716328442097, 0.0001703835732769221, 0.00001209274705615826 ]
{ "id": 0, "code_window": [ "\t) {\n", "\t\tsuper();\n", "\t\tthis._proxy = extHostContext.getProxy(ExtHostContext.ExtHostTreeViews);\n", "\t}\n", "\n", "\t$registerTreeViewDataProvider(treeViewId: string, options: { showCollapseAll: boolean, canSelectMany: boolean }): void {\n", "\t\tthis.logService.trace('MainThreadTreeViews#$registerTreeViewDataProvider', treeViewId, options);\n", "\n", "\t\tthis.extensionService.whenInstalledExtensionsRegistered().then(() => {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\tasync $registerTreeViewDataProvider(treeViewId: string, options: { showCollapseAll: boolean, canSelectMany: boolean }): Promise<void> {\n" ], "file_path": "src/vs/workbench/api/browser/mainThreadTreeViews.ts", "type": "replace", "edit_start_line_idx": 33 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { IClipboardService } from 'vs/platform/clipboard/common/clipboardService'; import { URI } from 'vs/base/common/uri'; import { $ } from 'vs/base/browser/dom'; export class BrowserClipboardService implements IClipboardService { declare readonly _serviceBrand: undefined; private readonly mapTextToType = new Map<string, string>(); // unsupported in web (only in-memory) async writeText(text: string, type?: string): Promise<void> { // With type: only in-memory is supported if (type) { this.mapTextToType.set(type, text); return; } // Guard access to navigator.clipboard with try/catch // as we have seen DOMExceptions in certain browsers // due to security policies. try { return await navigator.clipboard.writeText(text); } catch (error) { console.error(error); } // Fallback to textarea and execCommand solution const activeElement = document.activeElement; const textArea: HTMLTextAreaElement = document.body.appendChild($('textarea', { 'aria-hidden': true })); textArea.style.height = '1px'; textArea.style.width = '1px'; textArea.style.position = 'absolute'; textArea.value = text; textArea.focus(); textArea.select(); document.execCommand('copy'); if (activeElement instanceof HTMLElement) { activeElement.focus(); } document.body.removeChild(textArea); return; } async readText(type?: string): Promise<string> { // With type: only in-memory is supported if (type) { return this.mapTextToType.get(type) || ''; } // Guard access to navigator.clipboard with try/catch // as we have seen DOMExceptions in certain browsers // due to security policies. try { return await navigator.clipboard.readText(); } catch (error) { console.error(error); return ''; } } private findText = ''; // unsupported in web (only in-memory) async readFindText(): Promise<string> { return this.findText; } async writeFindText(text: string): Promise<void> { this.findText = text; } private resources: URI[] = []; // unsupported in web (only in-memory) async writeResources(resources: URI[]): Promise<void> { this.resources = resources; } async readResources(): Promise<URI[]> { return this.resources; } async hasResources(): Promise<boolean> { return this.resources.length > 0; } }
src/vs/platform/clipboard/browser/clipboardService.ts
0
https://github.com/microsoft/vscode/commit/44dbd182557ee8c164f3917a2f9dc09a37ff623c
[ 0.0001772024406818673, 0.0001698492415016517, 0.00016077345935627818, 0.00017046269204001874, 0.000004113921477255644 ]
{ "id": 0, "code_window": [ "\t) {\n", "\t\tsuper();\n", "\t\tthis._proxy = extHostContext.getProxy(ExtHostContext.ExtHostTreeViews);\n", "\t}\n", "\n", "\t$registerTreeViewDataProvider(treeViewId: string, options: { showCollapseAll: boolean, canSelectMany: boolean }): void {\n", "\t\tthis.logService.trace('MainThreadTreeViews#$registerTreeViewDataProvider', treeViewId, options);\n", "\n", "\t\tthis.extensionService.whenInstalledExtensionsRegistered().then(() => {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\tasync $registerTreeViewDataProvider(treeViewId: string, options: { showCollapseAll: boolean, canSelectMany: boolean }): Promise<void> {\n" ], "file_path": "src/vs/workbench/api/browser/mainThreadTreeViews.ts", "type": "replace", "edit_start_line_idx": 33 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { CodeAction, CodeActionTriggerType } from 'vs/editor/common/modes'; import { Position } from 'vs/editor/common/core/position'; export class CodeActionKind { private static readonly sep = '.'; public static readonly None = new CodeActionKind('@@none@@'); // Special code action that contains nothing public static readonly Empty = new CodeActionKind(''); public static readonly QuickFix = new CodeActionKind('quickfix'); public static readonly Refactor = new CodeActionKind('refactor'); public static readonly Source = new CodeActionKind('source'); public static readonly SourceOrganizeImports = CodeActionKind.Source.append('organizeImports'); public static readonly SourceFixAll = CodeActionKind.Source.append('fixAll'); constructor( public readonly value: string ) { } public equals(other: CodeActionKind): boolean { return this.value === other.value; } public contains(other: CodeActionKind): boolean { return this.equals(other) || this.value === '' || other.value.startsWith(this.value + CodeActionKind.sep); } public intersects(other: CodeActionKind): boolean { return this.contains(other) || other.contains(this); } public append(part: string): CodeActionKind { return new CodeActionKind(this.value + CodeActionKind.sep + part); } } export const enum CodeActionAutoApply { IfSingle = 'ifSingle', First = 'first', Never = 'never', } export interface CodeActionFilter { readonly include?: CodeActionKind; readonly excludes?: readonly CodeActionKind[]; readonly includeSourceActions?: boolean; readonly onlyIncludePreferredActions?: boolean; } export function mayIncludeActionsOfKind(filter: CodeActionFilter, providedKind: CodeActionKind): boolean { // A provided kind may be a subset or superset of our filtered kind. if (filter.include && !filter.include.intersects(providedKind)) { return false; } if (filter.excludes) { if (filter.excludes.some(exclude => excludesAction(providedKind, exclude, filter.include))) { return false; } } // Don't return source actions unless they are explicitly requested if (!filter.includeSourceActions && CodeActionKind.Source.contains(providedKind)) { return false; } return true; } export function filtersAction(filter: CodeActionFilter, action: CodeAction): boolean { const actionKind = action.kind ? new CodeActionKind(action.kind) : undefined; // Filter out actions by kind if (filter.include) { if (!actionKind || !filter.include.contains(actionKind)) { return false; } } if (filter.excludes) { if (actionKind && filter.excludes.some(exclude => excludesAction(actionKind, exclude, filter.include))) { return false; } } // Don't return source actions unless they are explicitly requested if (!filter.includeSourceActions) { if (actionKind && CodeActionKind.Source.contains(actionKind)) { return false; } } if (filter.onlyIncludePreferredActions) { if (!action.isPreferred) { return false; } } return true; } function excludesAction(providedKind: CodeActionKind, exclude: CodeActionKind, include: CodeActionKind | undefined): boolean { if (!exclude.contains(providedKind)) { return false; } if (include && exclude.contains(include)) { // The include is more specific, don't filter out return false; } return true; } export interface CodeActionTrigger { readonly type: CodeActionTriggerType; readonly filter?: CodeActionFilter; readonly autoApply?: CodeActionAutoApply; readonly context?: { readonly notAvailableMessage: string; readonly position: Position; }; } export class CodeActionCommandArgs { public static fromUser(arg: any, defaults: { kind: CodeActionKind, apply: CodeActionAutoApply }): CodeActionCommandArgs { if (!arg || typeof arg !== 'object') { return new CodeActionCommandArgs(defaults.kind, defaults.apply, false); } return new CodeActionCommandArgs( CodeActionCommandArgs.getKindFromUser(arg, defaults.kind), CodeActionCommandArgs.getApplyFromUser(arg, defaults.apply), CodeActionCommandArgs.getPreferredUser(arg)); } private static getApplyFromUser(arg: any, defaultAutoApply: CodeActionAutoApply) { switch (typeof arg.apply === 'string' ? arg.apply.toLowerCase() : '') { case 'first': return CodeActionAutoApply.First; case 'never': return CodeActionAutoApply.Never; case 'ifsingle': return CodeActionAutoApply.IfSingle; default: return defaultAutoApply; } } private static getKindFromUser(arg: any, defaultKind: CodeActionKind) { return typeof arg.kind === 'string' ? new CodeActionKind(arg.kind) : defaultKind; } private static getPreferredUser(arg: any): boolean { return typeof arg.preferred === 'boolean' ? arg.preferred : false; } private constructor( public readonly kind: CodeActionKind, public readonly apply: CodeActionAutoApply, public readonly preferred: boolean, ) { } }
src/vs/editor/contrib/codeAction/types.ts
0
https://github.com/microsoft/vscode/commit/44dbd182557ee8c164f3917a2f9dc09a37ff623c
[ 0.0001761448656907305, 0.00017049374582711607, 0.0001658384717302397, 0.00016980290820356458, 0.0000026576876734907273 ]
{ "id": 1, "code_window": [ "}\n", "\n", "export interface MainThreadTreeViewsShape extends IDisposable {\n", "\t$registerTreeViewDataProvider(treeViewId: string, options: { showCollapseAll: boolean, canSelectMany: boolean; }): void;\n", "\t$refresh(treeViewId: string, itemsToRefresh?: { [treeItemHandle: string]: ITreeItem; }): Promise<void>;\n", "\t$reveal(treeViewId: string, itemInfo: { item: ITreeItem, parentChain: ITreeItem[] } | undefined, options: IRevealOptions): Promise<void>;\n", "\t$setMessage(treeViewId: string, message: string): void;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t$registerTreeViewDataProvider(treeViewId: string, options: { showCollapseAll: boolean, canSelectMany: boolean; }): Promise<void>;\n" ], "file_path": "src/vs/workbench/api/common/extHost.protocol.ts", "type": "replace", "edit_start_line_idx": 287 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { localize } from 'vs/nls'; import type * as vscode from 'vscode'; import { basename } from 'vs/base/common/resources'; import { URI } from 'vs/base/common/uri'; import { Emitter, Event } from 'vs/base/common/event'; import { Disposable, DisposableStore, IDisposable } from 'vs/base/common/lifecycle'; import { ExtHostTreeViewsShape, MainThreadTreeViewsShape } from './extHost.protocol'; import { ITreeItem, TreeViewItemHandleArg, ITreeItemLabel, IRevealOptions } from 'vs/workbench/common/views'; import { ExtHostCommands, CommandsConverter } from 'vs/workbench/api/common/extHostCommands'; import { asPromise } from 'vs/base/common/async'; import { TreeItemCollapsibleState, ThemeIcon, MarkdownString as MarkdownStringType } from 'vs/workbench/api/common/extHostTypes'; import { isUndefinedOrNull, isString } from 'vs/base/common/types'; import { equals, coalesce } from 'vs/base/common/arrays'; import { ILogService } from 'vs/platform/log/common/log'; import { IExtensionDescription } from 'vs/platform/extensions/common/extensions'; import { MarkdownString } from 'vs/workbench/api/common/extHostTypeConverters'; import { IMarkdownString } from 'vs/base/common/htmlContent'; import { CancellationTokenSource } from 'vs/base/common/cancellation'; import { Command } from 'vs/editor/common/modes'; type TreeItemHandle = string; function toTreeItemLabel(label: any, extension: IExtensionDescription): ITreeItemLabel | undefined { if (isString(label)) { return { label }; } if (label && typeof label === 'object' && typeof label.label === 'string') { let highlights: [number, number][] | undefined = undefined; if (Array.isArray(label.highlights)) { highlights = (<[number, number][]>label.highlights).filter((highlight => highlight.length === 2 && typeof highlight[0] === 'number' && typeof highlight[1] === 'number')); highlights = highlights.length ? highlights : undefined; } return { label: label.label, highlights }; } return undefined; } export class ExtHostTreeViews implements ExtHostTreeViewsShape { private treeViews: Map<string, ExtHostTreeView<any>> = new Map<string, ExtHostTreeView<any>>(); constructor( private _proxy: MainThreadTreeViewsShape, private commands: ExtHostCommands, private logService: ILogService ) { function isTreeViewItemHandleArg(arg: any): boolean { return arg && arg.$treeViewId && arg.$treeItemHandle; } commands.registerArgumentProcessor({ processArgument: arg => { if (isTreeViewItemHandleArg(arg)) { return this.convertArgument(arg); } else if (Array.isArray(arg) && (arg.length > 0)) { return arg.map(item => { if (isTreeViewItemHandleArg(item)) { return this.convertArgument(item); } return item; }); } return arg; } }); } registerTreeDataProvider<T>(id: string, treeDataProvider: vscode.TreeDataProvider<T>, extension: IExtensionDescription): vscode.Disposable { const treeView = this.createTreeView(id, { treeDataProvider }, extension); return { dispose: () => treeView.dispose() }; } createTreeView<T>(viewId: string, options: vscode.TreeViewOptions<T>, extension: IExtensionDescription): vscode.TreeView<T> { if (!options || !options.treeDataProvider) { throw new Error('Options with treeDataProvider is mandatory'); } const treeView = this.createExtHostTreeView(viewId, options, extension); return { get onDidCollapseElement() { return treeView.onDidCollapseElement; }, get onDidExpandElement() { return treeView.onDidExpandElement; }, get selection() { return treeView.selectedElements; }, get onDidChangeSelection() { return treeView.onDidChangeSelection; }, get visible() { return treeView.visible; }, get onDidChangeVisibility() { return treeView.onDidChangeVisibility; }, get message() { return treeView.message; }, set message(message: string) { treeView.message = message; }, get title() { return treeView.title; }, set title(title: string) { treeView.title = title; }, get description() { return treeView.description; }, set description(description: string | undefined) { treeView.description = description; }, reveal: (element: T, options?: IRevealOptions): Promise<void> => { return treeView.reveal(element, options); }, dispose: () => { this.treeViews.delete(viewId); treeView.dispose(); } }; } $getChildren(treeViewId: string, treeItemHandle?: string): Promise<ITreeItem[]> { const treeView = this.treeViews.get(treeViewId); if (!treeView) { return Promise.reject(new Error(localize('treeView.notRegistered', 'No tree view with id \'{0}\' registered.', treeViewId))); } return treeView.getChildren(treeItemHandle); } async $hasResolve(treeViewId: string): Promise<boolean> { const treeView = this.treeViews.get(treeViewId); if (!treeView) { throw new Error(localize('treeView.notRegistered', 'No tree view with id \'{0}\' registered.', treeViewId)); } return treeView.hasResolve; } $resolve(treeViewId: string, treeItemHandle: string, token: vscode.CancellationToken): Promise<ITreeItem | undefined> { const treeView = this.treeViews.get(treeViewId); if (!treeView) { throw new Error(localize('treeView.notRegistered', 'No tree view with id \'{0}\' registered.', treeViewId)); } return treeView.resolveTreeItem(treeItemHandle, token); } $setExpanded(treeViewId: string, treeItemHandle: string, expanded: boolean): void { const treeView = this.treeViews.get(treeViewId); if (!treeView) { throw new Error(localize('treeView.notRegistered', 'No tree view with id \'{0}\' registered.', treeViewId)); } treeView.setExpanded(treeItemHandle, expanded); } $setSelection(treeViewId: string, treeItemHandles: string[]): void { const treeView = this.treeViews.get(treeViewId); if (!treeView) { throw new Error(localize('treeView.notRegistered', 'No tree view with id \'{0}\' registered.', treeViewId)); } treeView.setSelection(treeItemHandles); } $setVisible(treeViewId: string, isVisible: boolean): void { const treeView = this.treeViews.get(treeViewId); if (!treeView) { throw new Error(localize('treeView.notRegistered', 'No tree view with id \'{0}\' registered.', treeViewId)); } treeView.setVisible(isVisible); } private createExtHostTreeView<T>(id: string, options: vscode.TreeViewOptions<T>, extension: IExtensionDescription): ExtHostTreeView<T> { const treeView = new ExtHostTreeView<T>(id, options, this._proxy, this.commands.converter, this.logService, extension); this.treeViews.set(id, treeView); return treeView; } private convertArgument(arg: TreeViewItemHandleArg): any { const treeView = this.treeViews.get(arg.$treeViewId); return treeView ? treeView.getExtensionElement(arg.$treeItemHandle) : null; } } type Root = null | undefined | void; type TreeData<T> = { message: boolean, element: T | Root | false }; interface TreeNode extends IDisposable { item: ITreeItem; extensionItem: vscode.TreeItem; parent: TreeNode | Root; children?: TreeNode[]; disposableStore: DisposableStore; } class ExtHostTreeView<T> extends Disposable { private static readonly LABEL_HANDLE_PREFIX = '0'; private static readonly ID_HANDLE_PREFIX = '1'; private readonly dataProvider: vscode.TreeDataProvider<T>; private roots: TreeNode[] | null = null; private elements: Map<TreeItemHandle, T> = new Map<TreeItemHandle, T>(); private nodes: Map<T, TreeNode> = new Map<T, TreeNode>(); private _visible: boolean = false; get visible(): boolean { return this._visible; } private _selectedHandles: TreeItemHandle[] = []; get selectedElements(): T[] { return <T[]>this._selectedHandles.map(handle => this.getExtensionElement(handle)).filter(element => !isUndefinedOrNull(element)); } private _onDidExpandElement: Emitter<vscode.TreeViewExpansionEvent<T>> = this._register(new Emitter<vscode.TreeViewExpansionEvent<T>>()); readonly onDidExpandElement: Event<vscode.TreeViewExpansionEvent<T>> = this._onDidExpandElement.event; private _onDidCollapseElement: Emitter<vscode.TreeViewExpansionEvent<T>> = this._register(new Emitter<vscode.TreeViewExpansionEvent<T>>()); readonly onDidCollapseElement: Event<vscode.TreeViewExpansionEvent<T>> = this._onDidCollapseElement.event; private _onDidChangeSelection: Emitter<vscode.TreeViewSelectionChangeEvent<T>> = this._register(new Emitter<vscode.TreeViewSelectionChangeEvent<T>>()); readonly onDidChangeSelection: Event<vscode.TreeViewSelectionChangeEvent<T>> = this._onDidChangeSelection.event; private _onDidChangeVisibility: Emitter<vscode.TreeViewVisibilityChangeEvent> = this._register(new Emitter<vscode.TreeViewVisibilityChangeEvent>()); readonly onDidChangeVisibility: Event<vscode.TreeViewVisibilityChangeEvent> = this._onDidChangeVisibility.event; private _onDidChangeData: Emitter<TreeData<T>> = this._register(new Emitter<TreeData<T>>()); private refreshPromise: Promise<void> = Promise.resolve(); private refreshQueue: Promise<void> = Promise.resolve(); constructor( private viewId: string, options: vscode.TreeViewOptions<T>, private proxy: MainThreadTreeViewsShape, private commands: CommandsConverter, private logService: ILogService, private extension: IExtensionDescription ) { super(); if (extension.contributes && extension.contributes.views) { for (const location in extension.contributes.views) { for (const view of extension.contributes.views[location]) { if (view.id === viewId) { this._title = view.name; } } } } this.dataProvider = options.treeDataProvider; this.proxy.$registerTreeViewDataProvider(viewId, { showCollapseAll: !!options.showCollapseAll, canSelectMany: !!options.canSelectMany }); if (this.dataProvider.onDidChangeTreeData) { this._register(this.dataProvider.onDidChangeTreeData(element => this._onDidChangeData.fire({ message: false, element }))); } let refreshingPromise: Promise<void> | null; let promiseCallback: () => void; this._register(Event.debounce<TreeData<T>, { message: boolean, elements: (T | Root)[] }>(this._onDidChangeData.event, (result, current) => { if (!result) { result = { message: false, elements: [] }; } if (current.element !== false) { if (!refreshingPromise) { // New refresh has started refreshingPromise = new Promise(c => promiseCallback = c); this.refreshPromise = this.refreshPromise.then(() => refreshingPromise!); } result.elements.push(current.element); } if (current.message) { result.message = true; } return result; }, 200, true)(({ message, elements }) => { if (elements.length) { this.refreshQueue = this.refreshQueue.then(() => { const _promiseCallback = promiseCallback; refreshingPromise = null; return this.refresh(elements).then(() => _promiseCallback()); }); } if (message) { this.proxy.$setMessage(this.viewId, this._message); } })); } getChildren(parentHandle: TreeItemHandle | Root): Promise<ITreeItem[]> { const parentElement = parentHandle ? this.getExtensionElement(parentHandle) : undefined; if (parentHandle && !parentElement) { this.logService.error(`No tree item with id \'${parentHandle}\' found.`); return Promise.resolve([]); } const childrenNodes = this.getChildrenNodes(parentHandle); // Get it from cache return (childrenNodes ? Promise.resolve(childrenNodes) : this.fetchChildrenNodes(parentElement)) .then(nodes => nodes.map(n => n.item)); } getExtensionElement(treeItemHandle: TreeItemHandle): T | undefined { return this.elements.get(treeItemHandle); } reveal(element: T | undefined, options?: IRevealOptions): Promise<void> { options = options ? options : { select: true, focus: false }; const select = isUndefinedOrNull(options.select) ? true : options.select; const focus = isUndefinedOrNull(options.focus) ? false : options.focus; const expand = isUndefinedOrNull(options.expand) ? false : options.expand; if (typeof this.dataProvider.getParent !== 'function') { return Promise.reject(new Error(`Required registered TreeDataProvider to implement 'getParent' method to access 'reveal' method`)); } if (element) { return this.refreshPromise .then(() => this.resolveUnknownParentChain(element)) .then(parentChain => this.resolveTreeNode(element, parentChain[parentChain.length - 1]) .then(treeNode => this.proxy.$reveal(this.viewId, { item: treeNode.item, parentChain: parentChain.map(p => p.item) }, { select, focus, expand })), error => this.logService.error(error)); } else { return this.proxy.$reveal(this.viewId, undefined, { select, focus, expand }); } } private _message: string = ''; get message(): string { return this._message; } set message(message: string) { this._message = message; this._onDidChangeData.fire({ message: true, element: false }); } private _title: string = ''; get title(): string { return this._title; } set title(title: string) { this._title = title; this.proxy.$setTitle(this.viewId, title, this._description); } private _description: string | undefined; get description(): string | undefined { return this._description; } set description(description: string | undefined) { this._description = description; this.proxy.$setTitle(this.viewId, this._title, description); } setExpanded(treeItemHandle: TreeItemHandle, expanded: boolean): void { const element = this.getExtensionElement(treeItemHandle); if (element) { if (expanded) { this._onDidExpandElement.fire(Object.freeze({ element })); } else { this._onDidCollapseElement.fire(Object.freeze({ element })); } } } setSelection(treeItemHandles: TreeItemHandle[]): void { if (!equals(this._selectedHandles, treeItemHandles)) { this._selectedHandles = treeItemHandles; this._onDidChangeSelection.fire(Object.freeze({ selection: this.selectedElements })); } } setVisible(visible: boolean): void { if (visible !== this._visible) { this._visible = visible; this._onDidChangeVisibility.fire(Object.freeze({ visible: this._visible })); } } get hasResolve(): boolean { return !!this.dataProvider.resolveTreeItem; } async resolveTreeItem(treeItemHandle: string, token: vscode.CancellationToken): Promise<ITreeItem | undefined> { if (!this.dataProvider.resolveTreeItem) { return; } const element = this.elements.get(treeItemHandle); if (element) { const node = this.nodes.get(element); if (node) { const resolve = await this.dataProvider.resolveTreeItem(node.extensionItem, element, token) ?? node.extensionItem; // Resolvable elements. Currently only tooltip and command. node.item.tooltip = this.getTooltip(resolve.tooltip); node.item.command = this.getCommand(node.disposableStore, resolve.command); return node.item; } } return; } private resolveUnknownParentChain(element: T): Promise<TreeNode[]> { return this.resolveParent(element) .then((parent) => { if (!parent) { return Promise.resolve([]); } return this.resolveUnknownParentChain(parent) .then(result => this.resolveTreeNode(parent, result[result.length - 1]) .then(parentNode => { result.push(parentNode); return result; })); }); } private resolveParent(element: T): Promise<T | Root> { const node = this.nodes.get(element); if (node) { return Promise.resolve(node.parent ? this.elements.get(node.parent.item.handle) : undefined); } return asPromise(() => this.dataProvider.getParent!(element)); } private resolveTreeNode(element: T, parent?: TreeNode): Promise<TreeNode> { const node = this.nodes.get(element); if (node) { return Promise.resolve(node); } return asPromise(() => this.dataProvider.getTreeItem(element)) .then(extTreeItem => this.createHandle(element, extTreeItem, parent, true)) .then(handle => this.getChildren(parent ? parent.item.handle : undefined) .then(() => { const cachedElement = this.getExtensionElement(handle); if (cachedElement) { const node = this.nodes.get(cachedElement); if (node) { return Promise.resolve(node); } } throw new Error(`Cannot resolve tree item for element ${handle}`); })); } private getChildrenNodes(parentNodeOrHandle: TreeNode | TreeItemHandle | Root): TreeNode[] | null { if (parentNodeOrHandle) { let parentNode: TreeNode | undefined; if (typeof parentNodeOrHandle === 'string') { const parentElement = this.getExtensionElement(parentNodeOrHandle); parentNode = parentElement ? this.nodes.get(parentElement) : undefined; } else { parentNode = parentNodeOrHandle; } return parentNode ? parentNode.children || null : null; } return this.roots; } private async fetchChildrenNodes(parentElement?: T): Promise<TreeNode[]> { // clear children cache this.clearChildren(parentElement); const cts = new CancellationTokenSource(this._refreshCancellationSource.token); try { const parentNode = parentElement ? this.nodes.get(parentElement) : undefined; const elements = await this.dataProvider.getChildren(parentElement); if (cts.token.isCancellationRequested) { return []; } const items = await Promise.all(coalesce(elements || []).map(async element => { const item = await this.dataProvider.getTreeItem(element); return item && !cts.token.isCancellationRequested ? this.createAndRegisterTreeNode(element, item, parentNode) : null; })); if (cts.token.isCancellationRequested) { return []; } return coalesce(items); } finally { cts.dispose(); } } private _refreshCancellationSource = new CancellationTokenSource(); private refresh(elements: (T | Root)[]): Promise<void> { const hasRoot = elements.some(element => !element); if (hasRoot) { // Cancel any pending children fetches this._refreshCancellationSource.dispose(true); this._refreshCancellationSource = new CancellationTokenSource(); this.clearAll(); // clear cache return this.proxy.$refresh(this.viewId); } else { const handlesToRefresh = this.getHandlesToRefresh(<T[]>elements); if (handlesToRefresh.length) { return this.refreshHandles(handlesToRefresh); } } return Promise.resolve(undefined); } private getHandlesToRefresh(elements: T[]): TreeItemHandle[] { const elementsToUpdate = new Set<TreeItemHandle>(); for (const element of elements) { const elementNode = this.nodes.get(element); if (elementNode && !elementsToUpdate.has(elementNode.item.handle)) { // check if an ancestor of extElement is already in the elements to update list let currentNode: TreeNode | undefined = elementNode; while (currentNode && currentNode.parent && !elementsToUpdate.has(currentNode.parent.item.handle)) { const parentElement: T | undefined = this.elements.get(currentNode.parent.item.handle); currentNode = parentElement ? this.nodes.get(parentElement) : undefined; } if (currentNode && !currentNode.parent) { elementsToUpdate.add(elementNode.item.handle); } } } const handlesToUpdate: TreeItemHandle[] = []; // Take only top level elements elementsToUpdate.forEach((handle) => { const element = this.elements.get(handle); if (element) { const node = this.nodes.get(element); if (node && (!node.parent || !elementsToUpdate.has(node.parent.item.handle))) { handlesToUpdate.push(handle); } } }); return handlesToUpdate; } private refreshHandles(itemHandles: TreeItemHandle[]): Promise<void> { const itemsToRefresh: { [treeItemHandle: string]: ITreeItem } = {}; return Promise.all(itemHandles.map(treeItemHandle => this.refreshNode(treeItemHandle) .then(node => { if (node) { itemsToRefresh[treeItemHandle] = node.item; } }))) .then(() => Object.keys(itemsToRefresh).length ? this.proxy.$refresh(this.viewId, itemsToRefresh) : undefined); } private refreshNode(treeItemHandle: TreeItemHandle): Promise<TreeNode | null> { const extElement = this.getExtensionElement(treeItemHandle); if (extElement) { const existing = this.nodes.get(extElement); if (existing) { this.clearChildren(extElement); // clear children cache return asPromise(() => this.dataProvider.getTreeItem(extElement)) .then(extTreeItem => { if (extTreeItem) { const newNode = this.createTreeNode(extElement, extTreeItem, existing.parent); this.updateNodeCache(extElement, newNode, existing, existing.parent); existing.dispose(); return newNode; } return null; }); } } return Promise.resolve(null); } private createAndRegisterTreeNode(element: T, extTreeItem: vscode.TreeItem, parentNode: TreeNode | Root): TreeNode { const node = this.createTreeNode(element, extTreeItem, parentNode); if (extTreeItem.id && this.elements.has(node.item.handle)) { throw new Error(localize('treeView.duplicateElement', 'Element with id {0} is already registered', extTreeItem.id)); } this.addNodeToCache(element, node); this.addNodeToParentCache(node, parentNode); return node; } private getTooltip(tooltip?: string | vscode.MarkdownString): string | IMarkdownString | undefined { if (MarkdownStringType.isMarkdownString(tooltip)) { return MarkdownString.from(tooltip); } return tooltip; } private getCommand(disposable: DisposableStore, command?: vscode.Command): Command | undefined { return command ? this.commands.toInternal(command, disposable) : undefined; } private createTreeNode(element: T, extensionTreeItem: vscode.TreeItem, parent: TreeNode | Root): TreeNode { const disposableStore = new DisposableStore(); const handle = this.createHandle(element, extensionTreeItem, parent); const icon = this.getLightIconPath(extensionTreeItem); const item: ITreeItem = { handle, parentHandle: parent ? parent.item.handle : undefined, label: toTreeItemLabel(extensionTreeItem.label, this.extension), description: extensionTreeItem.description, resourceUri: extensionTreeItem.resourceUri, tooltip: this.getTooltip(extensionTreeItem.tooltip), command: this.getCommand(disposableStore, extensionTreeItem.command), contextValue: extensionTreeItem.contextValue, icon, iconDark: this.getDarkIconPath(extensionTreeItem) || icon, themeIcon: this.getThemeIcon(extensionTreeItem), collapsibleState: isUndefinedOrNull(extensionTreeItem.collapsibleState) ? TreeItemCollapsibleState.None : extensionTreeItem.collapsibleState, accessibilityInformation: extensionTreeItem.accessibilityInformation }; return { item, extensionItem: extensionTreeItem, parent, children: undefined, disposableStore, dispose(): void { disposableStore.dispose(); } }; } private getThemeIcon(extensionTreeItem: vscode.TreeItem): ThemeIcon | undefined { return extensionTreeItem.iconPath instanceof ThemeIcon ? extensionTreeItem.iconPath : undefined; } private createHandle(element: T, { id, label, resourceUri }: vscode.TreeItem, parent: TreeNode | Root, returnFirst?: boolean): TreeItemHandle { if (id) { return `${ExtHostTreeView.ID_HANDLE_PREFIX}/${id}`; } const treeItemLabel = toTreeItemLabel(label, this.extension); const prefix: string = parent ? parent.item.handle : ExtHostTreeView.LABEL_HANDLE_PREFIX; let elementId = treeItemLabel ? treeItemLabel.label : resourceUri ? basename(resourceUri) : ''; elementId = elementId.indexOf('/') !== -1 ? elementId.replace('/', '//') : elementId; const existingHandle = this.nodes.has(element) ? this.nodes.get(element)!.item.handle : undefined; const childrenNodes = (this.getChildrenNodes(parent) || []); let handle: TreeItemHandle; let counter = 0; do { handle = `${prefix}/${counter}:${elementId}`; if (returnFirst || !this.elements.has(handle) || existingHandle === handle) { // Return first if asked for or // Return if handle does not exist or // Return if handle is being reused break; } counter++; } while (counter <= childrenNodes.length); return handle; } private getLightIconPath(extensionTreeItem: vscode.TreeItem): URI | undefined { if (extensionTreeItem.iconPath && !(extensionTreeItem.iconPath instanceof ThemeIcon)) { if (typeof extensionTreeItem.iconPath === 'string' || URI.isUri(extensionTreeItem.iconPath)) { return this.getIconPath(extensionTreeItem.iconPath); } return this.getIconPath((<{ light: string | URI; dark: string | URI }>extensionTreeItem.iconPath).light); } return undefined; } private getDarkIconPath(extensionTreeItem: vscode.TreeItem): URI | undefined { if (extensionTreeItem.iconPath && !(extensionTreeItem.iconPath instanceof ThemeIcon) && (<{ light: string | URI; dark: string | URI }>extensionTreeItem.iconPath).dark) { return this.getIconPath((<{ light: string | URI; dark: string | URI }>extensionTreeItem.iconPath).dark); } return undefined; } private getIconPath(iconPath: string | URI): URI { if (URI.isUri(iconPath)) { return iconPath; } return URI.file(iconPath); } private addNodeToCache(element: T, node: TreeNode): void { this.elements.set(node.item.handle, element); this.nodes.set(element, node); } private updateNodeCache(element: T, newNode: TreeNode, existing: TreeNode, parentNode: TreeNode | Root): void { // Remove from the cache this.elements.delete(newNode.item.handle); this.nodes.delete(element); if (newNode.item.handle !== existing.item.handle) { this.elements.delete(existing.item.handle); } // Add the new node to the cache this.addNodeToCache(element, newNode); // Replace the node in parent's children nodes const childrenNodes = (this.getChildrenNodes(parentNode) || []); const childNode = childrenNodes.filter(c => c.item.handle === existing.item.handle)[0]; if (childNode) { childrenNodes.splice(childrenNodes.indexOf(childNode), 1, newNode); } } private addNodeToParentCache(node: TreeNode, parentNode: TreeNode | Root): void { if (parentNode) { if (!parentNode.children) { parentNode.children = []; } parentNode.children.push(node); } else { if (!this.roots) { this.roots = []; } this.roots.push(node); } } private clearChildren(parentElement?: T): void { if (parentElement) { const node = this.nodes.get(parentElement); if (node) { if (node.children) { for (const child of node.children) { const childElement = this.elements.get(child.item.handle); if (childElement) { this.clear(childElement); } } } node.children = undefined; } } else { this.clearAll(); } } private clear(element: T): void { const node = this.nodes.get(element); if (node) { if (node.children) { for (const child of node.children) { const childElement = this.elements.get(child.item.handle); if (childElement) { this.clear(childElement); } } } this.nodes.delete(element); this.elements.delete(node.item.handle); node.dispose(); } } private clearAll(): void { this.roots = null; this.elements.clear(); this.nodes.forEach(node => node.dispose()); this.nodes.clear(); } dispose() { this._refreshCancellationSource.dispose(); this.clearAll(); } }
src/vs/workbench/api/common/extHostTreeViews.ts
1
https://github.com/microsoft/vscode/commit/44dbd182557ee8c164f3917a2f9dc09a37ff623c
[ 0.9990000128746033, 0.047619666904211044, 0.00016155565390363336, 0.0001752553798723966, 0.20351539552211761 ]
{ "id": 1, "code_window": [ "}\n", "\n", "export interface MainThreadTreeViewsShape extends IDisposable {\n", "\t$registerTreeViewDataProvider(treeViewId: string, options: { showCollapseAll: boolean, canSelectMany: boolean; }): void;\n", "\t$refresh(treeViewId: string, itemsToRefresh?: { [treeItemHandle: string]: ITreeItem; }): Promise<void>;\n", "\t$reveal(treeViewId: string, itemInfo: { item: ITreeItem, parentChain: ITreeItem[] } | undefined, options: IRevealOptions): Promise<void>;\n", "\t$setMessage(treeViewId: string, message: string): void;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t$registerTreeViewDataProvider(treeViewId: string, options: { showCollapseAll: boolean, canSelectMany: boolean; }): Promise<void>;\n" ], "file_path": "src/vs/workbench/api/common/extHost.protocol.ts", "type": "replace", "edit_start_line_idx": 287 }
/*--------------------------------------------------------------------------------------------- * 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 'mocha'; import * as vscode from 'vscode'; import SymbolProvider from '../features/documentSymbolProvider'; import { InMemoryDocument } from './inMemoryDocument'; import { createNewMarkdownEngine } from './engine'; const testFileName = vscode.Uri.file('test.md'); function getSymbolsForFile(fileContents: string) { const doc = new InMemoryDocument(testFileName, fileContents); const provider = new SymbolProvider(createNewMarkdownEngine()); return provider.provideDocumentSymbols(doc); } suite('markdown.DocumentSymbolProvider', () => { test('Should not return anything for empty document', async () => { const symbols = await getSymbolsForFile(''); assert.strictEqual(symbols.length, 0); }); test('Should not return anything for document with no headers', async () => { const symbols = await getSymbolsForFile('a\na'); assert.strictEqual(symbols.length, 0); }); test('Should not return anything for document with # but no real headers', async () => { const symbols = await getSymbolsForFile('a#a\na#'); assert.strictEqual(symbols.length, 0); }); test('Should return single symbol for single header', async () => { const symbols = await getSymbolsForFile('# h'); assert.strictEqual(symbols.length, 1); assert.strictEqual(symbols[0].name, '# h'); }); test('Should not care about symbol level for single header', async () => { const symbols = await getSymbolsForFile('### h'); assert.strictEqual(symbols.length, 1); assert.strictEqual(symbols[0].name, '### h'); }); test('Should put symbols of same level in flat list', async () => { const symbols = await getSymbolsForFile('## h\n## h2'); assert.strictEqual(symbols.length, 2); assert.strictEqual(symbols[0].name, '## h'); assert.strictEqual(symbols[1].name, '## h2'); }); test('Should nest symbol of level - 1 under parent', async () => { const symbols = await getSymbolsForFile('# h\n## h2\n## h3'); assert.strictEqual(symbols.length, 1); assert.strictEqual(symbols[0].name, '# h'); assert.strictEqual(symbols[0].children.length, 2); assert.strictEqual(symbols[0].children[0].name, '## h2'); assert.strictEqual(symbols[0].children[1].name, '## h3'); }); test('Should nest symbol of level - n under parent', async () => { const symbols = await getSymbolsForFile('# h\n#### h2'); assert.strictEqual(symbols.length, 1); assert.strictEqual(symbols[0].name, '# h'); assert.strictEqual(symbols[0].children.length, 1); assert.strictEqual(symbols[0].children[0].name, '#### h2'); }); test('Should flatten children where lower level occurs first', async () => { const symbols = await getSymbolsForFile('# h\n### h2\n## h3'); assert.strictEqual(symbols.length, 1); assert.strictEqual(symbols[0].name, '# h'); assert.strictEqual(symbols[0].children.length, 2); assert.strictEqual(symbols[0].children[0].name, '### h2'); assert.strictEqual(symbols[0].children[1].name, '## h3'); }); test('Should handle line separator in file. Issue #63749', async () => { const symbols = await getSymbolsForFile(`# A - foo
 # B - bar`); assert.strictEqual(symbols.length, 2); assert.strictEqual(symbols[0].name, '# A'); assert.strictEqual(symbols[1].name, '# B'); }); });
extensions/markdown-language-features/src/test/documentSymbolProvider.test.ts
0
https://github.com/microsoft/vscode/commit/44dbd182557ee8c164f3917a2f9dc09a37ff623c
[ 0.0001783110637916252, 0.00017718611343298107, 0.00017570218187756836, 0.0001774702686816454, 8.707096981197537e-7 ]
{ "id": 1, "code_window": [ "}\n", "\n", "export interface MainThreadTreeViewsShape extends IDisposable {\n", "\t$registerTreeViewDataProvider(treeViewId: string, options: { showCollapseAll: boolean, canSelectMany: boolean; }): void;\n", "\t$refresh(treeViewId: string, itemsToRefresh?: { [treeItemHandle: string]: ITreeItem; }): Promise<void>;\n", "\t$reveal(treeViewId: string, itemInfo: { item: ITreeItem, parentChain: ITreeItem[] } | undefined, options: IRevealOptions): Promise<void>;\n", "\t$setMessage(treeViewId: string, message: string): void;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t$registerTreeViewDataProvider(treeViewId: string, options: { showCollapseAll: boolean, canSelectMany: boolean; }): Promise<void>;\n" ], "file_path": "src/vs/workbench/api/common/extHost.protocol.ts", "type": "replace", "edit_start_line_idx": 287 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import Tracer from '../utils/tracer'; export interface OngoingRequestCanceller { readonly cancellationPipeName: string | undefined; tryCancelOngoingRequest(seq: number): boolean; } export interface OngoingRequestCancellerFactory { create(serverId: string, tracer: Tracer): OngoingRequestCanceller; } const noopRequestCanceller = new class implements OngoingRequestCanceller { public readonly cancellationPipeName = undefined; public tryCancelOngoingRequest(_seq: number): boolean { return false; } }; export const noopRequestCancellerFactory = new class implements OngoingRequestCancellerFactory { create(_serverId: string, _tracer: Tracer): OngoingRequestCanceller { return noopRequestCanceller; } };
extensions/typescript-language-features/src/tsServer/cancellation.ts
0
https://github.com/microsoft/vscode/commit/44dbd182557ee8c164f3917a2f9dc09a37ff623c
[ 0.00017540254339110106, 0.0001716152619337663, 0.00016911636339500546, 0.00017032684991136193, 0.0000027232335924054496 ]
{ "id": 1, "code_window": [ "}\n", "\n", "export interface MainThreadTreeViewsShape extends IDisposable {\n", "\t$registerTreeViewDataProvider(treeViewId: string, options: { showCollapseAll: boolean, canSelectMany: boolean; }): void;\n", "\t$refresh(treeViewId: string, itemsToRefresh?: { [treeItemHandle: string]: ITreeItem; }): Promise<void>;\n", "\t$reveal(treeViewId: string, itemInfo: { item: ITreeItem, parentChain: ITreeItem[] } | undefined, options: IRevealOptions): Promise<void>;\n", "\t$setMessage(treeViewId: string, message: string): void;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t$registerTreeViewDataProvider(treeViewId: string, options: { showCollapseAll: boolean, canSelectMany: boolean; }): Promise<void>;\n" ], "file_path": "src/vs/workbench/api/common/extHost.protocol.ts", "type": "replace", "edit_start_line_idx": 287 }
/*--------------------------------------------------------------------------------------------- * 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 { IRange } from 'vs/editor/common/core/range'; import { IChange, ILineChange } from 'vs/editor/common/editorCommon'; import { IInplaceReplaceSupportResult, TextEdit } from 'vs/editor/common/modes'; import { createDecorator } from 'vs/platform/instantiation/common/instantiation'; export const ID_EDITOR_WORKER_SERVICE = 'editorWorkerService'; export const IEditorWorkerService = createDecorator<IEditorWorkerService>(ID_EDITOR_WORKER_SERVICE); export interface IDiffComputationResult { quitEarly: boolean; identical: boolean; changes: ILineChange[]; } export interface IEditorWorkerService { readonly _serviceBrand: undefined; canComputeDiff(original: URI, modified: URI): boolean; computeDiff(original: URI, modified: URI, ignoreTrimWhitespace: boolean, maxComputationTime: number): Promise<IDiffComputationResult | null>; canComputeDirtyDiff(original: URI, modified: URI): boolean; computeDirtyDiff(original: URI, modified: URI, ignoreTrimWhitespace: boolean): Promise<IChange[] | null>; computeMoreMinimalEdits(resource: URI, edits: TextEdit[] | null | undefined): Promise<TextEdit[] | undefined>; canComputeWordRanges(resource: URI): boolean; computeWordRanges(resource: URI, range: IRange): Promise<{ [word: string]: IRange[] } | null>; canNavigateValueSet(resource: URI): boolean; navigateValueSet(resource: URI, range: IRange, up: boolean): Promise<IInplaceReplaceSupportResult | null>; }
src/vs/editor/common/services/editorWorkerService.ts
0
https://github.com/microsoft/vscode/commit/44dbd182557ee8c164f3917a2f9dc09a37ff623c
[ 0.00017629857757128775, 0.00017219400615431368, 0.0001682465517660603, 0.00017211545491591096, 0.0000031850586310611106 ]
{ "id": 2, "code_window": [ "\tcreateTreeView<T>(viewId: string, options: vscode.TreeViewOptions<T>, extension: IExtensionDescription): vscode.TreeView<T> {\n", "\t\tif (!options || !options.treeDataProvider) {\n", "\t\t\tthrow new Error('Options with treeDataProvider is mandatory');\n", "\t\t}\n", "\n", "\t\tconst treeView = this.createExtHostTreeView(viewId, options, extension);\n", "\t\treturn {\n", "\t\t\tget onDidCollapseElement() { return treeView.onDidCollapseElement; },\n", "\t\t\tget onDidExpandElement() { return treeView.onDidExpandElement; },\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tconst registerPromise = this._proxy.$registerTreeViewDataProvider(viewId, { showCollapseAll: !!options.showCollapseAll, canSelectMany: !!options.canSelectMany });\n" ], "file_path": "src/vs/workbench/api/common/extHostTreeViews.ts", "type": "replace", "edit_start_line_idx": 86 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as performance from 'vs/base/common/performance'; import { VSBuffer } from 'vs/base/common/buffer'; import { CancellationToken } from 'vs/base/common/cancellation'; import { IRemoteConsoleLog } from 'vs/base/common/console'; import { SerializedError } from 'vs/base/common/errors'; import { IRelativePattern } from 'vs/base/common/glob'; import { IMarkdownString } from 'vs/base/common/htmlContent'; import { IDisposable } from 'vs/base/common/lifecycle'; import Severity from 'vs/base/common/severity'; import { URI, UriComponents } from 'vs/base/common/uri'; import { RenderLineNumbersType, TextEditorCursorStyle } from 'vs/editor/common/config/editorOptions'; import { IPosition } from 'vs/editor/common/core/position'; import { IRange } from 'vs/editor/common/core/range'; import { ISelection, Selection } from 'vs/editor/common/core/selection'; import * as editorCommon from 'vs/editor/common/editorCommon'; import { EndOfLineSequence, ISingleEditOperation } from 'vs/editor/common/model'; import { IModelChangedEvent } from 'vs/editor/common/model/mirrorTextModel'; import * as modes from 'vs/editor/common/modes'; import { CharacterPair, CommentRule, EnterAction } from 'vs/editor/common/modes/languageConfiguration'; import { ICommandHandlerDescription } from 'vs/platform/commands/common/commands'; import { ConfigurationTarget, IConfigurationData, IConfigurationChange, IConfigurationOverrides } from 'vs/platform/configuration/common/configuration'; import { ConfigurationScope } from 'vs/platform/configuration/common/configurationRegistry'; import { ExtensionIdentifier, IExtensionDescription } from 'vs/platform/extensions/common/extensions'; import * as files from 'vs/platform/files/common/files'; import { ResourceLabelFormatter } from 'vs/platform/label/common/label'; import { LogLevel } from 'vs/platform/log/common/log'; import { IMarkerData } from 'vs/platform/markers/common/markers'; import { IProgressOptions, IProgressStep } from 'vs/platform/progress/common/progress'; import * as quickInput from 'vs/platform/quickinput/common/quickInput'; import { RemoteAuthorityResolverErrorCode, ResolverResult, TunnelDescription, IRemoteConnectionData } from 'vs/platform/remote/common/remoteAuthorityResolver'; import * as statusbar from 'vs/workbench/services/statusbar/common/statusbar'; import { ClassifiedEvent, GDPRClassification, StrictPropertyCheck } from 'vs/platform/telemetry/common/gdprTypings'; import { ITelemetryInfo } from 'vs/platform/telemetry/common/telemetry'; import { ThemeColor } from 'vs/platform/theme/common/themeService'; import * as tasks from 'vs/workbench/api/common/shared/tasks'; import { IRevealOptions, ITreeItem } from 'vs/workbench/common/views'; import { IAdapterDescriptor, IConfig, IDebugSessionReplMode } from 'vs/workbench/contrib/debug/common/debug'; import { ITextQueryBuilderOptions } from 'vs/workbench/contrib/search/common/queryBuilder'; import { ITerminalDimensions, IShellLaunchConfig, ITerminalLaunchError } from 'vs/workbench/contrib/terminal/common/terminal'; import { ActivationKind, ExtensionActivationError, ExtensionHostKind } from 'vs/workbench/services/extensions/common/extensions'; import { createExtHostContextProxyIdentifier as createExtId, createMainContextProxyIdentifier as createMainId, IRPCProtocol } from 'vs/workbench/services/extensions/common/proxyIdentifier'; import * as search from 'vs/workbench/services/search/common/search'; import { EditorGroupColumn, SaveReason } from 'vs/workbench/common/editor'; import { ExtensionActivationReason } from 'vs/workbench/api/common/extHostExtensionActivator'; import { TunnelDto } from 'vs/workbench/api/common/extHostTunnelService'; import { TunnelCreationOptions, TunnelProviderFeatures, TunnelOptions } from 'vs/platform/remote/common/tunnel'; import { Timeline, TimelineChangeEvent, TimelineOptions, TimelineProviderDescriptor, InternalTimelineOptions } from 'vs/workbench/contrib/timeline/common/timeline'; import { revive } from 'vs/base/common/marshalling'; import { INotebookDisplayOrder, NotebookCellMetadata, NotebookDocumentMetadata, ICellEditOperation, NotebookCellsChangedEventDto, NotebookDataDto, IMainCellDto, INotebookDocumentFilter, TransientMetadata, INotebookCellStatusBarEntry, ICellRange, INotebookDecorationRenderOptions, INotebookExclusiveDocumentFilter, IOutputDto } from 'vs/workbench/contrib/notebook/common/notebookCommon'; import { CallHierarchyItem } from 'vs/workbench/contrib/callHierarchy/common/callHierarchy'; import { Dto } from 'vs/base/common/types'; import { ISerializableEnvironmentVariableCollection } from 'vs/workbench/contrib/terminal/common/environmentVariable'; import { DebugConfigurationProviderTriggerKind, WorkspaceTrustState } from 'vs/workbench/api/common/extHostTypes'; import { IAccessibilityInformation } from 'vs/platform/accessibility/common/accessibility'; import { IExtensionIdWithVersion } from 'vs/platform/userDataSync/common/extensionsStorageSync'; import { InternalTestItem, InternalTestResults, ITestState, RunTestForProviderRequest, RunTestsRequest, TestIdWithProvider, TestsDiff } from 'vs/workbench/contrib/testing/common/testCollection'; import { CandidatePort } from 'vs/workbench/services/remote/common/remoteExplorerService'; import { WorkspaceTrustStateChangeEvent } from 'vs/platform/workspace/common/workspaceTrust'; export interface IEnvironment { isExtensionDevelopmentDebug: boolean; appName: string; appRoot?: URI; appLanguage: string; appUriScheme: string; extensionDevelopmentLocationURI?: URI[]; extensionTestsLocationURI?: URI; globalStorageHome: URI; workspaceStorageHome: URI; webviewResourceRoot: string; webviewCspSource: string; useHostProxy?: boolean; } export interface IStaticWorkspaceData { id: string; name: string; configuration?: UriComponents | null; isUntitled?: boolean | null; } export interface IWorkspaceData extends IStaticWorkspaceData { folders: { uri: UriComponents, name: string, index: number; }[]; } export interface IInitData { version: string; commit?: string; parentPid: number; environment: IEnvironment; workspace?: IStaticWorkspaceData | null; resolvedExtensions: ExtensionIdentifier[]; hostExtensions: ExtensionIdentifier[]; extensions: IExtensionDescription[]; telemetryInfo: ITelemetryInfo; logLevel: LogLevel; logsLocation: URI; logFile: URI; autoStart: boolean; remote: { isRemote: boolean; authority: string | undefined; connectionData: IRemoteConnectionData | null; }; uiKind: UIKind; } export interface IConfigurationInitData extends IConfigurationData { configurationScopes: [string, ConfigurationScope | undefined][]; } export interface IExtHostContext extends IRPCProtocol { readonly remoteAuthority: string | null; readonly extensionHostKind: ExtensionHostKind; } export interface IMainContext extends IRPCProtocol { } export enum UIKind { Desktop = 1, Web = 2 } // --- main thread export interface MainThreadClipboardShape extends IDisposable { $readText(): Promise<string>; $writeText(value: string): Promise<void>; } export interface MainThreadCommandsShape extends IDisposable { $registerCommand(id: string): void; $unregisterCommand(id: string): void; $executeCommand<T>(id: string, args: any[], retry: boolean): Promise<T | undefined>; $getCommands(): Promise<string[]>; } export interface CommentProviderFeatures { reactionGroup?: modes.CommentReaction[]; reactionHandler?: boolean; options?: modes.CommentOptions; } export type CommentThreadChanges = Partial<{ range: IRange, label: string, contextValue: string, comments: modes.Comment[], collapseState: modes.CommentThreadCollapsibleState; canReply: boolean; }>; export interface MainThreadCommentsShape extends IDisposable { $registerCommentController(handle: number, id: string, label: string): void; $unregisterCommentController(handle: number): void; $updateCommentControllerFeatures(handle: number, features: CommentProviderFeatures): void; $createCommentThread(handle: number, commentThreadHandle: number, threadId: string, resource: UriComponents, range: IRange, extensionId: ExtensionIdentifier): modes.CommentThread | undefined; $updateCommentThread(handle: number, commentThreadHandle: number, threadId: string, resource: UriComponents, changes: CommentThreadChanges): void; $deleteCommentThread(handle: number, commentThreadHandle: number): void; $onDidCommentThreadsChange(handle: number, event: modes.CommentThreadChangedEvent): void; } export interface MainThreadAuthenticationShape extends IDisposable { $registerAuthenticationProvider(id: string, label: string, supportsMultipleAccounts: boolean): void; $unregisterAuthenticationProvider(id: string): void; $ensureProvider(id: string): Promise<void>; $sendDidChangeSessions(providerId: string, event: modes.AuthenticationSessionsChangeEvent): void; $getSession(providerId: string, scopes: string[], extensionId: string, extensionName: string, options: { createIfNone?: boolean, clearSessionPreference?: boolean }): Promise<modes.AuthenticationSession | undefined>; $removeSession(providerId: string, sessionId: string): Promise<void>; } export interface MainThreadSecretStateShape extends IDisposable { $getPassword(extensionId: string, key: string): Promise<string | undefined>; $setPassword(extensionId: string, key: string, value: string): Promise<void>; $deletePassword(extensionId: string, key: string): Promise<void>; } export interface MainThreadConfigurationShape extends IDisposable { $updateConfigurationOption(target: ConfigurationTarget | null, key: string, value: any, overrides: IConfigurationOverrides | undefined, scopeToLanguage: boolean | undefined): Promise<void>; $removeConfigurationOption(target: ConfigurationTarget | null, key: string, overrides: IConfigurationOverrides | undefined, scopeToLanguage: boolean | undefined): Promise<void>; } export interface MainThreadDiagnosticsShape extends IDisposable { $changeMany(owner: string, entries: [UriComponents, IMarkerData[] | undefined][]): void; $clear(owner: string): void; } export interface MainThreadDialogOpenOptions { defaultUri?: UriComponents; openLabel?: string; canSelectFiles?: boolean; canSelectFolders?: boolean; canSelectMany?: boolean; filters?: { [name: string]: string[]; }; title?: string; } export interface MainThreadDialogSaveOptions { defaultUri?: UriComponents; saveLabel?: string; filters?: { [name: string]: string[]; }; title?: string; } export interface MainThreadDiaglogsShape extends IDisposable { $showOpenDialog(options?: MainThreadDialogOpenOptions): Promise<UriComponents[] | undefined>; $showSaveDialog(options?: MainThreadDialogSaveOptions): Promise<UriComponents | undefined>; } export interface MainThreadDecorationsShape extends IDisposable { $registerDecorationProvider(handle: number, label: string): void; $unregisterDecorationProvider(handle: number): void; $onDidChange(handle: number, resources: UriComponents[] | null): void; } export interface MainThreadDocumentContentProvidersShape extends IDisposable { $registerTextContentProvider(handle: number, scheme: string): void; $unregisterTextContentProvider(handle: number): void; $onVirtualDocumentChange(uri: UriComponents, value: string): void; } export interface MainThreadDocumentsShape extends IDisposable { $tryCreateDocument(options?: { language?: string; content?: string; }): Promise<UriComponents>; $tryOpenDocument(uri: UriComponents): Promise<UriComponents>; $trySaveDocument(uri: UriComponents): Promise<boolean>; } export interface ITextEditorConfigurationUpdate { tabSize?: number | 'auto'; insertSpaces?: boolean | 'auto'; cursorStyle?: TextEditorCursorStyle; lineNumbers?: RenderLineNumbersType; } export interface IResolvedTextEditorConfiguration { tabSize: number; insertSpaces: boolean; cursorStyle: TextEditorCursorStyle; lineNumbers: RenderLineNumbersType; } export enum TextEditorRevealType { Default = 0, InCenter = 1, InCenterIfOutsideViewport = 2, AtTop = 3 } export interface IUndoStopOptions { undoStopBefore: boolean; undoStopAfter: boolean; } export interface IApplyEditsOptions extends IUndoStopOptions { setEndOfLine?: EndOfLineSequence; } export interface ITextDocumentShowOptions { position?: EditorGroupColumn; preserveFocus?: boolean; pinned?: boolean; selection?: IRange; } export interface MainThreadBulkEditsShape extends IDisposable { $tryApplyWorkspaceEdit(workspaceEditDto: IWorkspaceEditDto, undoRedoGroupId?: number): Promise<boolean>; } export interface MainThreadTextEditorsShape extends IDisposable { $tryShowTextDocument(resource: UriComponents, options: ITextDocumentShowOptions): Promise<string | undefined>; $registerTextEditorDecorationType(key: string, options: editorCommon.IDecorationRenderOptions): void; $removeTextEditorDecorationType(key: string): void; $tryShowEditor(id: string, position: EditorGroupColumn): Promise<void>; $tryHideEditor(id: string): Promise<void>; $trySetOptions(id: string, options: ITextEditorConfigurationUpdate): Promise<void>; $trySetDecorations(id: string, key: string, ranges: editorCommon.IDecorationOptions[]): Promise<void>; $trySetDecorationsFast(id: string, key: string, ranges: number[]): Promise<void>; $tryRevealRange(id: string, range: IRange, revealType: TextEditorRevealType): Promise<void>; $trySetSelections(id: string, selections: ISelection[]): Promise<void>; $tryApplyEdits(id: string, modelVersionId: number, edits: ISingleEditOperation[], opts: IApplyEditsOptions): Promise<boolean>; $tryInsertSnippet(id: string, template: string, selections: readonly IRange[], opts: IUndoStopOptions): Promise<boolean>; $getDiffInformation(id: string): Promise<editorCommon.ILineChange[]>; } export interface MainThreadTreeViewsShape extends IDisposable { $registerTreeViewDataProvider(treeViewId: string, options: { showCollapseAll: boolean, canSelectMany: boolean; }): void; $refresh(treeViewId: string, itemsToRefresh?: { [treeItemHandle: string]: ITreeItem; }): Promise<void>; $reveal(treeViewId: string, itemInfo: { item: ITreeItem, parentChain: ITreeItem[] } | undefined, options: IRevealOptions): Promise<void>; $setMessage(treeViewId: string, message: string): void; $setTitle(treeViewId: string, title: string, description: string | undefined): void; } export interface MainThreadDownloadServiceShape extends IDisposable { $download(uri: UriComponents, to: UriComponents): Promise<void>; } export interface MainThreadErrorsShape extends IDisposable { $onUnexpectedError(err: any | SerializedError): void; } export interface MainThreadConsoleShape extends IDisposable { $logExtensionHostMessage(msg: IRemoteConsoleLog): void; } export interface MainThreadKeytarShape extends IDisposable { $getPassword(service: string, account: string): Promise<string | null>; $setPassword(service: string, account: string, password: string): Promise<void>; $deletePassword(service: string, account: string): Promise<boolean>; $findPassword(service: string): Promise<string | null>; $findCredentials(service: string): Promise<Array<{ account: string, password: string; }>>; } export interface IRegExpDto { pattern: string; flags?: string; } export interface IIndentationRuleDto { decreaseIndentPattern: IRegExpDto; increaseIndentPattern: IRegExpDto; indentNextLinePattern?: IRegExpDto; unIndentedLinePattern?: IRegExpDto; } export interface IOnEnterRuleDto { beforeText: IRegExpDto; afterText?: IRegExpDto; previousLineText?: IRegExpDto; action: EnterAction; } export interface ILanguageConfigurationDto { comments?: CommentRule; brackets?: CharacterPair[]; wordPattern?: IRegExpDto; indentationRules?: IIndentationRuleDto; onEnterRules?: IOnEnterRuleDto[]; __electricCharacterSupport?: { brackets?: any; docComment?: { scope: string; open: string; lineStart: string; close?: string; }; }; __characterPairSupport?: { autoClosingPairs: { open: string; close: string; notIn?: string[]; }[]; }; } export type GlobPattern = string | { base: string; pattern: string; }; export interface IDocumentFilterDto { $serialized: true; language?: string; scheme?: string; pattern?: string | IRelativePattern; exclusive?: boolean; } export interface ISignatureHelpProviderMetadataDto { readonly triggerCharacters: readonly string[]; readonly retriggerCharacters: readonly string[]; } export interface MainThreadLanguageFeaturesShape extends IDisposable { $unregister(handle: number): void; $registerDocumentSymbolProvider(handle: number, selector: IDocumentFilterDto[], label: string): void; $registerCodeLensSupport(handle: number, selector: IDocumentFilterDto[], eventHandle: number | undefined): void; $emitCodeLensEvent(eventHandle: number, event?: any): void; $registerDefinitionSupport(handle: number, selector: IDocumentFilterDto[]): void; $registerDeclarationSupport(handle: number, selector: IDocumentFilterDto[]): void; $registerImplementationSupport(handle: number, selector: IDocumentFilterDto[]): void; $registerTypeDefinitionSupport(handle: number, selector: IDocumentFilterDto[]): void; $registerHoverProvider(handle: number, selector: IDocumentFilterDto[]): void; $registerEvaluatableExpressionProvider(handle: number, selector: IDocumentFilterDto[]): void; $registerInlineValuesProvider(handle: number, selector: IDocumentFilterDto[], eventHandle: number | undefined): void; $emitInlineValuesEvent(eventHandle: number, event?: any): void; $registerDocumentHighlightProvider(handle: number, selector: IDocumentFilterDto[]): void; $registerLinkedEditingRangeProvider(handle: number, selector: IDocumentFilterDto[]): void; $registerReferenceSupport(handle: number, selector: IDocumentFilterDto[]): void; $registerQuickFixSupport(handle: number, selector: IDocumentFilterDto[], metadata: ICodeActionProviderMetadataDto, displayName: string, supportsResolve: boolean): void; $registerDocumentFormattingSupport(handle: number, selector: IDocumentFilterDto[], extensionId: ExtensionIdentifier, displayName: string): void; $registerRangeFormattingSupport(handle: number, selector: IDocumentFilterDto[], extensionId: ExtensionIdentifier, displayName: string): void; $registerOnTypeFormattingSupport(handle: number, selector: IDocumentFilterDto[], autoFormatTriggerCharacters: string[], extensionId: ExtensionIdentifier): void; $registerNavigateTypeSupport(handle: number): void; $registerRenameSupport(handle: number, selector: IDocumentFilterDto[], supportsResolveInitialValues: boolean): void; $registerDocumentSemanticTokensProvider(handle: number, selector: IDocumentFilterDto[], legend: modes.SemanticTokensLegend, eventHandle: number | undefined): void; $emitDocumentSemanticTokensEvent(eventHandle: number): void; $registerDocumentRangeSemanticTokensProvider(handle: number, selector: IDocumentFilterDto[], legend: modes.SemanticTokensLegend): void; $registerSuggestSupport(handle: number, selector: IDocumentFilterDto[], triggerCharacters: string[], supportsResolveDetails: boolean, displayName: string): void; $registerSignatureHelpProvider(handle: number, selector: IDocumentFilterDto[], metadata: ISignatureHelpProviderMetadataDto): void; $registerInlineHintsProvider(handle: number, selector: IDocumentFilterDto[], eventHandle: number | undefined): void; $emitInlineHintsEvent(eventHandle: number, event?: any): void; $registerDocumentLinkProvider(handle: number, selector: IDocumentFilterDto[], supportsResolve: boolean): void; $registerDocumentColorProvider(handle: number, selector: IDocumentFilterDto[]): void; $registerFoldingRangeProvider(handle: number, selector: IDocumentFilterDto[], eventHandle: number | undefined): void; $emitFoldingRangeEvent(eventHandle: number, event?: any): void; $registerSelectionRangeProvider(handle: number, selector: IDocumentFilterDto[]): void; $registerCallHierarchyProvider(handle: number, selector: IDocumentFilterDto[]): void; $setLanguageConfiguration(handle: number, languageId: string, configuration: ILanguageConfigurationDto): void; } export interface MainThreadLanguagesShape extends IDisposable { $getLanguages(): Promise<string[]>; $changeLanguage(resource: UriComponents, languageId: string): Promise<void>; $tokensAtPosition(resource: UriComponents, position: IPosition): Promise<undefined | { type: modes.StandardTokenType, range: IRange }>; } export interface MainThreadMessageOptions { extension?: IExtensionDescription; modal?: boolean; useCustom?: boolean; } export interface MainThreadMessageServiceShape extends IDisposable { $showMessage(severity: Severity, message: string, options: MainThreadMessageOptions, commands: { title: string; isCloseAffordance: boolean; handle: number; }[]): Promise<number | undefined>; } export interface MainThreadOutputServiceShape extends IDisposable { $register(label: string, log: boolean, file?: UriComponents): Promise<string>; $append(channelId: string, value: string): Promise<void> | undefined; $update(channelId: string): Promise<void> | undefined; $clear(channelId: string, till: number): Promise<void> | undefined; $reveal(channelId: string, preserveFocus: boolean): Promise<void> | undefined; $close(channelId: string): Promise<void> | undefined; $dispose(channelId: string): Promise<void> | undefined; } export interface MainThreadProgressShape extends IDisposable { $startProgress(handle: number, options: IProgressOptions, extension?: IExtensionDescription): void; $progressReport(handle: number, message: IProgressStep): void; $progressEnd(handle: number): void; } /** * A terminal that is created on the extension host side is temporarily assigned * a UUID by the extension host that created it. Once the renderer side has assigned * a real numeric id, the numeric id will be used. * * All other terminals (that are not created on the extension host side) always * use the numeric id. */ export type TerminalIdentifier = number | string; export interface TerminalLaunchConfig { name?: string; shellPath?: string; shellArgs?: string[] | string; cwd?: string | UriComponents; env?: { [key: string]: string | null; }; waitOnExit?: boolean; strictEnv?: boolean; hideFromUser?: boolean; isExtensionTerminal?: boolean; isFeatureTerminal?: boolean; } export interface MainThreadTerminalServiceShape extends IDisposable { $createTerminal(extHostTerminalId: string, config: TerminalLaunchConfig): Promise<void>; $dispose(id: TerminalIdentifier): void; $hide(id: TerminalIdentifier): void; $sendText(id: TerminalIdentifier, text: string, addNewLine: boolean): void; $show(id: TerminalIdentifier, preserveFocus: boolean): void; $startSendingDataEvents(): void; $stopSendingDataEvents(): void; $startLinkProvider(): void; $stopLinkProvider(): void; $registerProcessSupport(isSupported: boolean): void; $setEnvironmentVariableCollection(extensionIdentifier: string, persistent: boolean, collection: ISerializableEnvironmentVariableCollection | undefined): void; // Process $sendProcessTitle(terminalId: number, title: string): void; $sendProcessData(terminalId: number, data: string): void; $sendProcessReady(terminalId: number, pid: number, cwd: string): void; $sendProcessExit(terminalId: number, exitCode: number | undefined): void; $sendProcessInitialCwd(terminalId: number, cwd: string): void; $sendProcessCwd(terminalId: number, initialCwd: string): void; $sendOverrideDimensions(terminalId: number, dimensions: ITerminalDimensions | undefined): void; $sendResolvedLaunchConfig(terminalId: number, shellLaunchConfig: IShellLaunchConfig): void; } export interface TransferQuickPickItems extends quickInput.IQuickPickItem { handle: number; } export interface TransferQuickInputButton { handle: number; iconPath: { dark: URI; light?: URI; } | { id: string; }; tooltip?: string; } export type TransferQuickInput = TransferQuickPick | TransferInputBox; export interface BaseTransferQuickInput { [key: string]: any; id: number; type?: 'quickPick' | 'inputBox'; enabled?: boolean; busy?: boolean; visible?: boolean; } export interface TransferQuickPick extends BaseTransferQuickInput { type?: 'quickPick'; value?: string; placeholder?: string; buttons?: TransferQuickInputButton[]; items?: TransferQuickPickItems[]; activeItems?: number[]; selectedItems?: number[]; canSelectMany?: boolean; ignoreFocusOut?: boolean; matchOnDescription?: boolean; matchOnDetail?: boolean; sortByLabel?: boolean; } export interface TransferInputBox extends BaseTransferQuickInput { type?: 'inputBox'; value?: string; placeholder?: string; password?: boolean; buttons?: TransferQuickInputButton[]; prompt?: string; validationMessage?: string; } export interface IInputBoxOptions { value?: string; valueSelection?: [number, number]; prompt?: string; placeHolder?: string; password?: boolean; ignoreFocusOut?: boolean; } export interface MainThreadQuickOpenShape extends IDisposable { $show(instance: number, options: quickInput.IPickOptions<TransferQuickPickItems>, token: CancellationToken): Promise<number | number[] | undefined>; $setItems(instance: number, items: TransferQuickPickItems[]): Promise<void>; $setError(instance: number, error: Error): Promise<void>; $input(options: IInputBoxOptions | undefined, validateInput: boolean, token: CancellationToken): Promise<string | undefined>; $createOrUpdate(params: TransferQuickInput): Promise<void>; $dispose(id: number): Promise<void>; } export interface MainThreadStatusBarShape extends IDisposable { $setEntry(id: number, statusId: string, statusName: string, text: string, tooltip: string | undefined, command: ICommandDto | undefined, color: string | ThemeColor | undefined, backgroundColor: string | ThemeColor | undefined, alignment: statusbar.StatusbarAlignment, priority: number | undefined, accessibilityInformation: IAccessibilityInformation | undefined): void; $dispose(id: number): void; } export interface MainThreadStorageShape extends IDisposable { $getValue<T>(shared: boolean, key: string): Promise<T | undefined>; $setValue(shared: boolean, key: string, value: object): Promise<void>; $registerExtensionStorageKeysToSync(extension: IExtensionIdWithVersion, keys: string[]): void; } export interface MainThreadTelemetryShape extends IDisposable { $publicLog(eventName: string, data?: any): void; $publicLog2<E extends ClassifiedEvent<T> = never, T extends GDPRClassification<T> = never>(eventName: string, data?: StrictPropertyCheck<T, E>): void; } export interface MainThreadEditorInsetsShape extends IDisposable { $createEditorInset(handle: number, id: string, uri: UriComponents, line: number, height: number, options: modes.IWebviewOptions, extensionId: ExtensionIdentifier, extensionLocation: UriComponents): Promise<void>; $disposeEditorInset(handle: number): void; $setHtml(handle: number, value: string): void; $setOptions(handle: number, options: modes.IWebviewOptions): void; $postMessage(handle: number, value: any): Promise<boolean>; } export interface ExtHostEditorInsetsShape { $onDidDispose(handle: number): void; $onDidReceiveMessage(handle: number, message: any): void; } //#region --- open editors model export interface MainThreadEditorTabsShape extends IDisposable { // manage tabs: move, close, rearrange etc } export interface IEditorTabDto { group: number; name: string; resource: UriComponents } export interface IExtHostEditorTabsShape { $acceptEditorTabs(tabs: IEditorTabDto[]): void; } //#endregion export type WebviewHandle = string; export interface WebviewPanelShowOptions { readonly viewColumn?: EditorGroupColumn; readonly preserveFocus?: boolean; } export interface WebviewExtensionDescription { readonly id: ExtensionIdentifier; readonly location: UriComponents; } export interface NotebookExtensionDescription { readonly id: ExtensionIdentifier; readonly location: UriComponents; readonly description?: string; } export enum WebviewEditorCapabilities { Editable, SupportsHotExit, } export interface CustomTextEditorCapabilities { readonly supportsMove?: boolean; } export interface MainThreadWebviewsShape extends IDisposable { $setHtml(handle: WebviewHandle, value: string): void; $setOptions(handle: WebviewHandle, options: modes.IWebviewOptions): void; $postMessage(handle: WebviewHandle, value: any): Promise<boolean> } export interface MainThreadWebviewPanelsShape extends IDisposable { $createWebviewPanel(extension: WebviewExtensionDescription, handle: WebviewHandle, viewType: string, title: string, showOptions: WebviewPanelShowOptions, options: modes.IWebviewPanelOptions & modes.IWebviewOptions): void; $disposeWebview(handle: WebviewHandle): void; $reveal(handle: WebviewHandle, showOptions: WebviewPanelShowOptions): void; $setTitle(handle: WebviewHandle, value: string): void; $setIconPath(handle: WebviewHandle, value: { light: UriComponents, dark: UriComponents; } | undefined): void; $registerSerializer(viewType: string): void; $unregisterSerializer(viewType: string): void; } export interface MainThreadCustomEditorsShape extends IDisposable { $registerTextEditorProvider(extension: WebviewExtensionDescription, viewType: string, options: modes.IWebviewPanelOptions, capabilities: CustomTextEditorCapabilities): void; $registerCustomEditorProvider(extension: WebviewExtensionDescription, viewType: string, options: modes.IWebviewPanelOptions, supportsMultipleEditorsPerDocument: boolean): void; $unregisterEditorProvider(viewType: string): void; $onDidEdit(resource: UriComponents, viewType: string, editId: number, label: string | undefined): void; $onContentChange(resource: UriComponents, viewType: string): void; } export interface MainThreadWebviewViewsShape extends IDisposable { $registerWebviewViewProvider(extension: WebviewExtensionDescription, viewType: string, options?: { retainContextWhenHidden?: boolean }): void; $unregisterWebviewViewProvider(viewType: string): void; $setWebviewViewTitle(handle: WebviewHandle, value: string | undefined): void; $setWebviewViewDescription(handle: WebviewHandle, value: string | undefined): void; $show(handle: WebviewHandle, preserveFocus: boolean): void; } export interface WebviewPanelViewStateData { [handle: string]: { readonly active: boolean; readonly visible: boolean; readonly position: EditorGroupColumn; }; } export interface ExtHostWebviewsShape { $onMessage(handle: WebviewHandle, message: any): void; $onMissingCsp(handle: WebviewHandle, extensionId: string): void; } export interface ExtHostWebviewPanelsShape { $onDidChangeWebviewPanelViewStates(newState: WebviewPanelViewStateData): void; $onDidDisposeWebviewPanel(handle: WebviewHandle): Promise<void>; $deserializeWebviewPanel(newWebviewHandle: WebviewHandle, viewType: string, title: string, state: any, position: EditorGroupColumn, options: modes.IWebviewOptions & modes.IWebviewPanelOptions): Promise<void>; } export interface ExtHostCustomEditorsShape { $resolveWebviewEditor(resource: UriComponents, newWebviewHandle: WebviewHandle, viewType: string, title: string, position: EditorGroupColumn, options: modes.IWebviewOptions & modes.IWebviewPanelOptions, cancellation: CancellationToken): Promise<void>; $createCustomDocument(resource: UriComponents, viewType: string, backupId: string | undefined, cancellation: CancellationToken): Promise<{ editable: boolean }>; $disposeCustomDocument(resource: UriComponents, viewType: string): Promise<void>; $undo(resource: UriComponents, viewType: string, editId: number, isDirty: boolean): Promise<void>; $redo(resource: UriComponents, viewType: string, editId: number, isDirty: boolean): Promise<void>; $revert(resource: UriComponents, viewType: string, cancellation: CancellationToken): Promise<void>; $disposeEdits(resourceComponents: UriComponents, viewType: string, editIds: number[]): void; $onSave(resource: UriComponents, viewType: string, cancellation: CancellationToken): Promise<void>; $onSaveAs(resource: UriComponents, viewType: string, targetResource: UriComponents, cancellation: CancellationToken): Promise<void>; $backup(resource: UriComponents, viewType: string, cancellation: CancellationToken): Promise<string>; $onMoveCustomEditor(handle: WebviewHandle, newResource: UriComponents, viewType: string): Promise<void>; } export interface ExtHostWebviewViewsShape { $resolveWebviewView(webviewHandle: WebviewHandle, viewType: string, title: string | undefined, state: any, cancellation: CancellationToken): Promise<void>; $onDidChangeWebviewViewVisibility(webviewHandle: WebviewHandle, visible: boolean): void; $disposeWebviewView(webviewHandle: WebviewHandle): void; } export enum CellKind { Markdown = 1, Code = 2 } export enum CellOutputKind { Text = 1, Error = 2, Rich = 3 } export interface ICellDto { handle: number; uri: UriComponents, source: string[]; language: string; cellKind: CellKind; outputs: IOutputDto[]; metadata?: NotebookCellMetadata; } export type NotebookCellsSplice = [ number /* start */, number /* delete count */, ICellDto[] ]; export type NotebookCellOutputsSplice = [ number /* start */, number /* delete count */, IOutputDto[] ]; export enum NotebookEditorRevealType { Default = 0, InCenter = 1, InCenterIfOutsideViewport = 2, AtTop = 3 } export interface INotebookDocumentShowOptions { position?: EditorGroupColumn; preserveFocus?: boolean; pinned?: boolean; selection?: ICellRange; } export type INotebookCellStatusBarEntryDto = Dto<INotebookCellStatusBarEntry>; export interface MainThreadNotebookShape extends IDisposable { $registerNotebookProvider(extension: NotebookExtensionDescription, viewType: string, supportBackup: boolean, options: { transientOutputs: boolean; transientMetadata: TransientMetadata; viewOptions?: { displayName: string; filenamePattern: (string | IRelativePattern | INotebookExclusiveDocumentFilter)[]; exclusive: boolean; }; }): Promise<void>; $updateNotebookProviderOptions(viewType: string, options?: { transientOutputs: boolean; transientMetadata: TransientMetadata; }): Promise<void>; $unregisterNotebookProvider(viewType: string): Promise<void>; $registerNotebookKernelProvider(extension: NotebookExtensionDescription, handle: number, documentFilter: INotebookDocumentFilter): Promise<void>; $unregisterNotebookKernelProvider(handle: number): Promise<void>; $onNotebookKernelChange(handle: number, uri: UriComponents | undefined): void; $tryApplyEdits(viewType: string, resource: UriComponents, modelVersionId: number, edits: ICellEditOperation[]): Promise<boolean>; $postMessage(editorId: string, forRendererId: string | undefined, value: any): Promise<boolean>; $setStatusBarEntry(id: number, statusBarEntry: INotebookCellStatusBarEntryDto): Promise<void>; $tryOpenDocument(uriComponents: UriComponents, viewType?: string): Promise<URI>; $tryShowNotebookDocument(uriComponents: UriComponents, viewType: string, options: INotebookDocumentShowOptions): Promise<string>; $tryRevealRange(id: string, range: ICellRange, revealType: NotebookEditorRevealType): Promise<void>; $registerNotebookEditorDecorationType(key: string, options: INotebookDecorationRenderOptions): void; $removeNotebookEditorDecorationType(key: string): void; $trySetDecorations(id: string, range: ICellRange, decorationKey: string): void; } export interface MainThreadUrlsShape extends IDisposable { $registerUriHandler(handle: number, extensionId: ExtensionIdentifier): Promise<void>; $unregisterUriHandler(handle: number): Promise<void>; $createAppUri(uri: UriComponents): Promise<UriComponents>; } export interface ExtHostUrlsShape { $handleExternalUri(handle: number, uri: UriComponents): Promise<void>; } export interface MainThreadUriOpenersShape extends IDisposable { $registerUriOpener(id: string, schemes: readonly string[], extensionId: ExtensionIdentifier, label: string): Promise<void>; $unregisterUriOpener(id: string): Promise<void>; } export interface ExtHostUriOpenersShape { $canOpenUri(id: string, uri: UriComponents, token: CancellationToken): Promise<modes.ExternalUriOpenerPriority>; $openUri(id: string, context: { resolvedUri: UriComponents, sourceUri: UriComponents }, token: CancellationToken): Promise<void>; } export interface ITextSearchComplete { limitHit?: boolean; } export interface MainThreadWorkspaceShape extends IDisposable { $startFileSearch(includePattern: string | null, includeFolder: UriComponents | null, excludePatternOrDisregardExcludes: string | false | null, maxResults: number | null, token: CancellationToken): Promise<UriComponents[] | null>; $startTextSearch(query: search.IPatternInfo, folder: UriComponents | null, options: ITextQueryBuilderOptions, requestId: number, token: CancellationToken): Promise<ITextSearchComplete | null>; $checkExists(folders: readonly UriComponents[], includes: string[], token: CancellationToken): Promise<boolean>; $saveAll(includeUntitled?: boolean): Promise<boolean>; $updateWorkspaceFolders(extensionName: string, index: number, deleteCount: number, workspaceFoldersToAdd: { uri: UriComponents, name?: string; }[]): Promise<void>; $resolveProxy(url: string): Promise<string | undefined>; $requireWorkspaceTrust(message?: string): Promise<WorkspaceTrustState> } export interface IFileChangeDto { resource: UriComponents; type: files.FileChangeType; } export interface MainThreadFileSystemShape extends IDisposable { $registerFileSystemProvider(handle: number, scheme: string, capabilities: files.FileSystemProviderCapabilities): Promise<void>; $unregisterProvider(handle: number): void; $onFileSystemChange(handle: number, resource: IFileChangeDto[]): void; $stat(uri: UriComponents): Promise<files.IStat>; $readdir(resource: UriComponents): Promise<[string, files.FileType][]>; $readFile(resource: UriComponents): Promise<VSBuffer>; $writeFile(resource: UriComponents, content: VSBuffer): Promise<void>; $rename(resource: UriComponents, target: UriComponents, opts: files.FileOverwriteOptions): Promise<void>; $copy(resource: UriComponents, target: UriComponents, opts: files.FileOverwriteOptions): Promise<void>; $mkdir(resource: UriComponents): Promise<void>; $delete(resource: UriComponents, opts: files.FileDeleteOptions): Promise<void>; } export interface MainThreadLabelServiceShape extends IDisposable { $registerResourceLabelFormatter(handle: number, formatter: ResourceLabelFormatter): void; $unregisterResourceLabelFormatter(handle: number): void; } export interface MainThreadSearchShape extends IDisposable { $registerFileSearchProvider(handle: number, scheme: string): void; $registerTextSearchProvider(handle: number, scheme: string): void; $unregisterProvider(handle: number): void; $handleFileMatch(handle: number, session: number, data: UriComponents[]): void; $handleTextMatch(handle: number, session: number, data: search.IRawFileMatch2[]): void; $handleTelemetry(eventName: string, data: any): void; } export interface MainThreadTaskShape extends IDisposable { $createTaskId(task: tasks.TaskDTO): Promise<string>; $registerTaskProvider(handle: number, type: string): Promise<void>; $unregisterTaskProvider(handle: number): Promise<void>; $fetchTasks(filter?: tasks.TaskFilterDTO): Promise<tasks.TaskDTO[]>; $getTaskExecution(value: tasks.TaskHandleDTO | tasks.TaskDTO): Promise<tasks.TaskExecutionDTO>; $executeTask(task: tasks.TaskHandleDTO | tasks.TaskDTO): Promise<tasks.TaskExecutionDTO>; $terminateTask(id: string): Promise<void>; $registerTaskSystem(scheme: string, info: tasks.TaskSystemInfoDTO): void; $customExecutionComplete(id: string, result?: number): Promise<void>; $registerSupportedExecutions(custom?: boolean, shell?: boolean, process?: boolean): Promise<void>; } export interface MainThreadExtensionServiceShape extends IDisposable { $activateExtension(extensionId: ExtensionIdentifier, reason: ExtensionActivationReason): Promise<void>; $onWillActivateExtension(extensionId: ExtensionIdentifier): Promise<void>; $onDidActivateExtension(extensionId: ExtensionIdentifier, codeLoadingTime: number, activateCallTime: number, activateResolvedTime: number, activationReason: ExtensionActivationReason): void; $onExtensionActivationError(extensionId: ExtensionIdentifier, error: ExtensionActivationError): Promise<void>; $onExtensionRuntimeError(extensionId: ExtensionIdentifier, error: SerializedError): void; $onExtensionHostExit(code: number): Promise<void>; $setPerformanceMarks(marks: performance.PerformanceMark[]): Promise<void>; } export interface SCMProviderFeatures { hasQuickDiffProvider?: boolean; count?: number; commitTemplate?: string; acceptInputCommand?: modes.Command; statusBarCommands?: ICommandDto[]; } export interface SCMGroupFeatures { hideWhenEmpty?: boolean; } export type SCMRawResource = [ number /*handle*/, UriComponents /*resourceUri*/, UriComponents[] /*icons: light, dark*/, string /*tooltip*/, boolean /*strike through*/, boolean /*faded*/, string /*context value*/, ICommandDto | undefined /*command*/ ]; export type SCMRawResourceSplice = [ number /* start */, number /* delete count */, SCMRawResource[] ]; export type SCMRawResourceSplices = [ number, /*handle*/ SCMRawResourceSplice[] ]; export interface MainThreadSCMShape extends IDisposable { $registerSourceControl(handle: number, id: string, label: string, rootUri: UriComponents | undefined): void; $updateSourceControl(handle: number, features: SCMProviderFeatures): void; $unregisterSourceControl(handle: number): void; $registerGroups(sourceControlHandle: number, groups: [number /*handle*/, string /*id*/, string /*label*/, SCMGroupFeatures][], splices: SCMRawResourceSplices[]): void; $updateGroup(sourceControlHandle: number, handle: number, features: SCMGroupFeatures): void; $updateGroupLabel(sourceControlHandle: number, handle: number, label: string): void; $unregisterGroup(sourceControlHandle: number, handle: number): void; $spliceResourceStates(sourceControlHandle: number, splices: SCMRawResourceSplices[]): void; $setInputBoxValue(sourceControlHandle: number, value: string): void; $setInputBoxPlaceholder(sourceControlHandle: number, placeholder: string): void; $setInputBoxVisibility(sourceControlHandle: number, visible: boolean): void; $setValidationProviderIsEnabled(sourceControlHandle: number, enabled: boolean): void; } export type DebugSessionUUID = string; export interface IDebugConfiguration { type: string; name: string; request: string; [key: string]: any; } export interface IStartDebuggingOptions { parentSessionID?: DebugSessionUUID; repl?: IDebugSessionReplMode; noDebug?: boolean; compact?: boolean; } export interface MainThreadDebugServiceShape extends IDisposable { $registerDebugTypes(debugTypes: string[]): void; $sessionCached(sessionID: string): void; $acceptDAMessage(handle: number, message: DebugProtocol.ProtocolMessage): void; $acceptDAError(handle: number, name: string, message: string, stack: string | undefined): void; $acceptDAExit(handle: number, code: number | undefined, signal: string | undefined): void; $registerDebugConfigurationProvider(type: string, triggerKind: DebugConfigurationProviderTriggerKind, hasProvideMethod: boolean, hasResolveMethod: boolean, hasResolve2Method: boolean, handle: number): Promise<void>; $registerDebugAdapterDescriptorFactory(type: string, handle: number): Promise<void>; $unregisterDebugConfigurationProvider(handle: number): void; $unregisterDebugAdapterDescriptorFactory(handle: number): void; $startDebugging(folder: UriComponents | undefined, nameOrConfig: string | IDebugConfiguration, options: IStartDebuggingOptions): Promise<boolean>; $stopDebugging(sessionId: DebugSessionUUID | undefined): Promise<void>; $setDebugSessionName(id: DebugSessionUUID, name: string): void; $customDebugAdapterRequest(id: DebugSessionUUID, command: string, args: any): Promise<any>; $getDebugProtocolBreakpoint(id: DebugSessionUUID, breakpoinId: string): Promise<DebugProtocol.Breakpoint | undefined>; $appendDebugConsole(value: string): void; $startBreakpointEvents(): void; $registerBreakpoints(breakpoints: Array<ISourceMultiBreakpointDto | IFunctionBreakpointDto | IDataBreakpointDto>): Promise<void>; $unregisterBreakpoints(breakpointIds: string[], functionBreakpointIds: string[], dataBreakpointIds: string[]): Promise<void>; } export interface IOpenUriOptions { readonly allowTunneling?: boolean; readonly allowContributedOpeners?: boolean | string; } export interface MainThreadWindowShape extends IDisposable { $getWindowVisibility(): Promise<boolean>; $openUri(uri: UriComponents, uriString: string | undefined, options: IOpenUriOptions): Promise<boolean>; $asExternalUri(uri: UriComponents, options: IOpenUriOptions): Promise<UriComponents>; } export enum CandidatePortSource { None = 0, Process = 1, Output = 2 } export interface MainThreadTunnelServiceShape extends IDisposable { $openTunnel(tunnelOptions: TunnelOptions, source: string | undefined): Promise<TunnelDto | undefined>; $closeTunnel(remote: { host: string, port: number }): Promise<void>; $getTunnels(): Promise<TunnelDescription[]>; $setTunnelProvider(features: TunnelProviderFeatures): Promise<void>; $setRemoteTunnelService(processId: number): Promise<void>; $setCandidateFilter(): Promise<void>; $onFoundNewCandidates(candidates: { host: string, port: number, detail: string }[]): Promise<void>; $setCandidatePortSource(source: CandidatePortSource): Promise<void>; } export interface MainThreadTimelineShape extends IDisposable { $registerTimelineProvider(provider: TimelineProviderDescriptor): void; $unregisterTimelineProvider(source: string): void; $emitTimelineChangeEvent(e: TimelineChangeEvent | undefined): void; } // -- extension host export interface ExtHostCommandsShape { $executeContributedCommand<T>(id: string, ...args: any[]): Promise<T>; $getContributedCommandHandlerDescriptions(): Promise<{ [id: string]: string | ICommandHandlerDescription; }>; } export interface ExtHostConfigurationShape { $initializeConfiguration(data: IConfigurationInitData): void; $acceptConfigurationChanged(data: IConfigurationInitData, change: IConfigurationChange): void; } export interface ExtHostDiagnosticsShape { $acceptMarkersChange(data: [UriComponents, IMarkerData[]][]): void; } export interface ExtHostDocumentContentProvidersShape { $provideTextDocumentContent(handle: number, uri: UriComponents): Promise<string | null | undefined>; } export interface IModelAddedData { uri: UriComponents; versionId: number; lines: string[]; EOL: string; modeId: string; isDirty: boolean; } export interface ExtHostDocumentsShape { $acceptModelModeChanged(strURL: UriComponents, oldModeId: string, newModeId: string): void; $acceptModelSaved(strURL: UriComponents): void; $acceptDirtyStateChanged(strURL: UriComponents, isDirty: boolean): void; $acceptModelChanged(strURL: UriComponents, e: IModelChangedEvent, isDirty: boolean): void; } export interface ExtHostDocumentSaveParticipantShape { $participateInSave(resource: UriComponents, reason: SaveReason): Promise<boolean[]>; } export interface ITextEditorAddData { id: string; documentUri: UriComponents; options: IResolvedTextEditorConfiguration; selections: ISelection[]; visibleRanges: IRange[]; editorPosition: EditorGroupColumn | undefined; } export interface ITextEditorPositionData { [id: string]: EditorGroupColumn; } export interface IEditorPropertiesChangeData { options: IResolvedTextEditorConfiguration | null; selections: ISelectionChangeEvent | null; visibleRanges: IRange[] | null; } export interface ISelectionChangeEvent { selections: Selection[]; source?: string; } export interface ExtHostEditorsShape { $acceptEditorPropertiesChanged(id: string, props: IEditorPropertiesChangeData): void; $acceptEditorPositionData(data: ITextEditorPositionData): void; } export interface IDocumentsAndEditorsDelta { removedDocuments?: UriComponents[]; addedDocuments?: IModelAddedData[]; removedEditors?: string[]; addedEditors?: ITextEditorAddData[]; newActiveEditor?: string | null; } export interface ExtHostDocumentsAndEditorsShape { $acceptDocumentsAndEditorsDelta(delta: IDocumentsAndEditorsDelta): void; } export interface ExtHostTreeViewsShape { $getChildren(treeViewId: string, treeItemHandle?: string): Promise<ITreeItem[]>; $setExpanded(treeViewId: string, treeItemHandle: string, expanded: boolean): void; $setSelection(treeViewId: string, treeItemHandles: string[]): void; $setVisible(treeViewId: string, visible: boolean): void; $hasResolve(treeViewId: string): Promise<boolean>; $resolve(treeViewId: string, treeItemHandle: string, token: CancellationToken): Promise<ITreeItem | undefined>; } export interface ExtHostWorkspaceShape { $initializeWorkspace(workspace: IWorkspaceData | null, trustState: WorkspaceTrustState): void; $acceptWorkspaceData(workspace: IWorkspaceData | null): void; $handleTextSearchResult(result: search.IRawFileMatch2, requestId: number): void; $onDidChangeWorkspaceTrustState(state: WorkspaceTrustStateChangeEvent): void; } export interface ExtHostFileSystemInfoShape { $acceptProviderInfos(scheme: string, capabilities: number | null): void; } export interface ExtHostFileSystemShape { $stat(handle: number, resource: UriComponents): Promise<files.IStat>; $readdir(handle: number, resource: UriComponents): Promise<[string, files.FileType][]>; $readFile(handle: number, resource: UriComponents): Promise<VSBuffer>; $writeFile(handle: number, resource: UriComponents, content: VSBuffer, opts: files.FileWriteOptions): Promise<void>; $rename(handle: number, resource: UriComponents, target: UriComponents, opts: files.FileOverwriteOptions): Promise<void>; $copy(handle: number, resource: UriComponents, target: UriComponents, opts: files.FileOverwriteOptions): Promise<void>; $mkdir(handle: number, resource: UriComponents): Promise<void>; $delete(handle: number, resource: UriComponents, opts: files.FileDeleteOptions): Promise<void>; $watch(handle: number, session: number, resource: UriComponents, opts: files.IWatchOptions): void; $unwatch(handle: number, session: number): void; $open(handle: number, resource: UriComponents, opts: files.FileOpenOptions): Promise<number>; $close(handle: number, fd: number): Promise<void>; $read(handle: number, fd: number, pos: number, length: number): Promise<VSBuffer>; $write(handle: number, fd: number, pos: number, data: VSBuffer): Promise<number>; } export interface ExtHostLabelServiceShape { $registerResourceLabelFormatter(formatter: ResourceLabelFormatter): IDisposable; } export interface ExtHostAuthenticationShape { $getSessions(id: string, scopes?: string[]): Promise<ReadonlyArray<modes.AuthenticationSession>>; $createSession(id: string, scopes: string[]): Promise<modes.AuthenticationSession>; $removeSession(id: string, sessionId: string): Promise<void>; $onDidChangeAuthenticationSessions(id: string, label: string, event: modes.AuthenticationSessionsChangeEvent): Promise<void>; $onDidChangeAuthenticationProviders(added: modes.AuthenticationProviderInformation[], removed: modes.AuthenticationProviderInformation[]): Promise<void>; $setProviders(providers: modes.AuthenticationProviderInformation[]): Promise<void>; } export interface ExtHostSecretStateShape { $onDidChangePassword(e: { extensionId: string, key: string }): Promise<void>; } export interface ExtHostSearchShape { $provideFileSearchResults(handle: number, session: number, query: search.IRawQuery, token: CancellationToken): Promise<search.ISearchCompleteStats>; $provideTextSearchResults(handle: number, session: number, query: search.IRawTextQuery, token: CancellationToken): Promise<search.ISearchCompleteStats>; $clearCache(cacheKey: string): Promise<void>; } export interface IResolveAuthorityErrorResult { type: 'error'; error: { message: string | undefined; code: RemoteAuthorityResolverErrorCode; detail: any; }; } export interface IResolveAuthorityOKResult { type: 'ok'; value: ResolverResult; } export type IResolveAuthorityResult = IResolveAuthorityErrorResult | IResolveAuthorityOKResult; export interface ExtHostExtensionServiceShape { $resolveAuthority(remoteAuthority: string, resolveAttempt: number): Promise<IResolveAuthorityResult>; $startExtensionHost(enabledExtensionIds: ExtensionIdentifier[]): Promise<void>; $activateByEvent(activationEvent: string, activationKind: ActivationKind): Promise<void>; $activate(extensionId: ExtensionIdentifier, reason: ExtensionActivationReason): Promise<boolean>; $setRemoteEnvironment(env: { [key: string]: string | null; }): Promise<void>; $updateRemoteConnectionData(connectionData: IRemoteConnectionData): Promise<void>; $deltaExtensions(toAdd: IExtensionDescription[], toRemove: ExtensionIdentifier[]): Promise<void>; $test_latency(n: number): Promise<number>; $test_up(b: VSBuffer): Promise<number>; $test_down(size: number): Promise<VSBuffer>; } export interface FileSystemEvents { created: UriComponents[]; changed: UriComponents[]; deleted: UriComponents[]; } export interface SourceTargetPair { source?: UriComponents; target: UriComponents; } export interface IWillRunFileOperationParticipation { edit: IWorkspaceEditDto; extensionNames: string[] } export interface ExtHostFileSystemEventServiceShape { $onFileEvent(events: FileSystemEvents): void; $onWillRunFileOperation(operation: files.FileOperation, files: SourceTargetPair[], timeout: number, token: CancellationToken): Promise<IWillRunFileOperationParticipation | undefined>; $onDidRunFileOperation(operation: files.FileOperation, files: SourceTargetPair[]): void; } export interface ObjectIdentifier { $ident?: number; } export namespace ObjectIdentifier { export const name = '$ident'; export function mixin<T>(obj: T, id: number): T & ObjectIdentifier { Object.defineProperty(obj, name, { value: id, enumerable: true }); return <T & ObjectIdentifier>obj; } export function of(obj: any): number { return obj[name]; } } export interface ExtHostHeapServiceShape { $onGarbageCollection(ids: number[]): void; } export interface IRawColorInfo { color: [number, number, number, number]; range: IRange; } export class IdObject { _id?: number; private static _n = 0; static mixin<T extends object>(object: T): T & IdObject { (<any>object)._id = IdObject._n++; return <any>object; } } export const enum ISuggestDataDtoField { label = 'a', kind = 'b', detail = 'c', documentation = 'd', sortText = 'e', filterText = 'f', preselect = 'g', insertText = 'h', insertTextRules = 'i', range = 'j', commitCharacters = 'k', additionalTextEdits = 'l', command = 'm', kindModifier = 'n', // to merge into label label2 = 'o', } export interface ISuggestDataDto { [ISuggestDataDtoField.label]: string; [ISuggestDataDtoField.label2]?: string | modes.CompletionItemLabel; [ISuggestDataDtoField.kind]?: modes.CompletionItemKind; [ISuggestDataDtoField.detail]?: string; [ISuggestDataDtoField.documentation]?: string | IMarkdownString; [ISuggestDataDtoField.sortText]?: string; [ISuggestDataDtoField.filterText]?: string; [ISuggestDataDtoField.preselect]?: true; [ISuggestDataDtoField.insertText]?: string; [ISuggestDataDtoField.insertTextRules]?: modes.CompletionItemInsertTextRule; [ISuggestDataDtoField.range]?: IRange | { insert: IRange, replace: IRange; }; [ISuggestDataDtoField.commitCharacters]?: string[]; [ISuggestDataDtoField.additionalTextEdits]?: ISingleEditOperation[]; [ISuggestDataDtoField.command]?: modes.Command; [ISuggestDataDtoField.kindModifier]?: modes.CompletionItemTag[]; // not-standard x?: ChainedCacheId; } export const enum ISuggestResultDtoField { defaultRanges = 'a', completions = 'b', isIncomplete = 'c', duration = 'd', } export interface ISuggestResultDto { [ISuggestResultDtoField.defaultRanges]: { insert: IRange, replace: IRange; }; [ISuggestResultDtoField.completions]: ISuggestDataDto[]; [ISuggestResultDtoField.isIncomplete]: undefined | true; [ISuggestResultDtoField.duration]: number; x?: number; } export interface ISignatureHelpDto { id: CacheId; signatures: modes.SignatureInformation[]; activeSignature: number; activeParameter: number; } export interface ISignatureHelpContextDto { readonly triggerKind: modes.SignatureHelpTriggerKind; readonly triggerCharacter?: string; readonly isRetrigger: boolean; readonly activeSignatureHelp?: ISignatureHelpDto; } export interface IInlineHintDto { text: string; range: IRange; kind: modes.InlineHintKind; whitespaceBefore?: boolean; whitespaceAfter?: boolean; hoverMessage?: string; } export interface IInlineHintsDto { hints: IInlineHintDto[] } export interface ILocationDto { uri: UriComponents; range: IRange; } export interface IDefinitionLinkDto { originSelectionRange?: IRange; uri: UriComponents; range: IRange; targetSelectionRange?: IRange; } export interface IWorkspaceSymbolDto extends IdObject { name: string; containerName?: string; kind: modes.SymbolKind; location: ILocationDto; } export interface IWorkspaceSymbolsDto extends IdObject { symbols: IWorkspaceSymbolDto[]; } export interface IWorkspaceEditEntryMetadataDto { needsConfirmation: boolean; label: string; description?: string; iconPath?: { id: string } | UriComponents | { light: UriComponents, dark: UriComponents }; } export const enum WorkspaceEditType { File = 1, Text = 2, Cell = 3, } export interface IWorkspaceFileEditDto { _type: WorkspaceEditType.File; oldUri?: UriComponents; newUri?: UriComponents; options?: modes.WorkspaceFileEditOptions metadata?: IWorkspaceEditEntryMetadataDto; } export interface IWorkspaceTextEditDto { _type: WorkspaceEditType.Text; resource: UriComponents; edit: modes.TextEdit; modelVersionId?: number; metadata?: IWorkspaceEditEntryMetadataDto; } export interface IWorkspaceCellEditDto { _type: WorkspaceEditType.Cell; resource: UriComponents; edit: ICellEditOperation; notebookVersionId?: number; metadata?: IWorkspaceEditEntryMetadataDto; } export interface IWorkspaceEditDto { edits: Array<IWorkspaceFileEditDto | IWorkspaceTextEditDto | IWorkspaceCellEditDto>; // todo@jrieken reject should go into rename rejectReason?: string; } export function reviveWorkspaceEditDto(data: IWorkspaceEditDto | undefined): modes.WorkspaceEdit { if (data && data.edits) { for (const edit of data.edits) { if (typeof (<IWorkspaceTextEditDto>edit).resource === 'object') { (<IWorkspaceTextEditDto>edit).resource = URI.revive((<IWorkspaceTextEditDto>edit).resource); } else { (<IWorkspaceFileEditDto>edit).newUri = URI.revive((<IWorkspaceFileEditDto>edit).newUri); (<IWorkspaceFileEditDto>edit).oldUri = URI.revive((<IWorkspaceFileEditDto>edit).oldUri); } if (edit.metadata && edit.metadata.iconPath) { edit.metadata = revive(edit.metadata); } } } return <modes.WorkspaceEdit>data; } export type ICommandDto = ObjectIdentifier & modes.Command; export interface ICodeActionDto { cacheId?: ChainedCacheId; title: string; edit?: IWorkspaceEditDto; diagnostics?: IMarkerData[]; command?: ICommandDto; kind?: string; isPreferred?: boolean; disabled?: string; } export interface ICodeActionListDto { cacheId: CacheId; actions: ReadonlyArray<ICodeActionDto>; } export interface ICodeActionProviderMetadataDto { readonly providedKinds?: readonly string[]; readonly documentation?: ReadonlyArray<{ readonly kind: string, readonly command: ICommandDto }>; } export type CacheId = number; export type ChainedCacheId = [CacheId, CacheId]; export interface ILinksListDto { id?: CacheId; links: ILinkDto[]; } export interface ILinkDto { cacheId?: ChainedCacheId; range: IRange; url?: string | UriComponents; tooltip?: string; } export interface ICodeLensListDto { cacheId?: number; lenses: ICodeLensDto[]; } export interface ICodeLensDto { cacheId?: ChainedCacheId; range: IRange; command?: ICommandDto; } export type ICallHierarchyItemDto = Dto<CallHierarchyItem>; export interface IIncomingCallDto { from: ICallHierarchyItemDto; fromRanges: IRange[]; } export interface IOutgoingCallDto { fromRanges: IRange[]; to: ICallHierarchyItemDto; } export interface ILanguageWordDefinitionDto { languageId: string; regexSource: string; regexFlags: string } export interface ILinkedEditingRangesDto { ranges: IRange[]; wordPattern?: IRegExpDto; } export interface IInlineValueContextDto { stoppedLocation: IRange; } export interface ExtHostLanguageFeaturesShape { $provideDocumentSymbols(handle: number, resource: UriComponents, token: CancellationToken): Promise<modes.DocumentSymbol[] | undefined>; $provideCodeLenses(handle: number, resource: UriComponents, token: CancellationToken): Promise<ICodeLensListDto | undefined>; $resolveCodeLens(handle: number, symbol: ICodeLensDto, token: CancellationToken): Promise<ICodeLensDto | undefined>; $releaseCodeLenses(handle: number, id: number): void; $provideDefinition(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<IDefinitionLinkDto[]>; $provideDeclaration(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<IDefinitionLinkDto[]>; $provideImplementation(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<IDefinitionLinkDto[]>; $provideTypeDefinition(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<IDefinitionLinkDto[]>; $provideHover(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<modes.Hover | undefined>; $provideEvaluatableExpression(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<modes.EvaluatableExpression | undefined>; $provideInlineValues(handle: number, resource: UriComponents, range: IRange, context: modes.InlineValueContext, token: CancellationToken): Promise<modes.InlineValue[] | undefined>; $provideDocumentHighlights(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<modes.DocumentHighlight[] | undefined>; $provideLinkedEditingRanges(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<ILinkedEditingRangesDto | undefined>; $provideReferences(handle: number, resource: UriComponents, position: IPosition, context: modes.ReferenceContext, token: CancellationToken): Promise<ILocationDto[] | undefined>; $provideCodeActions(handle: number, resource: UriComponents, rangeOrSelection: IRange | ISelection, context: modes.CodeActionContext, token: CancellationToken): Promise<ICodeActionListDto | undefined>; $resolveCodeAction(handle: number, id: ChainedCacheId, token: CancellationToken): Promise<IWorkspaceEditDto | undefined>; $releaseCodeActions(handle: number, cacheId: number): void; $provideDocumentFormattingEdits(handle: number, resource: UriComponents, options: modes.FormattingOptions, token: CancellationToken): Promise<ISingleEditOperation[] | undefined>; $provideDocumentRangeFormattingEdits(handle: number, resource: UriComponents, range: IRange, options: modes.FormattingOptions, token: CancellationToken): Promise<ISingleEditOperation[] | undefined>; $provideOnTypeFormattingEdits(handle: number, resource: UriComponents, position: IPosition, ch: string, options: modes.FormattingOptions, token: CancellationToken): Promise<ISingleEditOperation[] | undefined>; $provideWorkspaceSymbols(handle: number, search: string, token: CancellationToken): Promise<IWorkspaceSymbolsDto>; $resolveWorkspaceSymbol(handle: number, symbol: IWorkspaceSymbolDto, token: CancellationToken): Promise<IWorkspaceSymbolDto | undefined>; $releaseWorkspaceSymbols(handle: number, id: number): void; $provideRenameEdits(handle: number, resource: UriComponents, position: IPosition, newName: string, token: CancellationToken): Promise<IWorkspaceEditDto | undefined>; $resolveRenameLocation(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<modes.RenameLocation | undefined>; $provideDocumentSemanticTokens(handle: number, resource: UriComponents, previousResultId: number, token: CancellationToken): Promise<VSBuffer | null>; $releaseDocumentSemanticTokens(handle: number, semanticColoringResultId: number): void; $provideDocumentRangeSemanticTokens(handle: number, resource: UriComponents, range: IRange, token: CancellationToken): Promise<VSBuffer | null>; $provideCompletionItems(handle: number, resource: UriComponents, position: IPosition, context: modes.CompletionContext, token: CancellationToken): Promise<ISuggestResultDto | undefined>; $resolveCompletionItem(handle: number, id: ChainedCacheId, token: CancellationToken): Promise<ISuggestDataDto | undefined>; $releaseCompletionItems(handle: number, id: number): void; $provideSignatureHelp(handle: number, resource: UriComponents, position: IPosition, context: modes.SignatureHelpContext, token: CancellationToken): Promise<ISignatureHelpDto | undefined>; $releaseSignatureHelp(handle: number, id: number): void; $provideInlineHints(handle: number, resource: UriComponents, range: IRange, token: CancellationToken): Promise<IInlineHintsDto | undefined> $provideDocumentLinks(handle: number, resource: UriComponents, token: CancellationToken): Promise<ILinksListDto | undefined>; $resolveDocumentLink(handle: number, id: ChainedCacheId, token: CancellationToken): Promise<ILinkDto | undefined>; $releaseDocumentLinks(handle: number, id: number): void; $provideDocumentColors(handle: number, resource: UriComponents, token: CancellationToken): Promise<IRawColorInfo[]>; $provideColorPresentations(handle: number, resource: UriComponents, colorInfo: IRawColorInfo, token: CancellationToken): Promise<modes.IColorPresentation[] | undefined>; $provideFoldingRanges(handle: number, resource: UriComponents, context: modes.FoldingContext, token: CancellationToken): Promise<modes.FoldingRange[] | undefined>; $provideSelectionRanges(handle: number, resource: UriComponents, positions: IPosition[], token: CancellationToken): Promise<modes.SelectionRange[][]>; $prepareCallHierarchy(handle: number, resource: UriComponents, position: IPosition, token: CancellationToken): Promise<ICallHierarchyItemDto[] | undefined>; $provideCallHierarchyIncomingCalls(handle: number, sessionId: string, itemId: string, token: CancellationToken): Promise<IIncomingCallDto[] | undefined>; $provideCallHierarchyOutgoingCalls(handle: number, sessionId: string, itemId: string, token: CancellationToken): Promise<IOutgoingCallDto[] | undefined>; $releaseCallHierarchy(handle: number, sessionId: string): void; $setWordDefinitions(wordDefinitions: ILanguageWordDefinitionDto[]): void; } export interface ExtHostQuickOpenShape { $onItemSelected(handle: number): void; $validateInput(input: string): Promise<string | null | undefined>; $onDidChangeActive(sessionId: number, handles: number[]): void; $onDidChangeSelection(sessionId: number, handles: number[]): void; $onDidAccept(sessionId: number): void; $onDidChangeValue(sessionId: number, value: string): void; $onDidTriggerButton(sessionId: number, handle: number): void; $onDidHide(sessionId: number): void; } export interface IShellLaunchConfigDto { name?: string; executable?: string; args?: string[] | string; cwd?: string | UriComponents; env?: { [key: string]: string | null; }; hideFromUser?: boolean; flowControl?: boolean; } export interface IShellDefinitionDto { label: string; path: string; } export interface IShellAndArgsDto { shell: string; args: string[] | string | undefined; } export interface ITerminalLinkDto { /** The ID of the link to enable activation and disposal. */ id: number; /** The startIndex of the link in the line. */ startIndex: number; /** The length of the link in the line. */ length: number; /** The descriptive label for what the link does when activated. */ label?: string; } export interface ITerminalDimensionsDto { columns: number; rows: number; } export interface ExtHostTerminalServiceShape { $acceptTerminalClosed(id: number, exitCode: number | undefined): void; $acceptTerminalOpened(id: number, extHostTerminalId: string | undefined, name: string, shellLaunchConfig: IShellLaunchConfigDto): void; $acceptActiveTerminalChanged(id: number | null): void; $acceptTerminalProcessId(id: number, processId: number): void; $acceptTerminalProcessData(id: number, data: string): void; $acceptTerminalTitleChange(id: number, name: string): void; $acceptTerminalDimensions(id: number, cols: number, rows: number): void; $acceptTerminalMaximumDimensions(id: number, cols: number, rows: number): void; $spawnExtHostProcess(id: number, shellLaunchConfig: IShellLaunchConfigDto, activeWorkspaceRootUri: UriComponents | undefined, cols: number, rows: number, isWorkspaceShellAllowed: boolean): Promise<ITerminalLaunchError | undefined>; $startExtensionTerminal(id: number, initialDimensions: ITerminalDimensionsDto | undefined): Promise<ITerminalLaunchError | undefined>; $acceptProcessAckDataEvent(id: number, charCount: number): void; $acceptProcessInput(id: number, data: string): void; $acceptProcessResize(id: number, cols: number, rows: number): void; $acceptProcessShutdown(id: number, immediate: boolean): void; $acceptProcessRequestInitialCwd(id: number): void; $acceptProcessRequestCwd(id: number): void; $acceptProcessRequestLatency(id: number): number; $acceptWorkspacePermissionsChanged(isAllowed: boolean): void; $getAvailableShells(): Promise<IShellDefinitionDto[]>; $getDefaultShellAndArgs(useAutomationShell: boolean): Promise<IShellAndArgsDto>; $provideLinks(id: number, line: string): Promise<ITerminalLinkDto[]>; $activateLink(id: number, linkId: number): void; $initEnvironmentVariableCollections(collections: [string, ISerializableEnvironmentVariableCollection][]): void; } export interface ExtHostSCMShape { $provideOriginalResource(sourceControlHandle: number, uri: UriComponents, token: CancellationToken): Promise<UriComponents | null>; $onInputBoxValueChange(sourceControlHandle: number, value: string): void; $executeResourceCommand(sourceControlHandle: number, groupHandle: number, handle: number, preserveFocus: boolean): Promise<void>; $validateInput(sourceControlHandle: number, value: string, cursorPosition: number): Promise<[string, number] | undefined>; $setSelectedSourceControl(selectedSourceControlHandle: number | undefined): Promise<void>; } export interface ExtHostTaskShape { $provideTasks(handle: number, validTypes: { [key: string]: boolean; }): Thenable<tasks.TaskSetDTO>; $resolveTask(handle: number, taskDTO: tasks.TaskDTO): Thenable<tasks.TaskDTO | undefined>; $onDidStartTask(execution: tasks.TaskExecutionDTO, terminalId: number, resolvedDefinition: tasks.TaskDefinitionDTO): void; $onDidStartTaskProcess(value: tasks.TaskProcessStartedDTO): void; $onDidEndTaskProcess(value: tasks.TaskProcessEndedDTO): void; $OnDidEndTask(execution: tasks.TaskExecutionDTO): void; $resolveVariables(workspaceFolder: UriComponents, toResolve: { process?: { name: string; cwd?: string; }, variables: string[]; }): Promise<{ process?: string; variables: { [key: string]: string; }; }>; $getDefaultShellAndArgs(): Thenable<{ shell: string, args: string[] | string | undefined; }>; $jsonTasksSupported(): Thenable<boolean>; $findExecutable(command: string, cwd?: string, paths?: string[]): Promise<string | undefined>; } export interface IBreakpointDto { type: string; id?: string; enabled: boolean; condition?: string; hitCondition?: string; logMessage?: string; } export interface IFunctionBreakpointDto extends IBreakpointDto { type: 'function'; functionName: string; } export interface IDataBreakpointDto extends IBreakpointDto { type: 'data'; dataId: string; canPersist: boolean; label: string; accessTypes?: DebugProtocol.DataBreakpointAccessType[]; } export interface ISourceBreakpointDto extends IBreakpointDto { type: 'source'; uri: UriComponents; line: number; character: number; } export interface IBreakpointsDeltaDto { added?: Array<ISourceBreakpointDto | IFunctionBreakpointDto | IDataBreakpointDto>; removed?: string[]; changed?: Array<ISourceBreakpointDto | IFunctionBreakpointDto | IDataBreakpointDto>; } export interface ISourceMultiBreakpointDto { type: 'sourceMulti'; uri: UriComponents; lines: { id: string; enabled: boolean; condition?: string; hitCondition?: string; logMessage?: string; line: number; character: number; }[]; } export interface IDebugSessionFullDto { id: DebugSessionUUID; type: string; name: string; folderUri: UriComponents | undefined; configuration: IConfig; } export type IDebugSessionDto = IDebugSessionFullDto | DebugSessionUUID; export interface ExtHostDebugServiceShape { $substituteVariables(folder: UriComponents | undefined, config: IConfig): Promise<IConfig>; $runInTerminal(args: DebugProtocol.RunInTerminalRequestArguments, sessionId: string): Promise<number | undefined>; $startDASession(handle: number, session: IDebugSessionDto): Promise<void>; $stopDASession(handle: number): Promise<void>; $sendDAMessage(handle: number, message: DebugProtocol.ProtocolMessage): void; $resolveDebugConfiguration(handle: number, folder: UriComponents | undefined, debugConfiguration: IConfig, token: CancellationToken): Promise<IConfig | null | undefined>; $resolveDebugConfigurationWithSubstitutedVariables(handle: number, folder: UriComponents | undefined, debugConfiguration: IConfig, token: CancellationToken): Promise<IConfig | null | undefined>; $provideDebugConfigurations(handle: number, folder: UriComponents | undefined, token: CancellationToken): Promise<IConfig[]>; $provideDebugAdapter(handle: number, session: IDebugSessionDto): Promise<IAdapterDescriptor>; $acceptDebugSessionStarted(session: IDebugSessionDto): void; $acceptDebugSessionTerminated(session: IDebugSessionDto): void; $acceptDebugSessionActiveChanged(session: IDebugSessionDto | undefined): void; $acceptDebugSessionCustomEvent(session: IDebugSessionDto, event: any): void; $acceptBreakpointsDelta(delta: IBreakpointsDeltaDto): void; $acceptDebugSessionNameChanged(session: IDebugSessionDto, name: string): void; } export interface DecorationRequest { readonly id: number; readonly uri: UriComponents; } export type DecorationData = [boolean, string, string, ThemeColor]; export type DecorationReply = { [id: number]: DecorationData; }; export interface ExtHostDecorationsShape { $provideDecorations(handle: number, requests: DecorationRequest[], token: CancellationToken): Promise<DecorationReply>; } export interface ExtHostWindowShape { $onDidChangeWindowFocus(value: boolean): void; } export interface ExtHostLogServiceShape { $setLevel(level: LogLevel): void; } export interface MainThreadLogShape { $log(file: UriComponents, level: LogLevel, args: any[]): void; } export interface ExtHostOutputServiceShape { $setVisibleChannel(channelId: string | null): void; } export interface ExtHostProgressShape { $acceptProgressCanceled(handle: number): void; } export interface ExtHostCommentsShape { $createCommentThreadTemplate(commentControllerHandle: number, uriComponents: UriComponents, range: IRange): void; $updateCommentThreadTemplate(commentControllerHandle: number, threadHandle: number, range: IRange): Promise<void>; $deleteCommentThread(commentControllerHandle: number, commentThreadHandle: number): void; $provideCommentingRanges(commentControllerHandle: number, uriComponents: UriComponents, token: CancellationToken): Promise<IRange[] | undefined>; $toggleReaction(commentControllerHandle: number, threadHandle: number, uri: UriComponents, comment: modes.Comment, reaction: modes.CommentReaction): Promise<void>; } export interface INotebookSelectionChangeEvent { // handles selections: number[]; } export interface INotebookVisibleRangesEvent { ranges: ICellRange[]; } export interface INotebookEditorPropertiesChangeData { visibleRanges: INotebookVisibleRangesEvent | null; selections: INotebookSelectionChangeEvent | null; } export interface INotebookDocumentPropertiesChangeData { metadata: NotebookDocumentMetadata | null; } export interface INotebookModelAddedData { uri: UriComponents; versionId: number; cells: IMainCellDto[], viewType: string; metadata?: NotebookDocumentMetadata; attachedEditor?: { id: string; selections: number[]; visibleRanges: ICellRange[] } contentOptions: { transientOutputs: boolean; transientMetadata: TransientMetadata; } } export interface INotebookEditorAddData { id: string; documentUri: UriComponents; selections: number[]; visibleRanges: ICellRange[]; } export interface INotebookDocumentsAndEditorsDelta { removedDocuments?: UriComponents[]; addedDocuments?: INotebookModelAddedData[]; removedEditors?: string[]; addedEditors?: INotebookEditorAddData[]; newActiveEditor?: string | null; visibleEditors?: string[]; } export interface INotebookKernelInfoDto2 { id?: string; friendlyId: string; label: string; extension: ExtensionIdentifier; extensionLocation: UriComponents; providerHandle?: number; description?: string; detail?: string; isPreferred?: boolean; preloads?: UriComponents[]; supportedLanguages?: string[] } export interface ExtHostNotebookShape { $openNotebook(viewType: string, uri: UriComponents, backupId?: string): Promise<NotebookDataDto>; $resolveNotebookEditor(viewType: string, uri: UriComponents, editorId: string): Promise<void>; $provideNotebookKernels(handle: number, uri: UriComponents, token: CancellationToken): Promise<INotebookKernelInfoDto2[]>; $resolveNotebookKernel(handle: number, editorId: string, uri: UriComponents, kernelId: string, token: CancellationToken): Promise<void>; $executeNotebookKernelFromProvider(handle: number, uri: UriComponents, kernelId: string, cellHandle: number | undefined): Promise<void>; $cancelNotebookKernelFromProvider(handle: number, uri: UriComponents, kernelId: string, cellHandle: number | undefined): Promise<void>; $saveNotebook(viewType: string, uri: UriComponents, token: CancellationToken): Promise<boolean>; $saveNotebookAs(viewType: string, uri: UriComponents, target: UriComponents, token: CancellationToken): Promise<boolean>; $backup(viewType: string, uri: UriComponents, cancellation: CancellationToken): Promise<string | undefined>; $acceptDisplayOrder(displayOrder: INotebookDisplayOrder): void; $acceptNotebookActiveKernelChange(event: { uri: UriComponents, providerHandle: number | undefined, kernelFriendlyId: string | undefined }): void; $onDidReceiveMessage(editorId: string, rendererId: string | undefined, message: unknown): void; $acceptModelChanged(uriComponents: UriComponents, event: NotebookCellsChangedEventDto, isDirty: boolean): void; $acceptDirtyStateChanged(uriComponents: UriComponents, isDirty: boolean): void; $acceptModelSaved(uriComponents: UriComponents): void; $acceptEditorPropertiesChanged(id: string, data: INotebookEditorPropertiesChangeData): void; $acceptDocumentPropertiesChanged(uriComponents: UriComponents, data: INotebookDocumentPropertiesChangeData): void; $acceptDocumentAndEditorsDelta(delta: INotebookDocumentsAndEditorsDelta): void; } export interface ExtHostStorageShape { $acceptValue(shared: boolean, key: string, value: object | undefined): void; } export interface ExtHostThemingShape { $onColorThemeChange(themeType: string): void; } export interface MainThreadThemingShape extends IDisposable { } export interface ExtHostTunnelServiceShape { $forwardPort(tunnelOptions: TunnelOptions, tunnelCreationOptions: TunnelCreationOptions): Promise<TunnelDto | undefined>; $closeTunnel(remote: { host: string, port: number }, silent?: boolean): Promise<void>; $onDidTunnelsChange(): Promise<void>; $registerCandidateFinder(enable: boolean): Promise<void>; $applyCandidateFilter(candidates: CandidatePort[]): Promise<CandidatePort[]>; } export interface ExtHostTimelineShape { $getTimeline(source: string, uri: UriComponents, options: TimelineOptions, token: CancellationToken, internalOptions?: InternalTimelineOptions): Promise<Timeline | undefined>; } export const enum ExtHostTestingResource { Workspace, TextDocument } export interface ExtHostTestingShape { $runTestsForProvider(req: RunTestForProviderRequest, token: CancellationToken): Promise<void>; $subscribeToTests(resource: ExtHostTestingResource, uri: UriComponents): void; $unsubscribeFromTests(resource: ExtHostTestingResource, uri: UriComponents): void; $lookupTest(test: TestIdWithProvider): Promise<InternalTestItem | undefined>; $acceptDiff(resource: ExtHostTestingResource, uri: UriComponents, diff: TestsDiff): void; $publishTestResults(results: InternalTestResults): void; } export interface MainThreadTestingShape { $registerTestProvider(id: string): void; $unregisterTestProvider(id: string): void; $subscribeToDiffs(resource: ExtHostTestingResource, uri: UriComponents): void; $unsubscribeFromDiffs(resource: ExtHostTestingResource, uri: UriComponents): void; $publishDiff(resource: ExtHostTestingResource, uri: UriComponents, diff: TestsDiff): void; $updateTestStateInRun(runId: string, testId: string, state: ITestState): void; $runTests(req: RunTestsRequest, token: CancellationToken): Promise<string>; $retireTest(extId: string): void; } // --- proxy identifiers export const MainContext = { MainThreadAuthentication: createMainId<MainThreadAuthenticationShape>('MainThreadAuthentication'), MainThreadBulkEdits: createMainId<MainThreadBulkEditsShape>('MainThreadBulkEdits'), MainThreadClipboard: createMainId<MainThreadClipboardShape>('MainThreadClipboard'), MainThreadCommands: createMainId<MainThreadCommandsShape>('MainThreadCommands'), MainThreadComments: createMainId<MainThreadCommentsShape>('MainThreadComments'), MainThreadConfiguration: createMainId<MainThreadConfigurationShape>('MainThreadConfiguration'), MainThreadConsole: createMainId<MainThreadConsoleShape>('MainThreadConsole'), MainThreadDebugService: createMainId<MainThreadDebugServiceShape>('MainThreadDebugService'), MainThreadDecorations: createMainId<MainThreadDecorationsShape>('MainThreadDecorations'), MainThreadDiagnostics: createMainId<MainThreadDiagnosticsShape>('MainThreadDiagnostics'), MainThreadDialogs: createMainId<MainThreadDiaglogsShape>('MainThreadDiaglogs'), MainThreadDocuments: createMainId<MainThreadDocumentsShape>('MainThreadDocuments'), MainThreadDocumentContentProviders: createMainId<MainThreadDocumentContentProvidersShape>('MainThreadDocumentContentProviders'), MainThreadTextEditors: createMainId<MainThreadTextEditorsShape>('MainThreadTextEditors'), MainThreadEditorInsets: createMainId<MainThreadEditorInsetsShape>('MainThreadEditorInsets'), MainThreadEditorTabs: createMainId<MainThreadEditorTabsShape>('MainThreadEditorTabs'), MainThreadErrors: createMainId<MainThreadErrorsShape>('MainThreadErrors'), MainThreadTreeViews: createMainId<MainThreadTreeViewsShape>('MainThreadTreeViews'), MainThreadDownloadService: createMainId<MainThreadDownloadServiceShape>('MainThreadDownloadService'), MainThreadKeytar: createMainId<MainThreadKeytarShape>('MainThreadKeytar'), MainThreadLanguageFeatures: createMainId<MainThreadLanguageFeaturesShape>('MainThreadLanguageFeatures'), MainThreadLanguages: createMainId<MainThreadLanguagesShape>('MainThreadLanguages'), MainThreadLog: createMainId<MainThreadLogShape>('MainThread'), MainThreadMessageService: createMainId<MainThreadMessageServiceShape>('MainThreadMessageService'), MainThreadOutputService: createMainId<MainThreadOutputServiceShape>('MainThreadOutputService'), MainThreadProgress: createMainId<MainThreadProgressShape>('MainThreadProgress'), MainThreadQuickOpen: createMainId<MainThreadQuickOpenShape>('MainThreadQuickOpen'), MainThreadStatusBar: createMainId<MainThreadStatusBarShape>('MainThreadStatusBar'), MainThreadSecretState: createMainId<MainThreadSecretStateShape>('MainThreadSecretState'), MainThreadStorage: createMainId<MainThreadStorageShape>('MainThreadStorage'), MainThreadTelemetry: createMainId<MainThreadTelemetryShape>('MainThreadTelemetry'), MainThreadTerminalService: createMainId<MainThreadTerminalServiceShape>('MainThreadTerminalService'), MainThreadWebviews: createMainId<MainThreadWebviewsShape>('MainThreadWebviews'), MainThreadWebviewPanels: createMainId<MainThreadWebviewPanelsShape>('MainThreadWebviewPanels'), MainThreadWebviewViews: createMainId<MainThreadWebviewViewsShape>('MainThreadWebviewViews'), MainThreadCustomEditors: createMainId<MainThreadCustomEditorsShape>('MainThreadCustomEditors'), MainThreadUrls: createMainId<MainThreadUrlsShape>('MainThreadUrls'), MainThreadUriOpeners: createMainId<MainThreadUriOpenersShape>('MainThreadUriOpeners'), MainThreadWorkspace: createMainId<MainThreadWorkspaceShape>('MainThreadWorkspace'), MainThreadFileSystem: createMainId<MainThreadFileSystemShape>('MainThreadFileSystem'), MainThreadExtensionService: createMainId<MainThreadExtensionServiceShape>('MainThreadExtensionService'), MainThreadSCM: createMainId<MainThreadSCMShape>('MainThreadSCM'), MainThreadSearch: createMainId<MainThreadSearchShape>('MainThreadSearch'), MainThreadTask: createMainId<MainThreadTaskShape>('MainThreadTask'), MainThreadWindow: createMainId<MainThreadWindowShape>('MainThreadWindow'), MainThreadLabelService: createMainId<MainThreadLabelServiceShape>('MainThreadLabelService'), MainThreadNotebook: createMainId<MainThreadNotebookShape>('MainThreadNotebook'), MainThreadTheming: createMainId<MainThreadThemingShape>('MainThreadTheming'), MainThreadTunnelService: createMainId<MainThreadTunnelServiceShape>('MainThreadTunnelService'), MainThreadTimeline: createMainId<MainThreadTimelineShape>('MainThreadTimeline'), MainThreadTesting: createMainId<MainThreadTestingShape>('MainThreadTesting'), }; export const ExtHostContext = { ExtHostCommands: createExtId<ExtHostCommandsShape>('ExtHostCommands'), ExtHostConfiguration: createExtId<ExtHostConfigurationShape>('ExtHostConfiguration'), ExtHostDiagnostics: createExtId<ExtHostDiagnosticsShape>('ExtHostDiagnostics'), ExtHostDebugService: createExtId<ExtHostDebugServiceShape>('ExtHostDebugService'), ExtHostDecorations: createExtId<ExtHostDecorationsShape>('ExtHostDecorations'), ExtHostDocumentsAndEditors: createExtId<ExtHostDocumentsAndEditorsShape>('ExtHostDocumentsAndEditors'), ExtHostDocuments: createExtId<ExtHostDocumentsShape>('ExtHostDocuments'), ExtHostDocumentContentProviders: createExtId<ExtHostDocumentContentProvidersShape>('ExtHostDocumentContentProviders'), ExtHostDocumentSaveParticipant: createExtId<ExtHostDocumentSaveParticipantShape>('ExtHostDocumentSaveParticipant'), ExtHostEditors: createExtId<ExtHostEditorsShape>('ExtHostEditors'), ExtHostTreeViews: createExtId<ExtHostTreeViewsShape>('ExtHostTreeViews'), ExtHostFileSystem: createExtId<ExtHostFileSystemShape>('ExtHostFileSystem'), ExtHostFileSystemInfo: createExtId<ExtHostFileSystemInfoShape>('ExtHostFileSystemInfo'), ExtHostFileSystemEventService: createExtId<ExtHostFileSystemEventServiceShape>('ExtHostFileSystemEventService'), ExtHostLanguageFeatures: createExtId<ExtHostLanguageFeaturesShape>('ExtHostLanguageFeatures'), ExtHostQuickOpen: createExtId<ExtHostQuickOpenShape>('ExtHostQuickOpen'), ExtHostExtensionService: createExtId<ExtHostExtensionServiceShape>('ExtHostExtensionService'), ExtHostLogService: createExtId<ExtHostLogServiceShape>('ExtHostLogService'), ExtHostTerminalService: createExtId<ExtHostTerminalServiceShape>('ExtHostTerminalService'), ExtHostSCM: createExtId<ExtHostSCMShape>('ExtHostSCM'), ExtHostSearch: createExtId<ExtHostSearchShape>('ExtHostSearch'), ExtHostTask: createExtId<ExtHostTaskShape>('ExtHostTask'), ExtHostWorkspace: createExtId<ExtHostWorkspaceShape>('ExtHostWorkspace'), ExtHostWindow: createExtId<ExtHostWindowShape>('ExtHostWindow'), ExtHostWebviews: createExtId<ExtHostWebviewsShape>('ExtHostWebviews'), ExtHostWebviewPanels: createExtId<ExtHostWebviewPanelsShape>('ExtHostWebviewPanels'), ExtHostCustomEditors: createExtId<ExtHostCustomEditorsShape>('ExtHostCustomEditors'), ExtHostWebviewViews: createExtId<ExtHostWebviewViewsShape>('ExtHostWebviewViews'), ExtHostEditorInsets: createExtId<ExtHostEditorInsetsShape>('ExtHostEditorInsets'), ExtHostEditorTabs: createExtId<IExtHostEditorTabsShape>('ExtHostEditorTabs'), ExtHostProgress: createMainId<ExtHostProgressShape>('ExtHostProgress'), ExtHostComments: createMainId<ExtHostCommentsShape>('ExtHostComments'), ExtHostSecretState: createMainId<ExtHostSecretStateShape>('ExtHostSecretState'), ExtHostStorage: createMainId<ExtHostStorageShape>('ExtHostStorage'), ExtHostUrls: createExtId<ExtHostUrlsShape>('ExtHostUrls'), ExtHostUriOpeners: createExtId<ExtHostUriOpenersShape>('ExtHostUriOpeners'), ExtHostOutputService: createMainId<ExtHostOutputServiceShape>('ExtHostOutputService'), ExtHosLabelService: createMainId<ExtHostLabelServiceShape>('ExtHostLabelService'), ExtHostNotebook: createMainId<ExtHostNotebookShape>('ExtHostNotebook'), ExtHostTheming: createMainId<ExtHostThemingShape>('ExtHostTheming'), ExtHostTunnelService: createMainId<ExtHostTunnelServiceShape>('ExtHostTunnelService'), ExtHostAuthentication: createMainId<ExtHostAuthenticationShape>('ExtHostAuthentication'), ExtHostTimeline: createMainId<ExtHostTimelineShape>('ExtHostTimeline'), ExtHostTesting: createMainId<ExtHostTestingShape>('ExtHostTesting'), };
src/vs/workbench/api/common/extHost.protocol.ts
1
https://github.com/microsoft/vscode/commit/44dbd182557ee8c164f3917a2f9dc09a37ff623c
[ 0.0033779798541218042, 0.00021077453857287765, 0.00016307533951476216, 0.0001736506528686732, 0.0002621905878186226 ]
{ "id": 2, "code_window": [ "\tcreateTreeView<T>(viewId: string, options: vscode.TreeViewOptions<T>, extension: IExtensionDescription): vscode.TreeView<T> {\n", "\t\tif (!options || !options.treeDataProvider) {\n", "\t\t\tthrow new Error('Options with treeDataProvider is mandatory');\n", "\t\t}\n", "\n", "\t\tconst treeView = this.createExtHostTreeView(viewId, options, extension);\n", "\t\treturn {\n", "\t\t\tget onDidCollapseElement() { return treeView.onDidCollapseElement; },\n", "\t\t\tget onDidExpandElement() { return treeView.onDidExpandElement; },\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tconst registerPromise = this._proxy.$registerTreeViewDataProvider(viewId, { showCollapseAll: !!options.showCollapseAll, canSelectMany: !!options.canSelectMany });\n" ], "file_path": "src/vs/workbench/api/common/extHostTreeViews.ts", "type": "replace", "edit_start_line_idx": 86 }
"use strict"; /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ var _a; module.exports = new (_a = class ApiInterfaceNaming { constructor() { this.meta = { messages: { naming: 'Interfaces must not be prefixed with uppercase `I`', } }; } create(context) { return { ['TSInterfaceDeclaration Identifier']: (node) => { const name = node.name; if (ApiInterfaceNaming._nameRegExp.test(name)) { context.report({ node, messageId: 'naming' }); } } }; } }, _a._nameRegExp = /I[A-Z]/, _a);
build/lib/eslint/vscode-dts-interface-naming.js
0
https://github.com/microsoft/vscode/commit/44dbd182557ee8c164f3917a2f9dc09a37ff623c
[ 0.00017496240616310388, 0.0001702423905953765, 0.00016344663163181394, 0.00017128023318946362, 0.000004354887551016873 ]
{ "id": 2, "code_window": [ "\tcreateTreeView<T>(viewId: string, options: vscode.TreeViewOptions<T>, extension: IExtensionDescription): vscode.TreeView<T> {\n", "\t\tif (!options || !options.treeDataProvider) {\n", "\t\t\tthrow new Error('Options with treeDataProvider is mandatory');\n", "\t\t}\n", "\n", "\t\tconst treeView = this.createExtHostTreeView(viewId, options, extension);\n", "\t\treturn {\n", "\t\t\tget onDidCollapseElement() { return treeView.onDidCollapseElement; },\n", "\t\t\tget onDidExpandElement() { return treeView.onDidExpandElement; },\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tconst registerPromise = this._proxy.$registerTreeViewDataProvider(viewId, { showCollapseAll: !!options.showCollapseAll, canSelectMany: !!options.canSelectMany });\n" ], "file_path": "src/vs/workbench/api/common/extHostTreeViews.ts", "type": "replace", "edit_start_line_idx": 86 }
# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. # yarn lockfile v1 "@types/node@^12.19.9": version "12.19.9" resolved "https://registry.yarnpkg.com/@types/node/-/node-12.19.9.tgz#990ad687ad8b26ef6dcc34a4f69c33d40c95b679" integrity sha512-yj0DOaQeUrk3nJ0bd3Y5PeDRJ6W0r+kilosLA+dzF3dola/o9hxhMSg2sFvVcA2UHS5JSOsZp4S0c1OEXc4m1Q== vscode-nls@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/vscode-nls/-/vscode-nls-4.0.0.tgz#4001c8a6caba5cedb23a9c5ce1090395c0e44002" integrity sha512-qCfdzcH+0LgQnBpZA53bA32kzp9rpq/f66Som577ObeuDlFIrtbEJ+A/+CCxjIh4G8dpJYNCKIsxpRAHIfsbNw==
extensions/merge-conflict/yarn.lock
0
https://github.com/microsoft/vscode/commit/44dbd182557ee8c164f3917a2f9dc09a37ff623c
[ 0.00016990251606330276, 0.00016822078032419086, 0.00016653904458507895, 0.00016822078032419086, 0.0000016817357391119003 ]
{ "id": 2, "code_window": [ "\tcreateTreeView<T>(viewId: string, options: vscode.TreeViewOptions<T>, extension: IExtensionDescription): vscode.TreeView<T> {\n", "\t\tif (!options || !options.treeDataProvider) {\n", "\t\t\tthrow new Error('Options with treeDataProvider is mandatory');\n", "\t\t}\n", "\n", "\t\tconst treeView = this.createExtHostTreeView(viewId, options, extension);\n", "\t\treturn {\n", "\t\t\tget onDidCollapseElement() { return treeView.onDidCollapseElement; },\n", "\t\t\tget onDidExpandElement() { return treeView.onDidExpandElement; },\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tconst registerPromise = this._proxy.$registerTreeViewDataProvider(viewId, { showCollapseAll: !!options.showCollapseAll, canSelectMany: !!options.canSelectMany });\n" ], "file_path": "src/vs/workbench/api/common/extHostTreeViews.ts", "type": "replace", "edit_start_line_idx": 86 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { isNonEmptyArray } from 'vs/base/common/arrays'; import { DisposableStore } from 'vs/base/common/lifecycle'; import { ICodeEditor } from 'vs/editor/browser/editorBrowser'; import { ISelectedSuggestion, SuggestWidget } from './suggestWidget'; import { CharacterSet } from 'vs/editor/common/core/characterClassifier'; import { EditorOption } from 'vs/editor/common/config/editorOptions'; export class CommitCharacterController { private readonly _disposables = new DisposableStore(); private _active?: { readonly acceptCharacters: CharacterSet; readonly item: ISelectedSuggestion; }; constructor(editor: ICodeEditor, widget: SuggestWidget, accept: (selected: ISelectedSuggestion) => any) { this._disposables.add(widget.onDidShow(() => this._onItem(widget.getFocusedItem()))); this._disposables.add(widget.onDidFocus(this._onItem, this)); this._disposables.add(widget.onDidHide(this.reset, this)); this._disposables.add(editor.onWillType(text => { if (this._active && !widget.isFrozen()) { const ch = text.charCodeAt(text.length - 1); if (this._active.acceptCharacters.has(ch) && editor.getOption(EditorOption.acceptSuggestionOnCommitCharacter)) { accept(this._active.item); } } })); } private _onItem(selected: ISelectedSuggestion | undefined): void { if (!selected || !isNonEmptyArray(selected.item.completion.commitCharacters)) { // no item or no commit characters this.reset(); return; } if (this._active && this._active.item.item === selected.item) { // still the same item return; } // keep item and its commit characters const acceptCharacters = new CharacterSet(); for (const ch of selected.item.completion.commitCharacters) { if (ch.length > 0) { acceptCharacters.add(ch.charCodeAt(0)); } } this._active = { acceptCharacters, item: selected }; } reset(): void { this._active = undefined; } dispose() { this._disposables.dispose(); } }
src/vs/editor/contrib/suggest/suggestCommitCharacters.ts
0
https://github.com/microsoft/vscode/commit/44dbd182557ee8c164f3917a2f9dc09a37ff623c
[ 0.00017657752323430032, 0.0001730680523905903, 0.00016707122267689556, 0.0001742970198392868, 0.0000029028851713519543 ]
{ "id": 3, "code_window": [ "\t\t\t\ttreeView.description = description;\n", "\t\t\t},\n", "\t\t\treveal: (element: T, options?: IRevealOptions): Promise<void> => {\n", "\t\t\t\treturn treeView.reveal(element, options);\n", "\t\t\t},\n", "\t\t\tdispose: () => {\n", "\t\t\t\tthis.treeViews.delete(viewId);\n", "\t\t\t\ttreeView.dispose();\n", "\t\t\t}\n", "\t\t};\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tdispose: async () => {\n", "\t\t\t\t// Wait for the registration promise to finish before doing the dispose.\n", "\t\t\t\tawait registerPromise;\n" ], "file_path": "src/vs/workbench/api/common/extHostTreeViews.ts", "type": "replace", "edit_start_line_idx": 112 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { localize } from 'vs/nls'; import type * as vscode from 'vscode'; import { basename } from 'vs/base/common/resources'; import { URI } from 'vs/base/common/uri'; import { Emitter, Event } from 'vs/base/common/event'; import { Disposable, DisposableStore, IDisposable } from 'vs/base/common/lifecycle'; import { ExtHostTreeViewsShape, MainThreadTreeViewsShape } from './extHost.protocol'; import { ITreeItem, TreeViewItemHandleArg, ITreeItemLabel, IRevealOptions } from 'vs/workbench/common/views'; import { ExtHostCommands, CommandsConverter } from 'vs/workbench/api/common/extHostCommands'; import { asPromise } from 'vs/base/common/async'; import { TreeItemCollapsibleState, ThemeIcon, MarkdownString as MarkdownStringType } from 'vs/workbench/api/common/extHostTypes'; import { isUndefinedOrNull, isString } from 'vs/base/common/types'; import { equals, coalesce } from 'vs/base/common/arrays'; import { ILogService } from 'vs/platform/log/common/log'; import { IExtensionDescription } from 'vs/platform/extensions/common/extensions'; import { MarkdownString } from 'vs/workbench/api/common/extHostTypeConverters'; import { IMarkdownString } from 'vs/base/common/htmlContent'; import { CancellationTokenSource } from 'vs/base/common/cancellation'; import { Command } from 'vs/editor/common/modes'; type TreeItemHandle = string; function toTreeItemLabel(label: any, extension: IExtensionDescription): ITreeItemLabel | undefined { if (isString(label)) { return { label }; } if (label && typeof label === 'object' && typeof label.label === 'string') { let highlights: [number, number][] | undefined = undefined; if (Array.isArray(label.highlights)) { highlights = (<[number, number][]>label.highlights).filter((highlight => highlight.length === 2 && typeof highlight[0] === 'number' && typeof highlight[1] === 'number')); highlights = highlights.length ? highlights : undefined; } return { label: label.label, highlights }; } return undefined; } export class ExtHostTreeViews implements ExtHostTreeViewsShape { private treeViews: Map<string, ExtHostTreeView<any>> = new Map<string, ExtHostTreeView<any>>(); constructor( private _proxy: MainThreadTreeViewsShape, private commands: ExtHostCommands, private logService: ILogService ) { function isTreeViewItemHandleArg(arg: any): boolean { return arg && arg.$treeViewId && arg.$treeItemHandle; } commands.registerArgumentProcessor({ processArgument: arg => { if (isTreeViewItemHandleArg(arg)) { return this.convertArgument(arg); } else if (Array.isArray(arg) && (arg.length > 0)) { return arg.map(item => { if (isTreeViewItemHandleArg(item)) { return this.convertArgument(item); } return item; }); } return arg; } }); } registerTreeDataProvider<T>(id: string, treeDataProvider: vscode.TreeDataProvider<T>, extension: IExtensionDescription): vscode.Disposable { const treeView = this.createTreeView(id, { treeDataProvider }, extension); return { dispose: () => treeView.dispose() }; } createTreeView<T>(viewId: string, options: vscode.TreeViewOptions<T>, extension: IExtensionDescription): vscode.TreeView<T> { if (!options || !options.treeDataProvider) { throw new Error('Options with treeDataProvider is mandatory'); } const treeView = this.createExtHostTreeView(viewId, options, extension); return { get onDidCollapseElement() { return treeView.onDidCollapseElement; }, get onDidExpandElement() { return treeView.onDidExpandElement; }, get selection() { return treeView.selectedElements; }, get onDidChangeSelection() { return treeView.onDidChangeSelection; }, get visible() { return treeView.visible; }, get onDidChangeVisibility() { return treeView.onDidChangeVisibility; }, get message() { return treeView.message; }, set message(message: string) { treeView.message = message; }, get title() { return treeView.title; }, set title(title: string) { treeView.title = title; }, get description() { return treeView.description; }, set description(description: string | undefined) { treeView.description = description; }, reveal: (element: T, options?: IRevealOptions): Promise<void> => { return treeView.reveal(element, options); }, dispose: () => { this.treeViews.delete(viewId); treeView.dispose(); } }; } $getChildren(treeViewId: string, treeItemHandle?: string): Promise<ITreeItem[]> { const treeView = this.treeViews.get(treeViewId); if (!treeView) { return Promise.reject(new Error(localize('treeView.notRegistered', 'No tree view with id \'{0}\' registered.', treeViewId))); } return treeView.getChildren(treeItemHandle); } async $hasResolve(treeViewId: string): Promise<boolean> { const treeView = this.treeViews.get(treeViewId); if (!treeView) { throw new Error(localize('treeView.notRegistered', 'No tree view with id \'{0}\' registered.', treeViewId)); } return treeView.hasResolve; } $resolve(treeViewId: string, treeItemHandle: string, token: vscode.CancellationToken): Promise<ITreeItem | undefined> { const treeView = this.treeViews.get(treeViewId); if (!treeView) { throw new Error(localize('treeView.notRegistered', 'No tree view with id \'{0}\' registered.', treeViewId)); } return treeView.resolveTreeItem(treeItemHandle, token); } $setExpanded(treeViewId: string, treeItemHandle: string, expanded: boolean): void { const treeView = this.treeViews.get(treeViewId); if (!treeView) { throw new Error(localize('treeView.notRegistered', 'No tree view with id \'{0}\' registered.', treeViewId)); } treeView.setExpanded(treeItemHandle, expanded); } $setSelection(treeViewId: string, treeItemHandles: string[]): void { const treeView = this.treeViews.get(treeViewId); if (!treeView) { throw new Error(localize('treeView.notRegistered', 'No tree view with id \'{0}\' registered.', treeViewId)); } treeView.setSelection(treeItemHandles); } $setVisible(treeViewId: string, isVisible: boolean): void { const treeView = this.treeViews.get(treeViewId); if (!treeView) { throw new Error(localize('treeView.notRegistered', 'No tree view with id \'{0}\' registered.', treeViewId)); } treeView.setVisible(isVisible); } private createExtHostTreeView<T>(id: string, options: vscode.TreeViewOptions<T>, extension: IExtensionDescription): ExtHostTreeView<T> { const treeView = new ExtHostTreeView<T>(id, options, this._proxy, this.commands.converter, this.logService, extension); this.treeViews.set(id, treeView); return treeView; } private convertArgument(arg: TreeViewItemHandleArg): any { const treeView = this.treeViews.get(arg.$treeViewId); return treeView ? treeView.getExtensionElement(arg.$treeItemHandle) : null; } } type Root = null | undefined | void; type TreeData<T> = { message: boolean, element: T | Root | false }; interface TreeNode extends IDisposable { item: ITreeItem; extensionItem: vscode.TreeItem; parent: TreeNode | Root; children?: TreeNode[]; disposableStore: DisposableStore; } class ExtHostTreeView<T> extends Disposable { private static readonly LABEL_HANDLE_PREFIX = '0'; private static readonly ID_HANDLE_PREFIX = '1'; private readonly dataProvider: vscode.TreeDataProvider<T>; private roots: TreeNode[] | null = null; private elements: Map<TreeItemHandle, T> = new Map<TreeItemHandle, T>(); private nodes: Map<T, TreeNode> = new Map<T, TreeNode>(); private _visible: boolean = false; get visible(): boolean { return this._visible; } private _selectedHandles: TreeItemHandle[] = []; get selectedElements(): T[] { return <T[]>this._selectedHandles.map(handle => this.getExtensionElement(handle)).filter(element => !isUndefinedOrNull(element)); } private _onDidExpandElement: Emitter<vscode.TreeViewExpansionEvent<T>> = this._register(new Emitter<vscode.TreeViewExpansionEvent<T>>()); readonly onDidExpandElement: Event<vscode.TreeViewExpansionEvent<T>> = this._onDidExpandElement.event; private _onDidCollapseElement: Emitter<vscode.TreeViewExpansionEvent<T>> = this._register(new Emitter<vscode.TreeViewExpansionEvent<T>>()); readonly onDidCollapseElement: Event<vscode.TreeViewExpansionEvent<T>> = this._onDidCollapseElement.event; private _onDidChangeSelection: Emitter<vscode.TreeViewSelectionChangeEvent<T>> = this._register(new Emitter<vscode.TreeViewSelectionChangeEvent<T>>()); readonly onDidChangeSelection: Event<vscode.TreeViewSelectionChangeEvent<T>> = this._onDidChangeSelection.event; private _onDidChangeVisibility: Emitter<vscode.TreeViewVisibilityChangeEvent> = this._register(new Emitter<vscode.TreeViewVisibilityChangeEvent>()); readonly onDidChangeVisibility: Event<vscode.TreeViewVisibilityChangeEvent> = this._onDidChangeVisibility.event; private _onDidChangeData: Emitter<TreeData<T>> = this._register(new Emitter<TreeData<T>>()); private refreshPromise: Promise<void> = Promise.resolve(); private refreshQueue: Promise<void> = Promise.resolve(); constructor( private viewId: string, options: vscode.TreeViewOptions<T>, private proxy: MainThreadTreeViewsShape, private commands: CommandsConverter, private logService: ILogService, private extension: IExtensionDescription ) { super(); if (extension.contributes && extension.contributes.views) { for (const location in extension.contributes.views) { for (const view of extension.contributes.views[location]) { if (view.id === viewId) { this._title = view.name; } } } } this.dataProvider = options.treeDataProvider; this.proxy.$registerTreeViewDataProvider(viewId, { showCollapseAll: !!options.showCollapseAll, canSelectMany: !!options.canSelectMany }); if (this.dataProvider.onDidChangeTreeData) { this._register(this.dataProvider.onDidChangeTreeData(element => this._onDidChangeData.fire({ message: false, element }))); } let refreshingPromise: Promise<void> | null; let promiseCallback: () => void; this._register(Event.debounce<TreeData<T>, { message: boolean, elements: (T | Root)[] }>(this._onDidChangeData.event, (result, current) => { if (!result) { result = { message: false, elements: [] }; } if (current.element !== false) { if (!refreshingPromise) { // New refresh has started refreshingPromise = new Promise(c => promiseCallback = c); this.refreshPromise = this.refreshPromise.then(() => refreshingPromise!); } result.elements.push(current.element); } if (current.message) { result.message = true; } return result; }, 200, true)(({ message, elements }) => { if (elements.length) { this.refreshQueue = this.refreshQueue.then(() => { const _promiseCallback = promiseCallback; refreshingPromise = null; return this.refresh(elements).then(() => _promiseCallback()); }); } if (message) { this.proxy.$setMessage(this.viewId, this._message); } })); } getChildren(parentHandle: TreeItemHandle | Root): Promise<ITreeItem[]> { const parentElement = parentHandle ? this.getExtensionElement(parentHandle) : undefined; if (parentHandle && !parentElement) { this.logService.error(`No tree item with id \'${parentHandle}\' found.`); return Promise.resolve([]); } const childrenNodes = this.getChildrenNodes(parentHandle); // Get it from cache return (childrenNodes ? Promise.resolve(childrenNodes) : this.fetchChildrenNodes(parentElement)) .then(nodes => nodes.map(n => n.item)); } getExtensionElement(treeItemHandle: TreeItemHandle): T | undefined { return this.elements.get(treeItemHandle); } reveal(element: T | undefined, options?: IRevealOptions): Promise<void> { options = options ? options : { select: true, focus: false }; const select = isUndefinedOrNull(options.select) ? true : options.select; const focus = isUndefinedOrNull(options.focus) ? false : options.focus; const expand = isUndefinedOrNull(options.expand) ? false : options.expand; if (typeof this.dataProvider.getParent !== 'function') { return Promise.reject(new Error(`Required registered TreeDataProvider to implement 'getParent' method to access 'reveal' method`)); } if (element) { return this.refreshPromise .then(() => this.resolveUnknownParentChain(element)) .then(parentChain => this.resolveTreeNode(element, parentChain[parentChain.length - 1]) .then(treeNode => this.proxy.$reveal(this.viewId, { item: treeNode.item, parentChain: parentChain.map(p => p.item) }, { select, focus, expand })), error => this.logService.error(error)); } else { return this.proxy.$reveal(this.viewId, undefined, { select, focus, expand }); } } private _message: string = ''; get message(): string { return this._message; } set message(message: string) { this._message = message; this._onDidChangeData.fire({ message: true, element: false }); } private _title: string = ''; get title(): string { return this._title; } set title(title: string) { this._title = title; this.proxy.$setTitle(this.viewId, title, this._description); } private _description: string | undefined; get description(): string | undefined { return this._description; } set description(description: string | undefined) { this._description = description; this.proxy.$setTitle(this.viewId, this._title, description); } setExpanded(treeItemHandle: TreeItemHandle, expanded: boolean): void { const element = this.getExtensionElement(treeItemHandle); if (element) { if (expanded) { this._onDidExpandElement.fire(Object.freeze({ element })); } else { this._onDidCollapseElement.fire(Object.freeze({ element })); } } } setSelection(treeItemHandles: TreeItemHandle[]): void { if (!equals(this._selectedHandles, treeItemHandles)) { this._selectedHandles = treeItemHandles; this._onDidChangeSelection.fire(Object.freeze({ selection: this.selectedElements })); } } setVisible(visible: boolean): void { if (visible !== this._visible) { this._visible = visible; this._onDidChangeVisibility.fire(Object.freeze({ visible: this._visible })); } } get hasResolve(): boolean { return !!this.dataProvider.resolveTreeItem; } async resolveTreeItem(treeItemHandle: string, token: vscode.CancellationToken): Promise<ITreeItem | undefined> { if (!this.dataProvider.resolveTreeItem) { return; } const element = this.elements.get(treeItemHandle); if (element) { const node = this.nodes.get(element); if (node) { const resolve = await this.dataProvider.resolveTreeItem(node.extensionItem, element, token) ?? node.extensionItem; // Resolvable elements. Currently only tooltip and command. node.item.tooltip = this.getTooltip(resolve.tooltip); node.item.command = this.getCommand(node.disposableStore, resolve.command); return node.item; } } return; } private resolveUnknownParentChain(element: T): Promise<TreeNode[]> { return this.resolveParent(element) .then((parent) => { if (!parent) { return Promise.resolve([]); } return this.resolveUnknownParentChain(parent) .then(result => this.resolveTreeNode(parent, result[result.length - 1]) .then(parentNode => { result.push(parentNode); return result; })); }); } private resolveParent(element: T): Promise<T | Root> { const node = this.nodes.get(element); if (node) { return Promise.resolve(node.parent ? this.elements.get(node.parent.item.handle) : undefined); } return asPromise(() => this.dataProvider.getParent!(element)); } private resolveTreeNode(element: T, parent?: TreeNode): Promise<TreeNode> { const node = this.nodes.get(element); if (node) { return Promise.resolve(node); } return asPromise(() => this.dataProvider.getTreeItem(element)) .then(extTreeItem => this.createHandle(element, extTreeItem, parent, true)) .then(handle => this.getChildren(parent ? parent.item.handle : undefined) .then(() => { const cachedElement = this.getExtensionElement(handle); if (cachedElement) { const node = this.nodes.get(cachedElement); if (node) { return Promise.resolve(node); } } throw new Error(`Cannot resolve tree item for element ${handle}`); })); } private getChildrenNodes(parentNodeOrHandle: TreeNode | TreeItemHandle | Root): TreeNode[] | null { if (parentNodeOrHandle) { let parentNode: TreeNode | undefined; if (typeof parentNodeOrHandle === 'string') { const parentElement = this.getExtensionElement(parentNodeOrHandle); parentNode = parentElement ? this.nodes.get(parentElement) : undefined; } else { parentNode = parentNodeOrHandle; } return parentNode ? parentNode.children || null : null; } return this.roots; } private async fetchChildrenNodes(parentElement?: T): Promise<TreeNode[]> { // clear children cache this.clearChildren(parentElement); const cts = new CancellationTokenSource(this._refreshCancellationSource.token); try { const parentNode = parentElement ? this.nodes.get(parentElement) : undefined; const elements = await this.dataProvider.getChildren(parentElement); if (cts.token.isCancellationRequested) { return []; } const items = await Promise.all(coalesce(elements || []).map(async element => { const item = await this.dataProvider.getTreeItem(element); return item && !cts.token.isCancellationRequested ? this.createAndRegisterTreeNode(element, item, parentNode) : null; })); if (cts.token.isCancellationRequested) { return []; } return coalesce(items); } finally { cts.dispose(); } } private _refreshCancellationSource = new CancellationTokenSource(); private refresh(elements: (T | Root)[]): Promise<void> { const hasRoot = elements.some(element => !element); if (hasRoot) { // Cancel any pending children fetches this._refreshCancellationSource.dispose(true); this._refreshCancellationSource = new CancellationTokenSource(); this.clearAll(); // clear cache return this.proxy.$refresh(this.viewId); } else { const handlesToRefresh = this.getHandlesToRefresh(<T[]>elements); if (handlesToRefresh.length) { return this.refreshHandles(handlesToRefresh); } } return Promise.resolve(undefined); } private getHandlesToRefresh(elements: T[]): TreeItemHandle[] { const elementsToUpdate = new Set<TreeItemHandle>(); for (const element of elements) { const elementNode = this.nodes.get(element); if (elementNode && !elementsToUpdate.has(elementNode.item.handle)) { // check if an ancestor of extElement is already in the elements to update list let currentNode: TreeNode | undefined = elementNode; while (currentNode && currentNode.parent && !elementsToUpdate.has(currentNode.parent.item.handle)) { const parentElement: T | undefined = this.elements.get(currentNode.parent.item.handle); currentNode = parentElement ? this.nodes.get(parentElement) : undefined; } if (currentNode && !currentNode.parent) { elementsToUpdate.add(elementNode.item.handle); } } } const handlesToUpdate: TreeItemHandle[] = []; // Take only top level elements elementsToUpdate.forEach((handle) => { const element = this.elements.get(handle); if (element) { const node = this.nodes.get(element); if (node && (!node.parent || !elementsToUpdate.has(node.parent.item.handle))) { handlesToUpdate.push(handle); } } }); return handlesToUpdate; } private refreshHandles(itemHandles: TreeItemHandle[]): Promise<void> { const itemsToRefresh: { [treeItemHandle: string]: ITreeItem } = {}; return Promise.all(itemHandles.map(treeItemHandle => this.refreshNode(treeItemHandle) .then(node => { if (node) { itemsToRefresh[treeItemHandle] = node.item; } }))) .then(() => Object.keys(itemsToRefresh).length ? this.proxy.$refresh(this.viewId, itemsToRefresh) : undefined); } private refreshNode(treeItemHandle: TreeItemHandle): Promise<TreeNode | null> { const extElement = this.getExtensionElement(treeItemHandle); if (extElement) { const existing = this.nodes.get(extElement); if (existing) { this.clearChildren(extElement); // clear children cache return asPromise(() => this.dataProvider.getTreeItem(extElement)) .then(extTreeItem => { if (extTreeItem) { const newNode = this.createTreeNode(extElement, extTreeItem, existing.parent); this.updateNodeCache(extElement, newNode, existing, existing.parent); existing.dispose(); return newNode; } return null; }); } } return Promise.resolve(null); } private createAndRegisterTreeNode(element: T, extTreeItem: vscode.TreeItem, parentNode: TreeNode | Root): TreeNode { const node = this.createTreeNode(element, extTreeItem, parentNode); if (extTreeItem.id && this.elements.has(node.item.handle)) { throw new Error(localize('treeView.duplicateElement', 'Element with id {0} is already registered', extTreeItem.id)); } this.addNodeToCache(element, node); this.addNodeToParentCache(node, parentNode); return node; } private getTooltip(tooltip?: string | vscode.MarkdownString): string | IMarkdownString | undefined { if (MarkdownStringType.isMarkdownString(tooltip)) { return MarkdownString.from(tooltip); } return tooltip; } private getCommand(disposable: DisposableStore, command?: vscode.Command): Command | undefined { return command ? this.commands.toInternal(command, disposable) : undefined; } private createTreeNode(element: T, extensionTreeItem: vscode.TreeItem, parent: TreeNode | Root): TreeNode { const disposableStore = new DisposableStore(); const handle = this.createHandle(element, extensionTreeItem, parent); const icon = this.getLightIconPath(extensionTreeItem); const item: ITreeItem = { handle, parentHandle: parent ? parent.item.handle : undefined, label: toTreeItemLabel(extensionTreeItem.label, this.extension), description: extensionTreeItem.description, resourceUri: extensionTreeItem.resourceUri, tooltip: this.getTooltip(extensionTreeItem.tooltip), command: this.getCommand(disposableStore, extensionTreeItem.command), contextValue: extensionTreeItem.contextValue, icon, iconDark: this.getDarkIconPath(extensionTreeItem) || icon, themeIcon: this.getThemeIcon(extensionTreeItem), collapsibleState: isUndefinedOrNull(extensionTreeItem.collapsibleState) ? TreeItemCollapsibleState.None : extensionTreeItem.collapsibleState, accessibilityInformation: extensionTreeItem.accessibilityInformation }; return { item, extensionItem: extensionTreeItem, parent, children: undefined, disposableStore, dispose(): void { disposableStore.dispose(); } }; } private getThemeIcon(extensionTreeItem: vscode.TreeItem): ThemeIcon | undefined { return extensionTreeItem.iconPath instanceof ThemeIcon ? extensionTreeItem.iconPath : undefined; } private createHandle(element: T, { id, label, resourceUri }: vscode.TreeItem, parent: TreeNode | Root, returnFirst?: boolean): TreeItemHandle { if (id) { return `${ExtHostTreeView.ID_HANDLE_PREFIX}/${id}`; } const treeItemLabel = toTreeItemLabel(label, this.extension); const prefix: string = parent ? parent.item.handle : ExtHostTreeView.LABEL_HANDLE_PREFIX; let elementId = treeItemLabel ? treeItemLabel.label : resourceUri ? basename(resourceUri) : ''; elementId = elementId.indexOf('/') !== -1 ? elementId.replace('/', '//') : elementId; const existingHandle = this.nodes.has(element) ? this.nodes.get(element)!.item.handle : undefined; const childrenNodes = (this.getChildrenNodes(parent) || []); let handle: TreeItemHandle; let counter = 0; do { handle = `${prefix}/${counter}:${elementId}`; if (returnFirst || !this.elements.has(handle) || existingHandle === handle) { // Return first if asked for or // Return if handle does not exist or // Return if handle is being reused break; } counter++; } while (counter <= childrenNodes.length); return handle; } private getLightIconPath(extensionTreeItem: vscode.TreeItem): URI | undefined { if (extensionTreeItem.iconPath && !(extensionTreeItem.iconPath instanceof ThemeIcon)) { if (typeof extensionTreeItem.iconPath === 'string' || URI.isUri(extensionTreeItem.iconPath)) { return this.getIconPath(extensionTreeItem.iconPath); } return this.getIconPath((<{ light: string | URI; dark: string | URI }>extensionTreeItem.iconPath).light); } return undefined; } private getDarkIconPath(extensionTreeItem: vscode.TreeItem): URI | undefined { if (extensionTreeItem.iconPath && !(extensionTreeItem.iconPath instanceof ThemeIcon) && (<{ light: string | URI; dark: string | URI }>extensionTreeItem.iconPath).dark) { return this.getIconPath((<{ light: string | URI; dark: string | URI }>extensionTreeItem.iconPath).dark); } return undefined; } private getIconPath(iconPath: string | URI): URI { if (URI.isUri(iconPath)) { return iconPath; } return URI.file(iconPath); } private addNodeToCache(element: T, node: TreeNode): void { this.elements.set(node.item.handle, element); this.nodes.set(element, node); } private updateNodeCache(element: T, newNode: TreeNode, existing: TreeNode, parentNode: TreeNode | Root): void { // Remove from the cache this.elements.delete(newNode.item.handle); this.nodes.delete(element); if (newNode.item.handle !== existing.item.handle) { this.elements.delete(existing.item.handle); } // Add the new node to the cache this.addNodeToCache(element, newNode); // Replace the node in parent's children nodes const childrenNodes = (this.getChildrenNodes(parentNode) || []); const childNode = childrenNodes.filter(c => c.item.handle === existing.item.handle)[0]; if (childNode) { childrenNodes.splice(childrenNodes.indexOf(childNode), 1, newNode); } } private addNodeToParentCache(node: TreeNode, parentNode: TreeNode | Root): void { if (parentNode) { if (!parentNode.children) { parentNode.children = []; } parentNode.children.push(node); } else { if (!this.roots) { this.roots = []; } this.roots.push(node); } } private clearChildren(parentElement?: T): void { if (parentElement) { const node = this.nodes.get(parentElement); if (node) { if (node.children) { for (const child of node.children) { const childElement = this.elements.get(child.item.handle); if (childElement) { this.clear(childElement); } } } node.children = undefined; } } else { this.clearAll(); } } private clear(element: T): void { const node = this.nodes.get(element); if (node) { if (node.children) { for (const child of node.children) { const childElement = this.elements.get(child.item.handle); if (childElement) { this.clear(childElement); } } } this.nodes.delete(element); this.elements.delete(node.item.handle); node.dispose(); } } private clearAll(): void { this.roots = null; this.elements.clear(); this.nodes.forEach(node => node.dispose()); this.nodes.clear(); } dispose() { this._refreshCancellationSource.dispose(); this.clearAll(); } }
src/vs/workbench/api/common/extHostTreeViews.ts
1
https://github.com/microsoft/vscode/commit/44dbd182557ee8c164f3917a2f9dc09a37ff623c
[ 0.9621369242668152, 0.013528577983379364, 0.00016456161392852664, 0.00017486850265413523, 0.10955596715211868 ]
{ "id": 3, "code_window": [ "\t\t\t\ttreeView.description = description;\n", "\t\t\t},\n", "\t\t\treveal: (element: T, options?: IRevealOptions): Promise<void> => {\n", "\t\t\t\treturn treeView.reveal(element, options);\n", "\t\t\t},\n", "\t\t\tdispose: () => {\n", "\t\t\t\tthis.treeViews.delete(viewId);\n", "\t\t\t\ttreeView.dispose();\n", "\t\t\t}\n", "\t\t};\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tdispose: async () => {\n", "\t\t\t\t// Wait for the registration promise to finish before doing the dispose.\n", "\t\t\t\tawait registerPromise;\n" ], "file_path": "src/vs/workbench/api/common/extHostTreeViews.ts", "type": "replace", "edit_start_line_idx": 112 }
/*--------------------------------------------------------------------------------------------- * 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 { TestInstantiationService } from 'vs/platform/instantiation/test/common/instantiationServiceMock'; import { workbenchInstantiationService } from 'vs/workbench/test/browser/workbenchTestServices'; import { LinkDetector } from 'vs/workbench/contrib/debug/browser/linkDetector'; import { isWindows } from 'vs/base/common/platform'; import { WorkspaceFolder } from 'vs/platform/workspace/common/workspace'; import { URI } from 'vs/base/common/uri'; suite('Debug - Link Detector', () => { let linkDetector: LinkDetector; /** * Instantiate a {@link LinkDetector} for use by the functions being tested. */ setup(() => { const instantiationService: TestInstantiationService = <TestInstantiationService>workbenchInstantiationService(); linkDetector = instantiationService.createInstance(LinkDetector); }); /** * Assert that a given Element is an anchor element. * * @param element The Element to verify. */ function assertElementIsLink(element: Element) { assert(element instanceof HTMLAnchorElement); } test('noLinks', () => { const input = 'I am a string'; const expectedOutput = '<span>I am a string</span>'; const output = linkDetector.linkify(input); assert.equal(0, output.children.length); assert.equal('SPAN', output.tagName); assert.equal(expectedOutput, output.outerHTML); }); test('trailingNewline', () => { const input = 'I am a string\n'; const expectedOutput = '<span>I am a string\n</span>'; const output = linkDetector.linkify(input); assert.equal(0, output.children.length); assert.equal('SPAN', output.tagName); assert.equal(expectedOutput, output.outerHTML); }); test('trailingNewlineSplit', () => { const input = 'I am a string\n'; const expectedOutput = '<span>I am a string\n</span>'; const output = linkDetector.linkify(input, true); assert.equal(0, output.children.length); assert.equal('SPAN', output.tagName); assert.equal(expectedOutput, output.outerHTML); }); test('singleLineLink', () => { const input = isWindows ? 'C:\\foo\\bar.js:12:34' : '/Users/foo/bar.js:12:34'; const expectedOutput = isWindows ? '<span><a tabindex="0">C:\\foo\\bar.js:12:34<\/a><\/span>' : '<span><a tabindex="0">/Users/foo/bar.js:12:34<\/a><\/span>'; const output = linkDetector.linkify(input); assert.equal(1, output.children.length); assert.equal('SPAN', output.tagName); assert.equal('A', output.firstElementChild!.tagName); assert.equal(expectedOutput, output.outerHTML); assertElementIsLink(output.firstElementChild!); assert.equal(isWindows ? 'C:\\foo\\bar.js:12:34' : '/Users/foo/bar.js:12:34', output.firstElementChild!.textContent); }); test('relativeLink', () => { const input = '\./foo/bar.js'; const expectedOutput = '<span>\./foo/bar.js</span>'; const output = linkDetector.linkify(input); assert.equal(0, output.children.length); assert.equal('SPAN', output.tagName); assert.equal(expectedOutput, output.outerHTML); }); test('relativeLinkWithWorkspace', () => { const input = '\./foo/bar.js'; const expectedOutput = /^<span><a class="link">\.\/foo\/bar\.js<\/a><\/span>$/; const output = linkDetector.linkify(input, false, new WorkspaceFolder({ uri: URI.file('/path/to/workspace'), name: 'ws', index: 0 })); assert.equal('SPAN', output.tagName); assert(expectedOutput.test(output.outerHTML)); }); test('singleLineLinkAndText', function () { const input = isWindows ? 'The link: C:/foo/bar.js:12:34' : 'The link: /Users/foo/bar.js:12:34'; const expectedOutput = /^<span>The link: <a tabindex="0">.*\/foo\/bar.js:12:34<\/a><\/span>$/; const output = linkDetector.linkify(input); assert.equal(1, output.children.length); assert.equal('SPAN', output.tagName); assert.equal('A', output.children[0].tagName); assert(expectedOutput.test(output.outerHTML)); assertElementIsLink(output.children[0]); assert.equal(isWindows ? 'C:/foo/bar.js:12:34' : '/Users/foo/bar.js:12:34', output.children[0].textContent); }); test('singleLineMultipleLinks', () => { const input = isWindows ? 'Here is a link C:/foo/bar.js:12:34 and here is another D:/boo/far.js:56:78' : 'Here is a link /Users/foo/bar.js:12:34 and here is another /Users/boo/far.js:56:78'; const expectedOutput = /^<span>Here is a link <a tabindex="0">.*\/foo\/bar.js:12:34<\/a> and here is another <a tabindex="0">.*\/boo\/far.js:56:78<\/a><\/span>$/; const output = linkDetector.linkify(input); assert.equal(2, output.children.length); assert.equal('SPAN', output.tagName); assert.equal('A', output.children[0].tagName); assert.equal('A', output.children[1].tagName); assert(expectedOutput.test(output.outerHTML)); assertElementIsLink(output.children[0]); assertElementIsLink(output.children[1]); assert.equal(isWindows ? 'C:/foo/bar.js:12:34' : '/Users/foo/bar.js:12:34', output.children[0].textContent); assert.equal(isWindows ? 'D:/boo/far.js:56:78' : '/Users/boo/far.js:56:78', output.children[1].textContent); }); test('multilineNoLinks', () => { const input = 'Line one\nLine two\nLine three'; const expectedOutput = /^<span><span>Line one\n<\/span><span>Line two\n<\/span><span>Line three<\/span><\/span>$/; const output = linkDetector.linkify(input, true); assert.equal(3, output.children.length); assert.equal('SPAN', output.tagName); assert.equal('SPAN', output.children[0].tagName); assert.equal('SPAN', output.children[1].tagName); assert.equal('SPAN', output.children[2].tagName); assert(expectedOutput.test(output.outerHTML)); }); test('multilineTrailingNewline', () => { const input = 'I am a string\nAnd I am another\n'; const expectedOutput = '<span><span>I am a string\n<\/span><span>And I am another\n<\/span><\/span>'; const output = linkDetector.linkify(input, true); assert.equal(2, output.children.length); assert.equal('SPAN', output.tagName); assert.equal('SPAN', output.children[0].tagName); assert.equal('SPAN', output.children[1].tagName); assert.equal(expectedOutput, output.outerHTML); }); test('multilineWithLinks', () => { const input = isWindows ? 'I have a link for you\nHere it is: C:/foo/bar.js:12:34\nCool, huh?' : 'I have a link for you\nHere it is: /Users/foo/bar.js:12:34\nCool, huh?'; const expectedOutput = /^<span><span>I have a link for you\n<\/span><span>Here it is: <a tabindex="0">.*\/foo\/bar.js:12:34<\/a>\n<\/span><span>Cool, huh\?<\/span><\/span>$/; const output = linkDetector.linkify(input, true); assert.equal(3, output.children.length); assert.equal('SPAN', output.tagName); assert.equal('SPAN', output.children[0].tagName); assert.equal('SPAN', output.children[1].tagName); assert.equal('SPAN', output.children[2].tagName); assert.equal('A', output.children[1].children[0].tagName); assert(expectedOutput.test(output.outerHTML)); assertElementIsLink(output.children[1].children[0]); assert.equal(isWindows ? 'C:/foo/bar.js:12:34' : '/Users/foo/bar.js:12:34', output.children[1].children[0].textContent); }); });
src/vs/workbench/contrib/debug/test/browser/linkDetector.test.ts
0
https://github.com/microsoft/vscode/commit/44dbd182557ee8c164f3917a2f9dc09a37ff623c
[ 0.0001783702609827742, 0.00017421040683984756, 0.0001677502878010273, 0.00017500446119811386, 0.0000028281324375711847 ]
{ "id": 3, "code_window": [ "\t\t\t\ttreeView.description = description;\n", "\t\t\t},\n", "\t\t\treveal: (element: T, options?: IRevealOptions): Promise<void> => {\n", "\t\t\t\treturn treeView.reveal(element, options);\n", "\t\t\t},\n", "\t\t\tdispose: () => {\n", "\t\t\t\tthis.treeViews.delete(viewId);\n", "\t\t\t\ttreeView.dispose();\n", "\t\t\t}\n", "\t\t};\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tdispose: async () => {\n", "\t\t\t\t// Wait for the registration promise to finish before doing the dispose.\n", "\t\t\t\tawait registerPromise;\n" ], "file_path": "src/vs/workbench/api/common/extHostTreeViews.ts", "type": "replace", "edit_start_line_idx": 112 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { IFileService } from 'vs/platform/files/common/files'; import { URI } from 'vs/base/common/uri'; import { IModelService } from 'vs/editor/common/services/modelService'; import { ResourceMap } from 'vs/base/common/map'; import { DisposableStore } from 'vs/base/common/lifecycle'; import { Emitter, Event } from 'vs/base/common/event'; import { ITextModel } from 'vs/editor/common/model'; import { ResourceEdit, ResourceFileEdit, ResourceTextEdit } from 'vs/editor/browser/services/bulkEditService'; import { ResourceNotebookCellEdit } from 'vs/workbench/contrib/bulkEdit/browser/bulkCellEdits'; import { ILogService } from 'vs/platform/log/common/log'; export class ConflictDetector { private readonly _conflicts = new ResourceMap<boolean>(); private readonly _disposables = new DisposableStore(); private readonly _onDidConflict = new Emitter<this>(); readonly onDidConflict: Event<this> = this._onDidConflict.event; constructor( edits: ResourceEdit[], @IFileService fileService: IFileService, @IModelService modelService: IModelService, @ILogService logService: ILogService, ) { const _workspaceEditResources = new ResourceMap<boolean>(); for (let edit of edits) { if (edit instanceof ResourceTextEdit) { _workspaceEditResources.set(edit.resource, true); if (typeof edit.versionId === 'number') { const model = modelService.getModel(edit.resource); if (model && model.getVersionId() !== edit.versionId) { this._conflicts.set(edit.resource, true); this._onDidConflict.fire(this); } } } else if (edit instanceof ResourceFileEdit) { if (edit.newResource) { _workspaceEditResources.set(edit.newResource, true); } else if (edit.oldResource) { _workspaceEditResources.set(edit.oldResource, true); } } else if (edit instanceof ResourceNotebookCellEdit) { _workspaceEditResources.set(edit.resource, true); } else { logService.warn('UNKNOWN edit type', edit); } } // listen to file changes this._disposables.add(fileService.onDidFilesChange(e => { for (const uri of _workspaceEditResources.keys()) { // conflict happens when a file that we are working // on changes on disk. ignore changes for which a model // exists because we have a better check for models if (!modelService.getModel(uri) && e.contains(uri)) { this._conflicts.set(uri, true); this._onDidConflict.fire(this); break; } } })); // listen to model changes...? const onDidChangeModel = (model: ITextModel) => { // conflict if (_workspaceEditResources.has(model.uri)) { this._conflicts.set(model.uri, true); this._onDidConflict.fire(this); } }; for (let model of modelService.getModels()) { this._disposables.add(model.onDidChangeContent(() => onDidChangeModel(model))); } } dispose(): void { this._disposables.dispose(); this._onDidConflict.dispose(); } list(): URI[] { return [...this._conflicts.keys()]; } hasConflicts(): boolean { return this._conflicts.size > 0; } }
src/vs/workbench/contrib/bulkEdit/browser/conflicts.ts
0
https://github.com/microsoft/vscode/commit/44dbd182557ee8c164f3917a2f9dc09a37ff623c
[ 0.0001773520343704149, 0.0001733236131258309, 0.0001682242436800152, 0.0001730966178001836, 0.000002959085122711258 ]
{ "id": 3, "code_window": [ "\t\t\t\ttreeView.description = description;\n", "\t\t\t},\n", "\t\t\treveal: (element: T, options?: IRevealOptions): Promise<void> => {\n", "\t\t\t\treturn treeView.reveal(element, options);\n", "\t\t\t},\n", "\t\t\tdispose: () => {\n", "\t\t\t\tthis.treeViews.delete(viewId);\n", "\t\t\t\ttreeView.dispose();\n", "\t\t\t}\n", "\t\t};\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tdispose: async () => {\n", "\t\t\t\t// Wait for the registration promise to finish before doing the dispose.\n", "\t\t\t\tawait registerPromise;\n" ], "file_path": "src/vs/workbench/api/common/extHostTreeViews.ts", "type": "replace", "edit_start_line_idx": 112 }
{ "compilerOptions": { "target": "es2017", "module": "commonjs", "removeComments": false, "preserveConstEnums": true, "sourceMap": false, "resolveJsonModule": true, "experimentalDecorators": true, // enable JavaScript type checking for the language service // use the tsconfig.build.json for compiling which disable JavaScript // type checking so that JavaScript file are not transpiled "allowJs": true, "checkJs": true, "strict": true, "noUnusedLocals": true, "noUnusedParameters": true, "newLine": "lf" }, "include": [ "**/*.ts" ], "exclude": [ "node_modules/**" ] }
build/tsconfig.json
0
https://github.com/microsoft/vscode/commit/44dbd182557ee8c164f3917a2f9dc09a37ff623c
[ 0.00017780072812456638, 0.00017474545165896416, 0.00017192658560816199, 0.00017450907034799457, 0.0000024039270556386327 ]
{ "id": 4, "code_window": [ "\t\t\t\t}\n", "\t\t\t}\n", "\t\t}\n", "\t\tthis.dataProvider = options.treeDataProvider;\n", "\t\tthis.proxy.$registerTreeViewDataProvider(viewId, { showCollapseAll: !!options.showCollapseAll, canSelectMany: !!options.canSelectMany });\n", "\t\tif (this.dataProvider.onDidChangeTreeData) {\n", "\t\t\tthis._register(this.dataProvider.onDidChangeTreeData(element => this._onDidChangeData.fire({ message: false, element })));\n", "\t\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/api/common/extHostTreeViews.ts", "type": "replace", "edit_start_line_idx": 242 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { localize } from 'vs/nls'; import type * as vscode from 'vscode'; import { basename } from 'vs/base/common/resources'; import { URI } from 'vs/base/common/uri'; import { Emitter, Event } from 'vs/base/common/event'; import { Disposable, DisposableStore, IDisposable } from 'vs/base/common/lifecycle'; import { ExtHostTreeViewsShape, MainThreadTreeViewsShape } from './extHost.protocol'; import { ITreeItem, TreeViewItemHandleArg, ITreeItemLabel, IRevealOptions } from 'vs/workbench/common/views'; import { ExtHostCommands, CommandsConverter } from 'vs/workbench/api/common/extHostCommands'; import { asPromise } from 'vs/base/common/async'; import { TreeItemCollapsibleState, ThemeIcon, MarkdownString as MarkdownStringType } from 'vs/workbench/api/common/extHostTypes'; import { isUndefinedOrNull, isString } from 'vs/base/common/types'; import { equals, coalesce } from 'vs/base/common/arrays'; import { ILogService } from 'vs/platform/log/common/log'; import { IExtensionDescription } from 'vs/platform/extensions/common/extensions'; import { MarkdownString } from 'vs/workbench/api/common/extHostTypeConverters'; import { IMarkdownString } from 'vs/base/common/htmlContent'; import { CancellationTokenSource } from 'vs/base/common/cancellation'; import { Command } from 'vs/editor/common/modes'; type TreeItemHandle = string; function toTreeItemLabel(label: any, extension: IExtensionDescription): ITreeItemLabel | undefined { if (isString(label)) { return { label }; } if (label && typeof label === 'object' && typeof label.label === 'string') { let highlights: [number, number][] | undefined = undefined; if (Array.isArray(label.highlights)) { highlights = (<[number, number][]>label.highlights).filter((highlight => highlight.length === 2 && typeof highlight[0] === 'number' && typeof highlight[1] === 'number')); highlights = highlights.length ? highlights : undefined; } return { label: label.label, highlights }; } return undefined; } export class ExtHostTreeViews implements ExtHostTreeViewsShape { private treeViews: Map<string, ExtHostTreeView<any>> = new Map<string, ExtHostTreeView<any>>(); constructor( private _proxy: MainThreadTreeViewsShape, private commands: ExtHostCommands, private logService: ILogService ) { function isTreeViewItemHandleArg(arg: any): boolean { return arg && arg.$treeViewId && arg.$treeItemHandle; } commands.registerArgumentProcessor({ processArgument: arg => { if (isTreeViewItemHandleArg(arg)) { return this.convertArgument(arg); } else if (Array.isArray(arg) && (arg.length > 0)) { return arg.map(item => { if (isTreeViewItemHandleArg(item)) { return this.convertArgument(item); } return item; }); } return arg; } }); } registerTreeDataProvider<T>(id: string, treeDataProvider: vscode.TreeDataProvider<T>, extension: IExtensionDescription): vscode.Disposable { const treeView = this.createTreeView(id, { treeDataProvider }, extension); return { dispose: () => treeView.dispose() }; } createTreeView<T>(viewId: string, options: vscode.TreeViewOptions<T>, extension: IExtensionDescription): vscode.TreeView<T> { if (!options || !options.treeDataProvider) { throw new Error('Options with treeDataProvider is mandatory'); } const treeView = this.createExtHostTreeView(viewId, options, extension); return { get onDidCollapseElement() { return treeView.onDidCollapseElement; }, get onDidExpandElement() { return treeView.onDidExpandElement; }, get selection() { return treeView.selectedElements; }, get onDidChangeSelection() { return treeView.onDidChangeSelection; }, get visible() { return treeView.visible; }, get onDidChangeVisibility() { return treeView.onDidChangeVisibility; }, get message() { return treeView.message; }, set message(message: string) { treeView.message = message; }, get title() { return treeView.title; }, set title(title: string) { treeView.title = title; }, get description() { return treeView.description; }, set description(description: string | undefined) { treeView.description = description; }, reveal: (element: T, options?: IRevealOptions): Promise<void> => { return treeView.reveal(element, options); }, dispose: () => { this.treeViews.delete(viewId); treeView.dispose(); } }; } $getChildren(treeViewId: string, treeItemHandle?: string): Promise<ITreeItem[]> { const treeView = this.treeViews.get(treeViewId); if (!treeView) { return Promise.reject(new Error(localize('treeView.notRegistered', 'No tree view with id \'{0}\' registered.', treeViewId))); } return treeView.getChildren(treeItemHandle); } async $hasResolve(treeViewId: string): Promise<boolean> { const treeView = this.treeViews.get(treeViewId); if (!treeView) { throw new Error(localize('treeView.notRegistered', 'No tree view with id \'{0}\' registered.', treeViewId)); } return treeView.hasResolve; } $resolve(treeViewId: string, treeItemHandle: string, token: vscode.CancellationToken): Promise<ITreeItem | undefined> { const treeView = this.treeViews.get(treeViewId); if (!treeView) { throw new Error(localize('treeView.notRegistered', 'No tree view with id \'{0}\' registered.', treeViewId)); } return treeView.resolveTreeItem(treeItemHandle, token); } $setExpanded(treeViewId: string, treeItemHandle: string, expanded: boolean): void { const treeView = this.treeViews.get(treeViewId); if (!treeView) { throw new Error(localize('treeView.notRegistered', 'No tree view with id \'{0}\' registered.', treeViewId)); } treeView.setExpanded(treeItemHandle, expanded); } $setSelection(treeViewId: string, treeItemHandles: string[]): void { const treeView = this.treeViews.get(treeViewId); if (!treeView) { throw new Error(localize('treeView.notRegistered', 'No tree view with id \'{0}\' registered.', treeViewId)); } treeView.setSelection(treeItemHandles); } $setVisible(treeViewId: string, isVisible: boolean): void { const treeView = this.treeViews.get(treeViewId); if (!treeView) { throw new Error(localize('treeView.notRegistered', 'No tree view with id \'{0}\' registered.', treeViewId)); } treeView.setVisible(isVisible); } private createExtHostTreeView<T>(id: string, options: vscode.TreeViewOptions<T>, extension: IExtensionDescription): ExtHostTreeView<T> { const treeView = new ExtHostTreeView<T>(id, options, this._proxy, this.commands.converter, this.logService, extension); this.treeViews.set(id, treeView); return treeView; } private convertArgument(arg: TreeViewItemHandleArg): any { const treeView = this.treeViews.get(arg.$treeViewId); return treeView ? treeView.getExtensionElement(arg.$treeItemHandle) : null; } } type Root = null | undefined | void; type TreeData<T> = { message: boolean, element: T | Root | false }; interface TreeNode extends IDisposable { item: ITreeItem; extensionItem: vscode.TreeItem; parent: TreeNode | Root; children?: TreeNode[]; disposableStore: DisposableStore; } class ExtHostTreeView<T> extends Disposable { private static readonly LABEL_HANDLE_PREFIX = '0'; private static readonly ID_HANDLE_PREFIX = '1'; private readonly dataProvider: vscode.TreeDataProvider<T>; private roots: TreeNode[] | null = null; private elements: Map<TreeItemHandle, T> = new Map<TreeItemHandle, T>(); private nodes: Map<T, TreeNode> = new Map<T, TreeNode>(); private _visible: boolean = false; get visible(): boolean { return this._visible; } private _selectedHandles: TreeItemHandle[] = []; get selectedElements(): T[] { return <T[]>this._selectedHandles.map(handle => this.getExtensionElement(handle)).filter(element => !isUndefinedOrNull(element)); } private _onDidExpandElement: Emitter<vscode.TreeViewExpansionEvent<T>> = this._register(new Emitter<vscode.TreeViewExpansionEvent<T>>()); readonly onDidExpandElement: Event<vscode.TreeViewExpansionEvent<T>> = this._onDidExpandElement.event; private _onDidCollapseElement: Emitter<vscode.TreeViewExpansionEvent<T>> = this._register(new Emitter<vscode.TreeViewExpansionEvent<T>>()); readonly onDidCollapseElement: Event<vscode.TreeViewExpansionEvent<T>> = this._onDidCollapseElement.event; private _onDidChangeSelection: Emitter<vscode.TreeViewSelectionChangeEvent<T>> = this._register(new Emitter<vscode.TreeViewSelectionChangeEvent<T>>()); readonly onDidChangeSelection: Event<vscode.TreeViewSelectionChangeEvent<T>> = this._onDidChangeSelection.event; private _onDidChangeVisibility: Emitter<vscode.TreeViewVisibilityChangeEvent> = this._register(new Emitter<vscode.TreeViewVisibilityChangeEvent>()); readonly onDidChangeVisibility: Event<vscode.TreeViewVisibilityChangeEvent> = this._onDidChangeVisibility.event; private _onDidChangeData: Emitter<TreeData<T>> = this._register(new Emitter<TreeData<T>>()); private refreshPromise: Promise<void> = Promise.resolve(); private refreshQueue: Promise<void> = Promise.resolve(); constructor( private viewId: string, options: vscode.TreeViewOptions<T>, private proxy: MainThreadTreeViewsShape, private commands: CommandsConverter, private logService: ILogService, private extension: IExtensionDescription ) { super(); if (extension.contributes && extension.contributes.views) { for (const location in extension.contributes.views) { for (const view of extension.contributes.views[location]) { if (view.id === viewId) { this._title = view.name; } } } } this.dataProvider = options.treeDataProvider; this.proxy.$registerTreeViewDataProvider(viewId, { showCollapseAll: !!options.showCollapseAll, canSelectMany: !!options.canSelectMany }); if (this.dataProvider.onDidChangeTreeData) { this._register(this.dataProvider.onDidChangeTreeData(element => this._onDidChangeData.fire({ message: false, element }))); } let refreshingPromise: Promise<void> | null; let promiseCallback: () => void; this._register(Event.debounce<TreeData<T>, { message: boolean, elements: (T | Root)[] }>(this._onDidChangeData.event, (result, current) => { if (!result) { result = { message: false, elements: [] }; } if (current.element !== false) { if (!refreshingPromise) { // New refresh has started refreshingPromise = new Promise(c => promiseCallback = c); this.refreshPromise = this.refreshPromise.then(() => refreshingPromise!); } result.elements.push(current.element); } if (current.message) { result.message = true; } return result; }, 200, true)(({ message, elements }) => { if (elements.length) { this.refreshQueue = this.refreshQueue.then(() => { const _promiseCallback = promiseCallback; refreshingPromise = null; return this.refresh(elements).then(() => _promiseCallback()); }); } if (message) { this.proxy.$setMessage(this.viewId, this._message); } })); } getChildren(parentHandle: TreeItemHandle | Root): Promise<ITreeItem[]> { const parentElement = parentHandle ? this.getExtensionElement(parentHandle) : undefined; if (parentHandle && !parentElement) { this.logService.error(`No tree item with id \'${parentHandle}\' found.`); return Promise.resolve([]); } const childrenNodes = this.getChildrenNodes(parentHandle); // Get it from cache return (childrenNodes ? Promise.resolve(childrenNodes) : this.fetchChildrenNodes(parentElement)) .then(nodes => nodes.map(n => n.item)); } getExtensionElement(treeItemHandle: TreeItemHandle): T | undefined { return this.elements.get(treeItemHandle); } reveal(element: T | undefined, options?: IRevealOptions): Promise<void> { options = options ? options : { select: true, focus: false }; const select = isUndefinedOrNull(options.select) ? true : options.select; const focus = isUndefinedOrNull(options.focus) ? false : options.focus; const expand = isUndefinedOrNull(options.expand) ? false : options.expand; if (typeof this.dataProvider.getParent !== 'function') { return Promise.reject(new Error(`Required registered TreeDataProvider to implement 'getParent' method to access 'reveal' method`)); } if (element) { return this.refreshPromise .then(() => this.resolveUnknownParentChain(element)) .then(parentChain => this.resolveTreeNode(element, parentChain[parentChain.length - 1]) .then(treeNode => this.proxy.$reveal(this.viewId, { item: treeNode.item, parentChain: parentChain.map(p => p.item) }, { select, focus, expand })), error => this.logService.error(error)); } else { return this.proxy.$reveal(this.viewId, undefined, { select, focus, expand }); } } private _message: string = ''; get message(): string { return this._message; } set message(message: string) { this._message = message; this._onDidChangeData.fire({ message: true, element: false }); } private _title: string = ''; get title(): string { return this._title; } set title(title: string) { this._title = title; this.proxy.$setTitle(this.viewId, title, this._description); } private _description: string | undefined; get description(): string | undefined { return this._description; } set description(description: string | undefined) { this._description = description; this.proxy.$setTitle(this.viewId, this._title, description); } setExpanded(treeItemHandle: TreeItemHandle, expanded: boolean): void { const element = this.getExtensionElement(treeItemHandle); if (element) { if (expanded) { this._onDidExpandElement.fire(Object.freeze({ element })); } else { this._onDidCollapseElement.fire(Object.freeze({ element })); } } } setSelection(treeItemHandles: TreeItemHandle[]): void { if (!equals(this._selectedHandles, treeItemHandles)) { this._selectedHandles = treeItemHandles; this._onDidChangeSelection.fire(Object.freeze({ selection: this.selectedElements })); } } setVisible(visible: boolean): void { if (visible !== this._visible) { this._visible = visible; this._onDidChangeVisibility.fire(Object.freeze({ visible: this._visible })); } } get hasResolve(): boolean { return !!this.dataProvider.resolveTreeItem; } async resolveTreeItem(treeItemHandle: string, token: vscode.CancellationToken): Promise<ITreeItem | undefined> { if (!this.dataProvider.resolveTreeItem) { return; } const element = this.elements.get(treeItemHandle); if (element) { const node = this.nodes.get(element); if (node) { const resolve = await this.dataProvider.resolveTreeItem(node.extensionItem, element, token) ?? node.extensionItem; // Resolvable elements. Currently only tooltip and command. node.item.tooltip = this.getTooltip(resolve.tooltip); node.item.command = this.getCommand(node.disposableStore, resolve.command); return node.item; } } return; } private resolveUnknownParentChain(element: T): Promise<TreeNode[]> { return this.resolveParent(element) .then((parent) => { if (!parent) { return Promise.resolve([]); } return this.resolveUnknownParentChain(parent) .then(result => this.resolveTreeNode(parent, result[result.length - 1]) .then(parentNode => { result.push(parentNode); return result; })); }); } private resolveParent(element: T): Promise<T | Root> { const node = this.nodes.get(element); if (node) { return Promise.resolve(node.parent ? this.elements.get(node.parent.item.handle) : undefined); } return asPromise(() => this.dataProvider.getParent!(element)); } private resolveTreeNode(element: T, parent?: TreeNode): Promise<TreeNode> { const node = this.nodes.get(element); if (node) { return Promise.resolve(node); } return asPromise(() => this.dataProvider.getTreeItem(element)) .then(extTreeItem => this.createHandle(element, extTreeItem, parent, true)) .then(handle => this.getChildren(parent ? parent.item.handle : undefined) .then(() => { const cachedElement = this.getExtensionElement(handle); if (cachedElement) { const node = this.nodes.get(cachedElement); if (node) { return Promise.resolve(node); } } throw new Error(`Cannot resolve tree item for element ${handle}`); })); } private getChildrenNodes(parentNodeOrHandle: TreeNode | TreeItemHandle | Root): TreeNode[] | null { if (parentNodeOrHandle) { let parentNode: TreeNode | undefined; if (typeof parentNodeOrHandle === 'string') { const parentElement = this.getExtensionElement(parentNodeOrHandle); parentNode = parentElement ? this.nodes.get(parentElement) : undefined; } else { parentNode = parentNodeOrHandle; } return parentNode ? parentNode.children || null : null; } return this.roots; } private async fetchChildrenNodes(parentElement?: T): Promise<TreeNode[]> { // clear children cache this.clearChildren(parentElement); const cts = new CancellationTokenSource(this._refreshCancellationSource.token); try { const parentNode = parentElement ? this.nodes.get(parentElement) : undefined; const elements = await this.dataProvider.getChildren(parentElement); if (cts.token.isCancellationRequested) { return []; } const items = await Promise.all(coalesce(elements || []).map(async element => { const item = await this.dataProvider.getTreeItem(element); return item && !cts.token.isCancellationRequested ? this.createAndRegisterTreeNode(element, item, parentNode) : null; })); if (cts.token.isCancellationRequested) { return []; } return coalesce(items); } finally { cts.dispose(); } } private _refreshCancellationSource = new CancellationTokenSource(); private refresh(elements: (T | Root)[]): Promise<void> { const hasRoot = elements.some(element => !element); if (hasRoot) { // Cancel any pending children fetches this._refreshCancellationSource.dispose(true); this._refreshCancellationSource = new CancellationTokenSource(); this.clearAll(); // clear cache return this.proxy.$refresh(this.viewId); } else { const handlesToRefresh = this.getHandlesToRefresh(<T[]>elements); if (handlesToRefresh.length) { return this.refreshHandles(handlesToRefresh); } } return Promise.resolve(undefined); } private getHandlesToRefresh(elements: T[]): TreeItemHandle[] { const elementsToUpdate = new Set<TreeItemHandle>(); for (const element of elements) { const elementNode = this.nodes.get(element); if (elementNode && !elementsToUpdate.has(elementNode.item.handle)) { // check if an ancestor of extElement is already in the elements to update list let currentNode: TreeNode | undefined = elementNode; while (currentNode && currentNode.parent && !elementsToUpdate.has(currentNode.parent.item.handle)) { const parentElement: T | undefined = this.elements.get(currentNode.parent.item.handle); currentNode = parentElement ? this.nodes.get(parentElement) : undefined; } if (currentNode && !currentNode.parent) { elementsToUpdate.add(elementNode.item.handle); } } } const handlesToUpdate: TreeItemHandle[] = []; // Take only top level elements elementsToUpdate.forEach((handle) => { const element = this.elements.get(handle); if (element) { const node = this.nodes.get(element); if (node && (!node.parent || !elementsToUpdate.has(node.parent.item.handle))) { handlesToUpdate.push(handle); } } }); return handlesToUpdate; } private refreshHandles(itemHandles: TreeItemHandle[]): Promise<void> { const itemsToRefresh: { [treeItemHandle: string]: ITreeItem } = {}; return Promise.all(itemHandles.map(treeItemHandle => this.refreshNode(treeItemHandle) .then(node => { if (node) { itemsToRefresh[treeItemHandle] = node.item; } }))) .then(() => Object.keys(itemsToRefresh).length ? this.proxy.$refresh(this.viewId, itemsToRefresh) : undefined); } private refreshNode(treeItemHandle: TreeItemHandle): Promise<TreeNode | null> { const extElement = this.getExtensionElement(treeItemHandle); if (extElement) { const existing = this.nodes.get(extElement); if (existing) { this.clearChildren(extElement); // clear children cache return asPromise(() => this.dataProvider.getTreeItem(extElement)) .then(extTreeItem => { if (extTreeItem) { const newNode = this.createTreeNode(extElement, extTreeItem, existing.parent); this.updateNodeCache(extElement, newNode, existing, existing.parent); existing.dispose(); return newNode; } return null; }); } } return Promise.resolve(null); } private createAndRegisterTreeNode(element: T, extTreeItem: vscode.TreeItem, parentNode: TreeNode | Root): TreeNode { const node = this.createTreeNode(element, extTreeItem, parentNode); if (extTreeItem.id && this.elements.has(node.item.handle)) { throw new Error(localize('treeView.duplicateElement', 'Element with id {0} is already registered', extTreeItem.id)); } this.addNodeToCache(element, node); this.addNodeToParentCache(node, parentNode); return node; } private getTooltip(tooltip?: string | vscode.MarkdownString): string | IMarkdownString | undefined { if (MarkdownStringType.isMarkdownString(tooltip)) { return MarkdownString.from(tooltip); } return tooltip; } private getCommand(disposable: DisposableStore, command?: vscode.Command): Command | undefined { return command ? this.commands.toInternal(command, disposable) : undefined; } private createTreeNode(element: T, extensionTreeItem: vscode.TreeItem, parent: TreeNode | Root): TreeNode { const disposableStore = new DisposableStore(); const handle = this.createHandle(element, extensionTreeItem, parent); const icon = this.getLightIconPath(extensionTreeItem); const item: ITreeItem = { handle, parentHandle: parent ? parent.item.handle : undefined, label: toTreeItemLabel(extensionTreeItem.label, this.extension), description: extensionTreeItem.description, resourceUri: extensionTreeItem.resourceUri, tooltip: this.getTooltip(extensionTreeItem.tooltip), command: this.getCommand(disposableStore, extensionTreeItem.command), contextValue: extensionTreeItem.contextValue, icon, iconDark: this.getDarkIconPath(extensionTreeItem) || icon, themeIcon: this.getThemeIcon(extensionTreeItem), collapsibleState: isUndefinedOrNull(extensionTreeItem.collapsibleState) ? TreeItemCollapsibleState.None : extensionTreeItem.collapsibleState, accessibilityInformation: extensionTreeItem.accessibilityInformation }; return { item, extensionItem: extensionTreeItem, parent, children: undefined, disposableStore, dispose(): void { disposableStore.dispose(); } }; } private getThemeIcon(extensionTreeItem: vscode.TreeItem): ThemeIcon | undefined { return extensionTreeItem.iconPath instanceof ThemeIcon ? extensionTreeItem.iconPath : undefined; } private createHandle(element: T, { id, label, resourceUri }: vscode.TreeItem, parent: TreeNode | Root, returnFirst?: boolean): TreeItemHandle { if (id) { return `${ExtHostTreeView.ID_HANDLE_PREFIX}/${id}`; } const treeItemLabel = toTreeItemLabel(label, this.extension); const prefix: string = parent ? parent.item.handle : ExtHostTreeView.LABEL_HANDLE_PREFIX; let elementId = treeItemLabel ? treeItemLabel.label : resourceUri ? basename(resourceUri) : ''; elementId = elementId.indexOf('/') !== -1 ? elementId.replace('/', '//') : elementId; const existingHandle = this.nodes.has(element) ? this.nodes.get(element)!.item.handle : undefined; const childrenNodes = (this.getChildrenNodes(parent) || []); let handle: TreeItemHandle; let counter = 0; do { handle = `${prefix}/${counter}:${elementId}`; if (returnFirst || !this.elements.has(handle) || existingHandle === handle) { // Return first if asked for or // Return if handle does not exist or // Return if handle is being reused break; } counter++; } while (counter <= childrenNodes.length); return handle; } private getLightIconPath(extensionTreeItem: vscode.TreeItem): URI | undefined { if (extensionTreeItem.iconPath && !(extensionTreeItem.iconPath instanceof ThemeIcon)) { if (typeof extensionTreeItem.iconPath === 'string' || URI.isUri(extensionTreeItem.iconPath)) { return this.getIconPath(extensionTreeItem.iconPath); } return this.getIconPath((<{ light: string | URI; dark: string | URI }>extensionTreeItem.iconPath).light); } return undefined; } private getDarkIconPath(extensionTreeItem: vscode.TreeItem): URI | undefined { if (extensionTreeItem.iconPath && !(extensionTreeItem.iconPath instanceof ThemeIcon) && (<{ light: string | URI; dark: string | URI }>extensionTreeItem.iconPath).dark) { return this.getIconPath((<{ light: string | URI; dark: string | URI }>extensionTreeItem.iconPath).dark); } return undefined; } private getIconPath(iconPath: string | URI): URI { if (URI.isUri(iconPath)) { return iconPath; } return URI.file(iconPath); } private addNodeToCache(element: T, node: TreeNode): void { this.elements.set(node.item.handle, element); this.nodes.set(element, node); } private updateNodeCache(element: T, newNode: TreeNode, existing: TreeNode, parentNode: TreeNode | Root): void { // Remove from the cache this.elements.delete(newNode.item.handle); this.nodes.delete(element); if (newNode.item.handle !== existing.item.handle) { this.elements.delete(existing.item.handle); } // Add the new node to the cache this.addNodeToCache(element, newNode); // Replace the node in parent's children nodes const childrenNodes = (this.getChildrenNodes(parentNode) || []); const childNode = childrenNodes.filter(c => c.item.handle === existing.item.handle)[0]; if (childNode) { childrenNodes.splice(childrenNodes.indexOf(childNode), 1, newNode); } } private addNodeToParentCache(node: TreeNode, parentNode: TreeNode | Root): void { if (parentNode) { if (!parentNode.children) { parentNode.children = []; } parentNode.children.push(node); } else { if (!this.roots) { this.roots = []; } this.roots.push(node); } } private clearChildren(parentElement?: T): void { if (parentElement) { const node = this.nodes.get(parentElement); if (node) { if (node.children) { for (const child of node.children) { const childElement = this.elements.get(child.item.handle); if (childElement) { this.clear(childElement); } } } node.children = undefined; } } else { this.clearAll(); } } private clear(element: T): void { const node = this.nodes.get(element); if (node) { if (node.children) { for (const child of node.children) { const childElement = this.elements.get(child.item.handle); if (childElement) { this.clear(childElement); } } } this.nodes.delete(element); this.elements.delete(node.item.handle); node.dispose(); } } private clearAll(): void { this.roots = null; this.elements.clear(); this.nodes.forEach(node => node.dispose()); this.nodes.clear(); } dispose() { this._refreshCancellationSource.dispose(); this.clearAll(); } }
src/vs/workbench/api/common/extHostTreeViews.ts
1
https://github.com/microsoft/vscode/commit/44dbd182557ee8c164f3917a2f9dc09a37ff623c
[ 0.9971960783004761, 0.013934683986008167, 0.00016285640595015138, 0.00017278094310313463, 0.11355393379926682 ]
{ "id": 4, "code_window": [ "\t\t\t\t}\n", "\t\t\t}\n", "\t\t}\n", "\t\tthis.dataProvider = options.treeDataProvider;\n", "\t\tthis.proxy.$registerTreeViewDataProvider(viewId, { showCollapseAll: !!options.showCollapseAll, canSelectMany: !!options.canSelectMany });\n", "\t\tif (this.dataProvider.onDidChangeTreeData) {\n", "\t\t\tthis._register(this.dataProvider.onDidChangeTreeData(element => this._onDidChangeData.fire({ message: false, element })));\n", "\t\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/api/common/extHostTreeViews.ts", "type": "replace", "edit_start_line_idx": 242 }
{ // Each snippet is defined under a snippet name and has a scope, prefix, body and // description. The scope defines in watch languages the snippet is applicable. The prefix is what is // used to trigger the snippet and the body will be expanded and inserted.Possible variables are: // $1, $2 for tab stops, $0 for the final cursor position, and ${1:label}, ${2:another} for placeholders. // Placeholders with the same ids are connected. // Example: "MSFT Copyright Header": { "scope": "javascript,typescript,css", "prefix": [ "header", "stub", "copyright" ], "body": [ "/*---------------------------------------------------------------------------------------------", " * Copyright (c) Microsoft Corporation. All rights reserved.", " * Licensed under the MIT License. See License.txt in the project root for license information.", " *--------------------------------------------------------------------------------------------*/", "", "$0" ], "description": "Insert Copyright Statement" }, "TS -> Inject Service": { "scope": "typescript", "description": "Constructor Injection Pattern", "prefix": "@inject", "body": "@$1 private readonly _$2: ${1},$0" }, "TS -> Event & Emitter": { "scope": "typescript", "prefix": "emitter", "description": "Add emitter and event properties", "body": [ "private readonly _onDid$1 = new Emitter<$2>();", "readonly onDid$1: Event<$2> = this._onDid$1.event;" ], } }
.vscode/shared.code-snippets
0
https://github.com/microsoft/vscode/commit/44dbd182557ee8c164f3917a2f9dc09a37ff623c
[ 0.00017446678248234093, 0.0001719494757708162, 0.00017033854965120554, 0.00017152098007500172, 0.0000013900623798690503 ]
{ "id": 4, "code_window": [ "\t\t\t\t}\n", "\t\t\t}\n", "\t\t}\n", "\t\tthis.dataProvider = options.treeDataProvider;\n", "\t\tthis.proxy.$registerTreeViewDataProvider(viewId, { showCollapseAll: !!options.showCollapseAll, canSelectMany: !!options.canSelectMany });\n", "\t\tif (this.dataProvider.onDidChangeTreeData) {\n", "\t\t\tthis._register(this.dataProvider.onDidChangeTreeData(element => this._onDidChangeData.fire({ message: false, element })));\n", "\t\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/api/common/extHostTreeViews.ts", "type": "replace", "edit_start_line_idx": 242 }
{ "registrations": [ { "component": { "type": "git", "git": { "name": "rust-syntax", "repositoryUrl": "https://github.com/dustypomerleau/rust-syntax", "commitHash": "7b924664814131ae4509a537bb07960fe65dcaac" } }, "license": "MIT", "description": "A TextMate-style grammar for Rust.", "version": "0.4.3" } ], "version": 1 }
extensions/rust/cgmanifest.json
0
https://github.com/microsoft/vscode/commit/44dbd182557ee8c164f3917a2f9dc09a37ff623c
[ 0.00017306524387095124, 0.00017277768347412348, 0.00017249012307729572, 0.00017277768347412348, 2.8756039682775736e-7 ]
{ "id": 4, "code_window": [ "\t\t\t\t}\n", "\t\t\t}\n", "\t\t}\n", "\t\tthis.dataProvider = options.treeDataProvider;\n", "\t\tthis.proxy.$registerTreeViewDataProvider(viewId, { showCollapseAll: !!options.showCollapseAll, canSelectMany: !!options.canSelectMany });\n", "\t\tif (this.dataProvider.onDidChangeTreeData) {\n", "\t\t\tthis._register(this.dataProvider.onDidChangeTreeData(element => this._onDidChangeData.fire({ message: false, element })));\n", "\t\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/api/common/extHostTreeViews.ts", "type": "replace", "edit_start_line_idx": 242 }
# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. # yarn lockfile v1
extensions/groovy/yarn.lock
0
https://github.com/microsoft/vscode/commit/44dbd182557ee8c164f3917a2f9dc09a37ff623c
[ 0.0001708175550447777, 0.0001708175550447777, 0.0001708175550447777, 0.0001708175550447777, 0 ]
{ "id": 5, "code_window": [ "\tclass RecordingShape extends mock<MainThreadTreeViewsShape>() {\n", "\n", "\t\tonRefresh = new Emitter<{ [treeItemHandle: string]: ITreeItem }>();\n", "\n", "\t\t$registerTreeViewDataProvider(treeViewId: string): void {\n", "\t\t}\n", "\n", "\t\t$refresh(viewId: string, itemsToRefresh: { [treeItemHandle: string]: ITreeItem }): Promise<void> {\n", "\t\t\treturn Promise.resolve(null).then(() => {\n", "\t\t\t\tthis.onRefresh.fire(itemsToRefresh);\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tasync $registerTreeViewDataProvider(treeViewId: string): Promise<void> {\n" ], "file_path": "src/vs/workbench/test/browser/api/extHostTreeViews.test.ts", "type": "replace", "edit_start_line_idx": 28 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { localize } from 'vs/nls'; import type * as vscode from 'vscode'; import { basename } from 'vs/base/common/resources'; import { URI } from 'vs/base/common/uri'; import { Emitter, Event } from 'vs/base/common/event'; import { Disposable, DisposableStore, IDisposable } from 'vs/base/common/lifecycle'; import { ExtHostTreeViewsShape, MainThreadTreeViewsShape } from './extHost.protocol'; import { ITreeItem, TreeViewItemHandleArg, ITreeItemLabel, IRevealOptions } from 'vs/workbench/common/views'; import { ExtHostCommands, CommandsConverter } from 'vs/workbench/api/common/extHostCommands'; import { asPromise } from 'vs/base/common/async'; import { TreeItemCollapsibleState, ThemeIcon, MarkdownString as MarkdownStringType } from 'vs/workbench/api/common/extHostTypes'; import { isUndefinedOrNull, isString } from 'vs/base/common/types'; import { equals, coalesce } from 'vs/base/common/arrays'; import { ILogService } from 'vs/platform/log/common/log'; import { IExtensionDescription } from 'vs/platform/extensions/common/extensions'; import { MarkdownString } from 'vs/workbench/api/common/extHostTypeConverters'; import { IMarkdownString } from 'vs/base/common/htmlContent'; import { CancellationTokenSource } from 'vs/base/common/cancellation'; import { Command } from 'vs/editor/common/modes'; type TreeItemHandle = string; function toTreeItemLabel(label: any, extension: IExtensionDescription): ITreeItemLabel | undefined { if (isString(label)) { return { label }; } if (label && typeof label === 'object' && typeof label.label === 'string') { let highlights: [number, number][] | undefined = undefined; if (Array.isArray(label.highlights)) { highlights = (<[number, number][]>label.highlights).filter((highlight => highlight.length === 2 && typeof highlight[0] === 'number' && typeof highlight[1] === 'number')); highlights = highlights.length ? highlights : undefined; } return { label: label.label, highlights }; } return undefined; } export class ExtHostTreeViews implements ExtHostTreeViewsShape { private treeViews: Map<string, ExtHostTreeView<any>> = new Map<string, ExtHostTreeView<any>>(); constructor( private _proxy: MainThreadTreeViewsShape, private commands: ExtHostCommands, private logService: ILogService ) { function isTreeViewItemHandleArg(arg: any): boolean { return arg && arg.$treeViewId && arg.$treeItemHandle; } commands.registerArgumentProcessor({ processArgument: arg => { if (isTreeViewItemHandleArg(arg)) { return this.convertArgument(arg); } else if (Array.isArray(arg) && (arg.length > 0)) { return arg.map(item => { if (isTreeViewItemHandleArg(item)) { return this.convertArgument(item); } return item; }); } return arg; } }); } registerTreeDataProvider<T>(id: string, treeDataProvider: vscode.TreeDataProvider<T>, extension: IExtensionDescription): vscode.Disposable { const treeView = this.createTreeView(id, { treeDataProvider }, extension); return { dispose: () => treeView.dispose() }; } createTreeView<T>(viewId: string, options: vscode.TreeViewOptions<T>, extension: IExtensionDescription): vscode.TreeView<T> { if (!options || !options.treeDataProvider) { throw new Error('Options with treeDataProvider is mandatory'); } const treeView = this.createExtHostTreeView(viewId, options, extension); return { get onDidCollapseElement() { return treeView.onDidCollapseElement; }, get onDidExpandElement() { return treeView.onDidExpandElement; }, get selection() { return treeView.selectedElements; }, get onDidChangeSelection() { return treeView.onDidChangeSelection; }, get visible() { return treeView.visible; }, get onDidChangeVisibility() { return treeView.onDidChangeVisibility; }, get message() { return treeView.message; }, set message(message: string) { treeView.message = message; }, get title() { return treeView.title; }, set title(title: string) { treeView.title = title; }, get description() { return treeView.description; }, set description(description: string | undefined) { treeView.description = description; }, reveal: (element: T, options?: IRevealOptions): Promise<void> => { return treeView.reveal(element, options); }, dispose: () => { this.treeViews.delete(viewId); treeView.dispose(); } }; } $getChildren(treeViewId: string, treeItemHandle?: string): Promise<ITreeItem[]> { const treeView = this.treeViews.get(treeViewId); if (!treeView) { return Promise.reject(new Error(localize('treeView.notRegistered', 'No tree view with id \'{0}\' registered.', treeViewId))); } return treeView.getChildren(treeItemHandle); } async $hasResolve(treeViewId: string): Promise<boolean> { const treeView = this.treeViews.get(treeViewId); if (!treeView) { throw new Error(localize('treeView.notRegistered', 'No tree view with id \'{0}\' registered.', treeViewId)); } return treeView.hasResolve; } $resolve(treeViewId: string, treeItemHandle: string, token: vscode.CancellationToken): Promise<ITreeItem | undefined> { const treeView = this.treeViews.get(treeViewId); if (!treeView) { throw new Error(localize('treeView.notRegistered', 'No tree view with id \'{0}\' registered.', treeViewId)); } return treeView.resolveTreeItem(treeItemHandle, token); } $setExpanded(treeViewId: string, treeItemHandle: string, expanded: boolean): void { const treeView = this.treeViews.get(treeViewId); if (!treeView) { throw new Error(localize('treeView.notRegistered', 'No tree view with id \'{0}\' registered.', treeViewId)); } treeView.setExpanded(treeItemHandle, expanded); } $setSelection(treeViewId: string, treeItemHandles: string[]): void { const treeView = this.treeViews.get(treeViewId); if (!treeView) { throw new Error(localize('treeView.notRegistered', 'No tree view with id \'{0}\' registered.', treeViewId)); } treeView.setSelection(treeItemHandles); } $setVisible(treeViewId: string, isVisible: boolean): void { const treeView = this.treeViews.get(treeViewId); if (!treeView) { throw new Error(localize('treeView.notRegistered', 'No tree view with id \'{0}\' registered.', treeViewId)); } treeView.setVisible(isVisible); } private createExtHostTreeView<T>(id: string, options: vscode.TreeViewOptions<T>, extension: IExtensionDescription): ExtHostTreeView<T> { const treeView = new ExtHostTreeView<T>(id, options, this._proxy, this.commands.converter, this.logService, extension); this.treeViews.set(id, treeView); return treeView; } private convertArgument(arg: TreeViewItemHandleArg): any { const treeView = this.treeViews.get(arg.$treeViewId); return treeView ? treeView.getExtensionElement(arg.$treeItemHandle) : null; } } type Root = null | undefined | void; type TreeData<T> = { message: boolean, element: T | Root | false }; interface TreeNode extends IDisposable { item: ITreeItem; extensionItem: vscode.TreeItem; parent: TreeNode | Root; children?: TreeNode[]; disposableStore: DisposableStore; } class ExtHostTreeView<T> extends Disposable { private static readonly LABEL_HANDLE_PREFIX = '0'; private static readonly ID_HANDLE_PREFIX = '1'; private readonly dataProvider: vscode.TreeDataProvider<T>; private roots: TreeNode[] | null = null; private elements: Map<TreeItemHandle, T> = new Map<TreeItemHandle, T>(); private nodes: Map<T, TreeNode> = new Map<T, TreeNode>(); private _visible: boolean = false; get visible(): boolean { return this._visible; } private _selectedHandles: TreeItemHandle[] = []; get selectedElements(): T[] { return <T[]>this._selectedHandles.map(handle => this.getExtensionElement(handle)).filter(element => !isUndefinedOrNull(element)); } private _onDidExpandElement: Emitter<vscode.TreeViewExpansionEvent<T>> = this._register(new Emitter<vscode.TreeViewExpansionEvent<T>>()); readonly onDidExpandElement: Event<vscode.TreeViewExpansionEvent<T>> = this._onDidExpandElement.event; private _onDidCollapseElement: Emitter<vscode.TreeViewExpansionEvent<T>> = this._register(new Emitter<vscode.TreeViewExpansionEvent<T>>()); readonly onDidCollapseElement: Event<vscode.TreeViewExpansionEvent<T>> = this._onDidCollapseElement.event; private _onDidChangeSelection: Emitter<vscode.TreeViewSelectionChangeEvent<T>> = this._register(new Emitter<vscode.TreeViewSelectionChangeEvent<T>>()); readonly onDidChangeSelection: Event<vscode.TreeViewSelectionChangeEvent<T>> = this._onDidChangeSelection.event; private _onDidChangeVisibility: Emitter<vscode.TreeViewVisibilityChangeEvent> = this._register(new Emitter<vscode.TreeViewVisibilityChangeEvent>()); readonly onDidChangeVisibility: Event<vscode.TreeViewVisibilityChangeEvent> = this._onDidChangeVisibility.event; private _onDidChangeData: Emitter<TreeData<T>> = this._register(new Emitter<TreeData<T>>()); private refreshPromise: Promise<void> = Promise.resolve(); private refreshQueue: Promise<void> = Promise.resolve(); constructor( private viewId: string, options: vscode.TreeViewOptions<T>, private proxy: MainThreadTreeViewsShape, private commands: CommandsConverter, private logService: ILogService, private extension: IExtensionDescription ) { super(); if (extension.contributes && extension.contributes.views) { for (const location in extension.contributes.views) { for (const view of extension.contributes.views[location]) { if (view.id === viewId) { this._title = view.name; } } } } this.dataProvider = options.treeDataProvider; this.proxy.$registerTreeViewDataProvider(viewId, { showCollapseAll: !!options.showCollapseAll, canSelectMany: !!options.canSelectMany }); if (this.dataProvider.onDidChangeTreeData) { this._register(this.dataProvider.onDidChangeTreeData(element => this._onDidChangeData.fire({ message: false, element }))); } let refreshingPromise: Promise<void> | null; let promiseCallback: () => void; this._register(Event.debounce<TreeData<T>, { message: boolean, elements: (T | Root)[] }>(this._onDidChangeData.event, (result, current) => { if (!result) { result = { message: false, elements: [] }; } if (current.element !== false) { if (!refreshingPromise) { // New refresh has started refreshingPromise = new Promise(c => promiseCallback = c); this.refreshPromise = this.refreshPromise.then(() => refreshingPromise!); } result.elements.push(current.element); } if (current.message) { result.message = true; } return result; }, 200, true)(({ message, elements }) => { if (elements.length) { this.refreshQueue = this.refreshQueue.then(() => { const _promiseCallback = promiseCallback; refreshingPromise = null; return this.refresh(elements).then(() => _promiseCallback()); }); } if (message) { this.proxy.$setMessage(this.viewId, this._message); } })); } getChildren(parentHandle: TreeItemHandle | Root): Promise<ITreeItem[]> { const parentElement = parentHandle ? this.getExtensionElement(parentHandle) : undefined; if (parentHandle && !parentElement) { this.logService.error(`No tree item with id \'${parentHandle}\' found.`); return Promise.resolve([]); } const childrenNodes = this.getChildrenNodes(parentHandle); // Get it from cache return (childrenNodes ? Promise.resolve(childrenNodes) : this.fetchChildrenNodes(parentElement)) .then(nodes => nodes.map(n => n.item)); } getExtensionElement(treeItemHandle: TreeItemHandle): T | undefined { return this.elements.get(treeItemHandle); } reveal(element: T | undefined, options?: IRevealOptions): Promise<void> { options = options ? options : { select: true, focus: false }; const select = isUndefinedOrNull(options.select) ? true : options.select; const focus = isUndefinedOrNull(options.focus) ? false : options.focus; const expand = isUndefinedOrNull(options.expand) ? false : options.expand; if (typeof this.dataProvider.getParent !== 'function') { return Promise.reject(new Error(`Required registered TreeDataProvider to implement 'getParent' method to access 'reveal' method`)); } if (element) { return this.refreshPromise .then(() => this.resolveUnknownParentChain(element)) .then(parentChain => this.resolveTreeNode(element, parentChain[parentChain.length - 1]) .then(treeNode => this.proxy.$reveal(this.viewId, { item: treeNode.item, parentChain: parentChain.map(p => p.item) }, { select, focus, expand })), error => this.logService.error(error)); } else { return this.proxy.$reveal(this.viewId, undefined, { select, focus, expand }); } } private _message: string = ''; get message(): string { return this._message; } set message(message: string) { this._message = message; this._onDidChangeData.fire({ message: true, element: false }); } private _title: string = ''; get title(): string { return this._title; } set title(title: string) { this._title = title; this.proxy.$setTitle(this.viewId, title, this._description); } private _description: string | undefined; get description(): string | undefined { return this._description; } set description(description: string | undefined) { this._description = description; this.proxy.$setTitle(this.viewId, this._title, description); } setExpanded(treeItemHandle: TreeItemHandle, expanded: boolean): void { const element = this.getExtensionElement(treeItemHandle); if (element) { if (expanded) { this._onDidExpandElement.fire(Object.freeze({ element })); } else { this._onDidCollapseElement.fire(Object.freeze({ element })); } } } setSelection(treeItemHandles: TreeItemHandle[]): void { if (!equals(this._selectedHandles, treeItemHandles)) { this._selectedHandles = treeItemHandles; this._onDidChangeSelection.fire(Object.freeze({ selection: this.selectedElements })); } } setVisible(visible: boolean): void { if (visible !== this._visible) { this._visible = visible; this._onDidChangeVisibility.fire(Object.freeze({ visible: this._visible })); } } get hasResolve(): boolean { return !!this.dataProvider.resolveTreeItem; } async resolveTreeItem(treeItemHandle: string, token: vscode.CancellationToken): Promise<ITreeItem | undefined> { if (!this.dataProvider.resolveTreeItem) { return; } const element = this.elements.get(treeItemHandle); if (element) { const node = this.nodes.get(element); if (node) { const resolve = await this.dataProvider.resolveTreeItem(node.extensionItem, element, token) ?? node.extensionItem; // Resolvable elements. Currently only tooltip and command. node.item.tooltip = this.getTooltip(resolve.tooltip); node.item.command = this.getCommand(node.disposableStore, resolve.command); return node.item; } } return; } private resolveUnknownParentChain(element: T): Promise<TreeNode[]> { return this.resolveParent(element) .then((parent) => { if (!parent) { return Promise.resolve([]); } return this.resolveUnknownParentChain(parent) .then(result => this.resolveTreeNode(parent, result[result.length - 1]) .then(parentNode => { result.push(parentNode); return result; })); }); } private resolveParent(element: T): Promise<T | Root> { const node = this.nodes.get(element); if (node) { return Promise.resolve(node.parent ? this.elements.get(node.parent.item.handle) : undefined); } return asPromise(() => this.dataProvider.getParent!(element)); } private resolveTreeNode(element: T, parent?: TreeNode): Promise<TreeNode> { const node = this.nodes.get(element); if (node) { return Promise.resolve(node); } return asPromise(() => this.dataProvider.getTreeItem(element)) .then(extTreeItem => this.createHandle(element, extTreeItem, parent, true)) .then(handle => this.getChildren(parent ? parent.item.handle : undefined) .then(() => { const cachedElement = this.getExtensionElement(handle); if (cachedElement) { const node = this.nodes.get(cachedElement); if (node) { return Promise.resolve(node); } } throw new Error(`Cannot resolve tree item for element ${handle}`); })); } private getChildrenNodes(parentNodeOrHandle: TreeNode | TreeItemHandle | Root): TreeNode[] | null { if (parentNodeOrHandle) { let parentNode: TreeNode | undefined; if (typeof parentNodeOrHandle === 'string') { const parentElement = this.getExtensionElement(parentNodeOrHandle); parentNode = parentElement ? this.nodes.get(parentElement) : undefined; } else { parentNode = parentNodeOrHandle; } return parentNode ? parentNode.children || null : null; } return this.roots; } private async fetchChildrenNodes(parentElement?: T): Promise<TreeNode[]> { // clear children cache this.clearChildren(parentElement); const cts = new CancellationTokenSource(this._refreshCancellationSource.token); try { const parentNode = parentElement ? this.nodes.get(parentElement) : undefined; const elements = await this.dataProvider.getChildren(parentElement); if (cts.token.isCancellationRequested) { return []; } const items = await Promise.all(coalesce(elements || []).map(async element => { const item = await this.dataProvider.getTreeItem(element); return item && !cts.token.isCancellationRequested ? this.createAndRegisterTreeNode(element, item, parentNode) : null; })); if (cts.token.isCancellationRequested) { return []; } return coalesce(items); } finally { cts.dispose(); } } private _refreshCancellationSource = new CancellationTokenSource(); private refresh(elements: (T | Root)[]): Promise<void> { const hasRoot = elements.some(element => !element); if (hasRoot) { // Cancel any pending children fetches this._refreshCancellationSource.dispose(true); this._refreshCancellationSource = new CancellationTokenSource(); this.clearAll(); // clear cache return this.proxy.$refresh(this.viewId); } else { const handlesToRefresh = this.getHandlesToRefresh(<T[]>elements); if (handlesToRefresh.length) { return this.refreshHandles(handlesToRefresh); } } return Promise.resolve(undefined); } private getHandlesToRefresh(elements: T[]): TreeItemHandle[] { const elementsToUpdate = new Set<TreeItemHandle>(); for (const element of elements) { const elementNode = this.nodes.get(element); if (elementNode && !elementsToUpdate.has(elementNode.item.handle)) { // check if an ancestor of extElement is already in the elements to update list let currentNode: TreeNode | undefined = elementNode; while (currentNode && currentNode.parent && !elementsToUpdate.has(currentNode.parent.item.handle)) { const parentElement: T | undefined = this.elements.get(currentNode.parent.item.handle); currentNode = parentElement ? this.nodes.get(parentElement) : undefined; } if (currentNode && !currentNode.parent) { elementsToUpdate.add(elementNode.item.handle); } } } const handlesToUpdate: TreeItemHandle[] = []; // Take only top level elements elementsToUpdate.forEach((handle) => { const element = this.elements.get(handle); if (element) { const node = this.nodes.get(element); if (node && (!node.parent || !elementsToUpdate.has(node.parent.item.handle))) { handlesToUpdate.push(handle); } } }); return handlesToUpdate; } private refreshHandles(itemHandles: TreeItemHandle[]): Promise<void> { const itemsToRefresh: { [treeItemHandle: string]: ITreeItem } = {}; return Promise.all(itemHandles.map(treeItemHandle => this.refreshNode(treeItemHandle) .then(node => { if (node) { itemsToRefresh[treeItemHandle] = node.item; } }))) .then(() => Object.keys(itemsToRefresh).length ? this.proxy.$refresh(this.viewId, itemsToRefresh) : undefined); } private refreshNode(treeItemHandle: TreeItemHandle): Promise<TreeNode | null> { const extElement = this.getExtensionElement(treeItemHandle); if (extElement) { const existing = this.nodes.get(extElement); if (existing) { this.clearChildren(extElement); // clear children cache return asPromise(() => this.dataProvider.getTreeItem(extElement)) .then(extTreeItem => { if (extTreeItem) { const newNode = this.createTreeNode(extElement, extTreeItem, existing.parent); this.updateNodeCache(extElement, newNode, existing, existing.parent); existing.dispose(); return newNode; } return null; }); } } return Promise.resolve(null); } private createAndRegisterTreeNode(element: T, extTreeItem: vscode.TreeItem, parentNode: TreeNode | Root): TreeNode { const node = this.createTreeNode(element, extTreeItem, parentNode); if (extTreeItem.id && this.elements.has(node.item.handle)) { throw new Error(localize('treeView.duplicateElement', 'Element with id {0} is already registered', extTreeItem.id)); } this.addNodeToCache(element, node); this.addNodeToParentCache(node, parentNode); return node; } private getTooltip(tooltip?: string | vscode.MarkdownString): string | IMarkdownString | undefined { if (MarkdownStringType.isMarkdownString(tooltip)) { return MarkdownString.from(tooltip); } return tooltip; } private getCommand(disposable: DisposableStore, command?: vscode.Command): Command | undefined { return command ? this.commands.toInternal(command, disposable) : undefined; } private createTreeNode(element: T, extensionTreeItem: vscode.TreeItem, parent: TreeNode | Root): TreeNode { const disposableStore = new DisposableStore(); const handle = this.createHandle(element, extensionTreeItem, parent); const icon = this.getLightIconPath(extensionTreeItem); const item: ITreeItem = { handle, parentHandle: parent ? parent.item.handle : undefined, label: toTreeItemLabel(extensionTreeItem.label, this.extension), description: extensionTreeItem.description, resourceUri: extensionTreeItem.resourceUri, tooltip: this.getTooltip(extensionTreeItem.tooltip), command: this.getCommand(disposableStore, extensionTreeItem.command), contextValue: extensionTreeItem.contextValue, icon, iconDark: this.getDarkIconPath(extensionTreeItem) || icon, themeIcon: this.getThemeIcon(extensionTreeItem), collapsibleState: isUndefinedOrNull(extensionTreeItem.collapsibleState) ? TreeItemCollapsibleState.None : extensionTreeItem.collapsibleState, accessibilityInformation: extensionTreeItem.accessibilityInformation }; return { item, extensionItem: extensionTreeItem, parent, children: undefined, disposableStore, dispose(): void { disposableStore.dispose(); } }; } private getThemeIcon(extensionTreeItem: vscode.TreeItem): ThemeIcon | undefined { return extensionTreeItem.iconPath instanceof ThemeIcon ? extensionTreeItem.iconPath : undefined; } private createHandle(element: T, { id, label, resourceUri }: vscode.TreeItem, parent: TreeNode | Root, returnFirst?: boolean): TreeItemHandle { if (id) { return `${ExtHostTreeView.ID_HANDLE_PREFIX}/${id}`; } const treeItemLabel = toTreeItemLabel(label, this.extension); const prefix: string = parent ? parent.item.handle : ExtHostTreeView.LABEL_HANDLE_PREFIX; let elementId = treeItemLabel ? treeItemLabel.label : resourceUri ? basename(resourceUri) : ''; elementId = elementId.indexOf('/') !== -1 ? elementId.replace('/', '//') : elementId; const existingHandle = this.nodes.has(element) ? this.nodes.get(element)!.item.handle : undefined; const childrenNodes = (this.getChildrenNodes(parent) || []); let handle: TreeItemHandle; let counter = 0; do { handle = `${prefix}/${counter}:${elementId}`; if (returnFirst || !this.elements.has(handle) || existingHandle === handle) { // Return first if asked for or // Return if handle does not exist or // Return if handle is being reused break; } counter++; } while (counter <= childrenNodes.length); return handle; } private getLightIconPath(extensionTreeItem: vscode.TreeItem): URI | undefined { if (extensionTreeItem.iconPath && !(extensionTreeItem.iconPath instanceof ThemeIcon)) { if (typeof extensionTreeItem.iconPath === 'string' || URI.isUri(extensionTreeItem.iconPath)) { return this.getIconPath(extensionTreeItem.iconPath); } return this.getIconPath((<{ light: string | URI; dark: string | URI }>extensionTreeItem.iconPath).light); } return undefined; } private getDarkIconPath(extensionTreeItem: vscode.TreeItem): URI | undefined { if (extensionTreeItem.iconPath && !(extensionTreeItem.iconPath instanceof ThemeIcon) && (<{ light: string | URI; dark: string | URI }>extensionTreeItem.iconPath).dark) { return this.getIconPath((<{ light: string | URI; dark: string | URI }>extensionTreeItem.iconPath).dark); } return undefined; } private getIconPath(iconPath: string | URI): URI { if (URI.isUri(iconPath)) { return iconPath; } return URI.file(iconPath); } private addNodeToCache(element: T, node: TreeNode): void { this.elements.set(node.item.handle, element); this.nodes.set(element, node); } private updateNodeCache(element: T, newNode: TreeNode, existing: TreeNode, parentNode: TreeNode | Root): void { // Remove from the cache this.elements.delete(newNode.item.handle); this.nodes.delete(element); if (newNode.item.handle !== existing.item.handle) { this.elements.delete(existing.item.handle); } // Add the new node to the cache this.addNodeToCache(element, newNode); // Replace the node in parent's children nodes const childrenNodes = (this.getChildrenNodes(parentNode) || []); const childNode = childrenNodes.filter(c => c.item.handle === existing.item.handle)[0]; if (childNode) { childrenNodes.splice(childrenNodes.indexOf(childNode), 1, newNode); } } private addNodeToParentCache(node: TreeNode, parentNode: TreeNode | Root): void { if (parentNode) { if (!parentNode.children) { parentNode.children = []; } parentNode.children.push(node); } else { if (!this.roots) { this.roots = []; } this.roots.push(node); } } private clearChildren(parentElement?: T): void { if (parentElement) { const node = this.nodes.get(parentElement); if (node) { if (node.children) { for (const child of node.children) { const childElement = this.elements.get(child.item.handle); if (childElement) { this.clear(childElement); } } } node.children = undefined; } } else { this.clearAll(); } } private clear(element: T): void { const node = this.nodes.get(element); if (node) { if (node.children) { for (const child of node.children) { const childElement = this.elements.get(child.item.handle); if (childElement) { this.clear(childElement); } } } this.nodes.delete(element); this.elements.delete(node.item.handle); node.dispose(); } } private clearAll(): void { this.roots = null; this.elements.clear(); this.nodes.forEach(node => node.dispose()); this.nodes.clear(); } dispose() { this._refreshCancellationSource.dispose(); this.clearAll(); } }
src/vs/workbench/api/common/extHostTreeViews.ts
1
https://github.com/microsoft/vscode/commit/44dbd182557ee8c164f3917a2f9dc09a37ff623c
[ 0.8429761528968811, 0.01185018103569746, 0.0001644243748160079, 0.00017408342682756484, 0.09599099308252335 ]
{ "id": 5, "code_window": [ "\tclass RecordingShape extends mock<MainThreadTreeViewsShape>() {\n", "\n", "\t\tonRefresh = new Emitter<{ [treeItemHandle: string]: ITreeItem }>();\n", "\n", "\t\t$registerTreeViewDataProvider(treeViewId: string): void {\n", "\t\t}\n", "\n", "\t\t$refresh(viewId: string, itemsToRefresh: { [treeItemHandle: string]: ITreeItem }): Promise<void> {\n", "\t\t\treturn Promise.resolve(null).then(() => {\n", "\t\t\t\tthis.onRefresh.fire(itemsToRefresh);\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tasync $registerTreeViewDataProvider(treeViewId: string): Promise<void> {\n" ], "file_path": "src/vs/workbench/test/browser/api/extHostTreeViews.test.ts", "type": "replace", "edit_start_line_idx": 28 }
/*--------------------------------------------------------------------------------------------- * 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 { Range } from 'vs/editor/common/core/range'; import { EndOfLinePreference, EndOfLineSequence, IIdentifiedSingleEditOperation } from 'vs/editor/common/model'; import { MirrorTextModel } from 'vs/editor/common/model/mirrorTextModel'; import { TextModel } from 'vs/editor/common/model/textModel'; import { IModelContentChangedEvent } from 'vs/editor/common/model/textModelEvents'; import { assertSyncedModels, testApplyEditsWithSyncedModels } from 'vs/editor/test/common/model/editableTextModelTestUtils'; import { createTextModel } from 'vs/editor/test/common/editorTestUtils'; function createEditableTextModelFromString(text: string): TextModel { return createTextModel(text, TextModel.DEFAULT_CREATION_OPTIONS, null); } suite('EditorModel - EditableTextModel.applyEdits updates mightContainRTL', () => { function testApplyEdits(original: string[], edits: IIdentifiedSingleEditOperation[], before: boolean, after: boolean): void { let model = createEditableTextModelFromString(original.join('\n')); model.setEOL(EndOfLineSequence.LF); assert.strictEqual(model.mightContainRTL(), before); model.applyEdits(edits); assert.strictEqual(model.mightContainRTL(), after); model.dispose(); } function editOp(startLineNumber: number, startColumn: number, endLineNumber: number, endColumn: number, text: string[]): IIdentifiedSingleEditOperation { return { range: new Range(startLineNumber, startColumn, endLineNumber, endColumn), text: text.join('\n') }; } test('start with RTL, insert LTR', () => { testApplyEdits(['Hello,\nזוהי עובדה מבוססת שדעתו'], [editOp(1, 1, 1, 1, ['hello'])], true, true); }); test('start with RTL, delete RTL', () => { testApplyEdits(['Hello,\nזוהי עובדה מבוססת שדעתו'], [editOp(1, 1, 10, 10, [''])], true, true); }); test('start with RTL, insert RTL', () => { testApplyEdits(['Hello,\nזוהי עובדה מבוססת שדעתו'], [editOp(1, 1, 1, 1, ['هناك حقيقة مثبتة منذ زمن طويل'])], true, true); }); test('start with LTR, insert LTR', () => { testApplyEdits(['Hello,\nworld!'], [editOp(1, 1, 1, 1, ['hello'])], false, false); }); test('start with LTR, insert RTL 1', () => { testApplyEdits(['Hello,\nworld!'], [editOp(1, 1, 1, 1, ['هناك حقيقة مثبتة منذ زمن طويل'])], false, true); }); test('start with LTR, insert RTL 2', () => { testApplyEdits(['Hello,\nworld!'], [editOp(1, 1, 1, 1, ['זוהי עובדה מבוססת שדעתו'])], false, true); }); }); suite('EditorModel - EditableTextModel.applyEdits updates mightContainNonBasicASCII', () => { function testApplyEdits(original: string[], edits: IIdentifiedSingleEditOperation[], before: boolean, after: boolean): void { let model = createEditableTextModelFromString(original.join('\n')); model.setEOL(EndOfLineSequence.LF); assert.strictEqual(model.mightContainNonBasicASCII(), before); model.applyEdits(edits); assert.strictEqual(model.mightContainNonBasicASCII(), after); model.dispose(); } function editOp(startLineNumber: number, startColumn: number, endLineNumber: number, endColumn: number, text: string[]): IIdentifiedSingleEditOperation { return { range: new Range(startLineNumber, startColumn, endLineNumber, endColumn), text: text.join('\n') }; } test('start with NON-ASCII, insert ASCII', () => { testApplyEdits(['Hello,\nZürich'], [editOp(1, 1, 1, 1, ['hello', 'second line'])], true, true); }); test('start with NON-ASCII, delete NON-ASCII', () => { testApplyEdits(['Hello,\nZürich'], [editOp(1, 1, 10, 10, [''])], true, true); }); test('start with NON-ASCII, insert NON-ASCII', () => { testApplyEdits(['Hello,\nZürich'], [editOp(1, 1, 1, 1, ['Zürich'])], true, true); }); test('start with ASCII, insert ASCII', () => { testApplyEdits(['Hello,\nworld!'], [editOp(1, 1, 1, 1, ['hello', 'second line'])], false, false); }); test('start with ASCII, insert NON-ASCII', () => { testApplyEdits(['Hello,\nworld!'], [editOp(1, 1, 1, 1, ['Zürich', 'Zürich'])], false, true); }); }); suite('EditorModel - EditableTextModel.applyEdits', () => { function editOp(startLineNumber: number, startColumn: number, endLineNumber: number, endColumn: number, text: string[]): IIdentifiedSingleEditOperation { return { identifier: null, range: new Range(startLineNumber, startColumn, endLineNumber, endColumn), text: text.join('\n'), forceMoveMarkers: false }; } test('high-low surrogates 1', () => { testApplyEditsWithSyncedModels( [ '📚some', 'very nice', 'text' ], [ editOp(1, 2, 1, 2, ['a']) ], [ 'a📚some', 'very nice', 'text' ], /*inputEditsAreInvalid*/true ); }); test('high-low surrogates 2', () => { testApplyEditsWithSyncedModels( [ '📚some', 'very nice', 'text' ], [ editOp(1, 2, 1, 3, ['a']) ], [ 'asome', 'very nice', 'text' ], /*inputEditsAreInvalid*/true ); }); test('high-low surrogates 3', () => { testApplyEditsWithSyncedModels( [ '📚some', 'very nice', 'text' ], [ editOp(1, 1, 1, 2, ['a']) ], [ 'asome', 'very nice', 'text' ], /*inputEditsAreInvalid*/true ); }); test('high-low surrogates 4', () => { testApplyEditsWithSyncedModels( [ '📚some', 'very nice', 'text' ], [ editOp(1, 1, 1, 3, ['a']) ], [ 'asome', 'very nice', 'text' ], /*inputEditsAreInvalid*/true ); }); test('Bug 19872: Undo is funky', () => { testApplyEditsWithSyncedModels( [ 'something', ' A', '', ' B', 'something else' ], [ editOp(2, 1, 2, 2, ['']), editOp(3, 1, 4, 2, ['']) ], [ 'something', 'A', 'B', 'something else' ] ); }); test('Bug 19872: Undo is funky', () => { testApplyEditsWithSyncedModels( [ 'something', 'A', 'B', 'something else' ], [ editOp(2, 1, 2, 1, [' ']), editOp(3, 1, 3, 1, ['', ' ']) ], [ 'something', ' A', '', ' B', 'something else' ] ); }); test('insert empty text', () => { testApplyEditsWithSyncedModels( [ 'My First Line', '\t\tMy Second Line', ' Third Line', '', '1' ], [ editOp(1, 1, 1, 1, ['']) ], [ 'My First Line', '\t\tMy Second Line', ' Third Line', '', '1' ] ); }); test('last op is no-op', () => { testApplyEditsWithSyncedModels( [ 'My First Line', '\t\tMy Second Line', ' Third Line', '', '1' ], [ editOp(1, 1, 1, 2, ['']), editOp(4, 1, 4, 1, ['']) ], [ 'y First Line', '\t\tMy Second Line', ' Third Line', '', '1' ] ); }); test('insert text without newline 1', () => { testApplyEditsWithSyncedModels( [ 'My First Line', '\t\tMy Second Line', ' Third Line', '', '1' ], [ editOp(1, 1, 1, 1, ['foo ']) ], [ 'foo My First Line', '\t\tMy Second Line', ' Third Line', '', '1' ] ); }); test('insert text without newline 2', () => { testApplyEditsWithSyncedModels( [ 'My First Line', '\t\tMy Second Line', ' Third Line', '', '1' ], [ editOp(1, 3, 1, 3, [' foo']) ], [ 'My foo First Line', '\t\tMy Second Line', ' Third Line', '', '1' ] ); }); test('insert one newline', () => { testApplyEditsWithSyncedModels( [ 'My First Line', '\t\tMy Second Line', ' Third Line', '', '1' ], [ editOp(1, 4, 1, 4, ['', '']) ], [ 'My ', 'First Line', '\t\tMy Second Line', ' Third Line', '', '1' ] ); }); test('insert text with one newline', () => { testApplyEditsWithSyncedModels( [ 'My First Line', '\t\tMy Second Line', ' Third Line', '', '1' ], [ editOp(1, 3, 1, 3, [' new line', 'No longer']) ], [ 'My new line', 'No longer First Line', '\t\tMy Second Line', ' Third Line', '', '1' ] ); }); test('insert text with two newlines', () => { testApplyEditsWithSyncedModels( [ 'My First Line', '\t\tMy Second Line', ' Third Line', '', '1' ], [ editOp(1, 3, 1, 3, [' new line', 'One more line in the middle', 'No longer']) ], [ 'My new line', 'One more line in the middle', 'No longer First Line', '\t\tMy Second Line', ' Third Line', '', '1' ] ); }); test('insert text with many newlines', () => { testApplyEditsWithSyncedModels( [ 'My First Line', '\t\tMy Second Line', ' Third Line', '', '1' ], [ editOp(1, 3, 1, 3, ['', '', '', '', '']) ], [ 'My', '', '', '', ' First Line', '\t\tMy Second Line', ' Third Line', '', '1' ] ); }); test('insert multiple newlines', () => { testApplyEditsWithSyncedModels( [ 'My First Line', '\t\tMy Second Line', ' Third Line', '', '1' ], [ editOp(1, 3, 1, 3, ['', '', '', '', '']), editOp(3, 15, 3, 15, ['a', 'b']) ], [ 'My', '', '', '', ' First Line', '\t\tMy Second Line', ' Third Linea', 'b', '', '1' ] ); }); test('delete empty text', () => { testApplyEditsWithSyncedModels( [ 'My First Line', '\t\tMy Second Line', ' Third Line', '', '1' ], [ editOp(1, 1, 1, 1, ['']) ], [ 'My First Line', '\t\tMy Second Line', ' Third Line', '', '1' ] ); }); test('delete text from one line', () => { testApplyEditsWithSyncedModels( [ 'My First Line', '\t\tMy Second Line', ' Third Line', '', '1' ], [ editOp(1, 1, 1, 2, ['']) ], [ 'y First Line', '\t\tMy Second Line', ' Third Line', '', '1' ] ); }); test('delete text from one line 2', () => { testApplyEditsWithSyncedModels( [ 'My First Line', '\t\tMy Second Line', ' Third Line', '', '1' ], [ editOp(1, 1, 1, 3, ['a']) ], [ 'a First Line', '\t\tMy Second Line', ' Third Line', '', '1' ] ); }); test('delete all text from a line', () => { testApplyEditsWithSyncedModels( [ 'My First Line', '\t\tMy Second Line', ' Third Line', '', '1' ], [ editOp(1, 1, 1, 14, ['']) ], [ '', '\t\tMy Second Line', ' Third Line', '', '1' ] ); }); test('delete text from two lines', () => { testApplyEditsWithSyncedModels( [ 'My First Line', '\t\tMy Second Line', ' Third Line', '', '1' ], [ editOp(1, 4, 2, 6, ['']) ], [ 'My Second Line', ' Third Line', '', '1' ] ); }); test('delete text from many lines', () => { testApplyEditsWithSyncedModels( [ 'My First Line', '\t\tMy Second Line', ' Third Line', '', '1' ], [ editOp(1, 4, 3, 5, ['']) ], [ 'My Third Line', '', '1' ] ); }); test('delete everything', () => { testApplyEditsWithSyncedModels( [ 'My First Line', '\t\tMy Second Line', ' Third Line', '', '1' ], [ editOp(1, 1, 5, 2, ['']) ], [ '' ] ); }); test('two unrelated edits', () => { testApplyEditsWithSyncedModels( [ 'My First Line', '\t\tMy Second Line', ' Third Line', '', '123' ], [ editOp(2, 1, 2, 3, ['\t']), editOp(3, 1, 3, 5, ['']) ], [ 'My First Line', '\tMy Second Line', 'Third Line', '', '123' ] ); }); test('two edits on one line', () => { testApplyEditsWithSyncedModels( [ '\t\tfirst\t ', '\t\tsecond line', '\tthird line', 'fourth line', '\t\t<!@#fifth#@!>\t\t' ], [ editOp(5, 3, 5, 7, ['']), editOp(5, 12, 5, 16, ['']) ], [ '\t\tfirst\t ', '\t\tsecond line', '\tthird line', 'fourth line', '\t\tfifth\t\t' ] ); }); test('many edits', () => { testApplyEditsWithSyncedModels( [ '{"x" : 1}' ], [ editOp(1, 2, 1, 2, ['\n ']), editOp(1, 5, 1, 6, ['']), editOp(1, 9, 1, 9, ['\n']) ], [ '{', ' "x": 1', '}' ] ); }); test('many edits reversed', () => { testApplyEditsWithSyncedModels( [ '{', ' "x": 1', '}' ], [ editOp(1, 2, 2, 3, ['']), editOp(2, 6, 2, 6, [' ']), editOp(2, 9, 3, 1, ['']) ], [ '{"x" : 1}' ] ); }); test('replacing newlines 1', () => { testApplyEditsWithSyncedModels( [ '{', '"a": true,', '', '"b": true', '}' ], [ editOp(1, 2, 2, 1, ['', '\t']), editOp(2, 11, 4, 1, ['', '\t']) ], [ '{', '\t"a": true,', '\t"b": true', '}' ] ); }); test('replacing newlines 2', () => { testApplyEditsWithSyncedModels( [ 'some text', 'some more text', 'now comes an empty line', '', 'after empty line', 'and the last line' ], [ editOp(1, 5, 3, 1, [' text', 'some more text', 'some more text']), editOp(3, 2, 4, 1, ['o more lines', 'asd', 'asd', 'asd']), editOp(5, 1, 5, 6, ['zzzzzzzz']), editOp(5, 11, 6, 16, ['1', '2', '3', '4']) ], [ 'some text', 'some more text', 'some more textno more lines', 'asd', 'asd', 'asd', 'zzzzzzzz empt1', '2', '3', '4ne' ] ); }); test('advanced 1', () => { testApplyEditsWithSyncedModels( [ ' { "d": [', ' null', ' ] /*comment*/', ' ,"e": /*comment*/ [null] }', ], [ editOp(1, 1, 1, 2, ['']), editOp(1, 3, 1, 10, ['', ' ']), editOp(1, 16, 2, 14, ['', ' ']), editOp(2, 18, 3, 9, ['', ' ']), editOp(3, 22, 4, 9, ['']), editOp(4, 10, 4, 10, ['', ' ']), editOp(4, 28, 4, 28, ['', ' ']), editOp(4, 32, 4, 32, ['', ' ']), editOp(4, 33, 4, 34, ['', '']) ], [ '{', ' "d": [', ' null', ' ] /*comment*/,', ' "e": /*comment*/ [', ' null', ' ]', '}', ] ); }); test('advanced simplified', () => { testApplyEditsWithSyncedModels( [ ' abc', ' ,def' ], [ editOp(1, 1, 1, 4, ['']), editOp(1, 7, 2, 2, ['']), editOp(2, 3, 2, 3, ['', '']) ], [ 'abc,', 'def' ] ); }); test('issue #144', () => { testApplyEditsWithSyncedModels( [ 'package caddy', '', 'func main() {', '\tfmt.Println("Hello World! :)")', '}', '' ], [ editOp(1, 1, 6, 1, [ 'package caddy', '', 'import "fmt"', '', 'func main() {', '\tfmt.Println("Hello World! :)")', '}', '' ]) ], [ 'package caddy', '', 'import "fmt"', '', 'func main() {', '\tfmt.Println("Hello World! :)")', '}', '' ] ); }); test('issue #2586 Replacing selected end-of-line with newline locks up the document', () => { testApplyEditsWithSyncedModels( [ 'something', 'interesting' ], [ editOp(1, 10, 2, 1, ['', '']) ], [ 'something', 'interesting' ] ); }); test('issue #3980', () => { testApplyEditsWithSyncedModels( [ 'class A {', ' someProperty = false;', ' someMethod() {', ' this.someMethod();', ' }', '}', ], [ editOp(1, 8, 1, 9, ['', '']), editOp(3, 17, 3, 18, ['', '']), editOp(3, 18, 3, 18, [' ']), editOp(4, 5, 4, 5, [' ']), ], [ 'class A', '{', ' someProperty = false;', ' someMethod()', ' {', ' this.someMethod();', ' }', '}', ] ); }); function testApplyEditsFails(original: string[], edits: IIdentifiedSingleEditOperation[]): void { let model = createEditableTextModelFromString(original.join('\n')); let hasThrown = false; try { model.applyEdits(edits); } catch (err) { hasThrown = true; } assert.ok(hasThrown, 'expected model.applyEdits to fail.'); model.dispose(); } test('touching edits: two inserts at the same position', () => { testApplyEditsWithSyncedModels( [ 'hello world' ], [ editOp(1, 1, 1, 1, ['a']), editOp(1, 1, 1, 1, ['b']), ], [ 'abhello world' ] ); }); test('touching edits: insert and replace touching', () => { testApplyEditsWithSyncedModels( [ 'hello world' ], [ editOp(1, 1, 1, 1, ['b']), editOp(1, 1, 1, 3, ['ab']), ], [ 'babllo world' ] ); }); test('overlapping edits: two overlapping replaces', () => { testApplyEditsFails( [ 'hello world' ], [ editOp(1, 1, 1, 2, ['b']), editOp(1, 1, 1, 3, ['ab']), ] ); }); test('overlapping edits: two overlapping deletes', () => { testApplyEditsFails( [ 'hello world' ], [ editOp(1, 1, 1, 2, ['']), editOp(1, 1, 1, 3, ['']), ] ); }); test('touching edits: two touching replaces', () => { testApplyEditsWithSyncedModels( [ 'hello world' ], [ editOp(1, 1, 1, 2, ['H']), editOp(1, 2, 1, 3, ['E']), ], [ 'HEllo world' ] ); }); test('touching edits: two touching deletes', () => { testApplyEditsWithSyncedModels( [ 'hello world' ], [ editOp(1, 1, 1, 2, ['']), editOp(1, 2, 1, 3, ['']), ], [ 'llo world' ] ); }); test('touching edits: insert and replace', () => { testApplyEditsWithSyncedModels( [ 'hello world' ], [ editOp(1, 1, 1, 1, ['H']), editOp(1, 1, 1, 3, ['e']), ], [ 'Hello world' ] ); }); test('touching edits: replace and insert', () => { testApplyEditsWithSyncedModels( [ 'hello world' ], [ editOp(1, 1, 1, 3, ['H']), editOp(1, 3, 1, 3, ['e']), ], [ 'Hello world' ] ); }); test('change while emitting events 1', () => { assertSyncedModels('Hello', (model, assertMirrorModels) => { model.applyEdits([{ range: new Range(1, 6, 1, 6), text: ' world!', // forceMoveMarkers: false }]); assertMirrorModels(); }, (model) => { let isFirstTime = true; model.onDidChangeRawContent(() => { if (!isFirstTime) { return; } isFirstTime = false; model.applyEdits([{ range: new Range(1, 13, 1, 13), text: ' How are you?', // forceMoveMarkers: false }]); }); }); }); test('change while emitting events 2', () => { assertSyncedModels('Hello', (model, assertMirrorModels) => { model.applyEdits([{ range: new Range(1, 6, 1, 6), text: ' world!', // forceMoveMarkers: false }]); assertMirrorModels(); }, (model) => { let isFirstTime = true; model.onDidChangeContent((e: IModelContentChangedEvent) => { if (!isFirstTime) { return; } isFirstTime = false; model.applyEdits([{ range: new Range(1, 13, 1, 13), text: ' How are you?', // forceMoveMarkers: false }]); }); }); }); test('issue #1580: Changes in line endings are not correctly reflected in the extension host, leading to invalid offsets sent to external refactoring tools', () => { let model = createEditableTextModelFromString('Hello\nWorld!'); assert.strictEqual(model.getEOL(), '\n'); let mirrorModel2 = new MirrorTextModel(null!, model.getLinesContent(), model.getEOL(), model.getVersionId()); let mirrorModel2PrevVersionId = model.getVersionId(); model.onDidChangeContent((e: IModelContentChangedEvent) => { let versionId = e.versionId; if (versionId < mirrorModel2PrevVersionId) { console.warn('Model version id did not advance between edits (2)'); } mirrorModel2PrevVersionId = versionId; mirrorModel2.onEvents(e); }); let assertMirrorModels = () => { assert.strictEqual(mirrorModel2.getText(), model.getValue(), 'mirror model 2 text OK'); assert.strictEqual(mirrorModel2.version, model.getVersionId(), 'mirror model 2 version OK'); }; model.setEOL(EndOfLineSequence.CRLF); assertMirrorModels(); model.dispose(); mirrorModel2.dispose(); }); test('issue #47733: Undo mangles unicode characters', () => { let model = createEditableTextModelFromString('\'👁\''); model.applyEdits([ { range: new Range(1, 1, 1, 1), text: '"' }, { range: new Range(1, 2, 1, 2), text: '"' }, ]); assert.strictEqual(model.getValue(EndOfLinePreference.LF), '"\'"👁\''); assert.deepStrictEqual(model.validateRange(new Range(1, 3, 1, 4)), new Range(1, 3, 1, 4)); model.applyEdits([ { range: new Range(1, 1, 1, 2), text: null }, { range: new Range(1, 3, 1, 4), text: null }, ]); assert.strictEqual(model.getValue(EndOfLinePreference.LF), '\'👁\''); model.dispose(); }); test('issue #48741: Broken undo stack with move lines up with multiple cursors', () => { let model = createEditableTextModelFromString([ 'line1', 'line2', 'line3', '', ].join('\n')); const undoEdits = model.applyEdits([ { range: new Range(4, 1, 4, 1), text: 'line3', }, { range: new Range(3, 1, 3, 6), text: null, }, { range: new Range(2, 1, 3, 1), text: null, }, { range: new Range(3, 6, 3, 6), text: '\nline2' } ], true); model.applyEdits(undoEdits); assert.deepStrictEqual(model.getValue(), 'line1\nline2\nline3\n'); model.dispose(); }); });
src/vs/editor/test/common/model/editableTextModel.test.ts
0
https://github.com/microsoft/vscode/commit/44dbd182557ee8c164f3917a2f9dc09a37ff623c
[ 0.00017843983368948102, 0.0001740409788908437, 0.00016725980094633996, 0.00017438430222682655, 0.0000018817795535142068 ]
{ "id": 5, "code_window": [ "\tclass RecordingShape extends mock<MainThreadTreeViewsShape>() {\n", "\n", "\t\tonRefresh = new Emitter<{ [treeItemHandle: string]: ITreeItem }>();\n", "\n", "\t\t$registerTreeViewDataProvider(treeViewId: string): void {\n", "\t\t}\n", "\n", "\t\t$refresh(viewId: string, itemsToRefresh: { [treeItemHandle: string]: ITreeItem }): Promise<void> {\n", "\t\t\treturn Promise.resolve(null).then(() => {\n", "\t\t\t\tthis.onRefresh.fire(itemsToRefresh);\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tasync $registerTreeViewDataProvider(treeViewId: string): Promise<void> {\n" ], "file_path": "src/vs/workbench/test/browser/api/extHostTreeViews.test.ts", "type": "replace", "edit_start_line_idx": 28 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { LineTokens } from 'vs/editor/common/core/lineTokens'; import * as modes from 'vs/editor/common/modes'; export function createScopedLineTokens(context: LineTokens, offset: number): ScopedLineTokens { let tokenCount = context.getCount(); let tokenIndex = context.findTokenIndexAtOffset(offset); let desiredLanguageId = context.getLanguageId(tokenIndex); let lastTokenIndex = tokenIndex; while (lastTokenIndex + 1 < tokenCount && context.getLanguageId(lastTokenIndex + 1) === desiredLanguageId) { lastTokenIndex++; } let firstTokenIndex = tokenIndex; while (firstTokenIndex > 0 && context.getLanguageId(firstTokenIndex - 1) === desiredLanguageId) { firstTokenIndex--; } return new ScopedLineTokens( context, desiredLanguageId, firstTokenIndex, lastTokenIndex + 1, context.getStartOffset(firstTokenIndex), context.getEndOffset(lastTokenIndex) ); } export class ScopedLineTokens { _scopedLineTokensBrand: void; public readonly languageId: modes.LanguageId; private readonly _actual: LineTokens; private readonly _firstTokenIndex: number; private readonly _lastTokenIndex: number; public readonly firstCharOffset: number; private readonly _lastCharOffset: number; constructor( actual: LineTokens, languageId: modes.LanguageId, firstTokenIndex: number, lastTokenIndex: number, firstCharOffset: number, lastCharOffset: number ) { this._actual = actual; this.languageId = languageId; this._firstTokenIndex = firstTokenIndex; this._lastTokenIndex = lastTokenIndex; this.firstCharOffset = firstCharOffset; this._lastCharOffset = lastCharOffset; } public getLineContent(): string { const actualLineContent = this._actual.getLineContent(); return actualLineContent.substring(this.firstCharOffset, this._lastCharOffset); } public getActualLineContentBefore(offset: number): string { const actualLineContent = this._actual.getLineContent(); return actualLineContent.substring(0, this.firstCharOffset + offset); } public getTokenCount(): number { return this._lastTokenIndex - this._firstTokenIndex; } public findTokenIndexAtOffset(offset: number): number { return this._actual.findTokenIndexAtOffset(offset + this.firstCharOffset) - this._firstTokenIndex; } public getStandardTokenType(tokenIndex: number): modes.StandardTokenType { return this._actual.getStandardTokenType(tokenIndex + this._firstTokenIndex); } } const enum IgnoreBracketsInTokens { value = modes.StandardTokenType.Comment | modes.StandardTokenType.String | modes.StandardTokenType.RegEx } export function ignoreBracketsInToken(standardTokenType: modes.StandardTokenType): boolean { return (standardTokenType & IgnoreBracketsInTokens.value) !== 0; }
src/vs/editor/common/modes/supports.ts
0
https://github.com/microsoft/vscode/commit/44dbd182557ee8c164f3917a2f9dc09a37ff623c
[ 0.00017776276217773557, 0.00017471118189860135, 0.00017263788322452456, 0.00017461957759223878, 0.0000014178270930642611 ]
{ "id": 5, "code_window": [ "\tclass RecordingShape extends mock<MainThreadTreeViewsShape>() {\n", "\n", "\t\tonRefresh = new Emitter<{ [treeItemHandle: string]: ITreeItem }>();\n", "\n", "\t\t$registerTreeViewDataProvider(treeViewId: string): void {\n", "\t\t}\n", "\n", "\t\t$refresh(viewId: string, itemsToRefresh: { [treeItemHandle: string]: ITreeItem }): Promise<void> {\n", "\t\t\treturn Promise.resolve(null).then(() => {\n", "\t\t\t\tthis.onRefresh.fire(itemsToRefresh);\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tasync $registerTreeViewDataProvider(treeViewId: string): Promise<void> {\n" ], "file_path": "src/vs/workbench/test/browser/api/extHostTreeViews.test.ts", "type": "replace", "edit_start_line_idx": 28 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { ContextKeyExpr, RawContextKey } from 'vs/platform/contextkey/common/contextkey'; import { ICommandHandler } from 'vs/platform/commands/common/commands'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; import { IQuickInputService } from 'vs/platform/quickinput/common/quickInput'; export const inQuickPickContextKeyValue = 'inQuickOpen'; export const InQuickPickContextKey = new RawContextKey<boolean>(inQuickPickContextKeyValue, false); export const inQuickPickContext = ContextKeyExpr.has(inQuickPickContextKeyValue); export const defaultQuickAccessContextKeyValue = 'inFilesPicker'; export const defaultQuickAccessContext = ContextKeyExpr.and(inQuickPickContext, ContextKeyExpr.has(defaultQuickAccessContextKeyValue)); export interface IWorkbenchQuickAccessConfiguration { workbench: { commandPalette: { history: number; preserveInput: boolean; }, quickOpen: { enableExperimentalNewVersion: boolean; preserveInput: boolean; } }; } export function getQuickNavigateHandler(id: string, next?: boolean): ICommandHandler { return accessor => { const keybindingService = accessor.get(IKeybindingService); const quickInputService = accessor.get(IQuickInputService); const keys = keybindingService.lookupKeybindings(id); const quickNavigate = { keybindings: keys }; quickInputService.navigate(!!next, quickNavigate); }; }
src/vs/workbench/browser/quickaccess.ts
0
https://github.com/microsoft/vscode/commit/44dbd182557ee8c164f3917a2f9dc09a37ff623c
[ 0.0001763682084856555, 0.00017529272008687258, 0.0001731839292915538, 0.00017585318710189313, 0.0000011353929494362092 ]
{ "id": 0, "code_window": [ "// We can only have one node at the time claiming ownership for handling the swipe.\n", "// Otherwise, the UX would be confusing.\n", "// That's why we use a singleton here.\n", "let nodeHowClaimedTheSwipe = null;\n", "\n", "// Exported for test purposes.\n", "export function reset() {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "let nodeThatClaimedTheSwipe = null;\n" ], "file_path": "src/SwipeableDrawer/SwipeableDrawer.js", "type": "replace", "edit_start_line_idx": 18 }
/* eslint-disable consistent-this */ // @inheritedComponent Drawer import React from 'react'; import PropTypes from 'prop-types'; import ReactDOM from 'react-dom'; import Drawer, { getAnchor, isHorizontal } from '../Drawer/Drawer'; import { duration } from '../styles/transitions'; import withTheme from '../styles/withTheme'; import { getTransitionProps } from '../transitions/utils'; // This value is closed to what browsers are using internally to // trigger a native scroll. const UNCERTAINTY_THRESHOLD = 3; // px // We can only have one node at the time claiming ownership for handling the swipe. // Otherwise, the UX would be confusing. // That's why we use a singleton here. let nodeHowClaimedTheSwipe = null; // Exported for test purposes. export function reset() { nodeHowClaimedTheSwipe = null; } class SwipeableDrawer extends React.Component { state = { maybeSwiping: false, }; componentDidMount() { if (this.props.variant === 'temporary') { this.listenTouchStart(); } } componentDidUpdate(prevProps) { const variant = this.props.variant; const prevVariant = prevProps.variant; if (variant === 'temporary' && prevVariant !== 'temporary') { this.listenTouchStart(); } else if (variant !== 'temporary' && prevVariant === 'temporary') { this.removeTouchStart(); } } componentWillUnmount() { this.removeTouchStart(); this.removeBodyTouchListeners(); } getMaxTranslate() { return isHorizontal(this.props) ? this.paper.clientWidth : this.paper.clientHeight; } getTranslate(current) { const start = isHorizontal(this.props) ? this.startX : this.startY; return Math.min( Math.max( this.isSwiping === 'closing' ? start - current : this.getMaxTranslate() + start - current, 0, ), this.getMaxTranslate(), ); } setPosition(translate, options = {}) { const { mode = null, changeTransition = true } = options; const anchor = getAnchor(this.props); const rtlTranslateMultiplier = ['right', 'bottom'].indexOf(anchor) !== -1 ? 1 : -1; const transform = isHorizontal(this.props) ? `translate(${rtlTranslateMultiplier * translate}px, 0)` : `translate(0, ${rtlTranslateMultiplier * translate}px)`; const drawerStyle = this.paper.style; drawerStyle.webkitTransform = transform; drawerStyle.transform = transform; let transition = ''; if (mode) { transition = this.props.theme.transitions.create( 'all', getTransitionProps( { timeout: this.props.transitionDuration, }, { mode, }, ), ); } if (changeTransition) { drawerStyle.webkitTransition = transition; drawerStyle.transition = transition; } if (!this.props.disableBackdropTransition) { const backdropStyle = this.backdrop.style; backdropStyle.opacity = 1 - translate / this.getMaxTranslate(); if (changeTransition) { backdropStyle.webkitTransition = transition; backdropStyle.transition = transition; } } } handleBodyTouchStart = event => { // We are not supposed to hanlde this touch move. if (nodeHowClaimedTheSwipe !== null && nodeHowClaimedTheSwipe !== this) { return; } const { disableDiscovery, open, swipeAreaWidth } = this.props; const anchor = getAnchor(this.props); const currentX = anchor === 'right' ? document.body.offsetWidth - event.touches[0].pageX : event.touches[0].pageX; const currentY = anchor === 'bottom' ? window.innerHeight - event.touches[0].clientY : event.touches[0].clientY; if (!open) { if (isHorizontal(this.props)) { if (currentX > swipeAreaWidth) { return; } } else if (currentY > swipeAreaWidth) { return; } } nodeHowClaimedTheSwipe = this; this.startX = currentX; this.startY = currentY; this.setState({ maybeSwiping: true }); if (!open) { this.setPosition(this.getMaxTranslate() - (disableDiscovery ? 0 : swipeAreaWidth), { changeTransition: false, }); } document.body.addEventListener('touchmove', this.handleBodyTouchMove, { passive: false }); document.body.addEventListener('touchend', this.handleBodyTouchEnd); // https://plus.google.com/+PaulIrish/posts/KTwfn1Y2238 document.body.addEventListener('touchcancel', this.handleBodyTouchEnd); }; handleBodyTouchMove = event => { const anchor = getAnchor(this.props); const horizontalSwipe = isHorizontal(this.props); const currentX = anchor === 'right' ? document.body.offsetWidth - event.touches[0].pageX : event.touches[0].pageX; const currentY = anchor === 'bottom' ? window.innerHeight - event.touches[0].clientY : event.touches[0].clientY; // We don't know yet. if (this.isSwiping === undefined) { const dx = Math.abs(currentX - this.startX); const dy = Math.abs(currentY - this.startY); // If the user has moved his thumb some pixels in either direction, // we can safely make an assumption about whether he was intending // to swipe or scroll. const isSwiping = horizontalSwipe ? dx > UNCERTAINTY_THRESHOLD && dy <= UNCERTAINTY_THRESHOLD : dy > UNCERTAINTY_THRESHOLD && dx <= UNCERTAINTY_THRESHOLD; // We are likely to be swiping, let's prevent the scroll event on iOS. if (dx > dy) { event.preventDefault(); } if (isSwiping) { this.isSwiping = this.props.open ? 'closing' : 'opening'; // Shift the starting point. this.startX = currentX; this.startY = currentY; // Compensate for the part of the drawer displayed on touch start. if (!this.props.disableDiscovery && !this.props.open) { if (horizontalSwipe) { this.startX -= this.props.swipeAreaWidth; } else { this.startY -= this.props.swipeAreaWidth; } } } else if ( horizontalSwipe ? dx <= UNCERTAINTY_THRESHOLD && dy > UNCERTAINTY_THRESHOLD : dy <= UNCERTAINTY_THRESHOLD && dx > UNCERTAINTY_THRESHOLD ) { this.handleBodyTouchEnd(event); } } if (this.isSwiping === undefined) { return; } // We are swiping, let's prevent the scroll event on iOS. event.preventDefault(); this.setPosition(this.getTranslate(horizontalSwipe ? currentX : currentY)); }; handleBodyTouchEnd = event => { nodeHowClaimedTheSwipe = null; this.removeBodyTouchListeners(); this.setState({ maybeSwiping: false }); if (this.isSwiping === undefined) { return; } const anchor = getAnchor(this.props); let current; if (isHorizontal(this.props)) { current = anchor === 'right' ? document.body.offsetWidth - event.changedTouches[0].pageX : event.changedTouches[0].pageX; } else { current = anchor === 'bottom' ? window.innerHeight - event.changedTouches[0].clientY : event.changedTouches[0].clientY; } const translateRatio = this.getTranslate(current) / this.getMaxTranslate(); // We have to open or close after setting swiping to null, // because only then CSS transition is enabled. if (translateRatio > 0.5) { if (this.isSwiping === 'opening') { // Reset the position, the swipe was aborted. this.setPosition(this.getMaxTranslate(), { mode: 'enter', }); } else { this.props.onClose(); } } else if (this.isSwiping === 'opening') { this.props.onOpen(); } else { // Reset the position, the swipe was aborted. this.setPosition(0, { mode: 'exit', }); } this.isSwiping = undefined; }; backdrop = null; paper = null; isSwiping = undefined; startX = null; startY = null; listenTouchStart() { document.body.addEventListener('touchstart', this.handleBodyTouchStart); } removeTouchStart() { document.body.removeEventListener('touchstart', this.handleBodyTouchStart); } removeBodyTouchListeners() { document.body.removeEventListener('touchmove', this.handleBodyTouchMove, { passive: false }); document.body.removeEventListener('touchend', this.handleBodyTouchEnd); document.body.removeEventListener('touchcancel', this.handleBodyTouchEnd); } handleBackdropRef = node => { this.backdrop = node ? ReactDOM.findDOMNode(node) : null; }; handlePaperRef = node => { this.paper = node ? ReactDOM.findDOMNode(node) : null; }; render() { const { disableBackdropTransition, disableDiscovery, ModalProps: { BackdropProps, ...ModalPropsProp } = {}, onOpen, open, PaperProps, swipeAreaWidth, variant, ...other } = this.props; const { maybeSwiping } = this.state; return ( <Drawer open={variant === 'temporary' && maybeSwiping ? true : open} variant={variant} ModalProps={{ BackdropProps: { ...BackdropProps, ref: this.handleBackdropRef, }, ...ModalPropsProp, }} PaperProps={{ ...PaperProps, ref: this.handlePaperRef, }} {...other} /> ); } } SwipeableDrawer.propTypes = { /** * @ignore */ anchor: PropTypes.oneOf(['left', 'top', 'right', 'bottom']), /** * Disable the backdrop transition. * This can improve the FPS on low-end devices. */ disableBackdropTransition: PropTypes.bool, /** * If `true`, touching the screen near the edge of the drawer will not slide in the drawer a bit * to promote accidental discovery of the swipe gesture. */ disableDiscovery: PropTypes.bool, /** * @ignore */ ModalProps: PropTypes.object, /** * Callback fired when the component requests to be closed. * * @param {object} event The event source of the callback */ onClose: PropTypes.func.isRequired, /** * Callback fired when the component requests to be opened. * * @param {object} event The event source of the callback */ onOpen: PropTypes.func.isRequired, /** * If `true`, the drawer is open. */ open: PropTypes.bool.isRequired, /** * @ignore */ PaperProps: PropTypes.object, /** * The width of the left most (or right most) area in pixels where the * drawer can be swiped open from. */ swipeAreaWidth: PropTypes.number, /** * @ignore */ theme: PropTypes.object.isRequired, /** * The duration for the transition, in milliseconds. * You may specify a single timeout for all transitions, or individually with an object. */ transitionDuration: PropTypes.oneOfType([ PropTypes.number, PropTypes.shape({ enter: PropTypes.number, exit: PropTypes.number }), ]), /** * @ignore */ variant: PropTypes.oneOf(['permanent', 'persistent', 'temporary']), }; SwipeableDrawer.defaultProps = { anchor: 'left', disableBackdropTransition: false, disableDiscovery: false, swipeAreaWidth: 20, transitionDuration: { enter: duration.enteringScreen, exit: duration.leavingScreen }, variant: 'temporary', // Mobile first. }; export default withTheme()(SwipeableDrawer);
src/SwipeableDrawer/SwipeableDrawer.js
1
https://github.com/mui/material-ui/commit/5d126e65e30f7541e34b0c12bd68fa0c31ae71fa
[ 0.999539852142334, 0.12760457396507263, 0.00016408121155109257, 0.00017359477351419628, 0.3260740637779236 ]
{ "id": 0, "code_window": [ "// We can only have one node at the time claiming ownership for handling the swipe.\n", "// Otherwise, the UX would be confusing.\n", "// That's why we use a singleton here.\n", "let nodeHowClaimedTheSwipe = null;\n", "\n", "// Exported for test purposes.\n", "export function reset() {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "let nodeThatClaimedTheSwipe = null;\n" ], "file_path": "src/SwipeableDrawer/SwipeableDrawer.js", "type": "replace", "edit_start_line_idx": 18 }
import React from 'react'; import PropTypes from 'prop-types'; import KeyboardArrowLeft from '../internal/svg-icons/KeyboardArrowLeft'; import KeyboardArrowRight from '../internal/svg-icons/KeyboardArrowRight'; import withStyles from '../styles/withStyles'; import IconButton from '../IconButton'; export const styles = theme => ({ root: { flexShrink: 0, color: theme.palette.text.secondary, marginLeft: theme.spacing.unit * 2.5, }, }); /** * @ignore - internal component. */ class TablePaginationActions extends React.Component { handleBackButtonClick = event => { this.props.onChangePage(event, this.props.page - 1); }; handleNextButtonClick = event => { this.props.onChangePage(event, this.props.page + 1); }; render() { const { backIconButtonProps, classes, count, nextIconButtonProps, onChangePage, page, rowsPerPage, theme, ...other } = this.props; return ( <div className={classes.root} {...other}> <IconButton onClick={this.handleBackButtonClick} disabled={page === 0} {...backIconButtonProps} > {theme.direction === 'rtl' ? <KeyboardArrowRight /> : <KeyboardArrowLeft />} </IconButton> <IconButton onClick={this.handleNextButtonClick} disabled={page >= Math.ceil(count / rowsPerPage) - 1} {...nextIconButtonProps} > {theme.direction === 'rtl' ? <KeyboardArrowLeft /> : <KeyboardArrowRight />} </IconButton> </div> ); } } TablePaginationActions.propTypes = { /** * Properties applied to the back arrow `IconButton` element. */ backIconButtonProps: PropTypes.object, /** * Useful to extend the style applied to components. */ classes: PropTypes.object.isRequired, /** * The total number of rows. */ count: PropTypes.number.isRequired, /** * Properties applied to the next arrow `IconButton` element. */ nextIconButtonProps: PropTypes.object, /** * Callback fired when the page is changed. * * @param {object} event The event source of the callback * @param {number} page The page selected */ onChangePage: PropTypes.func.isRequired, /** * The zero-based index of the current page. */ page: PropTypes.number.isRequired, /** * The number of rows per page. */ rowsPerPage: PropTypes.number.isRequired, /** * @ignore */ theme: PropTypes.object.isRequired, }; export default withStyles(styles, { name: 'MuiTablePaginationActions', withTheme: true })( TablePaginationActions, );
src/Table/TablePaginationActions.js
0
https://github.com/mui/material-ui/commit/5d126e65e30f7541e34b0c12bd68fa0c31ae71fa
[ 0.00017582032887730747, 0.00016927911201491952, 0.00016439365572296083, 0.00016912345017772168, 0.0000037153918128751684 ]
{ "id": 0, "code_window": [ "// We can only have one node at the time claiming ownership for handling the swipe.\n", "// Otherwise, the UX would be confusing.\n", "// That's why we use a singleton here.\n", "let nodeHowClaimedTheSwipe = null;\n", "\n", "// Exported for test purposes.\n", "export function reset() {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "let nodeThatClaimedTheSwipe = null;\n" ], "file_path": "src/SwipeableDrawer/SwipeableDrawer.js", "type": "replace", "edit_start_line_idx": 18 }
import React from 'react'; import withRoot from 'docs/src/modules/components/withRoot'; import MarkdownDocs from 'docs/src/modules/components/MarkdownDocs'; import markdown from './bottom-navigation.md'; function Page() { return <MarkdownDocs markdown={markdown} />; } export default withRoot(Page);
pages/api/bottom-navigation.js
0
https://github.com/mui/material-ui/commit/5d126e65e30f7541e34b0c12bd68fa0c31ae71fa
[ 0.00017615022079553455, 0.00017353447037748992, 0.00017091873451136053, 0.00017353447037748992, 0.0000026157431420870125 ]
{ "id": 0, "code_window": [ "// We can only have one node at the time claiming ownership for handling the swipe.\n", "// Otherwise, the UX would be confusing.\n", "// That's why we use a singleton here.\n", "let nodeHowClaimedTheSwipe = null;\n", "\n", "// Exported for test purposes.\n", "export function reset() {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "let nodeThatClaimedTheSwipe = null;\n" ], "file_path": "src/SwipeableDrawer/SwipeableDrawer.js", "type": "replace", "edit_start_line_idx": 18 }
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; const SvgIconCustom = global.__MUI_SvgIcon__ || SvgIcon; let AccountBalance = props => <SvgIconCustom {...props}> <path d="M4 10v7h3v-7H4zm6 0v7h3v-7h-3zM2 22h19v-3H2v3zm14-12v7h3v-7h-3zm-4.5-9L2 6v2h19V6l-9.5-5z" /> </SvgIconCustom>; AccountBalance = pure(AccountBalance); AccountBalance.muiName = 'SvgIcon'; export default AccountBalance;
packages/material-ui-icons/src/AccountBalance.js
0
https://github.com/mui/material-ui/commit/5d126e65e30f7541e34b0c12bd68fa0c31ae71fa
[ 0.00017361430218443274, 0.0001726025657262653, 0.0001715908438200131, 0.0001726025657262653, 0.0000010117291822098196 ]
{ "id": 1, "code_window": [ "\n", "// Exported for test purposes.\n", "export function reset() {\n", " nodeHowClaimedTheSwipe = null;\n", "}\n", "\n", "class SwipeableDrawer extends React.Component {\n", " state = {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " nodeThatClaimedTheSwipe = null;\n" ], "file_path": "src/SwipeableDrawer/SwipeableDrawer.js", "type": "replace", "edit_start_line_idx": 22 }
/* eslint-disable consistent-this */ // @inheritedComponent Drawer import React from 'react'; import PropTypes from 'prop-types'; import ReactDOM from 'react-dom'; import Drawer, { getAnchor, isHorizontal } from '../Drawer/Drawer'; import { duration } from '../styles/transitions'; import withTheme from '../styles/withTheme'; import { getTransitionProps } from '../transitions/utils'; // This value is closed to what browsers are using internally to // trigger a native scroll. const UNCERTAINTY_THRESHOLD = 3; // px // We can only have one node at the time claiming ownership for handling the swipe. // Otherwise, the UX would be confusing. // That's why we use a singleton here. let nodeHowClaimedTheSwipe = null; // Exported for test purposes. export function reset() { nodeHowClaimedTheSwipe = null; } class SwipeableDrawer extends React.Component { state = { maybeSwiping: false, }; componentDidMount() { if (this.props.variant === 'temporary') { this.listenTouchStart(); } } componentDidUpdate(prevProps) { const variant = this.props.variant; const prevVariant = prevProps.variant; if (variant === 'temporary' && prevVariant !== 'temporary') { this.listenTouchStart(); } else if (variant !== 'temporary' && prevVariant === 'temporary') { this.removeTouchStart(); } } componentWillUnmount() { this.removeTouchStart(); this.removeBodyTouchListeners(); } getMaxTranslate() { return isHorizontal(this.props) ? this.paper.clientWidth : this.paper.clientHeight; } getTranslate(current) { const start = isHorizontal(this.props) ? this.startX : this.startY; return Math.min( Math.max( this.isSwiping === 'closing' ? start - current : this.getMaxTranslate() + start - current, 0, ), this.getMaxTranslate(), ); } setPosition(translate, options = {}) { const { mode = null, changeTransition = true } = options; const anchor = getAnchor(this.props); const rtlTranslateMultiplier = ['right', 'bottom'].indexOf(anchor) !== -1 ? 1 : -1; const transform = isHorizontal(this.props) ? `translate(${rtlTranslateMultiplier * translate}px, 0)` : `translate(0, ${rtlTranslateMultiplier * translate}px)`; const drawerStyle = this.paper.style; drawerStyle.webkitTransform = transform; drawerStyle.transform = transform; let transition = ''; if (mode) { transition = this.props.theme.transitions.create( 'all', getTransitionProps( { timeout: this.props.transitionDuration, }, { mode, }, ), ); } if (changeTransition) { drawerStyle.webkitTransition = transition; drawerStyle.transition = transition; } if (!this.props.disableBackdropTransition) { const backdropStyle = this.backdrop.style; backdropStyle.opacity = 1 - translate / this.getMaxTranslate(); if (changeTransition) { backdropStyle.webkitTransition = transition; backdropStyle.transition = transition; } } } handleBodyTouchStart = event => { // We are not supposed to hanlde this touch move. if (nodeHowClaimedTheSwipe !== null && nodeHowClaimedTheSwipe !== this) { return; } const { disableDiscovery, open, swipeAreaWidth } = this.props; const anchor = getAnchor(this.props); const currentX = anchor === 'right' ? document.body.offsetWidth - event.touches[0].pageX : event.touches[0].pageX; const currentY = anchor === 'bottom' ? window.innerHeight - event.touches[0].clientY : event.touches[0].clientY; if (!open) { if (isHorizontal(this.props)) { if (currentX > swipeAreaWidth) { return; } } else if (currentY > swipeAreaWidth) { return; } } nodeHowClaimedTheSwipe = this; this.startX = currentX; this.startY = currentY; this.setState({ maybeSwiping: true }); if (!open) { this.setPosition(this.getMaxTranslate() - (disableDiscovery ? 0 : swipeAreaWidth), { changeTransition: false, }); } document.body.addEventListener('touchmove', this.handleBodyTouchMove, { passive: false }); document.body.addEventListener('touchend', this.handleBodyTouchEnd); // https://plus.google.com/+PaulIrish/posts/KTwfn1Y2238 document.body.addEventListener('touchcancel', this.handleBodyTouchEnd); }; handleBodyTouchMove = event => { const anchor = getAnchor(this.props); const horizontalSwipe = isHorizontal(this.props); const currentX = anchor === 'right' ? document.body.offsetWidth - event.touches[0].pageX : event.touches[0].pageX; const currentY = anchor === 'bottom' ? window.innerHeight - event.touches[0].clientY : event.touches[0].clientY; // We don't know yet. if (this.isSwiping === undefined) { const dx = Math.abs(currentX - this.startX); const dy = Math.abs(currentY - this.startY); // If the user has moved his thumb some pixels in either direction, // we can safely make an assumption about whether he was intending // to swipe or scroll. const isSwiping = horizontalSwipe ? dx > UNCERTAINTY_THRESHOLD && dy <= UNCERTAINTY_THRESHOLD : dy > UNCERTAINTY_THRESHOLD && dx <= UNCERTAINTY_THRESHOLD; // We are likely to be swiping, let's prevent the scroll event on iOS. if (dx > dy) { event.preventDefault(); } if (isSwiping) { this.isSwiping = this.props.open ? 'closing' : 'opening'; // Shift the starting point. this.startX = currentX; this.startY = currentY; // Compensate for the part of the drawer displayed on touch start. if (!this.props.disableDiscovery && !this.props.open) { if (horizontalSwipe) { this.startX -= this.props.swipeAreaWidth; } else { this.startY -= this.props.swipeAreaWidth; } } } else if ( horizontalSwipe ? dx <= UNCERTAINTY_THRESHOLD && dy > UNCERTAINTY_THRESHOLD : dy <= UNCERTAINTY_THRESHOLD && dx > UNCERTAINTY_THRESHOLD ) { this.handleBodyTouchEnd(event); } } if (this.isSwiping === undefined) { return; } // We are swiping, let's prevent the scroll event on iOS. event.preventDefault(); this.setPosition(this.getTranslate(horizontalSwipe ? currentX : currentY)); }; handleBodyTouchEnd = event => { nodeHowClaimedTheSwipe = null; this.removeBodyTouchListeners(); this.setState({ maybeSwiping: false }); if (this.isSwiping === undefined) { return; } const anchor = getAnchor(this.props); let current; if (isHorizontal(this.props)) { current = anchor === 'right' ? document.body.offsetWidth - event.changedTouches[0].pageX : event.changedTouches[0].pageX; } else { current = anchor === 'bottom' ? window.innerHeight - event.changedTouches[0].clientY : event.changedTouches[0].clientY; } const translateRatio = this.getTranslate(current) / this.getMaxTranslate(); // We have to open or close after setting swiping to null, // because only then CSS transition is enabled. if (translateRatio > 0.5) { if (this.isSwiping === 'opening') { // Reset the position, the swipe was aborted. this.setPosition(this.getMaxTranslate(), { mode: 'enter', }); } else { this.props.onClose(); } } else if (this.isSwiping === 'opening') { this.props.onOpen(); } else { // Reset the position, the swipe was aborted. this.setPosition(0, { mode: 'exit', }); } this.isSwiping = undefined; }; backdrop = null; paper = null; isSwiping = undefined; startX = null; startY = null; listenTouchStart() { document.body.addEventListener('touchstart', this.handleBodyTouchStart); } removeTouchStart() { document.body.removeEventListener('touchstart', this.handleBodyTouchStart); } removeBodyTouchListeners() { document.body.removeEventListener('touchmove', this.handleBodyTouchMove, { passive: false }); document.body.removeEventListener('touchend', this.handleBodyTouchEnd); document.body.removeEventListener('touchcancel', this.handleBodyTouchEnd); } handleBackdropRef = node => { this.backdrop = node ? ReactDOM.findDOMNode(node) : null; }; handlePaperRef = node => { this.paper = node ? ReactDOM.findDOMNode(node) : null; }; render() { const { disableBackdropTransition, disableDiscovery, ModalProps: { BackdropProps, ...ModalPropsProp } = {}, onOpen, open, PaperProps, swipeAreaWidth, variant, ...other } = this.props; const { maybeSwiping } = this.state; return ( <Drawer open={variant === 'temporary' && maybeSwiping ? true : open} variant={variant} ModalProps={{ BackdropProps: { ...BackdropProps, ref: this.handleBackdropRef, }, ...ModalPropsProp, }} PaperProps={{ ...PaperProps, ref: this.handlePaperRef, }} {...other} /> ); } } SwipeableDrawer.propTypes = { /** * @ignore */ anchor: PropTypes.oneOf(['left', 'top', 'right', 'bottom']), /** * Disable the backdrop transition. * This can improve the FPS on low-end devices. */ disableBackdropTransition: PropTypes.bool, /** * If `true`, touching the screen near the edge of the drawer will not slide in the drawer a bit * to promote accidental discovery of the swipe gesture. */ disableDiscovery: PropTypes.bool, /** * @ignore */ ModalProps: PropTypes.object, /** * Callback fired when the component requests to be closed. * * @param {object} event The event source of the callback */ onClose: PropTypes.func.isRequired, /** * Callback fired when the component requests to be opened. * * @param {object} event The event source of the callback */ onOpen: PropTypes.func.isRequired, /** * If `true`, the drawer is open. */ open: PropTypes.bool.isRequired, /** * @ignore */ PaperProps: PropTypes.object, /** * The width of the left most (or right most) area in pixels where the * drawer can be swiped open from. */ swipeAreaWidth: PropTypes.number, /** * @ignore */ theme: PropTypes.object.isRequired, /** * The duration for the transition, in milliseconds. * You may specify a single timeout for all transitions, or individually with an object. */ transitionDuration: PropTypes.oneOfType([ PropTypes.number, PropTypes.shape({ enter: PropTypes.number, exit: PropTypes.number }), ]), /** * @ignore */ variant: PropTypes.oneOf(['permanent', 'persistent', 'temporary']), }; SwipeableDrawer.defaultProps = { anchor: 'left', disableBackdropTransition: false, disableDiscovery: false, swipeAreaWidth: 20, transitionDuration: { enter: duration.enteringScreen, exit: duration.leavingScreen }, variant: 'temporary', // Mobile first. }; export default withTheme()(SwipeableDrawer);
src/SwipeableDrawer/SwipeableDrawer.js
1
https://github.com/mui/material-ui/commit/5d126e65e30f7541e34b0c12bd68fa0c31ae71fa
[ 0.9990079998970032, 0.12385293841362, 0.0001668058685027063, 0.0001768550428096205, 0.3259744346141815 ]
{ "id": 1, "code_window": [ "\n", "// Exported for test purposes.\n", "export function reset() {\n", " nodeHowClaimedTheSwipe = null;\n", "}\n", "\n", "class SwipeableDrawer extends React.Component {\n", " state = {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " nodeThatClaimedTheSwipe = null;\n" ], "file_path": "src/SwipeableDrawer/SwipeableDrawer.js", "type": "replace", "edit_start_line_idx": 22 }
# Default Theme Here's what the theme object looks like with the default values: {{"demo": "pages/customization/default-theme/DefaultTheme.js", "hideEditButton": true}} The theme normalizes implementation by providing default values for palette, dark and light types, typography, breakpoints, shadows, transitions, etc. Tip: you can play with the theme object in your console too. **We expose a global `theme` variable on all the pages**. Please take note that the documentation site is using a custom theme. As a result, the demos you see here might disagree with the values above. If you want to learn more about how the theme is assembled, take a look at [`material-ui/style/createMuiTheme.js`](https://github.com/mui-org/material-ui/blob/v1-beta/src/styles/createMuiTheme.js), and the related imports which `createMuiTheme` uses.
docs/src/pages/customization/default-theme/default-theme.md
0
https://github.com/mui/material-ui/commit/5d126e65e30f7541e34b0c12bd68fa0c31ae71fa
[ 0.00017228811339009553, 0.00017216753622051328, 0.00017204695905093104, 0.00017216753622051328, 1.2057716958224773e-7 ]
{ "id": 1, "code_window": [ "\n", "// Exported for test purposes.\n", "export function reset() {\n", " nodeHowClaimedTheSwipe = null;\n", "}\n", "\n", "class SwipeableDrawer extends React.Component {\n", " state = {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " nodeThatClaimedTheSwipe = null;\n" ], "file_path": "src/SwipeableDrawer/SwipeableDrawer.js", "type": "replace", "edit_start_line_idx": 22 }
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; const SvgIconCustom = global.__MUI_SvgIcon__ || SvgIcon; let Queue = props => <SvgIconCustom {...props}> <path d="M4 6H2v14c0 1.1.9 2 2 2h14v-2H4V6zm16-4H8c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-1 9h-4v4h-2v-4H9V9h4V5h2v4h4v2z" /> </SvgIconCustom>; Queue = pure(Queue); Queue.muiName = 'SvgIcon'; export default Queue;
packages/material-ui-icons/src/Queue.js
0
https://github.com/mui/material-ui/commit/5d126e65e30f7541e34b0c12bd68fa0c31ae71fa
[ 0.00017087504966184497, 0.00017002940876409411, 0.0001691837824182585, 0.00017002940876409411, 8.456336217932403e-7 ]
{ "id": 1, "code_window": [ "\n", "// Exported for test purposes.\n", "export function reset() {\n", " nodeHowClaimedTheSwipe = null;\n", "}\n", "\n", "class SwipeableDrawer extends React.Component {\n", " state = {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " nodeThatClaimedTheSwipe = null;\n" ], "file_path": "src/SwipeableDrawer/SwipeableDrawer.js", "type": "replace", "edit_start_line_idx": 22 }
// @inheritedComponent ButtonBase import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import ButtonBase from '../ButtonBase'; import IconButton from '../IconButton'; import withStyles from '../styles/withStyles'; export const styles = theme => { const transition = { duration: theme.transitions.duration.shortest, }; return { root: { display: 'flex', minHeight: theme.spacing.unit * 6, transition: theme.transitions.create(['min-height', 'background-color'], transition), padding: `0 ${theme.spacing.unit * 3}px 0 ${theme.spacing.unit * 3}px`, '&:hover:not($disabled)': { cursor: 'pointer', }, }, expanded: { minHeight: 64, }, focused: { backgroundColor: theme.palette.grey[300], }, disabled: { opacity: 0.38, }, content: { display: 'flex', flexGrow: 1, transition: theme.transitions.create(['margin'], transition), margin: '12px 0', '& > :last-child': { paddingRight: theme.spacing.unit * 4, }, }, contentExpanded: { margin: '20px 0', }, expandIcon: { position: 'absolute', top: '50%', right: theme.spacing.unit, transform: 'translateY(-50%) rotate(0deg)', transition: theme.transitions.create('transform', transition), }, expandIconExpanded: { transform: 'translateY(-50%) rotate(180deg)', }, }; }; class ExpansionPanelSummary extends React.Component { state = { focused: false, }; handleFocus = () => { this.setState({ focused: true, }); }; handleBlur = () => { this.setState({ focused: false, }); }; handleChange = event => { const { onChange, onClick } = this.props; if (onChange) { onChange(event); } if (onClick) { onClick(event); } }; render() { const { children, classes, className, disabled, expanded, expandIcon, onChange, ...other } = this.props; const { focused } = this.state; return ( <ButtonBase focusRipple={false} disableRipple disabled={disabled} component="div" aria-expanded={expanded} className={classNames( classes.root, { [classes.disabled]: disabled, [classes.expanded]: expanded, [classes.focused]: focused, }, className, )} {...other} onKeyboardFocus={this.handleFocus} onBlur={this.handleBlur} onClick={this.handleChange} > <div className={classNames(classes.content, { [classes.contentExpanded]: expanded })}> {children} </div> {expandIcon && ( <IconButton disabled={disabled} className={classNames(classes.expandIcon, { [classes.expandIconExpanded]: expanded, })} component="div" tabIndex={-1} aria-hidden="true" > {expandIcon} </IconButton> )} </ButtonBase> ); } } ExpansionPanelSummary.propTypes = { /** * The content of the expansion panel summary. */ children: PropTypes.node, /** * Useful to extend the style applied to components. */ classes: PropTypes.object.isRequired, /** * @ignore */ className: PropTypes.string, /** * @ignore * If `true`, the summary will be displayed in a disabled state. */ disabled: PropTypes.bool, /** * @ignore * If `true`, expands the summary, otherwise collapse it. */ expanded: PropTypes.bool, /** * The icon to display as the expand indicator. */ expandIcon: PropTypes.node, /** * @ignore */ onChange: PropTypes.func, /** * @ignore */ onClick: PropTypes.func, }; ExpansionPanelSummary.defaultProps = { disabled: false, }; ExpansionPanelSummary.muiName = 'ExpansionPanelSummary'; export default withStyles(styles, { name: 'MuiExpansionPanelSummary' })(ExpansionPanelSummary);
src/ExpansionPanel/ExpansionPanelSummary.js
0
https://github.com/mui/material-ui/commit/5d126e65e30f7541e34b0c12bd68fa0c31ae71fa
[ 0.0002593992685433477, 0.0001745932240737602, 0.00016502295329701155, 0.00017012121679726988, 0.000020103594579268247 ]
{ "id": 2, "code_window": [ " componentWillUnmount() {\n", " this.removeTouchStart();\n", " this.removeBodyTouchListeners();\n", " }\n", "\n", " getMaxTranslate() {\n", " return isHorizontal(this.props) ? this.paper.clientWidth : this.paper.clientHeight;\n", " }\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " if (nodeThatClaimedTheSwipe === this) {\n", " nodeThatClaimedTheSwipe = null;\n", " }\n" ], "file_path": "src/SwipeableDrawer/SwipeableDrawer.js", "type": "add", "edit_start_line_idx": 50 }
/* eslint-disable consistent-this */ // @inheritedComponent Drawer import React from 'react'; import PropTypes from 'prop-types'; import ReactDOM from 'react-dom'; import Drawer, { getAnchor, isHorizontal } from '../Drawer/Drawer'; import { duration } from '../styles/transitions'; import withTheme from '../styles/withTheme'; import { getTransitionProps } from '../transitions/utils'; // This value is closed to what browsers are using internally to // trigger a native scroll. const UNCERTAINTY_THRESHOLD = 3; // px // We can only have one node at the time claiming ownership for handling the swipe. // Otherwise, the UX would be confusing. // That's why we use a singleton here. let nodeHowClaimedTheSwipe = null; // Exported for test purposes. export function reset() { nodeHowClaimedTheSwipe = null; } class SwipeableDrawer extends React.Component { state = { maybeSwiping: false, }; componentDidMount() { if (this.props.variant === 'temporary') { this.listenTouchStart(); } } componentDidUpdate(prevProps) { const variant = this.props.variant; const prevVariant = prevProps.variant; if (variant === 'temporary' && prevVariant !== 'temporary') { this.listenTouchStart(); } else if (variant !== 'temporary' && prevVariant === 'temporary') { this.removeTouchStart(); } } componentWillUnmount() { this.removeTouchStart(); this.removeBodyTouchListeners(); } getMaxTranslate() { return isHorizontal(this.props) ? this.paper.clientWidth : this.paper.clientHeight; } getTranslate(current) { const start = isHorizontal(this.props) ? this.startX : this.startY; return Math.min( Math.max( this.isSwiping === 'closing' ? start - current : this.getMaxTranslate() + start - current, 0, ), this.getMaxTranslate(), ); } setPosition(translate, options = {}) { const { mode = null, changeTransition = true } = options; const anchor = getAnchor(this.props); const rtlTranslateMultiplier = ['right', 'bottom'].indexOf(anchor) !== -1 ? 1 : -1; const transform = isHorizontal(this.props) ? `translate(${rtlTranslateMultiplier * translate}px, 0)` : `translate(0, ${rtlTranslateMultiplier * translate}px)`; const drawerStyle = this.paper.style; drawerStyle.webkitTransform = transform; drawerStyle.transform = transform; let transition = ''; if (mode) { transition = this.props.theme.transitions.create( 'all', getTransitionProps( { timeout: this.props.transitionDuration, }, { mode, }, ), ); } if (changeTransition) { drawerStyle.webkitTransition = transition; drawerStyle.transition = transition; } if (!this.props.disableBackdropTransition) { const backdropStyle = this.backdrop.style; backdropStyle.opacity = 1 - translate / this.getMaxTranslate(); if (changeTransition) { backdropStyle.webkitTransition = transition; backdropStyle.transition = transition; } } } handleBodyTouchStart = event => { // We are not supposed to hanlde this touch move. if (nodeHowClaimedTheSwipe !== null && nodeHowClaimedTheSwipe !== this) { return; } const { disableDiscovery, open, swipeAreaWidth } = this.props; const anchor = getAnchor(this.props); const currentX = anchor === 'right' ? document.body.offsetWidth - event.touches[0].pageX : event.touches[0].pageX; const currentY = anchor === 'bottom' ? window.innerHeight - event.touches[0].clientY : event.touches[0].clientY; if (!open) { if (isHorizontal(this.props)) { if (currentX > swipeAreaWidth) { return; } } else if (currentY > swipeAreaWidth) { return; } } nodeHowClaimedTheSwipe = this; this.startX = currentX; this.startY = currentY; this.setState({ maybeSwiping: true }); if (!open) { this.setPosition(this.getMaxTranslate() - (disableDiscovery ? 0 : swipeAreaWidth), { changeTransition: false, }); } document.body.addEventListener('touchmove', this.handleBodyTouchMove, { passive: false }); document.body.addEventListener('touchend', this.handleBodyTouchEnd); // https://plus.google.com/+PaulIrish/posts/KTwfn1Y2238 document.body.addEventListener('touchcancel', this.handleBodyTouchEnd); }; handleBodyTouchMove = event => { const anchor = getAnchor(this.props); const horizontalSwipe = isHorizontal(this.props); const currentX = anchor === 'right' ? document.body.offsetWidth - event.touches[0].pageX : event.touches[0].pageX; const currentY = anchor === 'bottom' ? window.innerHeight - event.touches[0].clientY : event.touches[0].clientY; // We don't know yet. if (this.isSwiping === undefined) { const dx = Math.abs(currentX - this.startX); const dy = Math.abs(currentY - this.startY); // If the user has moved his thumb some pixels in either direction, // we can safely make an assumption about whether he was intending // to swipe or scroll. const isSwiping = horizontalSwipe ? dx > UNCERTAINTY_THRESHOLD && dy <= UNCERTAINTY_THRESHOLD : dy > UNCERTAINTY_THRESHOLD && dx <= UNCERTAINTY_THRESHOLD; // We are likely to be swiping, let's prevent the scroll event on iOS. if (dx > dy) { event.preventDefault(); } if (isSwiping) { this.isSwiping = this.props.open ? 'closing' : 'opening'; // Shift the starting point. this.startX = currentX; this.startY = currentY; // Compensate for the part of the drawer displayed on touch start. if (!this.props.disableDiscovery && !this.props.open) { if (horizontalSwipe) { this.startX -= this.props.swipeAreaWidth; } else { this.startY -= this.props.swipeAreaWidth; } } } else if ( horizontalSwipe ? dx <= UNCERTAINTY_THRESHOLD && dy > UNCERTAINTY_THRESHOLD : dy <= UNCERTAINTY_THRESHOLD && dx > UNCERTAINTY_THRESHOLD ) { this.handleBodyTouchEnd(event); } } if (this.isSwiping === undefined) { return; } // We are swiping, let's prevent the scroll event on iOS. event.preventDefault(); this.setPosition(this.getTranslate(horizontalSwipe ? currentX : currentY)); }; handleBodyTouchEnd = event => { nodeHowClaimedTheSwipe = null; this.removeBodyTouchListeners(); this.setState({ maybeSwiping: false }); if (this.isSwiping === undefined) { return; } const anchor = getAnchor(this.props); let current; if (isHorizontal(this.props)) { current = anchor === 'right' ? document.body.offsetWidth - event.changedTouches[0].pageX : event.changedTouches[0].pageX; } else { current = anchor === 'bottom' ? window.innerHeight - event.changedTouches[0].clientY : event.changedTouches[0].clientY; } const translateRatio = this.getTranslate(current) / this.getMaxTranslate(); // We have to open or close after setting swiping to null, // because only then CSS transition is enabled. if (translateRatio > 0.5) { if (this.isSwiping === 'opening') { // Reset the position, the swipe was aborted. this.setPosition(this.getMaxTranslate(), { mode: 'enter', }); } else { this.props.onClose(); } } else if (this.isSwiping === 'opening') { this.props.onOpen(); } else { // Reset the position, the swipe was aborted. this.setPosition(0, { mode: 'exit', }); } this.isSwiping = undefined; }; backdrop = null; paper = null; isSwiping = undefined; startX = null; startY = null; listenTouchStart() { document.body.addEventListener('touchstart', this.handleBodyTouchStart); } removeTouchStart() { document.body.removeEventListener('touchstart', this.handleBodyTouchStart); } removeBodyTouchListeners() { document.body.removeEventListener('touchmove', this.handleBodyTouchMove, { passive: false }); document.body.removeEventListener('touchend', this.handleBodyTouchEnd); document.body.removeEventListener('touchcancel', this.handleBodyTouchEnd); } handleBackdropRef = node => { this.backdrop = node ? ReactDOM.findDOMNode(node) : null; }; handlePaperRef = node => { this.paper = node ? ReactDOM.findDOMNode(node) : null; }; render() { const { disableBackdropTransition, disableDiscovery, ModalProps: { BackdropProps, ...ModalPropsProp } = {}, onOpen, open, PaperProps, swipeAreaWidth, variant, ...other } = this.props; const { maybeSwiping } = this.state; return ( <Drawer open={variant === 'temporary' && maybeSwiping ? true : open} variant={variant} ModalProps={{ BackdropProps: { ...BackdropProps, ref: this.handleBackdropRef, }, ...ModalPropsProp, }} PaperProps={{ ...PaperProps, ref: this.handlePaperRef, }} {...other} /> ); } } SwipeableDrawer.propTypes = { /** * @ignore */ anchor: PropTypes.oneOf(['left', 'top', 'right', 'bottom']), /** * Disable the backdrop transition. * This can improve the FPS on low-end devices. */ disableBackdropTransition: PropTypes.bool, /** * If `true`, touching the screen near the edge of the drawer will not slide in the drawer a bit * to promote accidental discovery of the swipe gesture. */ disableDiscovery: PropTypes.bool, /** * @ignore */ ModalProps: PropTypes.object, /** * Callback fired when the component requests to be closed. * * @param {object} event The event source of the callback */ onClose: PropTypes.func.isRequired, /** * Callback fired when the component requests to be opened. * * @param {object} event The event source of the callback */ onOpen: PropTypes.func.isRequired, /** * If `true`, the drawer is open. */ open: PropTypes.bool.isRequired, /** * @ignore */ PaperProps: PropTypes.object, /** * The width of the left most (or right most) area in pixels where the * drawer can be swiped open from. */ swipeAreaWidth: PropTypes.number, /** * @ignore */ theme: PropTypes.object.isRequired, /** * The duration for the transition, in milliseconds. * You may specify a single timeout for all transitions, or individually with an object. */ transitionDuration: PropTypes.oneOfType([ PropTypes.number, PropTypes.shape({ enter: PropTypes.number, exit: PropTypes.number }), ]), /** * @ignore */ variant: PropTypes.oneOf(['permanent', 'persistent', 'temporary']), }; SwipeableDrawer.defaultProps = { anchor: 'left', disableBackdropTransition: false, disableDiscovery: false, swipeAreaWidth: 20, transitionDuration: { enter: duration.enteringScreen, exit: duration.leavingScreen }, variant: 'temporary', // Mobile first. }; export default withTheme()(SwipeableDrawer);
src/SwipeableDrawer/SwipeableDrawer.js
1
https://github.com/mui/material-ui/commit/5d126e65e30f7541e34b0c12bd68fa0c31ae71fa
[ 0.9991244673728943, 0.14537331461906433, 0.00016546822735108435, 0.00039043204742483795, 0.3379797041416168 ]
{ "id": 2, "code_window": [ " componentWillUnmount() {\n", " this.removeTouchStart();\n", " this.removeBodyTouchListeners();\n", " }\n", "\n", " getMaxTranslate() {\n", " return isHorizontal(this.props) ? this.paper.clientWidth : this.paper.clientHeight;\n", " }\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " if (nodeThatClaimedTheSwipe === this) {\n", " nodeThatClaimedTheSwipe = null;\n", " }\n" ], "file_path": "src/SwipeableDrawer/SwipeableDrawer.js", "type": "add", "edit_start_line_idx": 50 }
import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import { withStyles } from 'material-ui/styles'; const styles = theme => ({ root: theme.mixins.gutters({ paddingTop: 80, flex: '1 1 100%', maxWidth: '100%', margin: '0 auto', }), [theme.breakpoints.up(900 + theme.spacing.unit * 6)]: { root: { maxWidth: 900, }, }, }); function AppContent(props) { const { className, classes, children } = props; return <div className={classNames(classes.root, className)}>{children}</div>; } AppContent.propTypes = { children: PropTypes.node.isRequired, classes: PropTypes.object.isRequired, className: PropTypes.string, }; export default withStyles(styles)(AppContent);
docs/src/modules/components/AppContent.js
0
https://github.com/mui/material-ui/commit/5d126e65e30f7541e34b0c12bd68fa0c31ae71fa
[ 0.000309530645608902, 0.00022308609914034605, 0.00017027034482453018, 0.00020627171033993363, 0.00005619755029329099 ]
{ "id": 2, "code_window": [ " componentWillUnmount() {\n", " this.removeTouchStart();\n", " this.removeBodyTouchListeners();\n", " }\n", "\n", " getMaxTranslate() {\n", " return isHorizontal(this.props) ? this.paper.clientWidth : this.paper.clientHeight;\n", " }\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " if (nodeThatClaimedTheSwipe === this) {\n", " nodeThatClaimedTheSwipe = null;\n", " }\n" ], "file_path": "src/SwipeableDrawer/SwipeableDrawer.js", "type": "add", "edit_start_line_idx": 50 }
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; const SvgIconCustom = global.__MUI_SvgIcon__ || SvgIcon; let Loupe = props => <SvgIconCustom {...props}> <path d="M13 7h-2v4H7v2h4v4h2v-4h4v-2h-4V7zm-1-5C6.49 2 2 6.49 2 12s4.49 10 10 10h8c1.1 0 2-.9 2-2v-8c0-5.51-4.49-10-10-10zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8z" /> </SvgIconCustom>; Loupe = pure(Loupe); Loupe.muiName = 'SvgIcon'; export default Loupe;
packages/material-ui-icons/src/Loupe.js
0
https://github.com/mui/material-ui/commit/5d126e65e30f7541e34b0c12bd68fa0c31ae71fa
[ 0.00017839917563833296, 0.00017292913980782032, 0.00016745910397730768, 0.00017292913980782032, 0.000005470035830512643 ]
{ "id": 2, "code_window": [ " componentWillUnmount() {\n", " this.removeTouchStart();\n", " this.removeBodyTouchListeners();\n", " }\n", "\n", " getMaxTranslate() {\n", " return isHorizontal(this.props) ? this.paper.clientWidth : this.paper.clientHeight;\n", " }\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " if (nodeThatClaimedTheSwipe === this) {\n", " nodeThatClaimedTheSwipe = null;\n", " }\n" ], "file_path": "src/SwipeableDrawer/SwipeableDrawer.js", "type": "add", "edit_start_line_idx": 50 }
import * as React from 'react'; import { IPopperProps } from 'react-popper'; import { StandardProps } from '..'; export interface TooltipProps extends StandardProps<React.HTMLAttributes<HTMLDivElement>, TooltipClassKey, 'title'> { children: React.ReactElement<any>; disableFocusListener?: boolean; disableHoverListener?: boolean; disableTouchListener?: boolean; enterDelay?: number; enterTouchDelay?: number; id?: string; leaveDelay?: number; leaveTouchDelay?: number; onClose?: (event: React.ChangeEvent<{}>) => void; onOpen?: (event: React.ChangeEvent<{}>) => void; open?: boolean; placement?: | 'bottom-end' | 'bottom-start' | 'bottom' | 'left-end' | 'left-start' | 'left' | 'right-end' | 'right-start' | 'right' | 'top-end' | 'top-start' | 'top'; PopperProps?: Partial<PopperProps>; title: React.ReactNode; } export type TooltipClassKey = | 'root' | 'popper' | 'popperClose' | 'tooltip' | 'tooltipPlacementLeft' | 'tooltipPlacementRight' | 'tooltipPlacementTop' | 'tooltipPlacementBottom' | 'tooltipOpen'; interface PopperProps extends IPopperProps { PopperClassName: string; } declare const Tooltip: React.ComponentType<TooltipProps>; export default Tooltip;
src/Tooltip/Tooltip.d.ts
0
https://github.com/mui/material-ui/commit/5d126e65e30f7541e34b0c12bd68fa0c31ae71fa
[ 0.00022100743080955, 0.0001786816428648308, 0.00016518762276973575, 0.00017146021127700806, 0.00001936107946676202 ]
{ "id": 3, "code_window": [ " }\n", "\n", " handleBodyTouchStart = event => {\n", " // We are not supposed to hanlde this touch move.\n", " if (nodeHowClaimedTheSwipe !== null && nodeHowClaimedTheSwipe !== this) {\n", " return;\n", " }\n", "\n", " const { disableDiscovery, open, swipeAreaWidth } = this.props;\n", " const anchor = getAnchor(this.props);\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " if (nodeThatClaimedTheSwipe !== null && nodeThatClaimedTheSwipe !== this) {\n" ], "file_path": "src/SwipeableDrawer/SwipeableDrawer.js", "type": "replace", "edit_start_line_idx": 114 }
/* eslint-disable consistent-this */ // @inheritedComponent Drawer import React from 'react'; import PropTypes from 'prop-types'; import ReactDOM from 'react-dom'; import Drawer, { getAnchor, isHorizontal } from '../Drawer/Drawer'; import { duration } from '../styles/transitions'; import withTheme from '../styles/withTheme'; import { getTransitionProps } from '../transitions/utils'; // This value is closed to what browsers are using internally to // trigger a native scroll. const UNCERTAINTY_THRESHOLD = 3; // px // We can only have one node at the time claiming ownership for handling the swipe. // Otherwise, the UX would be confusing. // That's why we use a singleton here. let nodeHowClaimedTheSwipe = null; // Exported for test purposes. export function reset() { nodeHowClaimedTheSwipe = null; } class SwipeableDrawer extends React.Component { state = { maybeSwiping: false, }; componentDidMount() { if (this.props.variant === 'temporary') { this.listenTouchStart(); } } componentDidUpdate(prevProps) { const variant = this.props.variant; const prevVariant = prevProps.variant; if (variant === 'temporary' && prevVariant !== 'temporary') { this.listenTouchStart(); } else if (variant !== 'temporary' && prevVariant === 'temporary') { this.removeTouchStart(); } } componentWillUnmount() { this.removeTouchStart(); this.removeBodyTouchListeners(); } getMaxTranslate() { return isHorizontal(this.props) ? this.paper.clientWidth : this.paper.clientHeight; } getTranslate(current) { const start = isHorizontal(this.props) ? this.startX : this.startY; return Math.min( Math.max( this.isSwiping === 'closing' ? start - current : this.getMaxTranslate() + start - current, 0, ), this.getMaxTranslate(), ); } setPosition(translate, options = {}) { const { mode = null, changeTransition = true } = options; const anchor = getAnchor(this.props); const rtlTranslateMultiplier = ['right', 'bottom'].indexOf(anchor) !== -1 ? 1 : -1; const transform = isHorizontal(this.props) ? `translate(${rtlTranslateMultiplier * translate}px, 0)` : `translate(0, ${rtlTranslateMultiplier * translate}px)`; const drawerStyle = this.paper.style; drawerStyle.webkitTransform = transform; drawerStyle.transform = transform; let transition = ''; if (mode) { transition = this.props.theme.transitions.create( 'all', getTransitionProps( { timeout: this.props.transitionDuration, }, { mode, }, ), ); } if (changeTransition) { drawerStyle.webkitTransition = transition; drawerStyle.transition = transition; } if (!this.props.disableBackdropTransition) { const backdropStyle = this.backdrop.style; backdropStyle.opacity = 1 - translate / this.getMaxTranslate(); if (changeTransition) { backdropStyle.webkitTransition = transition; backdropStyle.transition = transition; } } } handleBodyTouchStart = event => { // We are not supposed to hanlde this touch move. if (nodeHowClaimedTheSwipe !== null && nodeHowClaimedTheSwipe !== this) { return; } const { disableDiscovery, open, swipeAreaWidth } = this.props; const anchor = getAnchor(this.props); const currentX = anchor === 'right' ? document.body.offsetWidth - event.touches[0].pageX : event.touches[0].pageX; const currentY = anchor === 'bottom' ? window.innerHeight - event.touches[0].clientY : event.touches[0].clientY; if (!open) { if (isHorizontal(this.props)) { if (currentX > swipeAreaWidth) { return; } } else if (currentY > swipeAreaWidth) { return; } } nodeHowClaimedTheSwipe = this; this.startX = currentX; this.startY = currentY; this.setState({ maybeSwiping: true }); if (!open) { this.setPosition(this.getMaxTranslate() - (disableDiscovery ? 0 : swipeAreaWidth), { changeTransition: false, }); } document.body.addEventListener('touchmove', this.handleBodyTouchMove, { passive: false }); document.body.addEventListener('touchend', this.handleBodyTouchEnd); // https://plus.google.com/+PaulIrish/posts/KTwfn1Y2238 document.body.addEventListener('touchcancel', this.handleBodyTouchEnd); }; handleBodyTouchMove = event => { const anchor = getAnchor(this.props); const horizontalSwipe = isHorizontal(this.props); const currentX = anchor === 'right' ? document.body.offsetWidth - event.touches[0].pageX : event.touches[0].pageX; const currentY = anchor === 'bottom' ? window.innerHeight - event.touches[0].clientY : event.touches[0].clientY; // We don't know yet. if (this.isSwiping === undefined) { const dx = Math.abs(currentX - this.startX); const dy = Math.abs(currentY - this.startY); // If the user has moved his thumb some pixels in either direction, // we can safely make an assumption about whether he was intending // to swipe or scroll. const isSwiping = horizontalSwipe ? dx > UNCERTAINTY_THRESHOLD && dy <= UNCERTAINTY_THRESHOLD : dy > UNCERTAINTY_THRESHOLD && dx <= UNCERTAINTY_THRESHOLD; // We are likely to be swiping, let's prevent the scroll event on iOS. if (dx > dy) { event.preventDefault(); } if (isSwiping) { this.isSwiping = this.props.open ? 'closing' : 'opening'; // Shift the starting point. this.startX = currentX; this.startY = currentY; // Compensate for the part of the drawer displayed on touch start. if (!this.props.disableDiscovery && !this.props.open) { if (horizontalSwipe) { this.startX -= this.props.swipeAreaWidth; } else { this.startY -= this.props.swipeAreaWidth; } } } else if ( horizontalSwipe ? dx <= UNCERTAINTY_THRESHOLD && dy > UNCERTAINTY_THRESHOLD : dy <= UNCERTAINTY_THRESHOLD && dx > UNCERTAINTY_THRESHOLD ) { this.handleBodyTouchEnd(event); } } if (this.isSwiping === undefined) { return; } // We are swiping, let's prevent the scroll event on iOS. event.preventDefault(); this.setPosition(this.getTranslate(horizontalSwipe ? currentX : currentY)); }; handleBodyTouchEnd = event => { nodeHowClaimedTheSwipe = null; this.removeBodyTouchListeners(); this.setState({ maybeSwiping: false }); if (this.isSwiping === undefined) { return; } const anchor = getAnchor(this.props); let current; if (isHorizontal(this.props)) { current = anchor === 'right' ? document.body.offsetWidth - event.changedTouches[0].pageX : event.changedTouches[0].pageX; } else { current = anchor === 'bottom' ? window.innerHeight - event.changedTouches[0].clientY : event.changedTouches[0].clientY; } const translateRatio = this.getTranslate(current) / this.getMaxTranslate(); // We have to open or close after setting swiping to null, // because only then CSS transition is enabled. if (translateRatio > 0.5) { if (this.isSwiping === 'opening') { // Reset the position, the swipe was aborted. this.setPosition(this.getMaxTranslate(), { mode: 'enter', }); } else { this.props.onClose(); } } else if (this.isSwiping === 'opening') { this.props.onOpen(); } else { // Reset the position, the swipe was aborted. this.setPosition(0, { mode: 'exit', }); } this.isSwiping = undefined; }; backdrop = null; paper = null; isSwiping = undefined; startX = null; startY = null; listenTouchStart() { document.body.addEventListener('touchstart', this.handleBodyTouchStart); } removeTouchStart() { document.body.removeEventListener('touchstart', this.handleBodyTouchStart); } removeBodyTouchListeners() { document.body.removeEventListener('touchmove', this.handleBodyTouchMove, { passive: false }); document.body.removeEventListener('touchend', this.handleBodyTouchEnd); document.body.removeEventListener('touchcancel', this.handleBodyTouchEnd); } handleBackdropRef = node => { this.backdrop = node ? ReactDOM.findDOMNode(node) : null; }; handlePaperRef = node => { this.paper = node ? ReactDOM.findDOMNode(node) : null; }; render() { const { disableBackdropTransition, disableDiscovery, ModalProps: { BackdropProps, ...ModalPropsProp } = {}, onOpen, open, PaperProps, swipeAreaWidth, variant, ...other } = this.props; const { maybeSwiping } = this.state; return ( <Drawer open={variant === 'temporary' && maybeSwiping ? true : open} variant={variant} ModalProps={{ BackdropProps: { ...BackdropProps, ref: this.handleBackdropRef, }, ...ModalPropsProp, }} PaperProps={{ ...PaperProps, ref: this.handlePaperRef, }} {...other} /> ); } } SwipeableDrawer.propTypes = { /** * @ignore */ anchor: PropTypes.oneOf(['left', 'top', 'right', 'bottom']), /** * Disable the backdrop transition. * This can improve the FPS on low-end devices. */ disableBackdropTransition: PropTypes.bool, /** * If `true`, touching the screen near the edge of the drawer will not slide in the drawer a bit * to promote accidental discovery of the swipe gesture. */ disableDiscovery: PropTypes.bool, /** * @ignore */ ModalProps: PropTypes.object, /** * Callback fired when the component requests to be closed. * * @param {object} event The event source of the callback */ onClose: PropTypes.func.isRequired, /** * Callback fired when the component requests to be opened. * * @param {object} event The event source of the callback */ onOpen: PropTypes.func.isRequired, /** * If `true`, the drawer is open. */ open: PropTypes.bool.isRequired, /** * @ignore */ PaperProps: PropTypes.object, /** * The width of the left most (or right most) area in pixels where the * drawer can be swiped open from. */ swipeAreaWidth: PropTypes.number, /** * @ignore */ theme: PropTypes.object.isRequired, /** * The duration for the transition, in milliseconds. * You may specify a single timeout for all transitions, or individually with an object. */ transitionDuration: PropTypes.oneOfType([ PropTypes.number, PropTypes.shape({ enter: PropTypes.number, exit: PropTypes.number }), ]), /** * @ignore */ variant: PropTypes.oneOf(['permanent', 'persistent', 'temporary']), }; SwipeableDrawer.defaultProps = { anchor: 'left', disableBackdropTransition: false, disableDiscovery: false, swipeAreaWidth: 20, transitionDuration: { enter: duration.enteringScreen, exit: duration.leavingScreen }, variant: 'temporary', // Mobile first. }; export default withTheme()(SwipeableDrawer);
src/SwipeableDrawer/SwipeableDrawer.js
1
https://github.com/mui/material-ui/commit/5d126e65e30f7541e34b0c12bd68fa0c31ae71fa
[ 0.9992352724075317, 0.3626495599746704, 0.00016366464842576534, 0.0011621474986895919, 0.46622762084007263 ]
{ "id": 3, "code_window": [ " }\n", "\n", " handleBodyTouchStart = event => {\n", " // We are not supposed to hanlde this touch move.\n", " if (nodeHowClaimedTheSwipe !== null && nodeHowClaimedTheSwipe !== this) {\n", " return;\n", " }\n", "\n", " const { disableDiscovery, open, swipeAreaWidth } = this.props;\n", " const anchor = getAnchor(this.props);\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " if (nodeThatClaimedTheSwipe !== null && nodeThatClaimedTheSwipe !== this) {\n" ], "file_path": "src/SwipeableDrawer/SwipeableDrawer.js", "type": "replace", "edit_start_line_idx": 114 }
/* eslint-disable no-console */ import { spy } from 'sinon'; class ConsoleErrorMock { consoleErrorContainer; spy = () => { this.consoleErrorContainer = console.error; console.error = spy(); }; reset = () => { console.error = this.consoleErrorContainer; delete this.consoleErrorContainer; }; callCount = () => { if (this.consoleErrorContainer) { return console.error.callCount; } throw new Error('Requested call count before spy() was called'); }; args = () => { if (this.consoleErrorContainer) { return console.error.args; } throw new Error('Requested call count before spy() was called'); }; } export default new ConsoleErrorMock();
test/utils/consoleErrorMock.js
0
https://github.com/mui/material-ui/commit/5d126e65e30f7541e34b0c12bd68fa0c31ae71fa
[ 0.00017316693265456706, 0.00017005170229822397, 0.0001673882215982303, 0.00016982582747004926, 0.000002162948476325255 ]
{ "id": 3, "code_window": [ " }\n", "\n", " handleBodyTouchStart = event => {\n", " // We are not supposed to hanlde this touch move.\n", " if (nodeHowClaimedTheSwipe !== null && nodeHowClaimedTheSwipe !== this) {\n", " return;\n", " }\n", "\n", " const { disableDiscovery, open, swipeAreaWidth } = this.props;\n", " const anchor = getAnchor(this.props);\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " if (nodeThatClaimedTheSwipe !== null && nodeThatClaimedTheSwipe !== this) {\n" ], "file_path": "src/SwipeableDrawer/SwipeableDrawer.js", "type": "replace", "edit_start_line_idx": 114 }
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; const SvgIconCustom = global.__MUI_SvgIcon__ || SvgIcon; let GpsFixed = props => <SvgIconCustom {...props}> <path d="M12 8c-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4-1.79-4-4-4zm8.94 3c-.46-4.17-3.77-7.48-7.94-7.94V1h-2v2.06C6.83 3.52 3.52 6.83 3.06 11H1v2h2.06c.46 4.17 3.77 7.48 7.94 7.94V23h2v-2.06c4.17-.46 7.48-3.77 7.94-7.94H23v-2h-2.06zM12 19c-3.87 0-7-3.13-7-7s3.13-7 7-7 7 3.13 7 7-3.13 7-7 7z" /> </SvgIconCustom>; GpsFixed = pure(GpsFixed); GpsFixed.muiName = 'SvgIcon'; export default GpsFixed;
packages/material-ui-icons/src/GpsFixed.js
0
https://github.com/mui/material-ui/commit/5d126e65e30f7541e34b0c12bd68fa0c31ae71fa
[ 0.00017494522035121918, 0.00017133023357018828, 0.00016771526134107262, 0.00017133023357018828, 0.000003614979505073279 ]
{ "id": 3, "code_window": [ " }\n", "\n", " handleBodyTouchStart = event => {\n", " // We are not supposed to hanlde this touch move.\n", " if (nodeHowClaimedTheSwipe !== null && nodeHowClaimedTheSwipe !== this) {\n", " return;\n", " }\n", "\n", " const { disableDiscovery, open, swipeAreaWidth } = this.props;\n", " const anchor = getAnchor(this.props);\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " if (nodeThatClaimedTheSwipe !== null && nodeThatClaimedTheSwipe !== this) {\n" ], "file_path": "src/SwipeableDrawer/SwipeableDrawer.js", "type": "replace", "edit_start_line_idx": 114 }
import React from 'react'; import withRoot from 'docs/src/modules/components/withRoot'; import MarkdownDocs from 'docs/src/modules/components/MarkdownDocs'; import markdown from 'docs/src/pages/getting-started/supported-platforms/supported-platforms.md'; function Page() { return <MarkdownDocs markdown={markdown} />; } export default withRoot(Page);
pages/getting-started/supported-platforms.js
0
https://github.com/mui/material-ui/commit/5d126e65e30f7541e34b0c12bd68fa0c31ae71fa
[ 0.00017648494394961745, 0.00017566021415404975, 0.00017483548435848206, 0.00017566021415404975, 8.247297955676913e-7 ]
{ "id": 4, "code_window": [ " return;\n", " }\n", " }\n", "\n", " nodeHowClaimedTheSwipe = this;\n", " this.startX = currentX;\n", " this.startY = currentY;\n", "\n", " this.setState({ maybeSwiping: true });\n", " if (!open) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " nodeThatClaimedTheSwipe = this;\n" ], "file_path": "src/SwipeableDrawer/SwipeableDrawer.js", "type": "replace", "edit_start_line_idx": 139 }
/* eslint-disable consistent-this */ // @inheritedComponent Drawer import React from 'react'; import PropTypes from 'prop-types'; import ReactDOM from 'react-dom'; import Drawer, { getAnchor, isHorizontal } from '../Drawer/Drawer'; import { duration } from '../styles/transitions'; import withTheme from '../styles/withTheme'; import { getTransitionProps } from '../transitions/utils'; // This value is closed to what browsers are using internally to // trigger a native scroll. const UNCERTAINTY_THRESHOLD = 3; // px // We can only have one node at the time claiming ownership for handling the swipe. // Otherwise, the UX would be confusing. // That's why we use a singleton here. let nodeHowClaimedTheSwipe = null; // Exported for test purposes. export function reset() { nodeHowClaimedTheSwipe = null; } class SwipeableDrawer extends React.Component { state = { maybeSwiping: false, }; componentDidMount() { if (this.props.variant === 'temporary') { this.listenTouchStart(); } } componentDidUpdate(prevProps) { const variant = this.props.variant; const prevVariant = prevProps.variant; if (variant === 'temporary' && prevVariant !== 'temporary') { this.listenTouchStart(); } else if (variant !== 'temporary' && prevVariant === 'temporary') { this.removeTouchStart(); } } componentWillUnmount() { this.removeTouchStart(); this.removeBodyTouchListeners(); } getMaxTranslate() { return isHorizontal(this.props) ? this.paper.clientWidth : this.paper.clientHeight; } getTranslate(current) { const start = isHorizontal(this.props) ? this.startX : this.startY; return Math.min( Math.max( this.isSwiping === 'closing' ? start - current : this.getMaxTranslate() + start - current, 0, ), this.getMaxTranslate(), ); } setPosition(translate, options = {}) { const { mode = null, changeTransition = true } = options; const anchor = getAnchor(this.props); const rtlTranslateMultiplier = ['right', 'bottom'].indexOf(anchor) !== -1 ? 1 : -1; const transform = isHorizontal(this.props) ? `translate(${rtlTranslateMultiplier * translate}px, 0)` : `translate(0, ${rtlTranslateMultiplier * translate}px)`; const drawerStyle = this.paper.style; drawerStyle.webkitTransform = transform; drawerStyle.transform = transform; let transition = ''; if (mode) { transition = this.props.theme.transitions.create( 'all', getTransitionProps( { timeout: this.props.transitionDuration, }, { mode, }, ), ); } if (changeTransition) { drawerStyle.webkitTransition = transition; drawerStyle.transition = transition; } if (!this.props.disableBackdropTransition) { const backdropStyle = this.backdrop.style; backdropStyle.opacity = 1 - translate / this.getMaxTranslate(); if (changeTransition) { backdropStyle.webkitTransition = transition; backdropStyle.transition = transition; } } } handleBodyTouchStart = event => { // We are not supposed to hanlde this touch move. if (nodeHowClaimedTheSwipe !== null && nodeHowClaimedTheSwipe !== this) { return; } const { disableDiscovery, open, swipeAreaWidth } = this.props; const anchor = getAnchor(this.props); const currentX = anchor === 'right' ? document.body.offsetWidth - event.touches[0].pageX : event.touches[0].pageX; const currentY = anchor === 'bottom' ? window.innerHeight - event.touches[0].clientY : event.touches[0].clientY; if (!open) { if (isHorizontal(this.props)) { if (currentX > swipeAreaWidth) { return; } } else if (currentY > swipeAreaWidth) { return; } } nodeHowClaimedTheSwipe = this; this.startX = currentX; this.startY = currentY; this.setState({ maybeSwiping: true }); if (!open) { this.setPosition(this.getMaxTranslate() - (disableDiscovery ? 0 : swipeAreaWidth), { changeTransition: false, }); } document.body.addEventListener('touchmove', this.handleBodyTouchMove, { passive: false }); document.body.addEventListener('touchend', this.handleBodyTouchEnd); // https://plus.google.com/+PaulIrish/posts/KTwfn1Y2238 document.body.addEventListener('touchcancel', this.handleBodyTouchEnd); }; handleBodyTouchMove = event => { const anchor = getAnchor(this.props); const horizontalSwipe = isHorizontal(this.props); const currentX = anchor === 'right' ? document.body.offsetWidth - event.touches[0].pageX : event.touches[0].pageX; const currentY = anchor === 'bottom' ? window.innerHeight - event.touches[0].clientY : event.touches[0].clientY; // We don't know yet. if (this.isSwiping === undefined) { const dx = Math.abs(currentX - this.startX); const dy = Math.abs(currentY - this.startY); // If the user has moved his thumb some pixels in either direction, // we can safely make an assumption about whether he was intending // to swipe or scroll. const isSwiping = horizontalSwipe ? dx > UNCERTAINTY_THRESHOLD && dy <= UNCERTAINTY_THRESHOLD : dy > UNCERTAINTY_THRESHOLD && dx <= UNCERTAINTY_THRESHOLD; // We are likely to be swiping, let's prevent the scroll event on iOS. if (dx > dy) { event.preventDefault(); } if (isSwiping) { this.isSwiping = this.props.open ? 'closing' : 'opening'; // Shift the starting point. this.startX = currentX; this.startY = currentY; // Compensate for the part of the drawer displayed on touch start. if (!this.props.disableDiscovery && !this.props.open) { if (horizontalSwipe) { this.startX -= this.props.swipeAreaWidth; } else { this.startY -= this.props.swipeAreaWidth; } } } else if ( horizontalSwipe ? dx <= UNCERTAINTY_THRESHOLD && dy > UNCERTAINTY_THRESHOLD : dy <= UNCERTAINTY_THRESHOLD && dx > UNCERTAINTY_THRESHOLD ) { this.handleBodyTouchEnd(event); } } if (this.isSwiping === undefined) { return; } // We are swiping, let's prevent the scroll event on iOS. event.preventDefault(); this.setPosition(this.getTranslate(horizontalSwipe ? currentX : currentY)); }; handleBodyTouchEnd = event => { nodeHowClaimedTheSwipe = null; this.removeBodyTouchListeners(); this.setState({ maybeSwiping: false }); if (this.isSwiping === undefined) { return; } const anchor = getAnchor(this.props); let current; if (isHorizontal(this.props)) { current = anchor === 'right' ? document.body.offsetWidth - event.changedTouches[0].pageX : event.changedTouches[0].pageX; } else { current = anchor === 'bottom' ? window.innerHeight - event.changedTouches[0].clientY : event.changedTouches[0].clientY; } const translateRatio = this.getTranslate(current) / this.getMaxTranslate(); // We have to open or close after setting swiping to null, // because only then CSS transition is enabled. if (translateRatio > 0.5) { if (this.isSwiping === 'opening') { // Reset the position, the swipe was aborted. this.setPosition(this.getMaxTranslate(), { mode: 'enter', }); } else { this.props.onClose(); } } else if (this.isSwiping === 'opening') { this.props.onOpen(); } else { // Reset the position, the swipe was aborted. this.setPosition(0, { mode: 'exit', }); } this.isSwiping = undefined; }; backdrop = null; paper = null; isSwiping = undefined; startX = null; startY = null; listenTouchStart() { document.body.addEventListener('touchstart', this.handleBodyTouchStart); } removeTouchStart() { document.body.removeEventListener('touchstart', this.handleBodyTouchStart); } removeBodyTouchListeners() { document.body.removeEventListener('touchmove', this.handleBodyTouchMove, { passive: false }); document.body.removeEventListener('touchend', this.handleBodyTouchEnd); document.body.removeEventListener('touchcancel', this.handleBodyTouchEnd); } handleBackdropRef = node => { this.backdrop = node ? ReactDOM.findDOMNode(node) : null; }; handlePaperRef = node => { this.paper = node ? ReactDOM.findDOMNode(node) : null; }; render() { const { disableBackdropTransition, disableDiscovery, ModalProps: { BackdropProps, ...ModalPropsProp } = {}, onOpen, open, PaperProps, swipeAreaWidth, variant, ...other } = this.props; const { maybeSwiping } = this.state; return ( <Drawer open={variant === 'temporary' && maybeSwiping ? true : open} variant={variant} ModalProps={{ BackdropProps: { ...BackdropProps, ref: this.handleBackdropRef, }, ...ModalPropsProp, }} PaperProps={{ ...PaperProps, ref: this.handlePaperRef, }} {...other} /> ); } } SwipeableDrawer.propTypes = { /** * @ignore */ anchor: PropTypes.oneOf(['left', 'top', 'right', 'bottom']), /** * Disable the backdrop transition. * This can improve the FPS on low-end devices. */ disableBackdropTransition: PropTypes.bool, /** * If `true`, touching the screen near the edge of the drawer will not slide in the drawer a bit * to promote accidental discovery of the swipe gesture. */ disableDiscovery: PropTypes.bool, /** * @ignore */ ModalProps: PropTypes.object, /** * Callback fired when the component requests to be closed. * * @param {object} event The event source of the callback */ onClose: PropTypes.func.isRequired, /** * Callback fired when the component requests to be opened. * * @param {object} event The event source of the callback */ onOpen: PropTypes.func.isRequired, /** * If `true`, the drawer is open. */ open: PropTypes.bool.isRequired, /** * @ignore */ PaperProps: PropTypes.object, /** * The width of the left most (or right most) area in pixels where the * drawer can be swiped open from. */ swipeAreaWidth: PropTypes.number, /** * @ignore */ theme: PropTypes.object.isRequired, /** * The duration for the transition, in milliseconds. * You may specify a single timeout for all transitions, or individually with an object. */ transitionDuration: PropTypes.oneOfType([ PropTypes.number, PropTypes.shape({ enter: PropTypes.number, exit: PropTypes.number }), ]), /** * @ignore */ variant: PropTypes.oneOf(['permanent', 'persistent', 'temporary']), }; SwipeableDrawer.defaultProps = { anchor: 'left', disableBackdropTransition: false, disableDiscovery: false, swipeAreaWidth: 20, transitionDuration: { enter: duration.enteringScreen, exit: duration.leavingScreen }, variant: 'temporary', // Mobile first. }; export default withTheme()(SwipeableDrawer);
src/SwipeableDrawer/SwipeableDrawer.js
1
https://github.com/mui/material-ui/commit/5d126e65e30f7541e34b0c12bd68fa0c31ae71fa
[ 0.9981147050857544, 0.1722923368215561, 0.00016209881869144738, 0.0004408188397064805, 0.3721245527267456 ]
{ "id": 4, "code_window": [ " return;\n", " }\n", " }\n", "\n", " nodeHowClaimedTheSwipe = this;\n", " this.startX = currentX;\n", " this.startY = currentY;\n", "\n", " this.setState({ maybeSwiping: true });\n", " if (!open) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " nodeThatClaimedTheSwipe = this;\n" ], "file_path": "src/SwipeableDrawer/SwipeableDrawer.js", "type": "replace", "edit_start_line_idx": 139 }
import React from 'react'; import withRoot from 'docs/src/modules/components/withRoot'; import MarkdownDocs from 'docs/src/modules/components/MarkdownDocs'; import markdown from './list-item-icon.md'; function Page() { return <MarkdownDocs markdown={markdown} />; } export default withRoot(Page);
pages/api/list-item-icon.js
0
https://github.com/mui/material-ui/commit/5d126e65e30f7541e34b0c12bd68fa0c31ae71fa
[ 0.00017362706421408802, 0.00017324283544439822, 0.00017285860667470843, 0.00017324283544439822, 3.8422876968979836e-7 ]
{ "id": 4, "code_window": [ " return;\n", " }\n", " }\n", "\n", " nodeHowClaimedTheSwipe = this;\n", " this.startX = currentX;\n", " this.startY = currentY;\n", "\n", " this.setState({ maybeSwiping: true });\n", " if (!open) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " nodeThatClaimedTheSwipe = this;\n" ], "file_path": "src/SwipeableDrawer/SwipeableDrawer.js", "type": "replace", "edit_start_line_idx": 139 }
export function focusKeyPressed(pressed: boolean): boolean; export function detectKeyboardFocus( instance: { keyboardFocusTimeout: any; keyboardFocusCheckTime: number; keyboardFocusMaxCheckTimes: number; }, element: Element, cb: () => void, attempt: number, ): void; export function listenForFocusKeys(window: Window): void;
src/utils/keyboardFocus.d.ts
0
https://github.com/mui/material-ui/commit/5d126e65e30f7541e34b0c12bd68fa0c31ae71fa
[ 0.00017128532635979354, 0.00017044565174728632, 0.00016960599168669432, 0.00017044565174728632, 8.396673365496099e-7 ]
{ "id": 4, "code_window": [ " return;\n", " }\n", " }\n", "\n", " nodeHowClaimedTheSwipe = this;\n", " this.startX = currentX;\n", " this.startY = currentY;\n", "\n", " this.setState({ maybeSwiping: true });\n", " if (!open) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " nodeThatClaimedTheSwipe = this;\n" ], "file_path": "src/SwipeableDrawer/SwipeableDrawer.js", "type": "replace", "edit_start_line_idx": 139 }
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; const SvgIconCustom = global.__MUI_SvgIcon__ || SvgIcon; let BrandingWatermark = props => <SvgIconCustom {...props}> <path d="M21 3H3c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16h-9v-6h9v6z" /> </SvgIconCustom>; BrandingWatermark = pure(BrandingWatermark); BrandingWatermark.muiName = 'SvgIcon'; export default BrandingWatermark;
packages/material-ui-icons/src/BrandingWatermark.js
0
https://github.com/mui/material-ui/commit/5d126e65e30f7541e34b0c12bd68fa0c31ae71fa
[ 0.00016801664605736732, 0.0001678025582805276, 0.0001675884850556031, 0.0001678025582805276, 2.1408050088211894e-7 ]
{ "id": 5, "code_window": [ " this.setPosition(this.getTranslate(horizontalSwipe ? currentX : currentY));\n", " };\n", "\n", " handleBodyTouchEnd = event => {\n", " nodeHowClaimedTheSwipe = null;\n", " this.removeBodyTouchListeners();\n", " this.setState({ maybeSwiping: false });\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " nodeThatClaimedTheSwipe = null;\n" ], "file_path": "src/SwipeableDrawer/SwipeableDrawer.js", "type": "replace", "edit_start_line_idx": 220 }
/* eslint-disable consistent-this */ // @inheritedComponent Drawer import React from 'react'; import PropTypes from 'prop-types'; import ReactDOM from 'react-dom'; import Drawer, { getAnchor, isHorizontal } from '../Drawer/Drawer'; import { duration } from '../styles/transitions'; import withTheme from '../styles/withTheme'; import { getTransitionProps } from '../transitions/utils'; // This value is closed to what browsers are using internally to // trigger a native scroll. const UNCERTAINTY_THRESHOLD = 3; // px // We can only have one node at the time claiming ownership for handling the swipe. // Otherwise, the UX would be confusing. // That's why we use a singleton here. let nodeHowClaimedTheSwipe = null; // Exported for test purposes. export function reset() { nodeHowClaimedTheSwipe = null; } class SwipeableDrawer extends React.Component { state = { maybeSwiping: false, }; componentDidMount() { if (this.props.variant === 'temporary') { this.listenTouchStart(); } } componentDidUpdate(prevProps) { const variant = this.props.variant; const prevVariant = prevProps.variant; if (variant === 'temporary' && prevVariant !== 'temporary') { this.listenTouchStart(); } else if (variant !== 'temporary' && prevVariant === 'temporary') { this.removeTouchStart(); } } componentWillUnmount() { this.removeTouchStart(); this.removeBodyTouchListeners(); } getMaxTranslate() { return isHorizontal(this.props) ? this.paper.clientWidth : this.paper.clientHeight; } getTranslate(current) { const start = isHorizontal(this.props) ? this.startX : this.startY; return Math.min( Math.max( this.isSwiping === 'closing' ? start - current : this.getMaxTranslate() + start - current, 0, ), this.getMaxTranslate(), ); } setPosition(translate, options = {}) { const { mode = null, changeTransition = true } = options; const anchor = getAnchor(this.props); const rtlTranslateMultiplier = ['right', 'bottom'].indexOf(anchor) !== -1 ? 1 : -1; const transform = isHorizontal(this.props) ? `translate(${rtlTranslateMultiplier * translate}px, 0)` : `translate(0, ${rtlTranslateMultiplier * translate}px)`; const drawerStyle = this.paper.style; drawerStyle.webkitTransform = transform; drawerStyle.transform = transform; let transition = ''; if (mode) { transition = this.props.theme.transitions.create( 'all', getTransitionProps( { timeout: this.props.transitionDuration, }, { mode, }, ), ); } if (changeTransition) { drawerStyle.webkitTransition = transition; drawerStyle.transition = transition; } if (!this.props.disableBackdropTransition) { const backdropStyle = this.backdrop.style; backdropStyle.opacity = 1 - translate / this.getMaxTranslate(); if (changeTransition) { backdropStyle.webkitTransition = transition; backdropStyle.transition = transition; } } } handleBodyTouchStart = event => { // We are not supposed to hanlde this touch move. if (nodeHowClaimedTheSwipe !== null && nodeHowClaimedTheSwipe !== this) { return; } const { disableDiscovery, open, swipeAreaWidth } = this.props; const anchor = getAnchor(this.props); const currentX = anchor === 'right' ? document.body.offsetWidth - event.touches[0].pageX : event.touches[0].pageX; const currentY = anchor === 'bottom' ? window.innerHeight - event.touches[0].clientY : event.touches[0].clientY; if (!open) { if (isHorizontal(this.props)) { if (currentX > swipeAreaWidth) { return; } } else if (currentY > swipeAreaWidth) { return; } } nodeHowClaimedTheSwipe = this; this.startX = currentX; this.startY = currentY; this.setState({ maybeSwiping: true }); if (!open) { this.setPosition(this.getMaxTranslate() - (disableDiscovery ? 0 : swipeAreaWidth), { changeTransition: false, }); } document.body.addEventListener('touchmove', this.handleBodyTouchMove, { passive: false }); document.body.addEventListener('touchend', this.handleBodyTouchEnd); // https://plus.google.com/+PaulIrish/posts/KTwfn1Y2238 document.body.addEventListener('touchcancel', this.handleBodyTouchEnd); }; handleBodyTouchMove = event => { const anchor = getAnchor(this.props); const horizontalSwipe = isHorizontal(this.props); const currentX = anchor === 'right' ? document.body.offsetWidth - event.touches[0].pageX : event.touches[0].pageX; const currentY = anchor === 'bottom' ? window.innerHeight - event.touches[0].clientY : event.touches[0].clientY; // We don't know yet. if (this.isSwiping === undefined) { const dx = Math.abs(currentX - this.startX); const dy = Math.abs(currentY - this.startY); // If the user has moved his thumb some pixels in either direction, // we can safely make an assumption about whether he was intending // to swipe or scroll. const isSwiping = horizontalSwipe ? dx > UNCERTAINTY_THRESHOLD && dy <= UNCERTAINTY_THRESHOLD : dy > UNCERTAINTY_THRESHOLD && dx <= UNCERTAINTY_THRESHOLD; // We are likely to be swiping, let's prevent the scroll event on iOS. if (dx > dy) { event.preventDefault(); } if (isSwiping) { this.isSwiping = this.props.open ? 'closing' : 'opening'; // Shift the starting point. this.startX = currentX; this.startY = currentY; // Compensate for the part of the drawer displayed on touch start. if (!this.props.disableDiscovery && !this.props.open) { if (horizontalSwipe) { this.startX -= this.props.swipeAreaWidth; } else { this.startY -= this.props.swipeAreaWidth; } } } else if ( horizontalSwipe ? dx <= UNCERTAINTY_THRESHOLD && dy > UNCERTAINTY_THRESHOLD : dy <= UNCERTAINTY_THRESHOLD && dx > UNCERTAINTY_THRESHOLD ) { this.handleBodyTouchEnd(event); } } if (this.isSwiping === undefined) { return; } // We are swiping, let's prevent the scroll event on iOS. event.preventDefault(); this.setPosition(this.getTranslate(horizontalSwipe ? currentX : currentY)); }; handleBodyTouchEnd = event => { nodeHowClaimedTheSwipe = null; this.removeBodyTouchListeners(); this.setState({ maybeSwiping: false }); if (this.isSwiping === undefined) { return; } const anchor = getAnchor(this.props); let current; if (isHorizontal(this.props)) { current = anchor === 'right' ? document.body.offsetWidth - event.changedTouches[0].pageX : event.changedTouches[0].pageX; } else { current = anchor === 'bottom' ? window.innerHeight - event.changedTouches[0].clientY : event.changedTouches[0].clientY; } const translateRatio = this.getTranslate(current) / this.getMaxTranslate(); // We have to open or close after setting swiping to null, // because only then CSS transition is enabled. if (translateRatio > 0.5) { if (this.isSwiping === 'opening') { // Reset the position, the swipe was aborted. this.setPosition(this.getMaxTranslate(), { mode: 'enter', }); } else { this.props.onClose(); } } else if (this.isSwiping === 'opening') { this.props.onOpen(); } else { // Reset the position, the swipe was aborted. this.setPosition(0, { mode: 'exit', }); } this.isSwiping = undefined; }; backdrop = null; paper = null; isSwiping = undefined; startX = null; startY = null; listenTouchStart() { document.body.addEventListener('touchstart', this.handleBodyTouchStart); } removeTouchStart() { document.body.removeEventListener('touchstart', this.handleBodyTouchStart); } removeBodyTouchListeners() { document.body.removeEventListener('touchmove', this.handleBodyTouchMove, { passive: false }); document.body.removeEventListener('touchend', this.handleBodyTouchEnd); document.body.removeEventListener('touchcancel', this.handleBodyTouchEnd); } handleBackdropRef = node => { this.backdrop = node ? ReactDOM.findDOMNode(node) : null; }; handlePaperRef = node => { this.paper = node ? ReactDOM.findDOMNode(node) : null; }; render() { const { disableBackdropTransition, disableDiscovery, ModalProps: { BackdropProps, ...ModalPropsProp } = {}, onOpen, open, PaperProps, swipeAreaWidth, variant, ...other } = this.props; const { maybeSwiping } = this.state; return ( <Drawer open={variant === 'temporary' && maybeSwiping ? true : open} variant={variant} ModalProps={{ BackdropProps: { ...BackdropProps, ref: this.handleBackdropRef, }, ...ModalPropsProp, }} PaperProps={{ ...PaperProps, ref: this.handlePaperRef, }} {...other} /> ); } } SwipeableDrawer.propTypes = { /** * @ignore */ anchor: PropTypes.oneOf(['left', 'top', 'right', 'bottom']), /** * Disable the backdrop transition. * This can improve the FPS on low-end devices. */ disableBackdropTransition: PropTypes.bool, /** * If `true`, touching the screen near the edge of the drawer will not slide in the drawer a bit * to promote accidental discovery of the swipe gesture. */ disableDiscovery: PropTypes.bool, /** * @ignore */ ModalProps: PropTypes.object, /** * Callback fired when the component requests to be closed. * * @param {object} event The event source of the callback */ onClose: PropTypes.func.isRequired, /** * Callback fired when the component requests to be opened. * * @param {object} event The event source of the callback */ onOpen: PropTypes.func.isRequired, /** * If `true`, the drawer is open. */ open: PropTypes.bool.isRequired, /** * @ignore */ PaperProps: PropTypes.object, /** * The width of the left most (or right most) area in pixels where the * drawer can be swiped open from. */ swipeAreaWidth: PropTypes.number, /** * @ignore */ theme: PropTypes.object.isRequired, /** * The duration for the transition, in milliseconds. * You may specify a single timeout for all transitions, or individually with an object. */ transitionDuration: PropTypes.oneOfType([ PropTypes.number, PropTypes.shape({ enter: PropTypes.number, exit: PropTypes.number }), ]), /** * @ignore */ variant: PropTypes.oneOf(['permanent', 'persistent', 'temporary']), }; SwipeableDrawer.defaultProps = { anchor: 'left', disableBackdropTransition: false, disableDiscovery: false, swipeAreaWidth: 20, transitionDuration: { enter: duration.enteringScreen, exit: duration.leavingScreen }, variant: 'temporary', // Mobile first. }; export default withTheme()(SwipeableDrawer);
src/SwipeableDrawer/SwipeableDrawer.js
1
https://github.com/mui/material-ui/commit/5d126e65e30f7541e34b0c12bd68fa0c31ae71fa
[ 0.9989847540855408, 0.15575236082077026, 0.00016463945212308317, 0.0012559238821268082, 0.3497338593006134 ]
{ "id": 5, "code_window": [ " this.setPosition(this.getTranslate(horizontalSwipe ? currentX : currentY));\n", " };\n", "\n", " handleBodyTouchEnd = event => {\n", " nodeHowClaimedTheSwipe = null;\n", " this.removeBodyTouchListeners();\n", " this.setState({ maybeSwiping: false });\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " nodeThatClaimedTheSwipe = null;\n" ], "file_path": "src/SwipeableDrawer/SwipeableDrawer.js", "type": "replace", "edit_start_line_idx": 220 }
import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import Transition from 'react-transition-group/Transition'; /** * @ignore - internal component. */ class Ripple extends React.Component { state = { visible: false, leaving: false, }; handleEnter = () => { this.setState({ visible: true, }); }; handleExit = () => { this.setState({ leaving: true, }); }; render() { const { classes, className: classNameProp, pulsate, rippleX, rippleY, rippleSize, ...other } = this.props; const { visible, leaving } = this.state; const rippleClassName = classNames( classes.ripple, { [classes.rippleVisible]: visible, [classes.ripplePulsate]: pulsate, }, classNameProp, ); const rippleStyles = { width: rippleSize, height: rippleSize, top: -(rippleSize / 2) + rippleY, left: -(rippleSize / 2) + rippleX, }; const childClassName = classNames(classes.child, { [classes.childLeaving]: leaving, [classes.childPulsate]: pulsate, }); return ( <Transition onEnter={this.handleEnter} onExit={this.handleExit} {...other}> <span className={rippleClassName} style={rippleStyles}> <span className={childClassName} /> </span> </Transition> ); } } Ripple.propTypes = { /** * Useful to extend the style applied to components. */ classes: PropTypes.object.isRequired, /** * @ignore */ className: PropTypes.string, /** * If `true`, the ripple pulsates, typically indicating the keyboard focus state of an element. */ pulsate: PropTypes.bool, /** * Diameter of the ripple. */ rippleSize: PropTypes.number, /** * Horizontal position of the ripple center. */ rippleX: PropTypes.number, /** * Vertical position of the ripple center. */ rippleY: PropTypes.number, }; Ripple.defaultProps = { pulsate: false, }; export default Ripple;
src/ButtonBase/Ripple.js
0
https://github.com/mui/material-ui/commit/5d126e65e30f7541e34b0c12bd68fa0c31ae71fa
[ 0.00021999742602929473, 0.00017651059897616506, 0.00016521266661584377, 0.00017058593221008778, 0.000016511543435626663 ]
{ "id": 5, "code_window": [ " this.setPosition(this.getTranslate(horizontalSwipe ? currentX : currentY));\n", " };\n", "\n", " handleBodyTouchEnd = event => {\n", " nodeHowClaimedTheSwipe = null;\n", " this.removeBodyTouchListeners();\n", " this.setState({ maybeSwiping: false });\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " nodeThatClaimedTheSwipe = null;\n" ], "file_path": "src/SwipeableDrawer/SwipeableDrawer.js", "type": "replace", "edit_start_line_idx": 220 }
import React from 'react'; import withRoot from 'docs/src/modules/components/withRoot'; import MarkdownDocs from 'docs/src/modules/components/MarkdownDocs'; import markdown from './list-subheader.md'; function Page() { return <MarkdownDocs markdown={markdown} />; } export default withRoot(Page);
pages/api/list-subheader.js
0
https://github.com/mui/material-ui/commit/5d126e65e30f7541e34b0c12bd68fa0c31ae71fa
[ 0.00017529085744172335, 0.00017354963347315788, 0.00017180842405650765, 0.00017354963347315788, 0.0000017412166926078498 ]
{ "id": 5, "code_window": [ " this.setPosition(this.getTranslate(horizontalSwipe ? currentX : currentY));\n", " };\n", "\n", " handleBodyTouchEnd = event => {\n", " nodeHowClaimedTheSwipe = null;\n", " this.removeBodyTouchListeners();\n", " this.setState({ maybeSwiping: false });\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " nodeThatClaimedTheSwipe = null;\n" ], "file_path": "src/SwipeableDrawer/SwipeableDrawer.js", "type": "replace", "edit_start_line_idx": 220 }
// flow-typed signature: d78a3d3bd73b794dd4c34fc9c804c0a1 // flow-typed version: <<STUB>>/babel-plugin-transform-dev-warning_v^0.1.0/flow_v0.59.0 /** * This is an autogenerated libdef stub for: * * 'babel-plugin-transform-dev-warning' * * Fill this stub out by replacing all the `any` types. * * Once filled out, we encourage you to share your work with the * community by sending a pull request to: * https://github.com/flowtype/flow-typed */ declare module 'babel-plugin-transform-dev-warning' { declare module.exports: any; } /** * We include stubs for each file inside this npm package in case you need to * require those files directly. Feel free to delete any files that aren't * needed. */ declare module 'babel-plugin-transform-dev-warning/lib/index' { declare module.exports: any; } declare module 'babel-plugin-transform-dev-warning/src/index' { declare module.exports: any; } declare module 'babel-plugin-transform-dev-warning/test/fixtures/simple/actual' { declare module.exports: any; } declare module 'babel-plugin-transform-dev-warning/test/fixtures/simple/expected' { declare module.exports: any; } declare module 'babel-plugin-transform-dev-warning/test/index' { declare module.exports: any; } // Filename aliases declare module 'babel-plugin-transform-dev-warning/lib/index.js' { declare module.exports: $Exports<'babel-plugin-transform-dev-warning/lib/index'>; } declare module 'babel-plugin-transform-dev-warning/src/index.js' { declare module.exports: $Exports<'babel-plugin-transform-dev-warning/src/index'>; } declare module 'babel-plugin-transform-dev-warning/test/fixtures/simple/actual.js' { declare module.exports: $Exports<'babel-plugin-transform-dev-warning/test/fixtures/simple/actual'>; } declare module 'babel-plugin-transform-dev-warning/test/fixtures/simple/expected.js' { declare module.exports: $Exports<'babel-plugin-transform-dev-warning/test/fixtures/simple/expected'>; } declare module 'babel-plugin-transform-dev-warning/test/index.js' { declare module.exports: $Exports<'babel-plugin-transform-dev-warning/test/index'>; }
flow-typed/npm/babel-plugin-transform-dev-warning_vx.x.x.js
0
https://github.com/mui/material-ui/commit/5d126e65e30f7541e34b0c12bd68fa0c31ae71fa
[ 0.00017196428962051868, 0.00016874413995537907, 0.0001631307095522061, 0.00016996572958305478, 0.0000032132879823620897 ]
{ "id": 6, "code_window": [ " assert.strictEqual(instance.isSwiping, 'closing', 'should be closing');\n", " fireBodyMouseEvent('touchend', { changedTouches: [params.closeTouches[1]] });\n", " assert.strictEqual(handleClose.callCount, 0, 'should not call onClose');\n", " });\n", "\n", " it('should not start swiping when swiping in the wrong direction', () => {\n", " fireBodyMouseEvent('touchstart', { touches: [params.openTouches[0]] });\n", " if (['left', 'right'].includes(params.anchor)) {\n", " fireBodyMouseEvent('touchmove', {\n", " touches: [\n", " {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " it('should ignore swiping in the wrong direction if discovery is disabled', () => {\n", " wrapper.setProps({ disableDiscovery: true });\n", "\n" ], "file_path": "src/SwipeableDrawer/SwipeableDrawer.spec.js", "type": "replace", "edit_start_line_idx": 206 }
/* eslint-disable consistent-this */ // @inheritedComponent Drawer import React from 'react'; import PropTypes from 'prop-types'; import ReactDOM from 'react-dom'; import Drawer, { getAnchor, isHorizontal } from '../Drawer/Drawer'; import { duration } from '../styles/transitions'; import withTheme from '../styles/withTheme'; import { getTransitionProps } from '../transitions/utils'; // This value is closed to what browsers are using internally to // trigger a native scroll. const UNCERTAINTY_THRESHOLD = 3; // px // We can only have one node at the time claiming ownership for handling the swipe. // Otherwise, the UX would be confusing. // That's why we use a singleton here. let nodeHowClaimedTheSwipe = null; // Exported for test purposes. export function reset() { nodeHowClaimedTheSwipe = null; } class SwipeableDrawer extends React.Component { state = { maybeSwiping: false, }; componentDidMount() { if (this.props.variant === 'temporary') { this.listenTouchStart(); } } componentDidUpdate(prevProps) { const variant = this.props.variant; const prevVariant = prevProps.variant; if (variant === 'temporary' && prevVariant !== 'temporary') { this.listenTouchStart(); } else if (variant !== 'temporary' && prevVariant === 'temporary') { this.removeTouchStart(); } } componentWillUnmount() { this.removeTouchStart(); this.removeBodyTouchListeners(); } getMaxTranslate() { return isHorizontal(this.props) ? this.paper.clientWidth : this.paper.clientHeight; } getTranslate(current) { const start = isHorizontal(this.props) ? this.startX : this.startY; return Math.min( Math.max( this.isSwiping === 'closing' ? start - current : this.getMaxTranslate() + start - current, 0, ), this.getMaxTranslate(), ); } setPosition(translate, options = {}) { const { mode = null, changeTransition = true } = options; const anchor = getAnchor(this.props); const rtlTranslateMultiplier = ['right', 'bottom'].indexOf(anchor) !== -1 ? 1 : -1; const transform = isHorizontal(this.props) ? `translate(${rtlTranslateMultiplier * translate}px, 0)` : `translate(0, ${rtlTranslateMultiplier * translate}px)`; const drawerStyle = this.paper.style; drawerStyle.webkitTransform = transform; drawerStyle.transform = transform; let transition = ''; if (mode) { transition = this.props.theme.transitions.create( 'all', getTransitionProps( { timeout: this.props.transitionDuration, }, { mode, }, ), ); } if (changeTransition) { drawerStyle.webkitTransition = transition; drawerStyle.transition = transition; } if (!this.props.disableBackdropTransition) { const backdropStyle = this.backdrop.style; backdropStyle.opacity = 1 - translate / this.getMaxTranslate(); if (changeTransition) { backdropStyle.webkitTransition = transition; backdropStyle.transition = transition; } } } handleBodyTouchStart = event => { // We are not supposed to hanlde this touch move. if (nodeHowClaimedTheSwipe !== null && nodeHowClaimedTheSwipe !== this) { return; } const { disableDiscovery, open, swipeAreaWidth } = this.props; const anchor = getAnchor(this.props); const currentX = anchor === 'right' ? document.body.offsetWidth - event.touches[0].pageX : event.touches[0].pageX; const currentY = anchor === 'bottom' ? window.innerHeight - event.touches[0].clientY : event.touches[0].clientY; if (!open) { if (isHorizontal(this.props)) { if (currentX > swipeAreaWidth) { return; } } else if (currentY > swipeAreaWidth) { return; } } nodeHowClaimedTheSwipe = this; this.startX = currentX; this.startY = currentY; this.setState({ maybeSwiping: true }); if (!open) { this.setPosition(this.getMaxTranslate() - (disableDiscovery ? 0 : swipeAreaWidth), { changeTransition: false, }); } document.body.addEventListener('touchmove', this.handleBodyTouchMove, { passive: false }); document.body.addEventListener('touchend', this.handleBodyTouchEnd); // https://plus.google.com/+PaulIrish/posts/KTwfn1Y2238 document.body.addEventListener('touchcancel', this.handleBodyTouchEnd); }; handleBodyTouchMove = event => { const anchor = getAnchor(this.props); const horizontalSwipe = isHorizontal(this.props); const currentX = anchor === 'right' ? document.body.offsetWidth - event.touches[0].pageX : event.touches[0].pageX; const currentY = anchor === 'bottom' ? window.innerHeight - event.touches[0].clientY : event.touches[0].clientY; // We don't know yet. if (this.isSwiping === undefined) { const dx = Math.abs(currentX - this.startX); const dy = Math.abs(currentY - this.startY); // If the user has moved his thumb some pixels in either direction, // we can safely make an assumption about whether he was intending // to swipe or scroll. const isSwiping = horizontalSwipe ? dx > UNCERTAINTY_THRESHOLD && dy <= UNCERTAINTY_THRESHOLD : dy > UNCERTAINTY_THRESHOLD && dx <= UNCERTAINTY_THRESHOLD; // We are likely to be swiping, let's prevent the scroll event on iOS. if (dx > dy) { event.preventDefault(); } if (isSwiping) { this.isSwiping = this.props.open ? 'closing' : 'opening'; // Shift the starting point. this.startX = currentX; this.startY = currentY; // Compensate for the part of the drawer displayed on touch start. if (!this.props.disableDiscovery && !this.props.open) { if (horizontalSwipe) { this.startX -= this.props.swipeAreaWidth; } else { this.startY -= this.props.swipeAreaWidth; } } } else if ( horizontalSwipe ? dx <= UNCERTAINTY_THRESHOLD && dy > UNCERTAINTY_THRESHOLD : dy <= UNCERTAINTY_THRESHOLD && dx > UNCERTAINTY_THRESHOLD ) { this.handleBodyTouchEnd(event); } } if (this.isSwiping === undefined) { return; } // We are swiping, let's prevent the scroll event on iOS. event.preventDefault(); this.setPosition(this.getTranslate(horizontalSwipe ? currentX : currentY)); }; handleBodyTouchEnd = event => { nodeHowClaimedTheSwipe = null; this.removeBodyTouchListeners(); this.setState({ maybeSwiping: false }); if (this.isSwiping === undefined) { return; } const anchor = getAnchor(this.props); let current; if (isHorizontal(this.props)) { current = anchor === 'right' ? document.body.offsetWidth - event.changedTouches[0].pageX : event.changedTouches[0].pageX; } else { current = anchor === 'bottom' ? window.innerHeight - event.changedTouches[0].clientY : event.changedTouches[0].clientY; } const translateRatio = this.getTranslate(current) / this.getMaxTranslate(); // We have to open or close after setting swiping to null, // because only then CSS transition is enabled. if (translateRatio > 0.5) { if (this.isSwiping === 'opening') { // Reset the position, the swipe was aborted. this.setPosition(this.getMaxTranslate(), { mode: 'enter', }); } else { this.props.onClose(); } } else if (this.isSwiping === 'opening') { this.props.onOpen(); } else { // Reset the position, the swipe was aborted. this.setPosition(0, { mode: 'exit', }); } this.isSwiping = undefined; }; backdrop = null; paper = null; isSwiping = undefined; startX = null; startY = null; listenTouchStart() { document.body.addEventListener('touchstart', this.handleBodyTouchStart); } removeTouchStart() { document.body.removeEventListener('touchstart', this.handleBodyTouchStart); } removeBodyTouchListeners() { document.body.removeEventListener('touchmove', this.handleBodyTouchMove, { passive: false }); document.body.removeEventListener('touchend', this.handleBodyTouchEnd); document.body.removeEventListener('touchcancel', this.handleBodyTouchEnd); } handleBackdropRef = node => { this.backdrop = node ? ReactDOM.findDOMNode(node) : null; }; handlePaperRef = node => { this.paper = node ? ReactDOM.findDOMNode(node) : null; }; render() { const { disableBackdropTransition, disableDiscovery, ModalProps: { BackdropProps, ...ModalPropsProp } = {}, onOpen, open, PaperProps, swipeAreaWidth, variant, ...other } = this.props; const { maybeSwiping } = this.state; return ( <Drawer open={variant === 'temporary' && maybeSwiping ? true : open} variant={variant} ModalProps={{ BackdropProps: { ...BackdropProps, ref: this.handleBackdropRef, }, ...ModalPropsProp, }} PaperProps={{ ...PaperProps, ref: this.handlePaperRef, }} {...other} /> ); } } SwipeableDrawer.propTypes = { /** * @ignore */ anchor: PropTypes.oneOf(['left', 'top', 'right', 'bottom']), /** * Disable the backdrop transition. * This can improve the FPS on low-end devices. */ disableBackdropTransition: PropTypes.bool, /** * If `true`, touching the screen near the edge of the drawer will not slide in the drawer a bit * to promote accidental discovery of the swipe gesture. */ disableDiscovery: PropTypes.bool, /** * @ignore */ ModalProps: PropTypes.object, /** * Callback fired when the component requests to be closed. * * @param {object} event The event source of the callback */ onClose: PropTypes.func.isRequired, /** * Callback fired when the component requests to be opened. * * @param {object} event The event source of the callback */ onOpen: PropTypes.func.isRequired, /** * If `true`, the drawer is open. */ open: PropTypes.bool.isRequired, /** * @ignore */ PaperProps: PropTypes.object, /** * The width of the left most (or right most) area in pixels where the * drawer can be swiped open from. */ swipeAreaWidth: PropTypes.number, /** * @ignore */ theme: PropTypes.object.isRequired, /** * The duration for the transition, in milliseconds. * You may specify a single timeout for all transitions, or individually with an object. */ transitionDuration: PropTypes.oneOfType([ PropTypes.number, PropTypes.shape({ enter: PropTypes.number, exit: PropTypes.number }), ]), /** * @ignore */ variant: PropTypes.oneOf(['permanent', 'persistent', 'temporary']), }; SwipeableDrawer.defaultProps = { anchor: 'left', disableBackdropTransition: false, disableDiscovery: false, swipeAreaWidth: 20, transitionDuration: { enter: duration.enteringScreen, exit: duration.leavingScreen }, variant: 'temporary', // Mobile first. }; export default withTheme()(SwipeableDrawer);
src/SwipeableDrawer/SwipeableDrawer.js
1
https://github.com/mui/material-ui/commit/5d126e65e30f7541e34b0c12bd68fa0c31ae71fa
[ 0.01663878932595253, 0.0016927928663790226, 0.0001610161707503721, 0.00017504033166915178, 0.003532132599502802 ]
{ "id": 6, "code_window": [ " assert.strictEqual(instance.isSwiping, 'closing', 'should be closing');\n", " fireBodyMouseEvent('touchend', { changedTouches: [params.closeTouches[1]] });\n", " assert.strictEqual(handleClose.callCount, 0, 'should not call onClose');\n", " });\n", "\n", " it('should not start swiping when swiping in the wrong direction', () => {\n", " fireBodyMouseEvent('touchstart', { touches: [params.openTouches[0]] });\n", " if (['left', 'right'].includes(params.anchor)) {\n", " fireBodyMouseEvent('touchmove', {\n", " touches: [\n", " {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " it('should ignore swiping in the wrong direction if discovery is disabled', () => {\n", " wrapper.setProps({ disableDiscovery: true });\n", "\n" ], "file_path": "src/SwipeableDrawer/SwipeableDrawer.spec.js", "type": "replace", "edit_start_line_idx": 206 }
import React from 'react'; import PropTypes from 'prop-types'; import { withStyles } from 'material-ui/styles'; import ExpansionPanel, { ExpansionPanelDetails, ExpansionPanelSummary, } from 'material-ui/ExpansionPanel'; import Typography from 'material-ui/Typography'; import ExpandMoreIcon from 'material-ui-icons/ExpandMore'; const styles = theme => ({ root: { flexGrow: 1, }, heading: { fontSize: theme.typography.pxToRem(15), flexBasis: '33.33%', flexShrink: 0, }, secondaryHeading: { fontSize: theme.typography.pxToRem(15), color: theme.palette.text.secondary, }, }); class ControlledExpansionPanels extends React.Component { state = { expanded: null, }; handleChange = panel => (event, expanded) => { this.setState({ expanded: expanded ? panel : false, }); }; render() { const { classes } = this.props; const { expanded } = this.state; return ( <div className={classes.root}> <ExpansionPanel expanded={expanded === 'panel1'} onChange={this.handleChange('panel1')}> <ExpansionPanelSummary expandIcon={<ExpandMoreIcon />}> <Typography className={classes.heading}>General settings</Typography> <Typography className={classes.secondaryHeading}>I am an expansion panel</Typography> </ExpansionPanelSummary> <ExpansionPanelDetails> <Typography> Nulla facilisi. Phasellus sollicitudin nulla et quam mattis feugiat. Aliquam eget maximus est, id dignissim quam. </Typography> </ExpansionPanelDetails> </ExpansionPanel> <ExpansionPanel expanded={expanded === 'panel2'} onChange={this.handleChange('panel2')}> <ExpansionPanelSummary expandIcon={<ExpandMoreIcon />}> <Typography className={classes.heading}>Users</Typography> <Typography className={classes.secondaryHeading}> You are currently not an owner </Typography> </ExpansionPanelSummary> <ExpansionPanelDetails> <Typography> Donec placerat, lectus sed mattis semper, neque lectus feugiat lectus, varius pulvinar diam eros in elit. Pellentesque convallis laoreet laoreet. </Typography> </ExpansionPanelDetails> </ExpansionPanel> <ExpansionPanel expanded={expanded === 'panel3'} onChange={this.handleChange('panel3')}> <ExpansionPanelSummary expandIcon={<ExpandMoreIcon />}> <Typography className={classes.heading}>Advanced settings</Typography> <Typography className={classes.secondaryHeading}> Filtering has been entirely disabled for whole web server </Typography> </ExpansionPanelSummary> <ExpansionPanelDetails> <Typography> Nunc vitae orci ultricies, auctor nunc in, volutpat nisl. Integer sit amet egestas eros, vitae egestas augue. Duis vel est augue. </Typography> </ExpansionPanelDetails> </ExpansionPanel> </div> ); } } ControlledExpansionPanels.propTypes = { classes: PropTypes.object.isRequired, }; export default withStyles(styles)(ControlledExpansionPanels);
docs/src/pages/demos/expansion-panels/ControlledExpansionPanels.js
0
https://github.com/mui/material-ui/commit/5d126e65e30f7541e34b0c12bd68fa0c31ae71fa
[ 0.00017497157386969775, 0.00016888053505681455, 0.0001628739555599168, 0.00016858763410709798, 0.0000036889466628053924 ]
{ "id": 6, "code_window": [ " assert.strictEqual(instance.isSwiping, 'closing', 'should be closing');\n", " fireBodyMouseEvent('touchend', { changedTouches: [params.closeTouches[1]] });\n", " assert.strictEqual(handleClose.callCount, 0, 'should not call onClose');\n", " });\n", "\n", " it('should not start swiping when swiping in the wrong direction', () => {\n", " fireBodyMouseEvent('touchstart', { touches: [params.openTouches[0]] });\n", " if (['left', 'right'].includes(params.anchor)) {\n", " fireBodyMouseEvent('touchmove', {\n", " touches: [\n", " {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " it('should ignore swiping in the wrong direction if discovery is disabled', () => {\n", " wrapper.setProps({ disableDiscovery: true });\n", "\n" ], "file_path": "src/SwipeableDrawer/SwipeableDrawer.spec.js", "type": "replace", "edit_start_line_idx": 206 }
export { default } from './AppBar'; export * from './AppBar';
src/AppBar/index.d.ts
0
https://github.com/mui/material-ui/commit/5d126e65e30f7541e34b0c12bd68fa0c31ae71fa
[ 0.0001689279597485438, 0.0001689279597485438, 0.0001689279597485438, 0.0001689279597485438, 0 ]
{ "id": 6, "code_window": [ " assert.strictEqual(instance.isSwiping, 'closing', 'should be closing');\n", " fireBodyMouseEvent('touchend', { changedTouches: [params.closeTouches[1]] });\n", " assert.strictEqual(handleClose.callCount, 0, 'should not call onClose');\n", " });\n", "\n", " it('should not start swiping when swiping in the wrong direction', () => {\n", " fireBodyMouseEvent('touchstart', { touches: [params.openTouches[0]] });\n", " if (['left', 'right'].includes(params.anchor)) {\n", " fireBodyMouseEvent('touchmove', {\n", " touches: [\n", " {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " it('should ignore swiping in the wrong direction if discovery is disabled', () => {\n", " wrapper.setProps({ disableDiscovery: true });\n", "\n" ], "file_path": "src/SwipeableDrawer/SwipeableDrawer.spec.js", "type": "replace", "edit_start_line_idx": 206 }
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; const SvgIconCustom = global.__MUI_SvgIcon__ || SvgIcon; let PlayCircleFilled = props => <SvgIconCustom {...props}> <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 14.5v-9l6 4.5-6 4.5z" /> </SvgIconCustom>; PlayCircleFilled = pure(PlayCircleFilled); PlayCircleFilled.muiName = 'SvgIcon'; export default PlayCircleFilled;
packages/material-ui-icons/src/PlayCircleFilled.js
0
https://github.com/mui/material-ui/commit/5d126e65e30f7541e34b0c12bd68fa0c31ae71fa
[ 0.00017310056136921048, 0.00017188148922286928, 0.00017066240252461284, 0.00017188148922286928, 0.0000012190794222988188 ]
{ "id": 0, "code_window": [ " delete global[key];\n", " }\n", "\n", " const filterArgIndex = process.argv.indexOf('--filter');\n", " if (filterArgIndex !== -1) {\n", " const filter = process.argv[filterArgIndex + 1];\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " return testRunner;\n", "}\n", "\n", "module.exports = collect;\n", "\n", "if (require.main === module) {\n", " console.log('Testing on Node', process.version);\n", " const browserNames = ['chromium', 'firefox', 'webkit'].filter(name => {\n", " return process.env.BROWSER === name || process.env.BROWSER === 'all';\n", " });\n", " const testRunner = collect(browserNames);\n", "\n" ], "file_path": "test/test.js", "type": "add", "edit_start_line_idx": 192 }
/** * Copyright 2017 Google Inc. All rights reserved. * Modifications copyright (c) Microsoft Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ const fs = require('fs'); const readline = require('readline'); const TestRunner = require('../utils/testrunner/'); const {Environment} = require('../utils/testrunner/Test'); function collect(browserNames) { let parallel = 1; if (process.env.PW_PARALLEL_TESTS) parallel = parseInt(process.env.PW_PARALLEL_TESTS.trim(), 10); const parallelArgIndex = process.argv.indexOf('-j'); if (parallelArgIndex !== -1) parallel = parseInt(process.argv[parallelArgIndex + 1], 10); require('events').defaultMaxListeners *= parallel; let timeout = process.env.CI ? 30 * 1000 : 10 * 1000; if (!isNaN(process.env.TIMEOUT)) timeout = parseInt(process.env.TIMEOUT * 1000, 10); const MAJOR_NODEJS_VERSION = parseInt(process.version.substring(1).split('.')[0], 10); if (MAJOR_NODEJS_VERSION >= 8 && require('inspector').url()) { console.log('Detected inspector - disabling timeout to be debugger-friendly'); timeout = 0; } const config = require('./test.config'); const testRunner = new TestRunner({ timeout, totalTimeout: process.env.CI ? 30 * 60 * 1000 : 0, // 30 minutes on CI parallel, breakOnFailure: process.argv.indexOf('--break-on-failure') !== -1, verbose: process.argv.includes('--verbose'), summary: !process.argv.includes('--verbose'), showSlowTests: process.env.CI ? 5 : 0, showMarkedAsFailingTests: 10, }); if (config.setupTestRunner) config.setupTestRunner(testRunner); for (const [key, value] of Object.entries(testRunner.api())) global[key] = value; // TODO: this should be a preinstalled playwright by default. const playwrightPath = config.playwrightPath; const playwright = require(playwrightPath); const playwrightEnvironment = new Environment('Playwright'); playwrightEnvironment.beforeAll(async state => { state.playwright = playwright; global.playwright = playwright; }); playwrightEnvironment.afterAll(async state => { delete state.playwright; delete global.playwright; }); testRunner.collector().useEnvironment(playwrightEnvironment); for (const e of config.globalEnvironments || []) testRunner.collector().useEnvironment(e); for (const browserName of browserNames) { const browserType = playwright[browserName]; const browserTypeEnvironment = new Environment('BrowserType'); browserTypeEnvironment.beforeAll(async state => { state.browserType = browserType; }); browserTypeEnvironment.afterAll(async state => { delete state.browserType; }); // TODO: maybe launch options per browser? const launchOptions = { ...(config.launchOptions || {}), handleSIGINT: false, }; if (launchOptions.executablePath) launchOptions.executablePath = launchOptions.executablePath[browserName]; if (launchOptions.executablePath) { const YELLOW_COLOR = '\x1b[33m'; const RESET_COLOR = '\x1b[0m'; console.warn(`${YELLOW_COLOR}WARN: running ${browserName} tests with ${launchOptions.executablePath}${RESET_COLOR}`); browserType._executablePath = launchOptions.executablePath; delete launchOptions.executablePath; } else { if (!fs.existsSync(browserType.executablePath())) throw new Error(`Browser is not downloaded. Run 'npm install' and try to re-run tests`); } const browserEnvironment = new Environment(browserName); browserEnvironment.beforeAll(async state => { state._logger = null; state.browser = await state.browserType.launch({...launchOptions, logger: { isEnabled: (name, severity) => { return name === 'browser' || (name === 'protocol' && config.dumpProtocolOnFailure); }, log: (name, severity, message, args) => { if (state._logger) state._logger(name, severity, message); } }}); }); browserEnvironment.afterAll(async state => { await state.browser.close(); delete state.browser; delete state._logger; }); browserEnvironment.beforeEach(async(state, testRun) => { state._logger = (name, severity, message) => { if (name === 'browser') { if (severity === 'warning') testRun.log(`\x1b[31m[browser]\x1b[0m ${message}`) else testRun.log(`\x1b[33m[browser]\x1b[0m ${message}`) } else if (name === 'protocol' && config.dumpProtocolOnFailure) { testRun.log(`\x1b[32m[protocol]\x1b[0m ${message}`) } } }); browserEnvironment.afterEach(async (state, testRun) => { state._logger = null; if (config.dumpProtocolOnFailure) { if (testRun.ok()) testRun.output().splice(0); } }); const pageEnvironment = new Environment('Page'); pageEnvironment.beforeEach(async state => { state.context = await state.browser.newContext(); state.page = await state.context.newPage(); }); pageEnvironment.afterEach(async state => { await state.context.close(); state.context = null; state.page = null; }); const suiteName = { 'chromium': 'Chromium', 'firefox': 'Firefox', 'webkit': 'WebKit' }[browserName]; describe(suiteName, () => { // In addition to state, expose these two on global so that describes can access them. global.playwright = playwright; global.browserType = browserType; testRunner.collector().useEnvironment(browserTypeEnvironment); for (const spec of config.specs || []) { const skip = spec.browsers && !spec.browsers.includes(browserName); (skip ? xdescribe : describe)(spec.title || '', () => { for (const e of spec.environments || ['page']) { if (e === 'browser') { testRunner.collector().useEnvironment(browserEnvironment); } else if (e === 'page') { testRunner.collector().useEnvironment(browserEnvironment); testRunner.collector().useEnvironment(pageEnvironment); } else { testRunner.collector().useEnvironment(e); } } for (const file of spec.files || []) { require(file); delete require.cache[require.resolve(file)]; } }); } delete global.browserType; delete global.playwright; }); } for (const [key, value] of Object.entries(testRunner.api())) { // expect is used when running tests, while the rest of api is not. if (key !== 'expect') delete global[key]; } const filterArgIndex = process.argv.indexOf('--filter'); if (filterArgIndex !== -1) { const filter = process.argv[filterArgIndex + 1]; testRunner.focusMatchingTests(new RegExp(filter, 'i')); } const repeatArgIndex = process.argv.indexOf('--repeat'); if (repeatArgIndex !== -1) { const repeat = parseInt(process.argv[repeatArgIndex + 1], 10); if (!isNaN(repeat)) testRunner.repeatAll(repeat); } return testRunner; } module.exports = collect; if (require.main === module) { console.log('Testing on Node', process.version); const browserNames = ['chromium', 'firefox', 'webkit'].filter(name => { return process.env.BROWSER === name || process.env.BROWSER === 'all'; }); const testRunner = collect(browserNames); testRunner.run().then(() => { delete global.expect; }); }
test/test.js
1
https://github.com/microsoft/playwright/commit/2d68830411ead95c37631b73cd88d8a32b08dd38
[ 0.9979808926582336, 0.04635074362158775, 0.00016928867262322456, 0.00017784221563488245, 0.2076742798089981 ]
{ "id": 0, "code_window": [ " delete global[key];\n", " }\n", "\n", " const filterArgIndex = process.argv.indexOf('--filter');\n", " if (filterArgIndex !== -1) {\n", " const filter = process.argv[filterArgIndex + 1];\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " return testRunner;\n", "}\n", "\n", "module.exports = collect;\n", "\n", "if (require.main === module) {\n", " console.log('Testing on Node', process.version);\n", " const browserNames = ['chromium', 'firefox', 'webkit'].filter(name => {\n", " return process.env.BROWSER === name || process.env.BROWSER === 'all';\n", " });\n", " const testRunner = collect(browserNames);\n", "\n" ], "file_path": "test/test.js", "type": "add", "edit_start_line_idx": 192 }
/** * Copyright 2017 Google Inc. All rights reserved. * Modifications copyright (c) Microsoft Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import * as types from './types'; export const DeviceDescriptors: types.Devices = { 'Blackberry PlayBook': { 'userAgent': 'Mozilla/5.0 (PlayBook; U; RIM Tablet OS 2.1.0; en-US) AppleWebKit/536.2+ (KHTML like Gecko) Version/7.2.1.0 Safari/536.2+', 'viewport': { 'width': 600, 'height': 1024 }, 'deviceScaleFactor': 1, 'isMobile': true, 'hasTouch': true }, 'Blackberry PlayBook landscape': { 'userAgent': 'Mozilla/5.0 (PlayBook; U; RIM Tablet OS 2.1.0; en-US) AppleWebKit/536.2+ (KHTML like Gecko) Version/7.2.1.0 Safari/536.2+', 'viewport': { 'width': 1024, 'height': 600 }, 'deviceScaleFactor': 1, 'isMobile': true, 'hasTouch': true }, 'BlackBerry Z30': { 'userAgent': 'Mozilla/5.0 (BB10; Touch) AppleWebKit/537.10+ (KHTML, like Gecko) Version/10.0.9.2372 Mobile Safari/537.10+', 'viewport': { 'width': 360, 'height': 640 }, 'deviceScaleFactor': 2, 'isMobile': true, 'hasTouch': true }, 'BlackBerry Z30 landscape': { 'userAgent': 'Mozilla/5.0 (BB10; Touch) AppleWebKit/537.10+ (KHTML, like Gecko) Version/10.0.9.2372 Mobile Safari/537.10+', 'viewport': { 'width': 640, 'height': 360 }, 'deviceScaleFactor': 2, 'isMobile': true, 'hasTouch': true }, 'Galaxy Note 3': { 'userAgent': 'Mozilla/5.0 (Linux; U; Android 4.3; en-us; SM-N900T Build/JSS15J) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30', 'viewport': { 'width': 360, 'height': 640 }, 'deviceScaleFactor': 3, 'isMobile': true, 'hasTouch': true }, 'Galaxy Note 3 landscape': { 'userAgent': 'Mozilla/5.0 (Linux; U; Android 4.3; en-us; SM-N900T Build/JSS15J) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30', 'viewport': { 'width': 640, 'height': 360 }, 'deviceScaleFactor': 3, 'isMobile': true, 'hasTouch': true }, 'Galaxy Note II': { 'userAgent': 'Mozilla/5.0 (Linux; U; Android 4.1; en-us; GT-N7100 Build/JRO03C) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30', 'viewport': { 'width': 360, 'height': 640 }, 'deviceScaleFactor': 2, 'isMobile': true, 'hasTouch': true }, 'Galaxy Note II landscape': { 'userAgent': 'Mozilla/5.0 (Linux; U; Android 4.1; en-us; GT-N7100 Build/JRO03C) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30', 'viewport': { 'width': 640, 'height': 360 }, 'deviceScaleFactor': 2, 'isMobile': true, 'hasTouch': true }, 'Galaxy S III': { 'userAgent': 'Mozilla/5.0 (Linux; U; Android 4.0; en-us; GT-I9300 Build/IMM76D) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30', 'viewport': { 'width': 360, 'height': 640 }, 'deviceScaleFactor': 2, 'isMobile': true, 'hasTouch': true }, 'Galaxy S III landscape': { 'userAgent': 'Mozilla/5.0 (Linux; U; Android 4.0; en-us; GT-I9300 Build/IMM76D) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30', 'viewport': { 'width': 640, 'height': 360 }, 'deviceScaleFactor': 2, 'isMobile': true, 'hasTouch': true }, 'Galaxy S5': { 'userAgent': 'Mozilla/5.0 (Linux; Android 5.0; SM-G900P Build/LRX21T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36', 'viewport': { 'width': 360, 'height': 640 }, 'deviceScaleFactor': 3, 'isMobile': true, 'hasTouch': true }, 'Galaxy S5 landscape': { 'userAgent': 'Mozilla/5.0 (Linux; Android 5.0; SM-G900P Build/LRX21T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36', 'viewport': { 'width': 640, 'height': 360 }, 'deviceScaleFactor': 3, 'isMobile': true, 'hasTouch': true }, 'iPad (gen 6)': { 'userAgent': 'Mozilla/5.0 (iPad; CPU OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0 Mobile/15E148 Safari/604.1', 'viewport': { 'width': 768, 'height': 1024 }, 'deviceScaleFactor': 2, 'isMobile': true, 'hasTouch': true }, 'iPad (gen 6) landscape': { 'userAgent': 'Mozilla/5.0 (iPad; CPU OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0 Mobile/15E148 Safari/604.1', 'viewport': { 'width': 1024, 'height': 768 }, 'deviceScaleFactor': 2, 'isMobile': true, 'hasTouch': true }, 'iPad (gen 7)': { 'userAgent': 'Mozilla/5.0 (iPad; CPU OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0 Mobile/15E148 Safari/604.1', 'viewport': { 'width': 810, 'height': 1080 }, 'deviceScaleFactor': 2, 'isMobile': true, 'hasTouch': true }, 'iPad (gen 7) landscape': { 'userAgent': 'Mozilla/5.0 (iPad; CPU OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0 Mobile/15E148 Safari/604.1', 'viewport': { 'width': 1080, 'height': 810 }, 'deviceScaleFactor': 2, 'isMobile': true, 'hasTouch': true }, 'iPad Mini': { 'userAgent': 'Mozilla/5.0 (iPad; CPU OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0 Mobile/15E148 Safari/604.1', 'viewport': { 'width': 768, 'height': 1024 }, 'deviceScaleFactor': 2, 'isMobile': true, 'hasTouch': true }, 'iPad Mini landscape': { 'userAgent': 'Mozilla/5.0 (iPad; CPU OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0 Mobile/15E148 Safari/604.1', 'viewport': { 'width': 1024, 'height': 768 }, 'deviceScaleFactor': 2, 'isMobile': true, 'hasTouch': true }, 'iPad Pro 11': { 'userAgent': 'Mozilla/5.0 (iPad; CPU OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0 Mobile/15E148 Safari/604.1', 'viewport': { 'width': 834, 'height': 1194 }, 'deviceScaleFactor': 2, 'isMobile': true, 'hasTouch': true }, 'iPad Pro 11 landscape': { 'userAgent': 'Mozilla/5.0 (iPad; CPU OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0 Mobile/15E148 Safari/604.1', 'viewport': { 'width': 1194, 'height': 834 }, 'deviceScaleFactor': 2, 'isMobile': true, 'hasTouch': true }, 'iPhone 6': { 'userAgent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1', 'viewport': { 'width': 375, 'height': 667 }, 'deviceScaleFactor': 2, 'isMobile': true, 'hasTouch': true }, 'iPhone 6 landscape': { 'userAgent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1', 'viewport': { 'width': 667, 'height': 375 }, 'deviceScaleFactor': 2, 'isMobile': true, 'hasTouch': true }, 'iPhone 6 Plus': { 'userAgent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1', 'viewport': { 'width': 414, 'height': 736 }, 'deviceScaleFactor': 3, 'isMobile': true, 'hasTouch': true }, 'iPhone 6 Plus landscape': { 'userAgent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1', 'viewport': { 'width': 736, 'height': 414 }, 'deviceScaleFactor': 3, 'isMobile': true, 'hasTouch': true }, 'iPhone 7': { 'userAgent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1', 'viewport': { 'width': 375, 'height': 667 }, 'deviceScaleFactor': 2, 'isMobile': true, 'hasTouch': true }, 'iPhone 7 landscape': { 'userAgent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1', 'viewport': { 'width': 667, 'height': 375 }, 'deviceScaleFactor': 2, 'isMobile': true, 'hasTouch': true }, 'iPhone 7 Plus': { 'userAgent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1', 'viewport': { 'width': 414, 'height': 736 }, 'deviceScaleFactor': 3, 'isMobile': true, 'hasTouch': true }, 'iPhone 7 Plus landscape': { 'userAgent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1', 'viewport': { 'width': 736, 'height': 414 }, 'deviceScaleFactor': 3, 'isMobile': true, 'hasTouch': true }, 'iPhone 8': { 'userAgent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1', 'viewport': { 'width': 375, 'height': 667 }, 'deviceScaleFactor': 2, 'isMobile': true, 'hasTouch': true }, 'iPhone 8 landscape': { 'userAgent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1', 'viewport': { 'width': 667, 'height': 375 }, 'deviceScaleFactor': 2, 'isMobile': true, 'hasTouch': true }, 'iPhone 8 Plus': { 'userAgent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1', 'viewport': { 'width': 414, 'height': 736 }, 'deviceScaleFactor': 3, 'isMobile': true, 'hasTouch': true }, 'iPhone 8 Plus landscape': { 'userAgent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1', 'viewport': { 'width': 736, 'height': 414 }, 'deviceScaleFactor': 3, 'isMobile': true, 'hasTouch': true }, 'iPhone SE': { 'userAgent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.0 Mobile/14E304 Safari/602.1', 'viewport': { 'width': 320, 'height': 568 }, 'deviceScaleFactor': 2, 'isMobile': true, 'hasTouch': true }, 'iPhone SE landscape': { 'userAgent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.0 Mobile/14E304 Safari/602.1', 'viewport': { 'width': 568, 'height': 320 }, 'deviceScaleFactor': 2, 'isMobile': true, 'hasTouch': true }, 'iPhone X': { 'userAgent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1', 'viewport': { 'width': 375, 'height': 812 }, 'deviceScaleFactor': 3, 'isMobile': true, 'hasTouch': true }, 'iPhone X landscape': { 'userAgent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1', 'viewport': { 'width': 812, 'height': 375 }, 'deviceScaleFactor': 3, 'isMobile': true, 'hasTouch': true }, 'iPhone XR': { 'userAgent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 12_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0 Mobile/15E148 Safari/604.1', 'viewport': { 'width': 414, 'height': 896 }, 'deviceScaleFactor': 3, 'isMobile': true, 'hasTouch': true }, 'iPhone XR landscape': { 'userAgent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 12_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0 Mobile/15E148 Safari/604.1', 'viewport': { 'width': 896, 'height': 414 }, 'deviceScaleFactor': 3, 'isMobile': true, 'hasTouch': true }, 'iPhone 11': { 'userAgent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0 Mobile/15E148 Safari/604.1', 'viewport': { 'width': 414, 'height': 896 }, 'deviceScaleFactor': 2, 'isMobile': true, 'hasTouch': true }, 'iPhone 11 landscape': { 'userAgent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0 Mobile/15E148 Safari/604.1', 'viewport': { 'width': 896, 'height': 414 }, 'deviceScaleFactor': 2, 'isMobile': true, 'hasTouch': true }, 'iPhone 11 Pro': { 'userAgent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0 Mobile/15E148 Safari/604.1', 'viewport': { 'width': 375, 'height': 812 }, 'deviceScaleFactor': 3, 'isMobile': true, 'hasTouch': true }, 'iPhone 11 Pro landscape': { 'userAgent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0 Mobile/15E148 Safari/604.1', 'viewport': { 'width': 812, 'height': 375 }, 'deviceScaleFactor': 3, 'isMobile': true, 'hasTouch': true }, 'iPhone 11 Pro Max': { 'userAgent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0 Mobile/15E148 Safari/604.1', 'viewport': { 'width': 414, 'height': 896 }, 'deviceScaleFactor': 3, 'isMobile': true, 'hasTouch': true }, 'iPhone 11 Pro Max landscape': { 'userAgent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0 Mobile/15E148 Safari/604.1', 'viewport': { 'width': 896, 'height': 414 }, 'deviceScaleFactor': 3, 'isMobile': true, 'hasTouch': true }, 'JioPhone 2': { 'userAgent': 'Mozilla/5.0 (Mobile; LYF/F300B/LYF-F300B-001-01-15-130718-i;Android; rv:48.0) Gecko/48.0 Firefox/48.0 KAIOS/2.5', 'viewport': { 'width': 240, 'height': 320 }, 'deviceScaleFactor': 1, 'isMobile': true, 'hasTouch': true }, 'JioPhone 2 landscape': { 'userAgent': 'Mozilla/5.0 (Mobile; LYF/F300B/LYF-F300B-001-01-15-130718-i;Android; rv:48.0) Gecko/48.0 Firefox/48.0 KAIOS/2.5', 'viewport': { 'width': 320, 'height': 240 }, 'deviceScaleFactor': 1, 'isMobile': true, 'hasTouch': true }, 'Kindle Fire HDX': { 'userAgent': 'Mozilla/5.0 (Linux; U; en-us; KFAPWI Build/JDQ39) AppleWebKit/535.19 (KHTML, like Gecko) Silk/3.13 Safari/535.19 Silk-Accelerated=true', 'viewport': { 'width': 800, 'height': 1280 }, 'deviceScaleFactor': 2, 'isMobile': true, 'hasTouch': true }, 'Kindle Fire HDX landscape': { 'userAgent': 'Mozilla/5.0 (Linux; U; en-us; KFAPWI Build/JDQ39) AppleWebKit/535.19 (KHTML, like Gecko) Silk/3.13 Safari/535.19 Silk-Accelerated=true', 'viewport': { 'width': 1280, 'height': 800 }, 'deviceScaleFactor': 2, 'isMobile': true, 'hasTouch': true }, 'LG Optimus L70': { 'userAgent': 'Mozilla/5.0 (Linux; U; Android 4.4.2; en-us; LGMS323 Build/KOT49I.MS32310c) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/75.0.3765.0 Mobile Safari/537.36', 'viewport': { 'width': 384, 'height': 640 }, 'deviceScaleFactor': 1.25, 'isMobile': true, 'hasTouch': true }, 'LG Optimus L70 landscape': { 'userAgent': 'Mozilla/5.0 (Linux; U; Android 4.4.2; en-us; LGMS323 Build/KOT49I.MS32310c) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/75.0.3765.0 Mobile Safari/537.36', 'viewport': { 'width': 640, 'height': 384 }, 'deviceScaleFactor': 1.25, 'isMobile': true, 'hasTouch': true }, 'Microsoft Lumia 550': { 'userAgent': 'Mozilla/5.0 (Windows Phone 10.0; Android 4.2.1; Microsoft; Lumia 550) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2486.0 Mobile Safari/537.36 Edge/14.14263', 'viewport': { 'width': 640, 'height': 360 }, 'deviceScaleFactor': 2, 'isMobile': true, 'hasTouch': true }, 'Microsoft Lumia 550 landscape': { 'userAgent': 'Mozilla/5.0 (Windows Phone 10.0; Android 4.2.1; Microsoft; Lumia 550) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2486.0 Mobile Safari/537.36 Edge/14.14263', 'viewport': { 'width': 360, 'height': 640 }, 'deviceScaleFactor': 2, 'isMobile': true, 'hasTouch': true }, 'Microsoft Lumia 950': { 'userAgent': 'Mozilla/5.0 (Windows Phone 10.0; Android 4.2.1; Microsoft; Lumia 950) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2486.0 Mobile Safari/537.36 Edge/14.14263', 'viewport': { 'width': 360, 'height': 640 }, 'deviceScaleFactor': 4, 'isMobile': true, 'hasTouch': true }, 'Microsoft Lumia 950 landscape': { 'userAgent': 'Mozilla/5.0 (Windows Phone 10.0; Android 4.2.1; Microsoft; Lumia 950) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2486.0 Mobile Safari/537.36 Edge/14.14263', 'viewport': { 'width': 640, 'height': 360 }, 'deviceScaleFactor': 4, 'isMobile': true, 'hasTouch': true }, 'Nexus 10': { 'userAgent': 'Mozilla/5.0 (Linux; Android 6.0.1; Nexus 10 Build/MOB31T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Safari/537.36', 'viewport': { 'width': 800, 'height': 1280 }, 'deviceScaleFactor': 2, 'isMobile': true, 'hasTouch': true }, 'Nexus 10 landscape': { 'userAgent': 'Mozilla/5.0 (Linux; Android 6.0.1; Nexus 10 Build/MOB31T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Safari/537.36', 'viewport': { 'width': 1280, 'height': 800 }, 'deviceScaleFactor': 2, 'isMobile': true, 'hasTouch': true }, 'Nexus 4': { 'userAgent': 'Mozilla/5.0 (Linux; Android 4.4.2; Nexus 4 Build/KOT49H) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36', 'viewport': { 'width': 384, 'height': 640 }, 'deviceScaleFactor': 2, 'isMobile': true, 'hasTouch': true }, 'Nexus 4 landscape': { 'userAgent': 'Mozilla/5.0 (Linux; Android 4.4.2; Nexus 4 Build/KOT49H) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36', 'viewport': { 'width': 640, 'height': 384 }, 'deviceScaleFactor': 2, 'isMobile': true, 'hasTouch': true }, 'Nexus 5': { 'userAgent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36', 'viewport': { 'width': 360, 'height': 640 }, 'deviceScaleFactor': 3, 'isMobile': true, 'hasTouch': true }, 'Nexus 5 landscape': { 'userAgent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36', 'viewport': { 'width': 640, 'height': 360 }, 'deviceScaleFactor': 3, 'isMobile': true, 'hasTouch': true }, 'Nexus 5X': { 'userAgent': 'Mozilla/5.0 (Linux; Android 8.0.0; Nexus 5X Build/OPR4.170623.006) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36', 'viewport': { 'width': 412, 'height': 732 }, 'deviceScaleFactor': 2.625, 'isMobile': true, 'hasTouch': true }, 'Nexus 5X landscape': { 'userAgent': 'Mozilla/5.0 (Linux; Android 8.0.0; Nexus 5X Build/OPR4.170623.006) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36', 'viewport': { 'width': 732, 'height': 412 }, 'deviceScaleFactor': 2.625, 'isMobile': true, 'hasTouch': true }, 'Nexus 6': { 'userAgent': 'Mozilla/5.0 (Linux; Android 7.1.1; Nexus 6 Build/N6F26U) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36', 'viewport': { 'width': 412, 'height': 732 }, 'deviceScaleFactor': 3.5, 'isMobile': true, 'hasTouch': true }, 'Nexus 6 landscape': { 'userAgent': 'Mozilla/5.0 (Linux; Android 7.1.1; Nexus 6 Build/N6F26U) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36', 'viewport': { 'width': 732, 'height': 412 }, 'deviceScaleFactor': 3.5, 'isMobile': true, 'hasTouch': true }, 'Nexus 6P': { 'userAgent': 'Mozilla/5.0 (Linux; Android 8.0.0; Nexus 6P Build/OPP3.170518.006) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36', 'viewport': { 'width': 412, 'height': 732 }, 'deviceScaleFactor': 3.5, 'isMobile': true, 'hasTouch': true }, 'Nexus 6P landscape': { 'userAgent': 'Mozilla/5.0 (Linux; Android 8.0.0; Nexus 6P Build/OPP3.170518.006) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36', 'viewport': { 'width': 732, 'height': 412 }, 'deviceScaleFactor': 3.5, 'isMobile': true, 'hasTouch': true }, 'Nexus 7': { 'userAgent': 'Mozilla/5.0 (Linux; Android 6.0.1; Nexus 7 Build/MOB30X) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Safari/537.36', 'viewport': { 'width': 600, 'height': 960 }, 'deviceScaleFactor': 2, 'isMobile': true, 'hasTouch': true }, 'Nexus 7 landscape': { 'userAgent': 'Mozilla/5.0 (Linux; Android 6.0.1; Nexus 7 Build/MOB30X) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Safari/537.36', 'viewport': { 'width': 960, 'height': 600 }, 'deviceScaleFactor': 2, 'isMobile': true, 'hasTouch': true }, 'Nokia Lumia 520': { 'userAgent': 'Mozilla/5.0 (compatible; MSIE 10.0; Windows Phone 8.0; Trident/6.0; IEMobile/10.0; ARM; Touch; NOKIA; Lumia 520)', 'viewport': { 'width': 320, 'height': 533 }, 'deviceScaleFactor': 1.5, 'isMobile': true, 'hasTouch': true }, 'Nokia Lumia 520 landscape': { 'userAgent': 'Mozilla/5.0 (compatible; MSIE 10.0; Windows Phone 8.0; Trident/6.0; IEMobile/10.0; ARM; Touch; NOKIA; Lumia 520)', 'viewport': { 'width': 533, 'height': 320 }, 'deviceScaleFactor': 1.5, 'isMobile': true, 'hasTouch': true }, 'Nokia N9': { 'userAgent': 'Mozilla/5.0 (MeeGo; NokiaN9) AppleWebKit/534.13 (KHTML, like Gecko) NokiaBrowser/8.5.0 Mobile Safari/534.13', 'viewport': { 'width': 480, 'height': 854 }, 'deviceScaleFactor': 1, 'isMobile': true, 'hasTouch': true }, 'Nokia N9 landscape': { 'userAgent': 'Mozilla/5.0 (MeeGo; NokiaN9) AppleWebKit/534.13 (KHTML, like Gecko) NokiaBrowser/8.5.0 Mobile Safari/534.13', 'viewport': { 'width': 854, 'height': 480 }, 'deviceScaleFactor': 1, 'isMobile': true, 'hasTouch': true }, 'Pixel 2': { 'userAgent': 'Mozilla/5.0 (Linux; Android 8.0; Pixel 2 Build/OPD3.170816.012) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36', 'viewport': { 'width': 411, 'height': 731 }, 'deviceScaleFactor': 2.625, 'isMobile': true, 'hasTouch': true }, 'Pixel 2 landscape': { 'userAgent': 'Mozilla/5.0 (Linux; Android 8.0; Pixel 2 Build/OPD3.170816.012) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36', 'viewport': { 'width': 731, 'height': 411 }, 'deviceScaleFactor': 2.625, 'isMobile': true, 'hasTouch': true }, 'Pixel 2 XL': { 'userAgent': 'Mozilla/5.0 (Linux; Android 8.0.0; Pixel 2 XL Build/OPD1.170816.004) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36', 'viewport': { 'width': 411, 'height': 823 }, 'deviceScaleFactor': 3.5, 'isMobile': true, 'hasTouch': true }, 'Pixel 2 XL landscape': { 'userAgent': 'Mozilla/5.0 (Linux; Android 8.0.0; Pixel 2 XL Build/OPD1.170816.004) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36', 'viewport': { 'width': 823, 'height': 411 }, 'deviceScaleFactor': 3.5, 'isMobile': true, 'hasTouch': true } };
src/deviceDescriptors.ts
0
https://github.com/microsoft/playwright/commit/2d68830411ead95c37631b73cd88d8a32b08dd38
[ 0.00017907116853166372, 0.00016846027574501932, 0.00016363157192245126, 0.00016869006503839046, 0.0000029160341910028365 ]
{ "id": 0, "code_window": [ " delete global[key];\n", " }\n", "\n", " const filterArgIndex = process.argv.indexOf('--filter');\n", " if (filterArgIndex !== -1) {\n", " const filter = process.argv[filterArgIndex + 1];\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " return testRunner;\n", "}\n", "\n", "module.exports = collect;\n", "\n", "if (require.main === module) {\n", " console.log('Testing on Node', process.version);\n", " const browserNames = ['chromium', 'firefox', 'webkit'].filter(name => {\n", " return process.env.BROWSER === name || process.env.BROWSER === 'all';\n", " });\n", " const testRunner = collect(browserNames);\n", "\n" ], "file_path": "test/test.js", "type": "add", "edit_start_line_idx": 192 }
/** * Copyright 2017 Google Inc. All rights reserved. * Modifications copyright (c) Microsoft Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // This file is only run when someone installs via the github repo const {execSync} = require('child_process'); const path = require('path'); const fs = require('fs'); const util = require('util'); const rmAsync = util.promisify(require('rimraf')); const existsAsync = path => fs.promises.access(path).then(() => true, e => false); (async () => { const SRC_FOLDER = path.join(__dirname, 'src'); const LIB_FOLDER = path.join(__dirname, 'lib'); const srcTypeScriptFiles = (await listFiles(path.join(__dirname, 'src'))).filter(filepath => filepath.toLowerCase().endsWith('.ts')); const outdatedFiles = await Promise.all(srcTypeScriptFiles.map(async srcFile => { const libFileTS = path.join(LIB_FOLDER, path.relative(SRC_FOLDER, srcFile)); const libFile = libFileTS.substring(0, libFileTS.lastIndexOf('.')) + '.js'; try { const [srcStat, libStat] = await Promise.all([fs.promises.stat(srcFile), fs.promises.stat(libFile)]); return srcStat.ctimeMs > libStat.ctimeMs; } catch (e) { // Either `.ts` of `.js` file is missing - rebuild is required. return true; } })); if (outdatedFiles.some(Boolean)) { console.log(`Rebuilding playwright...`); try { execSync('npm run build', { stdio: 'ignore' }); } catch (e) { } } await downloadAllBrowsersAndGenerateProtocolTypes(); })(); async function listFiles(dirpath) { const files = []; await dfs(dirpath); return files; async function dfs(dirpath) { const entries = await fs.promises.readdir(dirpath, {withFileTypes: true}); files.push(...entries.filter(entry => entry.isFile()).map(entry => path.join(dirpath, entry.name))); await Promise.all(entries.filter(entry => entry.isDirectory()).map(entry => dfs(path.join(dirpath, entry.name)))); } } async function downloadAllBrowsersAndGenerateProtocolTypes() { const {downloadBrowserWithProgressBar, localDownloadOptions} = require('./download-browser'); const protocolGenerator = require('./utils/protocol-types-generator'); const chromiumOptions = localDownloadOptions('chromium'); const firefoxOptions = localDownloadOptions('firefox'); const webkitOptions = localDownloadOptions('webkit'); if (!(await existsAsync(chromiumOptions.downloadPath))) { await downloadBrowserWithProgressBar(chromiumOptions); await protocolGenerator.generateChromiumProtocol(chromiumOptions.executablePath).catch(console.warn); } if (!(await existsAsync(firefoxOptions.downloadPath))) { await downloadBrowserWithProgressBar(firefoxOptions); await protocolGenerator.generateFirefoxProtocol(firefoxOptions.executablePath).catch(console.warn); } if (!(await existsAsync(webkitOptions.downloadPath))) { await downloadBrowserWithProgressBar(webkitOptions); await protocolGenerator.generateWebKitProtocol(webkitOptions.downloadPath).catch(console.warn); } // Cleanup stale revisions. const directories = new Set(await readdirAsync(path.join(__dirname, '.local-browsers'))); directories.delete(chromiumOptions.downloadPath); directories.delete(firefoxOptions.downloadPath); directories.delete(webkitOptions.downloadPath); // cleanup old browser directories. directories.add(path.join(__dirname, '.local-chromium')); directories.add(path.join(__dirname, '.local-firefox')); directories.add(path.join(__dirname, '.local-webkit')); await Promise.all([...directories].map(directory => rmAsync(directory))); try { console.log('Generating types...'); execSync('npm run generate-types'); } catch (e) { } async function readdirAsync(dirpath) { return fs.promises.readdir(dirpath).then(dirs => dirs.map(dir => path.join(dirpath, dir))); } }
install-from-github.js
0
https://github.com/microsoft/playwright/commit/2d68830411ead95c37631b73cd88d8a32b08dd38
[ 0.0005957562243565917, 0.00021584094793070108, 0.00016888012760318816, 0.00017709990788716823, 0.00012037964188493788 ]
{ "id": 0, "code_window": [ " delete global[key];\n", " }\n", "\n", " const filterArgIndex = process.argv.indexOf('--filter');\n", " if (filterArgIndex !== -1) {\n", " const filter = process.argv[filterArgIndex + 1];\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " return testRunner;\n", "}\n", "\n", "module.exports = collect;\n", "\n", "if (require.main === module) {\n", " console.log('Testing on Node', process.version);\n", " const browserNames = ['chromium', 'firefox', 'webkit'].filter(name => {\n", " return process.env.BROWSER === name || process.env.BROWSER === 'all';\n", " });\n", " const testRunner = collect(browserNames);\n", "\n" ], "file_path": "test/test.js", "type": "add", "edit_start_line_idx": 192 }
/** * Copyright 2018 Google Inc. All rights reserved. * Modifications copyright (c) Microsoft Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { helper, RegisteredListener } from '../helper'; import { ConnectionTransport, ProtocolRequest, ProtocolResponse } from '../transport'; import { logError, InnerLogger } from '../logger'; export class PipeTransport implements ConnectionTransport { private _pipeWrite: NodeJS.WritableStream | null; private _pendingMessage = ''; private _eventListeners: RegisteredListener[]; private _waitForNextTask = helper.makeWaitForNextTask(); onmessage?: (message: ProtocolResponse) => void; onclose?: () => void; constructor(pipeWrite: NodeJS.WritableStream, pipeRead: NodeJS.ReadableStream, logger: InnerLogger) { this._pipeWrite = pipeWrite; this._eventListeners = [ helper.addEventListener(pipeRead, 'data', buffer => this._dispatch(buffer)), helper.addEventListener(pipeRead, 'close', () => { helper.removeEventListeners(this._eventListeners); if (this.onclose) this.onclose.call(null); }), helper.addEventListener(pipeRead, 'error', logError(logger)), helper.addEventListener(pipeWrite, 'error', logError(logger)), ]; this.onmessage = undefined; this.onclose = undefined; } send(message: ProtocolRequest) { this._pipeWrite!.write(JSON.stringify(message)); this._pipeWrite!.write('\0'); } close() { throw new Error('unimplemented'); } _dispatch(buffer: Buffer) { let end = buffer.indexOf('\0'); if (end === -1) { this._pendingMessage += buffer.toString(); return; } const message = this._pendingMessage + buffer.toString(undefined, 0, end); this._waitForNextTask(() => { if (this.onmessage) this.onmessage.call(null, JSON.parse(message)); }); let start = end + 1; end = buffer.indexOf('\0', start); while (end !== -1) { const message = buffer.toString(undefined, start, end); this._waitForNextTask(() => { if (this.onmessage) this.onmessage.call(null, JSON.parse(message)); }); start = end + 1; end = buffer.indexOf('\0', start); } this._pendingMessage = buffer.toString(undefined, start); } }
src/server/pipeTransport.ts
0
https://github.com/microsoft/playwright/commit/2d68830411ead95c37631b73cd88d8a32b08dd38
[ 0.00017791350546758622, 0.00017203789320774376, 0.00016776994743850082, 0.0001693527738098055, 0.000003931028913939372 ]
{ "id": 1, "code_window": [ " const filterArgIndex = process.argv.indexOf('--filter');\n", " if (filterArgIndex !== -1) {\n", " const filter = process.argv[filterArgIndex + 1];\n", " testRunner.focusMatchingTests(new RegExp(filter, 'i'));\n", " }\n", "\n", " const repeatArgIndex = process.argv.indexOf('--repeat');\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " if (!testRunner.focusMatchingNameTests(new RegExp(filter, 'i')).length) {\n", " console.log('ERROR: no tests matched given `--filter` regex.');\n", " process.exit(1);\n", " }\n", " }\n", "\n", " const fileArgIndex = process.argv.indexOf('--file');\n", " if (fileArgIndex !== -1) {\n", " const filter = process.argv[fileArgIndex + 1];\n", " if (!testRunner.focusMatchingFilePath(new RegExp(filter, 'i')).length) {\n", " console.log('ERROR: no files matched given `--file` regex.');\n", " process.exit(1);\n", " }\n" ], "file_path": "test/test.js", "type": "replace", "edit_start_line_idx": 195 }
/** * Copyright 2017 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ const { TestRunner, Result, TestResult } = require('./TestRunner'); const { TestCollector, FocusedFilter, Repeater } = require('./TestCollector'); const Reporter = require('./Reporter'); const { Matchers } = require('./Matchers'); class DefaultTestRunner { constructor(options = {}) { const { // Our options. crashIfTestsAreFocusedOnCI = true, exit = true, reporter = true, // Collector options. timeout, // Runner options. parallel = 1, breakOnFailure, totalTimeout, hookTimeout = timeout, // Reporting options. showSlowTests, showMarkedAsFailingTests, verbose, summary, } = options; this._crashIfTestsAreFocusedOnCI = crashIfTestsAreFocusedOnCI; this._exit = exit; this._parallel = parallel; this._breakOnFailure = breakOnFailure; this._totalTimeout = totalTimeout; this._hookTimeout = hookTimeout; this._needReporter = reporter; this._showSlowTests = showSlowTests; this._showMarkedAsFailingTests = showMarkedAsFailingTests; this._verbose = verbose; this._summary = summary; this._filter = new FocusedFilter(); this._repeater = new Repeater(); this._collector = new TestCollector({ timeout }); this._api = { ...this._collector.api(), expect: new Matchers().expect, }; this._collector.addSuiteAttribute('only', s => this._filter.markFocused(s)); this._collector.addSuiteAttribute('skip', s => s.setSkipped(true)); this._collector.addSuiteModifier('repeat', (s, count) => this._repeater.repeat(s, count)); this._collector.addTestAttribute('only', t => this._filter.markFocused(t)); this._collector.addTestAttribute('skip', t => t.setSkipped(true)); this._collector.addTestAttribute('todo', t => t.setSkipped(true)); this._collector.addTestAttribute('slow', t => t.setTimeout(t.timeout() * 3)); this._collector.addTestModifier('repeat', (t, count) => this._repeater.repeat(t, count)); this._api.fdescribe = this._api.describe.only; this._api.xdescribe = this._api.describe.skip; this._api.fit = this._api.it.only; this._api.xit = this._api.it.skip; } collector() { return this._collector; } api() { return this._api; } focusMatchingTests(fullNameRegex) { for (const test of this._collector.tests()) { if (fullNameRegex.test(test.fullName())) this._filter.markFocused(test); } } repeatAll(repeatCount) { this._repeater.repeat(this._collector.rootSuite(), repeatCount); } async run() { let reporter = null; if (this._needReporter) { const reporterDelegate = { focusedSuites: () => this._filter.focusedTests(this._collector.suites()), focusedTests: () => this._filter.focusedSuites(this._collector.tests()), hasFocusedTestsOrSuites: () => this._filter.hasFocusedTestsOrSuites(), parallel: () => this._parallel, testCount: () => this._collector.tests().length, }; const reporterOptions = { showSlowTests: this._showSlowTests, showMarkedAsFailingTests: this._showMarkedAsFailingTests, verbose: this._verbose, summary: this._summary, }; reporter = new Reporter(reporterDelegate, reporterOptions); } if (this._crashIfTestsAreFocusedOnCI && process.env.CI && this._filter.hasFocusedTestsOrSuites()) { if (reporter) await reporter.onStarted([]); const result = new Result(); result.setResult(TestResult.Crashed, '"focused" tests or suites are probitted on CI'); if (reporter) await reporter.onFinished(result); if (this._exit) process.exit(result.exitCode); return result; } const testRuns = this._repeater.createTestRuns(this._filter.filter(this._collector.tests())); const testRunner = new TestRunner(); const result = await testRunner.run(testRuns, { parallel: this._parallel, breakOnFailure: this._breakOnFailure, totalTimeout: this._totalTimeout, hookTimeout: this._hookTimeout, onStarted: (...args) => reporter && reporter.onStarted(...args), onFinished: (...args) => reporter && reporter.onFinished(...args), onTestRunStarted: (...args) => reporter && reporter.onTestRunStarted(...args), onTestRunFinished: (...args) => reporter && reporter.onTestRunFinished(...args), }); if (this._exit) process.exit(result.exitCode); return result; } } module.exports = DefaultTestRunner;
utils/testrunner/index.js
1
https://github.com/microsoft/playwright/commit/2d68830411ead95c37631b73cd88d8a32b08dd38
[ 0.0032199337147176266, 0.0005593591486103833, 0.00016490105190314353, 0.0001772681571310386, 0.0009087418438866735 ]
{ "id": 1, "code_window": [ " const filterArgIndex = process.argv.indexOf('--filter');\n", " if (filterArgIndex !== -1) {\n", " const filter = process.argv[filterArgIndex + 1];\n", " testRunner.focusMatchingTests(new RegExp(filter, 'i'));\n", " }\n", "\n", " const repeatArgIndex = process.argv.indexOf('--repeat');\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " if (!testRunner.focusMatchingNameTests(new RegExp(filter, 'i')).length) {\n", " console.log('ERROR: no tests matched given `--filter` regex.');\n", " process.exit(1);\n", " }\n", " }\n", "\n", " const fileArgIndex = process.argv.indexOf('--file');\n", " if (fileArgIndex !== -1) {\n", " const filter = process.argv[fileArgIndex + 1];\n", " if (!testRunner.focusMatchingFilePath(new RegExp(filter, 'i')).length) {\n", " console.log('ERROR: no files matched given `--file` regex.');\n", " process.exit(1);\n", " }\n" ], "file_path": "test/test.js", "type": "replace", "edit_start_line_idx": 195 }
#!/bin/bash set -e set +x set -o pipefail if [[ ($1 == '--help') || ($1 == '-h') ]]; then echo "usage: $(basename $0) [firefox-linux|firefox-win32|firefox-win64|webkit-gtk|webkit-wpe|webkit-gtk-wpe|webkit-win64|webkit-mac-10.14|webkit-mac-10.15] [-f|--force]" echo echo "Prepares checkout under browser folder, applies patches, builds, archives, and uploads if build is missing." echo "Script will bail out early if the build for the browser version is already present." echo echo "Pass -f to upload anyway." echo echo "NOTE: This script is safe to run in a cronjob - it aquires a lock so that it does not run twice." exit 0 fi if [[ $# == 0 ]]; then echo "missing build flavor!" echo "try './$(basename $0) --help' for more information" exit 1 fi CURRENT_HOST_OS="$(uname)" CURRENT_HOST_OS_VERSION="" if [[ "$CURRENT_HOST_OS" == "Darwin" ]]; then CURRENT_HOST_OS_VERSION=$(sw_vers -productVersion | grep -o '^\d\+.\d\+') fi BROWSER_NAME="" EXTRA_BUILD_ARGS="" EXTRA_ARCHIVE_ARGS="" BUILD_FLAVOR="$1" BUILD_BLOB_NAME="" EXPECTED_HOST_OS="" EXPECTED_HOST_OS_VERSION="" if [[ "$BUILD_FLAVOR" == "firefox-linux" ]]; then BROWSER_NAME="firefox" EXPECTED_HOST_OS="Linux" BUILD_BLOB_NAME="firefox-linux.zip" elif [[ "$BUILD_FLAVOR" == "firefox-mac" ]]; then BROWSER_NAME="firefox" EXPECTED_HOST_OS="Darwin" EXPECTED_HOST_OS_VERSION="10.14" BUILD_BLOB_NAME="firefox-mac.zip" elif [[ "$BUILD_FLAVOR" == "firefox-win32" ]]; then BROWSER_NAME="firefox" EXPECTED_HOST_OS="MINGW" BUILD_BLOB_NAME="firefox-win32.zip" elif [[ "$BUILD_FLAVOR" == "firefox-win64" ]]; then BROWSER_NAME="firefox" EXTRA_BUILD_ARGS="--win64" EXPECTED_HOST_OS="MINGW" BUILD_BLOB_NAME="firefox-win64.zip" elif [[ "$BUILD_FLAVOR" == "webkit-gtk" ]]; then BROWSER_NAME="webkit" EXTRA_BUILD_ARGS="--gtk" EXTRA_ARCHIVE_ARGS="--gtk" EXPECTED_HOST_OS="Linux" BUILD_BLOB_NAME="minibrowser-gtk.zip" elif [[ "$BUILD_FLAVOR" == "webkit-wpe" ]]; then BROWSER_NAME="webkit" EXTRA_BUILD_ARGS="--wpe" EXTRA_ARCHIVE_ARGS="--wpe" EXPECTED_HOST_OS="Linux" BUILD_BLOB_NAME="minibrowser-wpe.zip" elif [[ "$BUILD_FLAVOR" == "webkit-gtk-wpe" ]]; then BROWSER_NAME="webkit" EXPECTED_HOST_OS="Linux" BUILD_BLOB_NAME="minibrowser-gtk-wpe.zip" elif [[ "$BUILD_FLAVOR" == "webkit-win64" ]]; then BROWSER_NAME="webkit" EXPECTED_HOST_OS="MINGW" BUILD_BLOB_NAME="minibrowser-win64.zip" elif [[ "$BUILD_FLAVOR" == "webkit-mac-10.14" ]]; then BROWSER_NAME="webkit" EXPECTED_HOST_OS="Darwin" EXPECTED_HOST_OS_VERSION="10.14" BUILD_BLOB_NAME="minibrowser-mac-10.14.zip" elif [[ "$BUILD_FLAVOR" == "webkit-mac-10.15" ]]; then BROWSER_NAME="webkit" EXPECTED_HOST_OS="Darwin" EXPECTED_HOST_OS_VERSION="10.15" BUILD_BLOB_NAME="minibrowser-mac-10.15.zip" else echo ERROR: unknown build flavor - "$BUILD_FLAVOR" exit 1 fi if [[ "$CURRENT_HOST_OS" != $EXPECTED_HOST_OS* ]]; then echo "ERROR: cannot build $BUILD_FLAVOR" echo " -- expected OS: $EXPECTED_HOST_OS" echo " -- current OS: $CURRENT_HOST_OS" exit 1 fi if [[ "$CURRENT_HOST_OS_VERSION" != "$EXPECTED_HOST_OS_VERSION" ]]; then echo "ERROR: cannot build $BUILD_FLAVOR" echo " -- expected OS Version: $EXPECTED_HOST_OS_VERSION" echo " -- current OS Version: $CURRENT_HOST_OS_VERSION" exit 1 fi if [[ $(uname) == MINGW* ]]; then ZIP_PATH="$PWD/archive-$BROWSER_NAME.zip" LOG_PATH="$PWD/log-$BROWSER_NAME.zip" else ZIP_PATH="/tmp/archive-$BROWSER_NAME.zip" LOG_PATH="/tmp/log-$BROWSER_NAME.zip" fi if [[ -f $ZIP_PATH ]]; then echo "Archive $ZIP_PATH already exists - remove and re-run the script." exit 1 fi trap "rm -rf ${ZIP_PATH}; rm -rf ${LOG_PATH}; cd $(pwd -P);" INT TERM EXIT cd "$(dirname "$0")" BUILD_NUMBER=$(cat ./$BROWSER_NAME/BUILD_NUMBER) BUILD_BLOB_PATH="${BROWSER_NAME}/${BUILD_NUMBER}/${BUILD_BLOB_NAME}" LOG_BLOB_NAME="${BUILD_BLOB_NAME%.zip}.log.gz" LOG_BLOB_PATH="${BROWSER_NAME}/${BUILD_NUMBER}/${LOG_BLOB_NAME}" # pull from upstream and check if a new build has to be uploaded. if ! [[ ($2 == '-f') || ($2 == '--force') ]]; then if ./upload.sh "${BUILD_BLOB_PATH}" --check; then echo "Build is already uploaded - no changes." exit 0 elif ./upload.sh "${LOG_BLOB_PATH}" --check; then echo "This build has already been attempted - skip building." exit 0 fi echo "Build is missing and has not been attempted - rebuilding" else echo "Force-rebuilding the build." fi function generate_and_upload_browser_build { # webkit-gtk-wpe is a special build doesn't need to be built. if [[ "$BUILD_FLAVOR" == "webkit-gtk-wpe" ]]; then echo "-- combining binaries together" if ! ./webkit/download_gtk_and_wpe_and_zip_together.sh $ZIP_PATH; then return 10 fi echo "-- uploading" if ! ./upload.sh $BUILD_BLOB_PATH $ZIP_PATH; then return 11 fi return 0 fi # Other browser flavors follow typical build flow. echo "-- preparing checkout" if ! ./prepare_checkout.sh $BROWSER_NAME; then return 20 fi echo "-- cleaning" if ! ./$BROWSER_NAME/clean.sh; then return 21 fi echo "-- building" if ! ./$BROWSER_NAME/build.sh "$EXTRA_BUILD_ARGS"; then return 22 fi echo "-- archiving to $ZIP_PATH" if ! ./$BROWSER_NAME/archive.sh $ZIP_PATH "$EXTRA_ARCHIVE_ARGS"; then return 23 fi echo "-- uploading" if ! ./upload.sh $BUILD_BLOB_PATH $ZIP_PATH; then return 24 fi return 0 } source ./buildbots/send_telegram_message.sh BUILD_ALIAS="$BUILD_FLAVOR r$BUILD_NUMBER" send_telegram_message "$BUILD_ALIAS -- started" if generate_and_upload_browser_build 2>&1 | ./sanitize_and_compress_log.js $LOG_PATH; then # Report successful build. Note: we don't know how to get zip size on MINGW. if [[ $(uname) == MINGW* ]]; then send_telegram_message "$BUILD_ALIAS -- uploaded" else UPLOAD_SIZE=$(du -h "$ZIP_PATH" | awk '{print $1}') send_telegram_message "$BUILD_ALIAS -- $UPLOAD_SIZE uploaded" fi # Check if we uploaded the last build. if ./tools/check_cdn.sh $BROWSER_NAME --has-all-builds; then LAST_COMMIT_MESSAGE=$(git log --format=%s -n 1 HEAD -- ./$BROWSER_NAME/BUILD_NUMBER) send_telegram_message "<b>$BROWSER_NAME r${BUILD_NUMBER} COMPLETE! ✅</b> $LAST_COMMIT_MESSAGE" fi else RESULT_CODE="$?" if (( RESULT_CODE == 10 )); then FAILED_STEP="./download_gtk_and_wpe_and_zip_together.sh" elif (( RESULT_CODE == 11 )); then FAILED_STEP="./upload.sh" elif (( RESULT_CODE == 20 )); then FAILED_STEP="./prepare_checkout.sh" elif (( RESULT_CODE == 21 )); then FAILED_STEP="./clean.sh" elif (( RESULT_CODE == 22 )); then FAILED_STEP="./build.sh" elif (( RESULT_CODE == 23 )); then FAILED_STEP="./archive.sh" elif (( RESULT_CODE == 24 )); then FAILED_STEP="./upload.sh" else FAILED_STEP="<unknown step>" fi # Upload logs only in case of failure and report failure. ./upload.sh ${LOG_BLOB_PATH} ${LOG_PATH} || true send_telegram_message "$BUILD_ALIAS -- ${FAILED_STEP} failed! ❌ <a href='https://playwright.azureedge.net/builds/${LOG_BLOB_PATH}'>${LOG_BLOB_NAME}</a>" fi
browser_patches/checkout_build_archive_upload.sh
0
https://github.com/microsoft/playwright/commit/2d68830411ead95c37631b73cd88d8a32b08dd38
[ 0.0001785004133125767, 0.00017251711688004434, 0.00016617086657788604, 0.00017282941553276032, 0.0000036061126138520194 ]
{ "id": 1, "code_window": [ " const filterArgIndex = process.argv.indexOf('--filter');\n", " if (filterArgIndex !== -1) {\n", " const filter = process.argv[filterArgIndex + 1];\n", " testRunner.focusMatchingTests(new RegExp(filter, 'i'));\n", " }\n", "\n", " const repeatArgIndex = process.argv.indexOf('--repeat');\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " if (!testRunner.focusMatchingNameTests(new RegExp(filter, 'i')).length) {\n", " console.log('ERROR: no tests matched given `--filter` regex.');\n", " process.exit(1);\n", " }\n", " }\n", "\n", " const fileArgIndex = process.argv.indexOf('--file');\n", " if (fileArgIndex !== -1) {\n", " const filter = process.argv[fileArgIndex + 1];\n", " if (!testRunner.focusMatchingFilePath(new RegExp(filter, 'i')).length) {\n", " console.log('ERROR: no files matched given `--file` regex.');\n", " process.exit(1);\n", " }\n" ], "file_path": "test/test.js", "type": "replace", "edit_start_line_idx": 195 }
/** * Copyright (c) Microsoft Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import * as js from './javascript'; import * as dom from './dom'; type NoHandles<Arg> = Arg extends js.JSHandle ? never : (Arg extends object ? { [Key in keyof Arg]: NoHandles<Arg[Key]> } : Arg); type Unboxed<Arg> = Arg extends dom.ElementHandle<infer T> ? T : Arg extends js.JSHandle<infer T> ? T : Arg extends NoHandles<Arg> ? Arg : Arg extends Array<infer T> ? Array<Unboxed<T>> : Arg extends object ? { [Key in keyof Arg]: Unboxed<Arg[Key]> } : Arg; export type Func0<R> = string | (() => R | Promise<R>); export type Func1<Arg, R> = string | ((arg: Unboxed<Arg>) => R | Promise<R>); export type FuncOn<On, Arg2, R> = string | ((on: On, arg2: Unboxed<Arg2>) => R | Promise<R>); export type SmartHandle<T> = T extends Node ? dom.ElementHandle<T> : js.JSHandle<T>; export type Size = { width: number, height: number }; export type Point = { x: number, y: number }; export type Rect = Size & Point; export type Quad = [ Point, Point, Point, Point ]; export type TimeoutOptions = { timeout?: number }; export type WaitForElementOptions = TimeoutOptions & { waitFor?: 'attached' | 'detached' | 'visible' | 'hidden' }; export type Polling = 'raf' | 'mutation' | number; export type WaitForFunctionOptions = TimeoutOptions & { polling?: Polling }; export type LifecycleEvent = 'load' | 'domcontentloaded' | 'networkidle'; export const kLifecycleEvents: Set<LifecycleEvent> = new Set(['load', 'domcontentloaded', 'networkidle']); export type NavigateOptions = TimeoutOptions & { waitUntil?: LifecycleEvent, }; export type NavigatingActionWaitOptions = TimeoutOptions & { noWaitAfter?: boolean, }; export type PointerActionWaitOptions = TimeoutOptions & { force?: boolean, }; export type WaitForNavigationOptions = TimeoutOptions & { waitUntil?: LifecycleEvent, url?: URLMatch }; export type ExtendedWaitForNavigationOptions = TimeoutOptions & { waitUntil?: LifecycleEvent | 'commit', url?: URLMatch }; export type ElementScreenshotOptions = { type?: 'png' | 'jpeg', path?: string, quality?: number, omitBackground?: boolean, }; export type ScreenshotOptions = ElementScreenshotOptions & { fullPage?: boolean, clip?: Rect, }; export type URLMatch = string | RegExp | ((url: URL) => boolean); export type Credentials = { username: string; password: string; }; export type Geolocation = { longitude: number; latitude: number; accuracy?: number; }; export type SelectOption = { value?: string; label?: string; index?: number; }; export type FilePayload = { name: string, mimeType: string, buffer: Buffer, }; export type FileTransferPayload = { name: string, type: string, data: string, }; export type MediaType = 'screen' | 'print'; export const mediaTypes: Set<MediaType> = new Set(['screen', 'print']); export type ColorScheme = 'dark' | 'light' | 'no-preference'; export const colorSchemes: Set<ColorScheme> = new Set(['dark', 'light', 'no-preference']); export type DeviceDescriptor = { userAgent: string, viewport: Size, deviceScaleFactor: number, isMobile: boolean, hasTouch: boolean }; export type Devices = { [name: string]: DeviceDescriptor }; export type PDFOptions = { scale?: number, displayHeaderFooter?: boolean, headerTemplate?: string, footerTemplate?: string, printBackground?: boolean, landscape?: boolean, pageRanges?: string, format?: string, width?: string|number, height?: string|number, preferCSSPageSize?: boolean, margin?: {top?: string|number, bottom?: string|number, left?: string|number, right?: string|number}, path?: string, } export type CoverageEntry = { url: string, text: string, ranges: {start: number, end: number}[] }; export type CSSCoverageOptions = { resetOnNavigation?: boolean, }; export type JSCoverageOptions = { resetOnNavigation?: boolean, reportAnonymousScripts?: boolean, }; export type ParsedSelector = { name: string, body: string, }[];
src/types.ts
0
https://github.com/microsoft/playwright/commit/2d68830411ead95c37631b73cd88d8a32b08dd38
[ 0.00017758893955033273, 0.0001742948079481721, 0.00016760974540375173, 0.00017482000112067908, 0.0000026813822842086665 ]
{ "id": 1, "code_window": [ " const filterArgIndex = process.argv.indexOf('--filter');\n", " if (filterArgIndex !== -1) {\n", " const filter = process.argv[filterArgIndex + 1];\n", " testRunner.focusMatchingTests(new RegExp(filter, 'i'));\n", " }\n", "\n", " const repeatArgIndex = process.argv.indexOf('--repeat');\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " if (!testRunner.focusMatchingNameTests(new RegExp(filter, 'i')).length) {\n", " console.log('ERROR: no tests matched given `--filter` regex.');\n", " process.exit(1);\n", " }\n", " }\n", "\n", " const fileArgIndex = process.argv.indexOf('--file');\n", " if (fileArgIndex !== -1) {\n", " const filter = process.argv[fileArgIndex + 1];\n", " if (!testRunner.focusMatchingFilePath(new RegExp(filter, 'i')).length) {\n", " console.log('ERROR: no files matched given `--file` regex.');\n", " process.exit(1);\n", " }\n" ], "file_path": "test/test.js", "type": "replace", "edit_start_line_idx": 195 }
/** * Copyright 2019 Google Inc. All rights reserved. * Modifications copyright (c) Microsoft Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import * as fs from 'fs'; import * as mime from 'mime'; import * as util from 'util'; import * as dom from './dom'; import { assert, helper } from './helper'; import { Page } from './page'; import * as types from './types'; export class Screenshotter { private _queue = new TaskQueue(); private _page: Page; constructor(page: Page) { this._page = page; const browserContext = page.context(); this._queue = (browserContext as any)[taskQueueSymbol]; if (!this._queue) { this._queue = new TaskQueue(); (browserContext as any)[taskQueueSymbol] = this._queue; } } private async _originalViewportSize(): Promise<{ viewportSize: types.Size, originalViewportSize: types.Size | null }> { const originalViewportSize = this._page.viewportSize(); let viewportSize = originalViewportSize; if (!viewportSize) { const context = await this._page.mainFrame()._utilityContext(); viewportSize = await context.evaluateInternal(() => { if (!document.body || !document.documentElement) return null; return { width: Math.max(document.body.offsetWidth, document.documentElement.offsetWidth), height: Math.max(document.body.offsetHeight, document.documentElement.offsetHeight), }; }); if (!viewportSize) throw new Error(kScreenshotDuringNavigationError); } return { viewportSize, originalViewportSize }; } private async _fullPageSize(): Promise<types.Size> { const context = await this._page.mainFrame()._utilityContext(); const fullPageSize = await context.evaluateInternal(() => { if (!document.body || !document.documentElement) return null; return { width: Math.max( document.body.scrollWidth, document.documentElement.scrollWidth, document.body.offsetWidth, document.documentElement.offsetWidth, document.body.clientWidth, document.documentElement.clientWidth ), height: Math.max( document.body.scrollHeight, document.documentElement.scrollHeight, document.body.offsetHeight, document.documentElement.offsetHeight, document.body.clientHeight, document.documentElement.clientHeight ), }; }); if (!fullPageSize) throw new Error(kScreenshotDuringNavigationError); return fullPageSize; } async screenshotPage(options: types.ScreenshotOptions = {}): Promise<Buffer> { const format = validateScreenshotOptions(options); return this._queue.postTask(async () => { const { viewportSize, originalViewportSize } = await this._originalViewportSize(); if (options.fullPage) { const fullPageSize = await this._fullPageSize(); let documentRect = { x: 0, y: 0, width: fullPageSize.width, height: fullPageSize.height }; let overridenViewportSize: types.Size | null = null; const fitsViewport = fullPageSize.width <= viewportSize.width && fullPageSize.height <= viewportSize.height; if (!this._page._delegate.canScreenshotOutsideViewport() && !fitsViewport) { overridenViewportSize = fullPageSize; await this._page.setViewportSize(overridenViewportSize); } if (options.clip) documentRect = trimClipToSize(options.clip, documentRect); return await this._screenshot(format, documentRect, undefined, options, overridenViewportSize, originalViewportSize); } const viewportRect = options.clip ? trimClipToSize(options.clip, viewportSize) : { x: 0, y: 0, ...viewportSize }; return await this._screenshot(format, undefined, viewportRect, options, null, originalViewportSize); }).catch(rewriteError); } async screenshotElement(handle: dom.ElementHandle, options: types.ElementScreenshotOptions = {}): Promise<Buffer> { const format = validateScreenshotOptions(options); return this._queue.postTask(async () => { const { viewportSize, originalViewportSize } = await this._originalViewportSize(); await handle.scrollIntoViewIfNeeded(); let boundingBox = await handle.boundingBox(); assert(boundingBox, 'Node is either not visible or not an HTMLElement'); assert(boundingBox.width !== 0, 'Node has 0 width.'); assert(boundingBox.height !== 0, 'Node has 0 height.'); let overridenViewportSize: types.Size | null = null; const fitsViewport = boundingBox.width <= viewportSize.width && boundingBox.height <= viewportSize.height; if (!this._page._delegate.canScreenshotOutsideViewport() && !fitsViewport) { overridenViewportSize = helper.enclosingIntSize({ width: Math.max(viewportSize.width, boundingBox.width), height: Math.max(viewportSize.height, boundingBox.height), }); await this._page.setViewportSize(overridenViewportSize); await handle.scrollIntoViewIfNeeded(); boundingBox = await handle.boundingBox(); assert(boundingBox, 'Node is either not visible or not an HTMLElement'); assert(boundingBox.width !== 0, 'Node has 0 width.'); assert(boundingBox.height !== 0, 'Node has 0 height.'); } const context = await this._page.mainFrame()._utilityContext(); const scrollOffset = await context.evaluateInternal(() => ({ x: window.scrollX, y: window.scrollY })); const documentRect = { ...boundingBox }; documentRect.x += scrollOffset.x; documentRect.y += scrollOffset.y; return await this._screenshot(format, helper.enclosingIntRect(documentRect), undefined, options, overridenViewportSize, originalViewportSize); }).catch(rewriteError); } private async _screenshot(format: 'png' | 'jpeg', documentRect: types.Rect | undefined, viewportRect: types.Rect | undefined, options: types.ElementScreenshotOptions, overridenViewportSize: types.Size | null, originalViewportSize: types.Size | null): Promise<Buffer> { const shouldSetDefaultBackground = options.omitBackground && format === 'png'; if (shouldSetDefaultBackground) await this._page._delegate.setBackgroundColor({ r: 0, g: 0, b: 0, a: 0}); const buffer = await this._page._delegate.takeScreenshot(format, documentRect, viewportRect, options.quality); if (shouldSetDefaultBackground) await this._page._delegate.setBackgroundColor(); if (overridenViewportSize) { assert(!this._page._delegate.canScreenshotOutsideViewport()); if (originalViewportSize) await this._page.setViewportSize(originalViewportSize); else await this._page._delegate.resetViewport(); } if (options.path) await util.promisify(fs.writeFile)(options.path, buffer); return buffer; } } const taskQueueSymbol = Symbol('TaskQueue'); class TaskQueue { private _chain: Promise<any>; constructor() { this._chain = Promise.resolve(); } postTask(task: () => any): Promise<any> { const result = this._chain.then(task); this._chain = result.catch(() => {}); return result; } } function trimClipToSize(clip: types.Rect, size: types.Size): types.Rect { const p1 = { x: Math.max(0, Math.min(clip.x, size.width)), y: Math.max(0, Math.min(clip.y, size.height)) }; const p2 = { x: Math.max(0, Math.min(clip.x + clip.width, size.width)), y: Math.max(0, Math.min(clip.y + clip.height, size.height)) }; const result = { x: p1.x, y: p1.y, width: p2.x - p1.x, height: p2.y - p1.y }; assert(result.width && result.height, 'Clipped area is either empty or outside the resulting image'); return result; } function validateScreenshotOptions(options: types.ScreenshotOptions): 'png' | 'jpeg' { let format: 'png' | 'jpeg' | null = null; // options.type takes precedence over inferring the type from options.path // because it may be a 0-length file with no extension created beforehand (i.e. as a temp file). if (options.type) { assert(options.type === 'png' || options.type === 'jpeg', 'Unknown options.type value: ' + options.type); format = options.type; } else if (options.path) { const mimeType = mime.getType(options.path); if (mimeType === 'image/png') format = 'png'; else if (mimeType === 'image/jpeg') format = 'jpeg'; assert(format, 'Unsupported screenshot mime type: ' + mimeType); } if (!format) format = 'png'; if (options.quality) { assert(format === 'jpeg', 'options.quality is unsupported for the ' + format + ' screenshots'); assert(typeof options.quality === 'number', 'Expected options.quality to be a number but found ' + (typeof options.quality)); assert(Number.isInteger(options.quality), 'Expected options.quality to be an integer'); assert(options.quality >= 0 && options.quality <= 100, 'Expected options.quality to be between 0 and 100 (inclusive), got ' + options.quality); } if (options.clip) { assert(typeof options.clip.x === 'number', 'Expected options.clip.x to be a number but found ' + (typeof options.clip.x)); assert(typeof options.clip.y === 'number', 'Expected options.clip.y to be a number but found ' + (typeof options.clip.y)); assert(typeof options.clip.width === 'number', 'Expected options.clip.width to be a number but found ' + (typeof options.clip.width)); assert(typeof options.clip.height === 'number', 'Expected options.clip.height to be a number but found ' + (typeof options.clip.height)); assert(options.clip.width !== 0, 'Expected options.clip.width not to be 0.'); assert(options.clip.height !== 0, 'Expected options.clip.height not to be 0.'); } return format; } export const kScreenshotDuringNavigationError = 'Cannot take a screenshot while page is navigating'; function rewriteError(e: any) { if (typeof e === 'object' && e instanceof Error && e.message.includes('Execution context was destroyed')) e.message = kScreenshotDuringNavigationError; throw e; }
src/screenshotter.ts
0
https://github.com/microsoft/playwright/commit/2d68830411ead95c37631b73cd88d8a32b08dd38
[ 0.0001790103706298396, 0.00017590634524822235, 0.00017017425852827728, 0.00017648094217292964, 0.000002065446551569039 ]
{ "id": 2, "code_window": [ " const repeat = parseInt(process.argv[repeatArgIndex + 1], 10);\n", " if (!isNaN(repeat))\n", " testRunner.repeatAll(repeat);\n", " }\n", "\n", " return testRunner;\n", "}\n", "\n", "module.exports = collect;\n", "\n", "if (require.main === module) {\n", " console.log('Testing on Node', process.version);\n", " const browserNames = ['chromium', 'firefox', 'webkit'].filter(name => {\n", " return process.env.BROWSER === name || process.env.BROWSER === 'all';\n", " });\n", " const testRunner = collect(browserNames);\n", " testRunner.run().then(() => { delete global.expect; });\n", "}" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep" ], "after_edit": [], "file_path": "test/test.js", "type": "replace", "edit_start_line_idx": 205 }
/** * Copyright 2017 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ const { TestRunner, Result, TestResult } = require('./TestRunner'); const { TestCollector, FocusedFilter, Repeater } = require('./TestCollector'); const Reporter = require('./Reporter'); const { Matchers } = require('./Matchers'); class DefaultTestRunner { constructor(options = {}) { const { // Our options. crashIfTestsAreFocusedOnCI = true, exit = true, reporter = true, // Collector options. timeout, // Runner options. parallel = 1, breakOnFailure, totalTimeout, hookTimeout = timeout, // Reporting options. showSlowTests, showMarkedAsFailingTests, verbose, summary, } = options; this._crashIfTestsAreFocusedOnCI = crashIfTestsAreFocusedOnCI; this._exit = exit; this._parallel = parallel; this._breakOnFailure = breakOnFailure; this._totalTimeout = totalTimeout; this._hookTimeout = hookTimeout; this._needReporter = reporter; this._showSlowTests = showSlowTests; this._showMarkedAsFailingTests = showMarkedAsFailingTests; this._verbose = verbose; this._summary = summary; this._filter = new FocusedFilter(); this._repeater = new Repeater(); this._collector = new TestCollector({ timeout }); this._api = { ...this._collector.api(), expect: new Matchers().expect, }; this._collector.addSuiteAttribute('only', s => this._filter.markFocused(s)); this._collector.addSuiteAttribute('skip', s => s.setSkipped(true)); this._collector.addSuiteModifier('repeat', (s, count) => this._repeater.repeat(s, count)); this._collector.addTestAttribute('only', t => this._filter.markFocused(t)); this._collector.addTestAttribute('skip', t => t.setSkipped(true)); this._collector.addTestAttribute('todo', t => t.setSkipped(true)); this._collector.addTestAttribute('slow', t => t.setTimeout(t.timeout() * 3)); this._collector.addTestModifier('repeat', (t, count) => this._repeater.repeat(t, count)); this._api.fdescribe = this._api.describe.only; this._api.xdescribe = this._api.describe.skip; this._api.fit = this._api.it.only; this._api.xit = this._api.it.skip; } collector() { return this._collector; } api() { return this._api; } focusMatchingTests(fullNameRegex) { for (const test of this._collector.tests()) { if (fullNameRegex.test(test.fullName())) this._filter.markFocused(test); } } repeatAll(repeatCount) { this._repeater.repeat(this._collector.rootSuite(), repeatCount); } async run() { let reporter = null; if (this._needReporter) { const reporterDelegate = { focusedSuites: () => this._filter.focusedTests(this._collector.suites()), focusedTests: () => this._filter.focusedSuites(this._collector.tests()), hasFocusedTestsOrSuites: () => this._filter.hasFocusedTestsOrSuites(), parallel: () => this._parallel, testCount: () => this._collector.tests().length, }; const reporterOptions = { showSlowTests: this._showSlowTests, showMarkedAsFailingTests: this._showMarkedAsFailingTests, verbose: this._verbose, summary: this._summary, }; reporter = new Reporter(reporterDelegate, reporterOptions); } if (this._crashIfTestsAreFocusedOnCI && process.env.CI && this._filter.hasFocusedTestsOrSuites()) { if (reporter) await reporter.onStarted([]); const result = new Result(); result.setResult(TestResult.Crashed, '"focused" tests or suites are probitted on CI'); if (reporter) await reporter.onFinished(result); if (this._exit) process.exit(result.exitCode); return result; } const testRuns = this._repeater.createTestRuns(this._filter.filter(this._collector.tests())); const testRunner = new TestRunner(); const result = await testRunner.run(testRuns, { parallel: this._parallel, breakOnFailure: this._breakOnFailure, totalTimeout: this._totalTimeout, hookTimeout: this._hookTimeout, onStarted: (...args) => reporter && reporter.onStarted(...args), onFinished: (...args) => reporter && reporter.onFinished(...args), onTestRunStarted: (...args) => reporter && reporter.onTestRunStarted(...args), onTestRunFinished: (...args) => reporter && reporter.onTestRunFinished(...args), }); if (this._exit) process.exit(result.exitCode); return result; } } module.exports = DefaultTestRunner;
utils/testrunner/index.js
1
https://github.com/microsoft/playwright/commit/2d68830411ead95c37631b73cd88d8a32b08dd38
[ 0.001192779978737235, 0.0003699332883115858, 0.00016509911802131683, 0.00017428389401175082, 0.00034253078047186136 ]
{ "id": 2, "code_window": [ " const repeat = parseInt(process.argv[repeatArgIndex + 1], 10);\n", " if (!isNaN(repeat))\n", " testRunner.repeatAll(repeat);\n", " }\n", "\n", " return testRunner;\n", "}\n", "\n", "module.exports = collect;\n", "\n", "if (require.main === module) {\n", " console.log('Testing on Node', process.version);\n", " const browserNames = ['chromium', 'firefox', 'webkit'].filter(name => {\n", " return process.env.BROWSER === name || process.env.BROWSER === 'all';\n", " });\n", " const testRunner = collect(browserNames);\n", " testRunner.run().then(() => { delete global.expect; });\n", "}" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep" ], "after_edit": [], "file_path": "test/test.js", "type": "replace", "edit_start_line_idx": 205 }
# Running Playwright in Docker [Dockerfile.bionic](Dockerfile.bionic) is a playwright-ready image of playwright. This image includes all the dependencies needed to run browsers in a Docker container. Building image: ``` $ sudo docker build -t microsoft/playwright:bionic -f Dockerfile.bionic . ``` Running image: ``` $ sudo docker container run -it --rm --security-opt seccomp=chrome.json microsoft/playwright:bionic /bin/bash ``` > **NOTE**: The seccomp profile is coming from Jessie Frazelle. It's needed > to run Chrome without sandbox.
docs/docker/README.md
0
https://github.com/microsoft/playwright/commit/2d68830411ead95c37631b73cd88d8a32b08dd38
[ 0.00016671206685714424, 0.0001640574773773551, 0.00016229398897849023, 0.00016316633264068514, 0.000001910573701024987 ]
{ "id": 2, "code_window": [ " const repeat = parseInt(process.argv[repeatArgIndex + 1], 10);\n", " if (!isNaN(repeat))\n", " testRunner.repeatAll(repeat);\n", " }\n", "\n", " return testRunner;\n", "}\n", "\n", "module.exports = collect;\n", "\n", "if (require.main === module) {\n", " console.log('Testing on Node', process.version);\n", " const browserNames = ['chromium', 'firefox', 'webkit'].filter(name => {\n", " return process.env.BROWSER === name || process.env.BROWSER === 'all';\n", " });\n", " const testRunner = collect(browserNames);\n", " testRunner.run().then(() => { delete global.expect; });\n", "}" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep" ], "after_edit": [], "file_path": "test/test.js", "type": "replace", "edit_start_line_idx": 205 }
<script> var globalVar = 123; </script>
test/assets/global-var.html
0
https://github.com/microsoft/playwright/commit/2d68830411ead95c37631b73cd88d8a32b08dd38
[ 0.00017054201452992857, 0.00017054201452992857, 0.00017054201452992857, 0.00017054201452992857, 0 ]
{ "id": 2, "code_window": [ " const repeat = parseInt(process.argv[repeatArgIndex + 1], 10);\n", " if (!isNaN(repeat))\n", " testRunner.repeatAll(repeat);\n", " }\n", "\n", " return testRunner;\n", "}\n", "\n", "module.exports = collect;\n", "\n", "if (require.main === module) {\n", " console.log('Testing on Node', process.version);\n", " const browserNames = ['chromium', 'firefox', 'webkit'].filter(name => {\n", " return process.env.BROWSER === name || process.env.BROWSER === 'all';\n", " });\n", " const testRunner = collect(browserNames);\n", " testRunner.run().then(() => { delete global.expect; });\n", "}" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep" ], "after_edit": [], "file_path": "test/test.js", "type": "replace", "edit_start_line_idx": 205 }
<style> body, html { margin: 0; padding: 0; } @keyframes move { from { marign-left: 0; } to { margin-left: 100px; } } </style> <script> function addButton() { const button = document.createElement('button'); button.textContent = 'Click me'; button.style.animation = '3s linear move'; button.style.animationIterationCount = 'infinite'; button.addEventListener('click', () => window.clicked = true); document.body.appendChild(button); } function stopButton(remove) { const button = document.querySelector('button'); button.style.marginLeft = button.getBoundingClientRect().left + 'px'; button.style.animation = ''; if (remove) button.remove(); } </script>
test/assets/input/animating-button.html
0
https://github.com/microsoft/playwright/commit/2d68830411ead95c37631b73cd88d8a32b08dd38
[ 0.0001750326482579112, 0.00017301829939242452, 0.00017196232511196285, 0.00017205991025548428, 0.0000014249202422433882 ]
{ "id": 3, "code_window": [ " api() {\n", " return this._api;\n", " }\n", "\n", " focusMatchingTests(fullNameRegex) {\n", " for (const test of this._collector.tests()) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ " focusMatchingNameTests(fullNameRegex) {\n", " const focusedTests = [];\n" ], "file_path": "utils/testrunner/index.js", "type": "replace", "edit_start_line_idx": 84 }
/** * Copyright 2017 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ const { TestRunner, Result, TestResult } = require('./TestRunner'); const { TestCollector, FocusedFilter, Repeater } = require('./TestCollector'); const Reporter = require('./Reporter'); const { Matchers } = require('./Matchers'); class DefaultTestRunner { constructor(options = {}) { const { // Our options. crashIfTestsAreFocusedOnCI = true, exit = true, reporter = true, // Collector options. timeout, // Runner options. parallel = 1, breakOnFailure, totalTimeout, hookTimeout = timeout, // Reporting options. showSlowTests, showMarkedAsFailingTests, verbose, summary, } = options; this._crashIfTestsAreFocusedOnCI = crashIfTestsAreFocusedOnCI; this._exit = exit; this._parallel = parallel; this._breakOnFailure = breakOnFailure; this._totalTimeout = totalTimeout; this._hookTimeout = hookTimeout; this._needReporter = reporter; this._showSlowTests = showSlowTests; this._showMarkedAsFailingTests = showMarkedAsFailingTests; this._verbose = verbose; this._summary = summary; this._filter = new FocusedFilter(); this._repeater = new Repeater(); this._collector = new TestCollector({ timeout }); this._api = { ...this._collector.api(), expect: new Matchers().expect, }; this._collector.addSuiteAttribute('only', s => this._filter.markFocused(s)); this._collector.addSuiteAttribute('skip', s => s.setSkipped(true)); this._collector.addSuiteModifier('repeat', (s, count) => this._repeater.repeat(s, count)); this._collector.addTestAttribute('only', t => this._filter.markFocused(t)); this._collector.addTestAttribute('skip', t => t.setSkipped(true)); this._collector.addTestAttribute('todo', t => t.setSkipped(true)); this._collector.addTestAttribute('slow', t => t.setTimeout(t.timeout() * 3)); this._collector.addTestModifier('repeat', (t, count) => this._repeater.repeat(t, count)); this._api.fdescribe = this._api.describe.only; this._api.xdescribe = this._api.describe.skip; this._api.fit = this._api.it.only; this._api.xit = this._api.it.skip; } collector() { return this._collector; } api() { return this._api; } focusMatchingTests(fullNameRegex) { for (const test of this._collector.tests()) { if (fullNameRegex.test(test.fullName())) this._filter.markFocused(test); } } repeatAll(repeatCount) { this._repeater.repeat(this._collector.rootSuite(), repeatCount); } async run() { let reporter = null; if (this._needReporter) { const reporterDelegate = { focusedSuites: () => this._filter.focusedTests(this._collector.suites()), focusedTests: () => this._filter.focusedSuites(this._collector.tests()), hasFocusedTestsOrSuites: () => this._filter.hasFocusedTestsOrSuites(), parallel: () => this._parallel, testCount: () => this._collector.tests().length, }; const reporterOptions = { showSlowTests: this._showSlowTests, showMarkedAsFailingTests: this._showMarkedAsFailingTests, verbose: this._verbose, summary: this._summary, }; reporter = new Reporter(reporterDelegate, reporterOptions); } if (this._crashIfTestsAreFocusedOnCI && process.env.CI && this._filter.hasFocusedTestsOrSuites()) { if (reporter) await reporter.onStarted([]); const result = new Result(); result.setResult(TestResult.Crashed, '"focused" tests or suites are probitted on CI'); if (reporter) await reporter.onFinished(result); if (this._exit) process.exit(result.exitCode); return result; } const testRuns = this._repeater.createTestRuns(this._filter.filter(this._collector.tests())); const testRunner = new TestRunner(); const result = await testRunner.run(testRuns, { parallel: this._parallel, breakOnFailure: this._breakOnFailure, totalTimeout: this._totalTimeout, hookTimeout: this._hookTimeout, onStarted: (...args) => reporter && reporter.onStarted(...args), onFinished: (...args) => reporter && reporter.onFinished(...args), onTestRunStarted: (...args) => reporter && reporter.onTestRunStarted(...args), onTestRunFinished: (...args) => reporter && reporter.onTestRunFinished(...args), }); if (this._exit) process.exit(result.exitCode); return result; } } module.exports = DefaultTestRunner;
utils/testrunner/index.js
1
https://github.com/microsoft/playwright/commit/2d68830411ead95c37631b73cd88d8a32b08dd38
[ 0.9977691173553467, 0.1327209770679474, 0.00016583024989813566, 0.0015044307801872492, 0.32676371932029724 ]
{ "id": 3, "code_window": [ " api() {\n", " return this._api;\n", " }\n", "\n", " focusMatchingTests(fullNameRegex) {\n", " for (const test of this._collector.tests()) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ " focusMatchingNameTests(fullNameRegex) {\n", " const focusedTests = [];\n" ], "file_path": "utils/testrunner/index.js", "type": "replace", "edit_start_line_idx": 84 }
# exclude all examples and README.md examples/ README.md # repeats from .gitignore node_modules .npmignore .DS_Store *.swp *.pyc .vscode package-lock.json yarn.lock
utils/testrunner/.npmignore
0
https://github.com/microsoft/playwright/commit/2d68830411ead95c37631b73cd88d8a32b08dd38
[ 0.00017547933384776115, 0.00017518909589853138, 0.0001748988579493016, 0.00017518909589853138, 2.9023794922977686e-7 ]
{ "id": 3, "code_window": [ " api() {\n", " return this._api;\n", " }\n", "\n", " focusMatchingTests(fullNameRegex) {\n", " for (const test of this._collector.tests()) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ " focusMatchingNameTests(fullNameRegex) {\n", " const focusedTests = [];\n" ], "file_path": "utils/testrunner/index.js", "type": "replace", "edit_start_line_idx": 84 }
--- name: Feature request about: Request new features to be added title: "[Feature]" labels: '' assignees: '' --- Let us know what functionality you'd like to see in Playwright and what is your use case. Do you think others might benefit from this as well?
.github/ISSUE_TEMPLATE/feature_request.md
0
https://github.com/microsoft/playwright/commit/2d68830411ead95c37631b73cd88d8a32b08dd38
[ 0.0001758971338858828, 0.00017211251542903483, 0.0001683279115241021, 0.00017211251542903483, 0.0000037846111808903515 ]
{ "id": 3, "code_window": [ " api() {\n", " return this._api;\n", " }\n", "\n", " focusMatchingTests(fullNameRegex) {\n", " for (const test of this._collector.tests()) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ " focusMatchingNameTests(fullNameRegex) {\n", " const focusedTests = [];\n" ], "file_path": "utils/testrunner/index.js", "type": "replace", "edit_start_line_idx": 84 }
const Events = { Foo: { a: 'a', b: 'b', c: 'c', }, }; module.exports = {Events};
utils/doclint/check_public_api/test/check-sorting/events.js
0
https://github.com/microsoft/playwright/commit/2d68830411ead95c37631b73cd88d8a32b08dd38
[ 0.00017127289902418852, 0.00017127289902418852, 0.00017127289902418852, 0.00017127289902418852, 0 ]
{ "id": 4, "code_window": [ " for (const test of this._collector.tests()) {\n", " if (fullNameRegex.test(test.fullName()))\n", " this._filter.markFocused(test);\n" ], "labels": [ "keep", "replace", "keep" ], "after_edit": [ " if (fullNameRegex.test(test.fullName())) {\n" ], "file_path": "utils/testrunner/index.js", "type": "replace", "edit_start_line_idx": 86 }
/** * Copyright 2017 Google Inc. All rights reserved. * Modifications copyright (c) Microsoft Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ const fs = require('fs'); const readline = require('readline'); const TestRunner = require('../utils/testrunner/'); const {Environment} = require('../utils/testrunner/Test'); function collect(browserNames) { let parallel = 1; if (process.env.PW_PARALLEL_TESTS) parallel = parseInt(process.env.PW_PARALLEL_TESTS.trim(), 10); const parallelArgIndex = process.argv.indexOf('-j'); if (parallelArgIndex !== -1) parallel = parseInt(process.argv[parallelArgIndex + 1], 10); require('events').defaultMaxListeners *= parallel; let timeout = process.env.CI ? 30 * 1000 : 10 * 1000; if (!isNaN(process.env.TIMEOUT)) timeout = parseInt(process.env.TIMEOUT * 1000, 10); const MAJOR_NODEJS_VERSION = parseInt(process.version.substring(1).split('.')[0], 10); if (MAJOR_NODEJS_VERSION >= 8 && require('inspector').url()) { console.log('Detected inspector - disabling timeout to be debugger-friendly'); timeout = 0; } const config = require('./test.config'); const testRunner = new TestRunner({ timeout, totalTimeout: process.env.CI ? 30 * 60 * 1000 : 0, // 30 minutes on CI parallel, breakOnFailure: process.argv.indexOf('--break-on-failure') !== -1, verbose: process.argv.includes('--verbose'), summary: !process.argv.includes('--verbose'), showSlowTests: process.env.CI ? 5 : 0, showMarkedAsFailingTests: 10, }); if (config.setupTestRunner) config.setupTestRunner(testRunner); for (const [key, value] of Object.entries(testRunner.api())) global[key] = value; // TODO: this should be a preinstalled playwright by default. const playwrightPath = config.playwrightPath; const playwright = require(playwrightPath); const playwrightEnvironment = new Environment('Playwright'); playwrightEnvironment.beforeAll(async state => { state.playwright = playwright; global.playwright = playwright; }); playwrightEnvironment.afterAll(async state => { delete state.playwright; delete global.playwright; }); testRunner.collector().useEnvironment(playwrightEnvironment); for (const e of config.globalEnvironments || []) testRunner.collector().useEnvironment(e); for (const browserName of browserNames) { const browserType = playwright[browserName]; const browserTypeEnvironment = new Environment('BrowserType'); browserTypeEnvironment.beforeAll(async state => { state.browserType = browserType; }); browserTypeEnvironment.afterAll(async state => { delete state.browserType; }); // TODO: maybe launch options per browser? const launchOptions = { ...(config.launchOptions || {}), handleSIGINT: false, }; if (launchOptions.executablePath) launchOptions.executablePath = launchOptions.executablePath[browserName]; if (launchOptions.executablePath) { const YELLOW_COLOR = '\x1b[33m'; const RESET_COLOR = '\x1b[0m'; console.warn(`${YELLOW_COLOR}WARN: running ${browserName} tests with ${launchOptions.executablePath}${RESET_COLOR}`); browserType._executablePath = launchOptions.executablePath; delete launchOptions.executablePath; } else { if (!fs.existsSync(browserType.executablePath())) throw new Error(`Browser is not downloaded. Run 'npm install' and try to re-run tests`); } const browserEnvironment = new Environment(browserName); browserEnvironment.beforeAll(async state => { state._logger = null; state.browser = await state.browserType.launch({...launchOptions, logger: { isEnabled: (name, severity) => { return name === 'browser' || (name === 'protocol' && config.dumpProtocolOnFailure); }, log: (name, severity, message, args) => { if (state._logger) state._logger(name, severity, message); } }}); }); browserEnvironment.afterAll(async state => { await state.browser.close(); delete state.browser; delete state._logger; }); browserEnvironment.beforeEach(async(state, testRun) => { state._logger = (name, severity, message) => { if (name === 'browser') { if (severity === 'warning') testRun.log(`\x1b[31m[browser]\x1b[0m ${message}`) else testRun.log(`\x1b[33m[browser]\x1b[0m ${message}`) } else if (name === 'protocol' && config.dumpProtocolOnFailure) { testRun.log(`\x1b[32m[protocol]\x1b[0m ${message}`) } } }); browserEnvironment.afterEach(async (state, testRun) => { state._logger = null; if (config.dumpProtocolOnFailure) { if (testRun.ok()) testRun.output().splice(0); } }); const pageEnvironment = new Environment('Page'); pageEnvironment.beforeEach(async state => { state.context = await state.browser.newContext(); state.page = await state.context.newPage(); }); pageEnvironment.afterEach(async state => { await state.context.close(); state.context = null; state.page = null; }); const suiteName = { 'chromium': 'Chromium', 'firefox': 'Firefox', 'webkit': 'WebKit' }[browserName]; describe(suiteName, () => { // In addition to state, expose these two on global so that describes can access them. global.playwright = playwright; global.browserType = browserType; testRunner.collector().useEnvironment(browserTypeEnvironment); for (const spec of config.specs || []) { const skip = spec.browsers && !spec.browsers.includes(browserName); (skip ? xdescribe : describe)(spec.title || '', () => { for (const e of spec.environments || ['page']) { if (e === 'browser') { testRunner.collector().useEnvironment(browserEnvironment); } else if (e === 'page') { testRunner.collector().useEnvironment(browserEnvironment); testRunner.collector().useEnvironment(pageEnvironment); } else { testRunner.collector().useEnvironment(e); } } for (const file of spec.files || []) { require(file); delete require.cache[require.resolve(file)]; } }); } delete global.browserType; delete global.playwright; }); } for (const [key, value] of Object.entries(testRunner.api())) { // expect is used when running tests, while the rest of api is not. if (key !== 'expect') delete global[key]; } const filterArgIndex = process.argv.indexOf('--filter'); if (filterArgIndex !== -1) { const filter = process.argv[filterArgIndex + 1]; testRunner.focusMatchingTests(new RegExp(filter, 'i')); } const repeatArgIndex = process.argv.indexOf('--repeat'); if (repeatArgIndex !== -1) { const repeat = parseInt(process.argv[repeatArgIndex + 1], 10); if (!isNaN(repeat)) testRunner.repeatAll(repeat); } return testRunner; } module.exports = collect; if (require.main === module) { console.log('Testing on Node', process.version); const browserNames = ['chromium', 'firefox', 'webkit'].filter(name => { return process.env.BROWSER === name || process.env.BROWSER === 'all'; }); const testRunner = collect(browserNames); testRunner.run().then(() => { delete global.expect; }); }
test/test.js
1
https://github.com/microsoft/playwright/commit/2d68830411ead95c37631b73cd88d8a32b08dd38
[ 0.0013312242226675153, 0.00022734975209459662, 0.00016504718223586679, 0.0001727915514493361, 0.0002414859482087195 ]
{ "id": 4, "code_window": [ " for (const test of this._collector.tests()) {\n", " if (fullNameRegex.test(test.fullName()))\n", " this._filter.markFocused(test);\n" ], "labels": [ "keep", "replace", "keep" ], "after_edit": [ " if (fullNameRegex.test(test.fullName())) {\n" ], "file_path": "utils/testrunner/index.js", "type": "replace", "edit_start_line_idx": 86 }
type ServerResponse = import('http').ServerResponse; type IncomingMessage = import('http').IncomingMessage; type Falsy = false|""|0|null|undefined; interface Expect<T> { toBe(other: T, message?: string): void; toBeFalsy(message?: string): void; toBeTruthy(message?: string): void; toContain(other: any, message?: string): void; toEqual(other: T, message?: string): void; toBeNull(message?: string): void; toBeInstanceOf(other: Function, message?: string): void; toBeGreaterThan(other: number, message?: string): void; toBeGreaterThanOrEqual(other: number, message?: string): void; toBeLessThan(other: number, message?: string): void; toBeLessThanOrEqual(other: number, message?: string): void; toBeCloseTo(other: number, precision: number, message?: string): void; toBeGolden(golden: {goldenPath: string, outputPath: string, goldenName: string}): void; not: Expect<T>; } type DescribeFunction = ((name: string, inner: () => void) => void) & {fail(condition: boolean): DescribeFunction}; type ItFunction<STATE> = ((name: string, inner: (state: STATE) => Promise<void>) => void) & {fail(condition: boolean): ItFunction<STATE>; repeat(n: number): ItFunction<STATE>}; type TestRunner<STATE> = { describe: DescribeFunction; xdescribe: DescribeFunction; fdescribe: DescribeFunction; it: ItFunction<STATE>; xit: ItFunction<STATE>; fit: ItFunction<STATE>; dit: ItFunction<STATE>; beforeAll, beforeEach, afterAll, afterEach; }; interface TestSetup<STATE> { testRunner: TestRunner<STATE>; product: 'Chromium'|'Firefox'|'WebKit'; FFOX: boolean; WEBKIT: boolean; CHROMIUM: boolean; MAC: boolean; LINUX: boolean; WIN: boolean; playwright: typeof import('../index'); browserType: import('../index').BrowserType<import('../index').Browser>; selectors: import('../src/selectors').Selectors; expect<T>(value: T): Expect<T>; defaultBrowserOptions: import('../src/server/browserType').LaunchOptions; playwrightPath; headless: boolean; ASSETS_DIR: string; } type TestState = { server: TestServer; httpsServer: TestServer; sourceServer: TestServer; }; type BrowserState = TestState & { browser: import('../index').Browser; browserServer: import('../index').BrowserServer; }; type PageState = BrowserState & { context: import('../index').BrowserContext; page: import('../index').Page; }; type ChromiumPageState = PageState & { browser: import('../index').ChromiumBrowser; }; type TestSuite = (setup: TestSetup<TestState>) => void; type BrowserTestSuite = (setup: TestSetup<BrowserState>) => void; type PageTestSuite = (setup: TestSetup<PageState>) => void; type ChromiumTestSuite = (setup: TestSetup<ChromiumPageState>) => void; interface TestServer { enableHTTPCache(pathPrefix: string); setAuth(path: string, username: string, password: string); enableGzip(path: string); setCSP(path: string, csp: string); stop(): Promise<void>; setRoute(path: string, handler: (message: IncomingMessage, response: ServerResponse) => void); setRedirect(from: string, to: string); waitForRequest(path: string): Promise<IncomingMessage>; reset(); serveFile(request: IncomingMessage, response: ServerResponse, pathName: string); PORT: number; PREFIX: string; CROSS_PROCESS_PREFIX: string; EMPTY_PAGE: string; }
test/types.d.ts
0
https://github.com/microsoft/playwright/commit/2d68830411ead95c37631b73cd88d8a32b08dd38
[ 0.00018044818716589361, 0.00017340829072054476, 0.00016631004109513015, 0.00017389115237165242, 0.000004503517175180605 ]
{ "id": 4, "code_window": [ " for (const test of this._collector.tests()) {\n", " if (fullNameRegex.test(test.fullName()))\n", " this._filter.markFocused(test);\n" ], "labels": [ "keep", "replace", "keep" ], "after_edit": [ " if (fullNameRegex.test(test.fullName())) {\n" ], "file_path": "utils/testrunner/index.js", "type": "replace", "edit_start_line_idx": 86 }
/** * Copyright 2018 Google Inc. All rights reserved. * Modifications copyright (c) Microsoft Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ const fs = require('fs'); const path = require('path'); const { helper } = require('../lib/helper'); const vm = require('vm'); const {FFOX, CHROMIUM, WEBKIT} = require('./utils').testOptions(browserType); describe('Page.route', function() { it('should intercept', async({page, server}) => { let intercepted = false; await page.route('**/empty.html', (route, request) => { expect(route.request()).toBe(request); expect(request.url()).toContain('empty.html'); expect(request.headers()['user-agent']).toBeTruthy(); expect(request.method()).toBe('GET'); expect(request.postData()).toBe(null); expect(request.isNavigationRequest()).toBe(true); expect(request.resourceType()).toBe('document'); expect(request.frame() === page.mainFrame()).toBe(true); expect(request.frame().url()).toBe('about:blank'); route.continue(); intercepted = true; }); const response = await page.goto(server.EMPTY_PAGE); expect(response.ok()).toBe(true); expect(intercepted).toBe(true); }); it('should unroute', async({page, server}) => { let intercepted = []; const handler1 = route => { intercepted.push(1); route.continue(); }; await page.route('**/empty.html', handler1); await page.route('**/empty.html', route => { intercepted.push(2); route.continue(); }); await page.route('**/empty.html', route => { intercepted.push(3); route.continue(); }); await page.route('**/*', route => { intercepted.push(4); route.continue(); }); await page.goto(server.EMPTY_PAGE); expect(intercepted).toEqual([1]); intercepted = []; await page.unroute('**/empty.html', handler1); await page.goto(server.EMPTY_PAGE); expect(intercepted).toEqual([2]); intercepted = []; await page.unroute('**/empty.html'); await page.goto(server.EMPTY_PAGE); expect(intercepted).toEqual([4]); }); it('should work when POST is redirected with 302', async({page, server}) => { server.setRedirect('/rredirect', '/empty.html'); await page.goto(server.EMPTY_PAGE); await page.route('**/*', route => route.continue()); await page.setContent(` <form action='/rredirect' method='post'> <input type="hidden" id="foo" name="foo" value="FOOBAR"> </form> `); await Promise.all([ page.$eval('form', form => form.submit()), page.waitForNavigation() ]); }); // @see https://github.com/GoogleChrome/puppeteer/issues/3973 it('should work when header manipulation headers with redirect', async({page, server}) => { server.setRedirect('/rrredirect', '/empty.html'); await page.route('**/*', route => { const headers = Object.assign({}, route.request().headers(), { foo: 'bar' }); route.continue({ headers }); }); await page.goto(server.PREFIX + '/rrredirect'); }); // @see https://github.com/GoogleChrome/puppeteer/issues/4743 it('should be able to remove headers', async({page, server}) => { await page.route('**/*', route => { const headers = Object.assign({}, route.request().headers(), { foo: 'bar', origin: undefined, // remove "origin" header }); route.continue({ headers }); }); const [serverRequest] = await Promise.all([ server.waitForRequest('/empty.html'), page.goto(server.PREFIX + '/empty.html') ]); expect(serverRequest.headers.origin).toBe(undefined); }); it('should contain referer header', async({page, server}) => { const requests = []; await page.route('**/*', route => { requests.push(route.request()); route.continue(); }); await page.goto(server.PREFIX + '/one-style.html'); expect(requests[1].url()).toContain('/one-style.css'); expect(requests[1].headers().referer).toContain('/one-style.html'); }); it('should properly return navigation response when URL has cookies', async({context, page, server}) => { // Setup cookie. await page.goto(server.EMPTY_PAGE); await context.addCookies([{ url: server.EMPTY_PAGE, name: 'foo', value: 'bar'}]); // Setup request interception. await page.route('**/*', route => route.continue()); const response = await page.reload(); expect(response.status()).toBe(200); }); it('should show custom HTTP headers', async({page, server}) => { await page.setExtraHTTPHeaders({ foo: 'bar' }); await page.route('**/*', route => { expect(route.request().headers()['foo']).toBe('bar'); route.continue(); }); const response = await page.goto(server.EMPTY_PAGE); expect(response.ok()).toBe(true); }); // @see https://github.com/GoogleChrome/puppeteer/issues/4337 it('should work with redirect inside sync XHR', async({page, server}) => { await page.goto(server.EMPTY_PAGE); server.setRedirect('/logo.png', '/pptr.png'); await page.route('**/*', route => route.continue()); const status = await page.evaluate(async() => { const request = new XMLHttpRequest(); request.open('GET', '/logo.png', false); // `false` makes the request synchronous request.send(null); return request.status; }); expect(status).toBe(200); }); it('should work with custom referer headers', async({page, server}) => { await page.setExtraHTTPHeaders({ 'referer': server.EMPTY_PAGE }); await page.route('**/*', route => { expect(route.request().headers()['referer']).toBe(server.EMPTY_PAGE); route.continue(); }); const response = await page.goto(server.EMPTY_PAGE); expect(response.ok()).toBe(true); }); it('should be abortable', async({page, server}) => { await page.route(/\.css$/, route => route.abort()); let failedRequests = 0; page.on('requestfailed', event => ++failedRequests); const response = await page.goto(server.PREFIX + '/one-style.html'); expect(response.ok()).toBe(true); expect(response.request().failure()).toBe(null); expect(failedRequests).toBe(1); }); it('should be abortable with custom error codes', async({page, server}) => { await page.route('**/*', route => route.abort('internetdisconnected')); let failedRequest = null; page.on('requestfailed', request => failedRequest = request); await page.goto(server.EMPTY_PAGE).catch(e => {}); expect(failedRequest).toBeTruthy(); if (WEBKIT) expect(failedRequest.failure().errorText).toBe('Request intercepted'); else if (FFOX) expect(failedRequest.failure().errorText).toBe('NS_ERROR_OFFLINE'); else expect(failedRequest.failure().errorText).toBe('net::ERR_INTERNET_DISCONNECTED'); }); it('should send referer', async({page, server}) => { await page.setExtraHTTPHeaders({ referer: 'http://google.com/' }); await page.route('**/*', route => route.continue()); const [request] = await Promise.all([ server.waitForRequest('/grid.html'), page.goto(server.PREFIX + '/grid.html'), ]); expect(request.headers['referer']).toBe('http://google.com/'); }); it('should fail navigation when aborting main resource', async({page, server}) => { await page.route('**/*', route => route.abort()); let error = null; await page.goto(server.EMPTY_PAGE).catch(e => error = e); expect(error).toBeTruthy(); if (WEBKIT) expect(error.message).toContain('Request intercepted'); else if (FFOX) expect(error.message).toContain('NS_ERROR_FAILURE'); else expect(error.message).toContain('net::ERR_FAILED'); }); it('should work with redirects', async({page, server}) => { const requests = []; await page.route('**/*', route => { route.continue(); requests.push(route.request()); }); server.setRedirect('/non-existing-page.html', '/non-existing-page-2.html'); server.setRedirect('/non-existing-page-2.html', '/non-existing-page-3.html'); server.setRedirect('/non-existing-page-3.html', '/non-existing-page-4.html'); server.setRedirect('/non-existing-page-4.html', '/empty.html'); const response = await page.goto(server.PREFIX + '/non-existing-page.html'); expect(response.status()).toBe(200); expect(response.url()).toContain('empty.html'); expect(requests.length).toBe(5); expect(requests[2].resourceType()).toBe('document'); const chain = []; for (let r = response.request(); r; r = r.redirectedFrom()) { chain.push(r); expect(r.isNavigationRequest()).toBe(true); } expect(chain.length).toBe(5); expect(chain[0].url()).toContain('/empty.html'); expect(chain[1].url()).toContain('/non-existing-page-4.html'); expect(chain[2].url()).toContain('/non-existing-page-3.html'); expect(chain[3].url()).toContain('/non-existing-page-2.html'); expect(chain[4].url()).toContain('/non-existing-page.html'); for (let i = 0; i < chain.length; i++) expect(chain[i].redirectedTo()).toBe(i ? chain[i - 1] : null); }); it('should work with redirects for subresources', async({page, server}) => { const requests = []; await page.route('**/*', route => { route.continue(); requests.push(route.request()); }); server.setRedirect('/one-style.css', '/two-style.css'); server.setRedirect('/two-style.css', '/three-style.css'); server.setRedirect('/three-style.css', '/four-style.css'); server.setRoute('/four-style.css', (req, res) => res.end('body {box-sizing: border-box; }')); const response = await page.goto(server.PREFIX + '/one-style.html'); expect(response.status()).toBe(200); expect(response.url()).toContain('one-style.html'); expect(requests.length).toBe(5); expect(requests[0].resourceType()).toBe('document'); let r = requests.find(r => r.url().includes('/four-style.css')); for (const url of ['/four-style.css', '/three-style.css', '/two-style.css', '/one-style.css']) { expect(r.resourceType()).toBe('stylesheet'); expect(r.url()).toContain(url); r = r.redirectedFrom(); } expect(r).toBe(null); }); it('should work with equal requests', async({page, server}) => { await page.goto(server.EMPTY_PAGE); let responseCount = 1; server.setRoute('/zzz', (req, res) => res.end((responseCount++) * 11 + '')); let spinner = false; // Cancel 2nd request. await page.route('**/*', route => { spinner ? route.abort() : route.continue(); spinner = !spinner; }); const results = []; for (let i = 0; i < 3; i++) results.push(await page.evaluate(() => fetch('/zzz').then(response => response.text()).catch(e => 'FAILED'))); expect(results).toEqual(['11', 'FAILED', '22']); }); it('should navigate to dataURL and not fire dataURL requests', async({page, server}) => { const requests = []; await page.route('**/*', route => { requests.push(route.request()); route.continue(); }); const dataURL = 'data:text/html,<div>yo</div>'; const response = await page.goto(dataURL); expect(response).toBe(null); expect(requests.length).toBe(0); }); it('should be able to fetch dataURL and not fire dataURL requests', async({page, server}) => { await page.goto(server.EMPTY_PAGE); const requests = []; await page.route('**/*', route => { requests.push(route.request()); route.continue(); }); const dataURL = 'data:text/html,<div>yo</div>'; const text = await page.evaluate(url => fetch(url).then(r => r.text()), dataURL); expect(text).toBe('<div>yo</div>'); expect(requests.length).toBe(0); }); it('should navigate to URL with hash and and fire requests without hash', async({page, server}) => { const requests = []; await page.route('**/*', route => { requests.push(route.request()); route.continue(); }); const response = await page.goto(server.EMPTY_PAGE + '#hash'); expect(response.status()).toBe(200); expect(response.url()).toBe(server.EMPTY_PAGE); expect(requests.length).toBe(1); expect(requests[0].url()).toBe(server.EMPTY_PAGE); }); it('should work with encoded server', async({page, server}) => { // The requestWillBeSent will report encoded URL, whereas interception will // report URL as-is. @see crbug.com/759388 await page.route('**/*', route => route.continue()); const response = await page.goto(server.PREFIX + '/some nonexisting page'); expect(response.status()).toBe(404); }); it('should work with badly encoded server', async({page, server}) => { server.setRoute('/malformed?rnd=%911', (req, res) => res.end()); await page.route('**/*', route => route.continue()); const response = await page.goto(server.PREFIX + '/malformed?rnd=%911'); expect(response.status()).toBe(200); }); it('should work with encoded server - 2', async({page, server}) => { // The requestWillBeSent will report URL as-is, whereas interception will // report encoded URL for stylesheet. @see crbug.com/759388 const requests = []; await page.route('**/*', route => { route.continue(); requests.push(route.request()); }); const response = await page.goto(`data:text/html,<link rel="stylesheet" href="${server.PREFIX}/fonts?helvetica|arial"/>`); expect(response).toBe(null); expect(requests.length).toBe(1); expect((await requests[0].response()).status()).toBe(404); }); it('should not throw "Invalid Interception Id" if the request was cancelled', async({page, server}) => { await page.setContent('<iframe></iframe>'); let route = null; await page.route('**/*', async r => route = r); page.$eval('iframe', (frame, url) => frame.src = url, server.EMPTY_PAGE), // Wait for request interception. await page.waitForEvent('request'); // Delete frame to cause request to be canceled. await page.$eval('iframe', frame => frame.remove()); let error = null; await route.continue().catch(e => error = e); expect(error).toBe(null); }); it('should intercept main resource during cross-process navigation', async({page, server}) => { await page.goto(server.EMPTY_PAGE); let intercepted = false; await page.route(server.CROSS_PROCESS_PREFIX + '/empty.html', route => { intercepted = true; route.continue(); }); const response = await page.goto(server.CROSS_PROCESS_PREFIX + '/empty.html'); expect(response.ok()).toBe(true); expect(intercepted).toBe(true); }); it('should create a redirect', async({page, server}) => { await page.goto(server.PREFIX + '/empty.html'); await page.route('**/*', async(route, request) => { if (request.url() !== server.PREFIX + '/redirect_this') return route.continue(); await route.fulfill({ status: 301, headers: { 'location': '/empty.html', } }); }); const text = await page.evaluate(async url => { const data = await fetch(url); return data.text(); }, server.PREFIX + '/redirect_this'); expect(text).toBe(''); }); }); describe('Request.continue', function() { it('should work', async({page, server}) => { await page.route('**/*', route => route.continue()); await page.goto(server.EMPTY_PAGE); }); it('should amend HTTP headers', async({page, server}) => { await page.route('**/*', route => { const headers = Object.assign({}, route.request().headers()); headers['FOO'] = 'bar'; route.continue({ headers }); }); await page.goto(server.EMPTY_PAGE); const [request] = await Promise.all([ server.waitForRequest('/sleep.zzz'), page.evaluate(() => fetch('/sleep.zzz')) ]); expect(request.headers['foo']).toBe('bar'); }); it('should amend method', async({page, server}) => { const sRequest = server.waitForRequest('/sleep.zzz'); await page.goto(server.EMPTY_PAGE); await page.route('**/*', route => route.continue({ method: 'POST' })); const [request] = await Promise.all([ server.waitForRequest('/sleep.zzz'), page.evaluate(() => fetch('/sleep.zzz')) ]); expect(request.method).toBe('POST'); expect((await sRequest).method).toBe('POST'); }); it('should amend method on main request', async({page, server}) => { const request = server.waitForRequest('/empty.html'); await page.route('**/*', route => route.continue({ method: 'POST' })); await page.goto(server.EMPTY_PAGE); expect((await request).method).toBe('POST'); }); it('should amend post data', async({page, server}) => { await page.goto(server.EMPTY_PAGE); await page.route('**/*', route => { route.continue({ postData: 'doggo' }); }); const [serverRequest] = await Promise.all([ server.waitForRequest('/sleep.zzz'), page.evaluate(() => fetch('/sleep.zzz', { method: 'POST', body: 'birdy' })) ]); expect(await serverRequest.postBody).toBe('doggo'); }); }); describe('Request.fulfill', function() { it('should work', async({page, server}) => { await page.route('**/*', route => { route.fulfill({ status: 201, headers: { foo: 'bar' }, contentType: 'text/html', body: 'Yo, page!' }); }); const response = await page.goto(server.EMPTY_PAGE); expect(response.status()).toBe(201); expect(response.headers().foo).toBe('bar'); expect(await page.evaluate(() => document.body.textContent)).toBe('Yo, page!'); }); it('should work with status code 422', async({page, server}) => { await page.route('**/*', route => { route.fulfill({ status: 422, body: 'Yo, page!' }); }); const response = await page.goto(server.EMPTY_PAGE); expect(response.status()).toBe(422); expect(response.statusText()).toBe('Unprocessable Entity'); expect(await page.evaluate(() => document.body.textContent)).toBe('Yo, page!'); }); it('should allow mocking binary responses', async({page, server, golden}) => { await page.route('**/*', route => { const imageBuffer = fs.readFileSync(path.join(__dirname, 'assets', 'pptr.png')); route.fulfill({ contentType: 'image/png', body: imageBuffer }); }); await page.evaluate(PREFIX => { const img = document.createElement('img'); img.src = PREFIX + '/does-not-exist.png'; document.body.appendChild(img); return new Promise(fulfill => img.onload = fulfill); }, server.PREFIX); const img = await page.$('img'); expect(await img.screenshot()).toBeGolden(golden('mock-binary-response.png')); }); it('should work with file path', async({page, server, golden}) => { await page.route('**/*', route => route.fulfill({ contentType: 'shouldBeIgnored', path: path.join(__dirname, 'assets', 'pptr.png') })); await page.evaluate(PREFIX => { const img = document.createElement('img'); img.src = PREFIX + '/does-not-exist.png'; document.body.appendChild(img); return new Promise(fulfill => img.onload = fulfill); }, server.PREFIX); const img = await page.$('img'); expect(await img.screenshot()).toBeGolden(golden('mock-binary-response.png')); }); it('should stringify intercepted request response headers', async({page, server}) => { await page.route('**/*', route => { route.fulfill({ status: 200, headers: { 'foo': true }, body: 'Yo, page!' }); }); const response = await page.goto(server.EMPTY_PAGE); expect(response.status()).toBe(200); const headers = response.headers(); expect(headers.foo).toBe('true'); expect(await page.evaluate(() => document.body.textContent)).toBe('Yo, page!'); }); it('should not modify the headers sent to the server', async({page, server}) => { await page.goto(server.PREFIX + '/empty.html'); const interceptedRequests = []; //this is just to enable request interception, which disables caching in chromium await page.route(server.PREFIX + '/unused'); server.setRoute('/something', (request, response) => { interceptedRequests.push(request); response.writeHead(200, { 'Access-Control-Allow-Origin': '*' }); response.end('done'); }); const text = await page.evaluate(async url => { const data = await fetch(url); return data.text(); }, server.CROSS_PROCESS_PREFIX + '/something'); expect(text).toBe('done'); let playwrightRequest; await page.route(server.CROSS_PROCESS_PREFIX + '/something', (route, request) => { playwrightRequest = request; route.continue({ headers: { ...request.headers() } }); }); const textAfterRoute = await page.evaluate(async url => { const data = await fetch(url); return data.text(); }, server.CROSS_PROCESS_PREFIX + '/something'); expect(textAfterRoute).toBe('done'); expect(interceptedRequests.length).toBe(2); expect(interceptedRequests[1].headers).toEqual(interceptedRequests[0].headers); }); it('should include the origin header', async({page, server}) => { await page.goto(server.PREFIX + '/empty.html'); let interceptedRequest; await page.route(server.CROSS_PROCESS_PREFIX + '/something', (route, request) => { interceptedRequest = request; route.fulfill({ headers: { 'Access-Control-Allow-Origin': '*', }, contentType: 'text/plain', body: 'done' }); }); const text = await page.evaluate(async url => { const data = await fetch(url); return data.text(); }, server.CROSS_PROCESS_PREFIX + '/something'); expect(text).toBe('done'); expect(interceptedRequest.headers()['origin']).toEqual(server.PREFIX); }); }); describe('Interception vs isNavigationRequest', () => { it('should work with request interception', async({page, server}) => { const requests = new Map(); await page.route('**/*', route => { requests.set(route.request().url().split('/').pop(), route.request()); route.continue(); }); server.setRedirect('/rrredirect', '/frames/one-frame.html'); await page.goto(server.PREFIX + '/rrredirect'); expect(requests.get('rrredirect').isNavigationRequest()).toBe(true); expect(requests.get('one-frame.html').isNavigationRequest()).toBe(true); expect(requests.get('frame.html').isNavigationRequest()).toBe(true); expect(requests.get('script.js').isNavigationRequest()).toBe(false); expect(requests.get('style.css').isNavigationRequest()).toBe(false); }); }); describe('ignoreHTTPSErrors', function() { it('should work with request interception', async({browser, httpsServer}) => { const context = await browser.newContext({ ignoreHTTPSErrors: true }); const page = await context.newPage(); await page.route('**/*', route => route.continue()); const response = await page.goto(httpsServer.EMPTY_PAGE); expect(response.status()).toBe(200); await context.close(); }); }); describe('service worker', function() { it('should intercept after a service worker', async({browser, page, server, context}) => { await page.goto(server.PREFIX + '/serviceworkers/fetchdummy/sw.html'); await page.evaluate(() => window.activationPromise); // Sanity check. const swResponse = await page.evaluate(() => fetchDummy('foo')); expect(swResponse).toBe('responseFromServiceWorker:foo'); await page.route('**/foo', route => { const slash = route.request().url().lastIndexOf('/'); const name = route.request().url().substring(slash + 1); route.fulfill({ status: 200, contentType: 'text/css', body: 'responseFromInterception:' + name }); }); // Page route is applied after service worker fetch event. const swResponse2 = await page.evaluate(() => fetchDummy('foo')); expect(swResponse2).toBe('responseFromServiceWorker:foo'); // Page route is not applied to service worker initiated fetch. const nonInterceptedResponse = await page.evaluate(() => fetchDummy('passthrough')); expect(nonInterceptedResponse).toBe('FAILURE: Not Found'); }); }); describe('glob', function() { it('should work with glob', async({newPage, httpsServer}) => { expect(helper.globToRegex('**/*.js').test('https://localhost:8080/foo.js')).toBeTruthy(); expect(helper.globToRegex('**/*.css').test('https://localhost:8080/foo.js')).toBeFalsy(); expect(helper.globToRegex('*.js').test('https://localhost:8080/foo.js')).toBeFalsy(); expect(helper.globToRegex('https://**/*.js').test('https://localhost:8080/foo.js')).toBeTruthy(); expect(helper.globToRegex('http://localhost:8080/simple/path.js').test('http://localhost:8080/simple/path.js')).toBeTruthy(); expect(helper.globToRegex('http://localhost:8080/?imple/path.js').test('http://localhost:8080/Simple/path.js')).toBeTruthy(); expect(helper.globToRegex('**/{a,b}.js').test('https://localhost:8080/a.js')).toBeTruthy(); expect(helper.globToRegex('**/{a,b}.js').test('https://localhost:8080/b.js')).toBeTruthy(); expect(helper.globToRegex('**/{a,b}.js').test('https://localhost:8080/c.js')).toBeFalsy(); expect(helper.globToRegex('**/*.{png,jpg,jpeg}').test('https://localhost:8080/c.jpg')).toBeTruthy(); expect(helper.globToRegex('**/*.{png,jpg,jpeg}').test('https://localhost:8080/c.jpeg')).toBeTruthy(); expect(helper.globToRegex('**/*.{png,jpg,jpeg}').test('https://localhost:8080/c.png')).toBeTruthy(); expect(helper.globToRegex('**/*.{png,jpg,jpeg}').test('https://localhost:8080/c.css')).toBeFalsy(); }); }); describe('regexp', function() { it('should work with regular expression passed from a different context', async({page, server}) => { const ctx = vm.createContext(); const regexp = vm.runInContext('new RegExp("empty\\.html")', ctx); let intercepted = false; await page.route(regexp, (route, request) => { expect(route.request()).toBe(request); expect(request.url()).toContain('empty.html'); expect(request.headers()['user-agent']).toBeTruthy(); expect(request.method()).toBe('GET'); expect(request.postData()).toBe(null); expect(request.isNavigationRequest()).toBe(true); expect(request.resourceType()).toBe('document'); expect(request.frame() === page.mainFrame()).toBe(true); expect(request.frame().url()).toBe('about:blank'); route.continue(); intercepted = true; }); const response = await page.goto(server.EMPTY_PAGE); expect(response.ok()).toBe(true); expect(intercepted).toBe(true); }); });
test/interception.spec.js
0
https://github.com/microsoft/playwright/commit/2d68830411ead95c37631b73cd88d8a32b08dd38
[ 0.00017880141967907548, 0.00017254348495043814, 0.00016657047672197223, 0.00017265911446884274, 0.0000028365734578983393 ]
{ "id": 4, "code_window": [ " for (const test of this._collector.tests()) {\n", " if (fullNameRegex.test(test.fullName()))\n", " this._filter.markFocused(test);\n" ], "labels": [ "keep", "replace", "keep" ], "after_edit": [ " if (fullNameRegex.test(test.fullName())) {\n" ], "file_path": "utils/testrunner/index.js", "type": "replace", "edit_start_line_idx": 86 }
<!DOCTYPE html> <html> <head> <title>Rotated button test</title> </head> <body> <script src="mouse-helper.js"></script> <button onclick="clicked();">Click target</button> <style> button { transform: rotateY(180deg); } </style> <script> window.result = 'Was not clicked'; function clicked() { result = 'Clicked'; } </script> </body> </html>
test/assets/input/rotatedButton.html
0
https://github.com/microsoft/playwright/commit/2d68830411ead95c37631b73cd88d8a32b08dd38
[ 0.00017895543714985251, 0.00017335447773803025, 0.00016997041529975832, 0.00017113758076447994, 0.000003989037395513151 ]
{ "id": 5, "code_window": [ " this._filter.markFocused(test);\n", " }\n" ], "labels": [ "add", "keep" ], "after_edit": [ " focusedTests.push(test);\n", " }\n" ], "file_path": "utils/testrunner/index.js", "type": "add", "edit_start_line_idx": 88 }
/** * Copyright 2017 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ const { TestRunner, Result, TestResult } = require('./TestRunner'); const { TestCollector, FocusedFilter, Repeater } = require('./TestCollector'); const Reporter = require('./Reporter'); const { Matchers } = require('./Matchers'); class DefaultTestRunner { constructor(options = {}) { const { // Our options. crashIfTestsAreFocusedOnCI = true, exit = true, reporter = true, // Collector options. timeout, // Runner options. parallel = 1, breakOnFailure, totalTimeout, hookTimeout = timeout, // Reporting options. showSlowTests, showMarkedAsFailingTests, verbose, summary, } = options; this._crashIfTestsAreFocusedOnCI = crashIfTestsAreFocusedOnCI; this._exit = exit; this._parallel = parallel; this._breakOnFailure = breakOnFailure; this._totalTimeout = totalTimeout; this._hookTimeout = hookTimeout; this._needReporter = reporter; this._showSlowTests = showSlowTests; this._showMarkedAsFailingTests = showMarkedAsFailingTests; this._verbose = verbose; this._summary = summary; this._filter = new FocusedFilter(); this._repeater = new Repeater(); this._collector = new TestCollector({ timeout }); this._api = { ...this._collector.api(), expect: new Matchers().expect, }; this._collector.addSuiteAttribute('only', s => this._filter.markFocused(s)); this._collector.addSuiteAttribute('skip', s => s.setSkipped(true)); this._collector.addSuiteModifier('repeat', (s, count) => this._repeater.repeat(s, count)); this._collector.addTestAttribute('only', t => this._filter.markFocused(t)); this._collector.addTestAttribute('skip', t => t.setSkipped(true)); this._collector.addTestAttribute('todo', t => t.setSkipped(true)); this._collector.addTestAttribute('slow', t => t.setTimeout(t.timeout() * 3)); this._collector.addTestModifier('repeat', (t, count) => this._repeater.repeat(t, count)); this._api.fdescribe = this._api.describe.only; this._api.xdescribe = this._api.describe.skip; this._api.fit = this._api.it.only; this._api.xit = this._api.it.skip; } collector() { return this._collector; } api() { return this._api; } focusMatchingTests(fullNameRegex) { for (const test of this._collector.tests()) { if (fullNameRegex.test(test.fullName())) this._filter.markFocused(test); } } repeatAll(repeatCount) { this._repeater.repeat(this._collector.rootSuite(), repeatCount); } async run() { let reporter = null; if (this._needReporter) { const reporterDelegate = { focusedSuites: () => this._filter.focusedTests(this._collector.suites()), focusedTests: () => this._filter.focusedSuites(this._collector.tests()), hasFocusedTestsOrSuites: () => this._filter.hasFocusedTestsOrSuites(), parallel: () => this._parallel, testCount: () => this._collector.tests().length, }; const reporterOptions = { showSlowTests: this._showSlowTests, showMarkedAsFailingTests: this._showMarkedAsFailingTests, verbose: this._verbose, summary: this._summary, }; reporter = new Reporter(reporterDelegate, reporterOptions); } if (this._crashIfTestsAreFocusedOnCI && process.env.CI && this._filter.hasFocusedTestsOrSuites()) { if (reporter) await reporter.onStarted([]); const result = new Result(); result.setResult(TestResult.Crashed, '"focused" tests or suites are probitted on CI'); if (reporter) await reporter.onFinished(result); if (this._exit) process.exit(result.exitCode); return result; } const testRuns = this._repeater.createTestRuns(this._filter.filter(this._collector.tests())); const testRunner = new TestRunner(); const result = await testRunner.run(testRuns, { parallel: this._parallel, breakOnFailure: this._breakOnFailure, totalTimeout: this._totalTimeout, hookTimeout: this._hookTimeout, onStarted: (...args) => reporter && reporter.onStarted(...args), onFinished: (...args) => reporter && reporter.onFinished(...args), onTestRunStarted: (...args) => reporter && reporter.onTestRunStarted(...args), onTestRunFinished: (...args) => reporter && reporter.onTestRunFinished(...args), }); if (this._exit) process.exit(result.exitCode); return result; } } module.exports = DefaultTestRunner;
utils/testrunner/index.js
1
https://github.com/microsoft/playwright/commit/2d68830411ead95c37631b73cd88d8a32b08dd38
[ 0.9757606983184814, 0.2326653152704239, 0.00016480486374348402, 0.00024404822033829987, 0.3852717876434326 ]
{ "id": 5, "code_window": [ " this._filter.markFocused(test);\n", " }\n" ], "labels": [ "add", "keep" ], "after_edit": [ " focusedTests.push(test);\n", " }\n" ], "file_path": "utils/testrunner/index.js", "type": "add", "edit_start_line_idx": 88 }
export class Foo { }
utils/doclint/check_public_api/test/diff-classes/foo.ts
0
https://github.com/microsoft/playwright/commit/2d68830411ead95c37631b73cd88d8a32b08dd38
[ 0.00017297748127020895, 0.00017297748127020895, 0.00017297748127020895, 0.00017297748127020895, 0 ]