hunk
dict
file
stringlengths
0
11.8M
file_path
stringlengths
2
234
label
int64
0
1
commit_url
stringlengths
74
103
dependency_score
sequencelengths
5
5
{ "id": 5, "code_window": [ "}\n", "\n", ".monaco-menu .monaco-action-bar.vertical .submenu-indicator {\n", "\tpadding: 0.8em .5em;\n", "}\n", "\n", ".monaco-menu .monaco-action-bar.vertical .action-item.disabled .keybinding,\n", ".monaco-menu .monaco-action-bar.vertical .action-item.disabled .submenu-indicator {\n", "\topacity: 0.4;\n", "}\n" ], "labels": [ "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/base/browser/ui/menu/menu.css", "type": "replace", "edit_start_line_idx": 64 }
{ "": [ "--------------------------------------------------------------------------------------------", "Copyright (c) Microsoft Corporation. All rights reserved.", "Licensed under the MIT License. See License.txt in the project root for license information.", "--------------------------------------------------------------------------------------------", "Do not edit this file. It is machine generated." ], "typescript.projectConfigNoWorkspace": "Bir TypeScript veya JavaScript projesini kullanmak için lütfen bir klasör açın", "typescript.projectConfigUnsupportedFile": "TypeScript mi yoksa JavaScript mi projesi olduğu tespit edilemedi. Desteklenmeyen dosya türü", "typescript.projectConfigCouldNotGetInfo": "TypeScript mi yoksa JavaScript mi projesi olduğu tespit edilemedi", "typescript.noTypeScriptProjectConfig": "Dosya bir TypeScript projesinin parçası değil. Daha fazla bilgi almak için [buraya]({0}) tıklayın.", "typescript.noJavaScriptProjectConfig": "Dosya bir JavaScript projesinin parçası değil. Daha fazla bilgi almak için [buraya]({0}) tıklayın.", "typescript.configureTsconfigQuickPick": "tsconfig.json'u yapılandır", "typescript.configureJsconfigQuickPick": "jsconfig.json'u yapılandır" }
i18n/trk/extensions/typescript-language-features/out/commands.i18n.json
0
https://github.com/microsoft/vscode/commit/26e5a55cd8452477bfb7a472ea9475761600adf0
[ 0.00017597529222257435, 0.00017365072562824935, 0.00017132615903392434, 0.00017365072562824935, 0.000002324566594325006 ]
{ "id": 5, "code_window": [ "}\n", "\n", ".monaco-menu .monaco-action-bar.vertical .submenu-indicator {\n", "\tpadding: 0.8em .5em;\n", "}\n", "\n", ".monaco-menu .monaco-action-bar.vertical .action-item.disabled .keybinding,\n", ".monaco-menu .monaco-action-bar.vertical .action-item.disabled .submenu-indicator {\n", "\topacity: 0.4;\n", "}\n" ], "labels": [ "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/base/browser/ui/menu/menu.css", "type": "replace", "edit_start_line_idx": 64 }
{ "": [ "--------------------------------------------------------------------------------------------", "Copyright (c) Microsoft Corporation. All rights reserved.", "Licensed under the MIT License. See License.txt in the project root for license information.", "--------------------------------------------------------------------------------------------", "Do not edit this file. It is machine generated." ], "notCompatibleDownload": "Téléchargement impossible car l'extension compatible avec la version actuelle '{0}' de VS Code est introuvable." }
i18n/fra/src/vs/platform/extensionManagement/node/extensionGalleryService.i18n.json
0
https://github.com/microsoft/vscode/commit/26e5a55cd8452477bfb7a472ea9475761600adf0
[ 0.00017565494636073709, 0.00017285611829720438, 0.0001700573047855869, 0.00017285611829720438, 0.000002798820787575096 ]
{ "id": 6, "code_window": [ ".monaco-workbench > .part.menubar {\n", "\tdisplay: flex;\n", "\tposition: absolute;\n", "\tfont-size: 12px;\n", "\tbox-sizing: border-box;\n", "\tpadding-left: 35px;\n", "\tpadding-right: 138px;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/browser/parts/menubar/media/menubarpart.css", "type": "replace", "edit_start_line_idx": 8 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ .monaco-menu .monaco-action-bar.vertical { margin-left: 0; overflow: visible; } .monaco-menu .monaco-action-bar.vertical .actions-container { display: block; } .monaco-menu .monaco-action-bar.vertical .action-item { padding: 0; -ms-transform: none; -webkit-transform: none; -moz-transform: none; -o-transform: none; transform: none; display: -ms-flexbox; display: flex; } .monaco-menu .monaco-action-bar.vertical .action-item.active { -ms-transform: none; -webkit-transform: none; -moz-transform: none; -o-transform: none; transform: none; } .monaco-menu .monaco-action-bar.vertical .action-item.focused { background-color: #E4E4E4; } .monaco-menu .monaco-action-bar.vertical .action-menu-item { -ms-flex: 1 1 auto; flex: 1 1 auto; display: -ms-flexbox; display: flex; } .monaco-menu .monaco-action-bar.vertical .action-label { -ms-flex: 1 1 auto; flex: 1 1 auto; text-decoration: none; padding: 0.8em 1em; line-height: 1.1em; background: none; } .monaco-menu .monaco-action-bar.vertical .keybinding, .monaco-menu .monaco-action-bar.vertical .submenu-indicator { display: inline-block; -ms-flex: 2 1 auto; flex: 2 1 auto; padding: 0.8em 1em; line-height: 1.1em; font-size: 12px; text-align: right; } .monaco-menu .monaco-action-bar.vertical .submenu-indicator { padding: 0.8em .5em; } .monaco-menu .monaco-action-bar.vertical .action-item.disabled .keybinding, .monaco-menu .monaco-action-bar.vertical .action-item.disabled .submenu-indicator { opacity: 0.4; } .monaco-menu .monaco-action-bar.vertical .action-label:not(.separator) { display: inline-block; -webkit-box-sizing: border-box; -o-box-sizing: border-box; -moz-box-sizing: border-box; -ms-box-sizing: border-box; box-sizing: border-box; margin: 0; } .monaco-menu .monaco-action-bar.vertical .action-label.separator { padding: 0.5em 0 0 0; margin-bottom: 0.5em; width: 100%; } .monaco-menu .monaco-action-bar.vertical .action-label.separator.text { padding: 0.7em 1em 0.1em 1em; font-weight: bold; opacity: 1; } .monaco-menu .monaco-action-bar.vertical .action-label:hover { color: inherit; } .monaco-menu .monaco-action-bar.vertical .action-label.checked:after { content: ' \2713'; } /* Context Menu */ .context-view.monaco-menu-container { font-family: "Segoe WPC", "Segoe UI", ".SFNSDisplay-Light", "SFUIText-Light", "HelveticaNeue-Light", sans-serif, "Droid Sans Fallback"; outline: 0; box-shadow: 0 2px 8px #A8A8A8; border: none; color: #646465; background-color: white; -webkit-animation: fadeIn 0.083s linear; -o-animation: fadeIn 0.083s linear; -moz-animation: fadeIn 0.083s linear; -ms-animation: fadeIn 0.083s linear; animation: fadeIn 0.083s linear; } .context-view.monaco-menu-container :focus { outline: 0; } .monaco-menu .monaco-action-bar.vertical .action-item { border: 1px solid transparent; /* prevents jumping behaviour on hover or focus */ } /* Dark theme */ .vs-dark .monaco-menu .monaco-action-bar.vertical .action-item.focused { background-color: #4B4C4D; } .vs-dark .context-view.monaco-menu-container { box-shadow: 0 2px 8px #000; color: #BBB; background-color: #2D2F31; } /* High Contrast Theming */ .hc-black .context-view.monaco-menu-container { border: 2px solid #6FC3DF; color: white; background-color: #0C141F; box-shadow: none; } .hc-black .monaco-menu .monaco-action-bar.vertical .action-item.focused { background: none; border: 1px dotted #f38518; }
src/vs/base/browser/ui/menu/menu.css
1
https://github.com/microsoft/vscode/commit/26e5a55cd8452477bfb7a472ea9475761600adf0
[ 0.0008505028672516346, 0.0003396357933524996, 0.00016562371456529945, 0.0002584397152531892, 0.0001897703332360834 ]
{ "id": 6, "code_window": [ ".monaco-workbench > .part.menubar {\n", "\tdisplay: flex;\n", "\tposition: absolute;\n", "\tfont-size: 12px;\n", "\tbox-sizing: border-box;\n", "\tpadding-left: 35px;\n", "\tpadding-right: 138px;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/browser/parts/menubar/media/menubarpart.css", "type": "replace", "edit_start_line_idx": 8 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { CancellationToken, Disposable, FormattingOptions, TextDocument, window, workspace as Workspace, workspace, WorkspaceConfiguration } from 'vscode'; import * as Proto from '../protocol'; import { ITypeScriptServiceClient } from '../typescriptService'; import API from '../utils/api'; import { isTypeScriptDocument } from '../utils/languageModeIds'; function objsAreEqual<T>(a: T, b: T): boolean { let keys = Object.keys(a); for (let i = 0; i < keys.length; i++) { let key = keys[i]; if ((a as any)[key] !== (b as any)[key]) { return false; } } return true; } interface FileConfiguration { formatOptions: Proto.FormatCodeSettings; preferences: Proto.UserPreferences; } function areFileConfigurationsEqual(a: FileConfiguration, b: FileConfiguration): boolean { return ( objsAreEqual(a.formatOptions, b.formatOptions) && objsAreEqual(a.preferences, b.preferences) ); } export default class FileConfigurationManager { private onDidCloseTextDocumentSub: Disposable | undefined; private formatOptions: { [key: string]: FileConfiguration | undefined } = Object.create(null); public constructor( private readonly client: ITypeScriptServiceClient ) { this.onDidCloseTextDocumentSub = Workspace.onDidCloseTextDocument((textDocument) => { const key = textDocument.uri.toString(); // When a document gets closed delete the cached formatting options. // This is necessary since the tsserver now closed a project when its // last file in it closes which drops the stored formatting options // as well. delete this.formatOptions[key]; }); } public dispose() { if (this.onDidCloseTextDocumentSub) { this.onDidCloseTextDocumentSub.dispose(); this.onDidCloseTextDocumentSub = undefined; } } public async ensureConfigurationForDocument( document: TextDocument, token: CancellationToken | undefined ): Promise<void> { const editor = window.visibleTextEditors.find(editor => editor.document.fileName === document.fileName); if (editor) { const formattingOptions = { tabSize: editor.options.tabSize, insertSpaces: editor.options.insertSpaces } as FormattingOptions; return this.ensureConfigurationOptions(document, formattingOptions, token); } } public async ensureConfigurationOptions( document: TextDocument, options: FormattingOptions, token: CancellationToken | undefined ): Promise<void> { const file = this.client.toPath(document.uri); if (!file) { return; } const key = document.uri.toString(); const cachedOptions = this.formatOptions[key]; const currentOptions = this.getFileOptions(document, options); if (cachedOptions && areFileConfigurationsEqual(cachedOptions, currentOptions)) { return; } this.formatOptions[key] = currentOptions; const args: Proto.ConfigureRequestArguments = { file, ...currentOptions, }; await this.client.execute('configure', args, token); } public reset() { this.formatOptions = Object.create(null); } private getFileOptions( document: TextDocument, options: FormattingOptions ): FileConfiguration { return { formatOptions: this.getFormatOptions(document, options), preferences: this.getPreferences(document) }; } private getFormatOptions( document: TextDocument, options: FormattingOptions ): Proto.FormatCodeSettings { const config = workspace.getConfiguration( isTypeScriptDocument(document) ? 'typescript.format' : 'javascript.format', document.uri); return { tabSize: options.tabSize, indentSize: options.tabSize, convertTabsToSpaces: options.insertSpaces, // We can use \n here since the editor normalizes later on to its line endings. newLineCharacter: '\n', insertSpaceAfterCommaDelimiter: config.get<boolean>('insertSpaceAfterCommaDelimiter'), insertSpaceAfterConstructor: config.get<boolean>('insertSpaceAfterConstructor'), insertSpaceAfterSemicolonInForStatements: config.get<boolean>('insertSpaceAfterSemicolonInForStatements'), insertSpaceBeforeAndAfterBinaryOperators: config.get<boolean>('insertSpaceBeforeAndAfterBinaryOperators'), insertSpaceAfterKeywordsInControlFlowStatements: config.get<boolean>('insertSpaceAfterKeywordsInControlFlowStatements'), insertSpaceAfterFunctionKeywordForAnonymousFunctions: config.get<boolean>('insertSpaceAfterFunctionKeywordForAnonymousFunctions'), insertSpaceBeforeFunctionParenthesis: config.get<boolean>('insertSpaceBeforeFunctionParenthesis'), insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: config.get<boolean>('insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis'), insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: config.get<boolean>('insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets'), insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces: config.get<boolean>('insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces'), insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: config.get<boolean>('insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces'), insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces: config.get<boolean>('insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces'), insertSpaceAfterTypeAssertion: config.get<boolean>('insertSpaceAfterTypeAssertion'), placeOpenBraceOnNewLineForFunctions: config.get<boolean>('placeOpenBraceOnNewLineForFunctions'), placeOpenBraceOnNewLineForControlBlocks: config.get<boolean>('placeOpenBraceOnNewLineForControlBlocks'), }; } private getPreferences(document: TextDocument): Proto.UserPreferences { if (!this.client.apiVersion.gte(API.v290)) { return {}; } const preferences = workspace.getConfiguration( isTypeScriptDocument(document) ? 'typescript.preferences' : 'javascript.preferences', document.uri); return { quotePreference: getQuoteStylePreference(preferences), importModuleSpecifierPreference: getImportModuleSpecifierPreference(preferences), allowTextChangesInNewFiles: document.uri.scheme === 'file' }; } } function getQuoteStylePreference(config: WorkspaceConfiguration) { switch (config.get<string>('quoteStyle')) { case 'single': return 'single'; case 'double': return 'double'; default: return undefined; } } function getImportModuleSpecifierPreference(config: WorkspaceConfiguration) { switch (config.get<string>('importModuleSpecifier')) { case 'relative': return 'relative'; case 'non-relative': return 'non-relative'; default: return undefined; } }
extensions/typescript-language-features/src/features/fileConfigurationManager.ts
0
https://github.com/microsoft/vscode/commit/26e5a55cd8452477bfb7a472ea9475761600adf0
[ 0.00034828518982976675, 0.00018316156638320535, 0.00016535389295313507, 0.00017322221538051963, 0.000040509828977519646 ]
{ "id": 6, "code_window": [ ".monaco-workbench > .part.menubar {\n", "\tdisplay: flex;\n", "\tposition: absolute;\n", "\tfont-size: 12px;\n", "\tbox-sizing: border-box;\n", "\tpadding-left: 35px;\n", "\tpadding-right: 138px;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/browser/parts/menubar/media/menubarpart.css", "type": "replace", "edit_start_line_idx": 8 }
{ "": [ "--------------------------------------------------------------------------------------------", "Copyright (c) Microsoft Corporation. All rights reserved.", "Licensed under the MIT License. See License.txt in the project root for license information.", "--------------------------------------------------------------------------------------------", "Do not edit this file. It is machine generated." ], "errorKeybindingsFileDirty": "Kaydedilmemiş değişiklikler içerdiği için tuş bağları yapılandırma dosyasına yazılamıyor. Lütfen dosyayı kaydedin ve tekrar deneyin.", "parseErrors": "Tuş bağları yapılandırma dosyasına yazılamıyor. Lütfen dosyadaki hata/uyarıları düzeltmek için dosyayı açın ve tekrar deneyin.", "errorInvalidConfiguration": "Tuş bağları yapılandırma dosyasına yazılamadı. Dosyada dizi olmayan bir nesne var. Temizlemek için lütfen dosyayı açın ve yeniden deneyin.", "emptyKeybindingsHeader": "Varsayılanların üzerine yazmak için tuş bağlarınızı bu dosyaya yerleştirin" }
i18n/trk/src/vs/workbench/services/keybinding/common/keybindingEditing.i18n.json
0
https://github.com/microsoft/vscode/commit/26e5a55cd8452477bfb7a472ea9475761600adf0
[ 0.0001683680311543867, 0.00016769359353929758, 0.00016701914137229323, 0.00016769359353929758, 6.744448910467327e-7 ]
{ "id": 6, "code_window": [ ".monaco-workbench > .part.menubar {\n", "\tdisplay: flex;\n", "\tposition: absolute;\n", "\tfont-size: 12px;\n", "\tbox-sizing: border-box;\n", "\tpadding-left: 35px;\n", "\tpadding-right: 138px;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/browser/parts/menubar/media/menubarpart.css", "type": "replace", "edit_start_line_idx": 8 }
{ "": [ "--------------------------------------------------------------------------------------------", "Copyright (c) Microsoft Corporation. All rights reserved.", "Licensed under the MIT License. See License.txt in the project root for license information.", "--------------------------------------------------------------------------------------------", "Do not edit this file. It is machine generated." ], "acceptCurrentChange": "Accepter la modification actuelle", "acceptIncomingChange": "Accepter la modification entrante", "acceptBothChanges": "Accepter les deux modifications", "compareChanges": "Comparer les modifications" }
i18n/fra/extensions/merge-conflict/out/codelensProvider.i18n.json
0
https://github.com/microsoft/vscode/commit/26e5a55cd8452477bfb7a472ea9475761600adf0
[ 0.00017620599828660488, 0.00017604234744794667, 0.00017587868205737323, 0.00017604234744794667, 1.636581146158278e-7 ]
{ "id": 7, "code_window": [ ".monaco-shell .monaco-menu .monaco-action-bar.vertical {\n", "\tpadding: .5em 0;\n", "}\n", "\n", ".monaco-shell .monaco-menu .monaco-action-bar.vertical .action-label:not(.separator),\n", ".monaco-shell .monaco-menu .monaco-action-bar.vertical .keybinding {\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep" ], "after_edit": [ ".monaco-shell .monaco-menu .monaco-action-bar.vertical .action-menu-item {\n", "\theight: 1.8em;\n", "}\n", "\n" ], "file_path": "src/vs/workbench/electron-browser/media/shell.css", "type": "add", "edit_start_line_idx": 71 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ .monaco-workbench > .part.menubar { display: flex; position: absolute; font-size: 12px; box-sizing: border-box; padding-left: 35px; padding-right: 138px; height: 30px; } .monaco-workbench.fullscreen > .part.menubar { position: absolute; width: 100%; margin: 0px; padding: 0px 5px; } .monaco-workbench > .part.menubar > .menubar-menu-button { display: flex; flex-shrink: 0; align-items: center; box-sizing: border-box; padding: 0px 8px; position: relative; cursor: default; -webkit-app-region: no-drag; zoom: 1; } .menubar-menu-items-holder { position: absolute; left: 0px; opacity: 1; } .menubar-menu-items-holder.monaco-menu-container { box-shadow: 0 2px 4px; } .vs-dark .menubar-menu-items-holder.monaco-menu-container { box-shadow: 0 2px 4px; }
src/vs/workbench/browser/parts/menubar/media/menubarpart.css
1
https://github.com/microsoft/vscode/commit/26e5a55cd8452477bfb7a472ea9475761600adf0
[ 0.0010512156877666712, 0.0004348816873971373, 0.00016797739954199642, 0.00030844597495160997, 0.0003269280132371932 ]
{ "id": 7, "code_window": [ ".monaco-shell .monaco-menu .monaco-action-bar.vertical {\n", "\tpadding: .5em 0;\n", "}\n", "\n", ".monaco-shell .monaco-menu .monaco-action-bar.vertical .action-label:not(.separator),\n", ".monaco-shell .monaco-menu .monaco-action-bar.vertical .keybinding {\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep" ], "after_edit": [ ".monaco-shell .monaco-menu .monaco-action-bar.vertical .action-menu-item {\n", "\theight: 1.8em;\n", "}\n", "\n" ], "file_path": "src/vs/workbench/electron-browser/media/shell.css", "type": "add", "edit_start_line_idx": 71 }
{ "": [ "--------------------------------------------------------------------------------------------", "Copyright (c) Microsoft Corporation. All rights reserved.", "Licensed under the MIT License. See License.txt in the project root for license information.", "--------------------------------------------------------------------------------------------", "Do not edit this file. It is machine generated." ], "displayName": "HTML Dili Özellikleri", "description": "HTML, Razor ve Handlebar dosyaları için zengin dil desteği sağlar.", "html.format.enable.desc": "Varsayılan HTML biçimlendiricisini etkinleştirin/devre dışı bırakın", "html.format.wrapLineLength.desc": "Satır başına en fazla karakter miktarı (0 = devre dışı bırak)", "html.format.unformatted.desc": "Yeniden biçimlendirilmeyecek virgülle ayrılmış etiketler listesi. 'null' değeri, https://www.w3.org/TR/html5/dom.html#phrasing-content adresinde listelenen tüm etiketleri varsayılan olarak belirler.", "html.format.contentUnformatted.desc": "İçeriğin yeniden biçimlendirilmeyeceği virgülle ayrılmış etiketler listesi. 'null' değeri, 'pre' etiketini varsayılan olarak belirler.", "html.format.indentInnerHtml.desc": "<head> ve <body> bölümlerini girintile.", "html.format.preserveNewLines.desc": "Ögelerden önceki mevcut satır sonlarının korunup korunmayacağı. Yalnızca ögelerden önce çalışır, etiketler içinde veya metinde çalışmaz.", "html.format.maxPreserveNewLines.desc": "Bir öbekte korunacak maksimum satır sonu sayısı. Sınırsız için 'null' değerini kullanın.", "html.format.indentHandlebars.desc": "{{#foo}} ve {{/foo}}'yu biçimlendir ve girintile.", "html.format.endWithNewline.desc": "Boş bir satırla bitir.", "html.format.extraLiners.desc": "Kendilerinden önce ek bir boş satır bulunması gereken virgülle ayrılmış etiketler listesi. 'null' değeri, \"head, body, /html\" değerini varsayılan olarak belirler.", "html.format.wrapAttributes.desc": "Öznitelikleri sarmala.", "html.format.wrapAttributes.auto": "Öznitelikleri sadece satır uzunluğu aşıldığında sarmala.", "html.format.wrapAttributes.force": "İlki hariç tüm öznitelikleri sarmala.", "html.format.wrapAttributes.forcealign": "İlki hariç tüm öznitelikleri sarmala ve hizada tut.", "html.format.wrapAttributes.forcemultiline": "Tüm öznitelikleri sarmala.", "html.suggest.angular1.desc": "Yerleşik HTML dili desteğinin Angular V1 etiketlerini ve özelliklerini önerip önermeyeceğini yapılandırır.", "html.suggest.ionic.desc": "Yerleşik HTML dili desteğinin Ionic etiketlerini, özelliklerini ve değerlerini önerip önermeyeceğini yapılandırır.", "html.suggest.html5.desc": "Yerleşik HTML dili desteğinin HTML5 etiketlerini, özelliklerini ve değerlerini önerip önermeyeceğini yapılandırır.", "html.trace.server.desc": "VS Code ve HTML dil sunucusu arasındaki iletişimi izler.", "html.validate.scripts": "Yerleşik HTML dili desteğinin HTML5 gömülü betikleri doğrulayıp doğrulamayacağını yapılandırır.", "html.validate.styles": "Yerleşik HTML dili desteğinin HTML5 gömülü stilleri doğrulayıp doğrulamayacağını yapılandırır.", "html.autoClosingTags": "HTML etiketlerinin otomatik kapatılmasını etkinleştirin/devre dışı bırakın" }
i18n/trk/extensions/html-language-features/package.i18n.json
0
https://github.com/microsoft/vscode/commit/26e5a55cd8452477bfb7a472ea9475761600adf0
[ 0.0001758971338858828, 0.00016937435430008918, 0.0001645092124817893, 0.0001685455208644271, 0.000004732546585728414 ]
{ "id": 7, "code_window": [ ".monaco-shell .monaco-menu .monaco-action-bar.vertical {\n", "\tpadding: .5em 0;\n", "}\n", "\n", ".monaco-shell .monaco-menu .monaco-action-bar.vertical .action-label:not(.separator),\n", ".monaco-shell .monaco-menu .monaco-action-bar.vertical .keybinding {\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep" ], "after_edit": [ ".monaco-shell .monaco-menu .monaco-action-bar.vertical .action-menu-item {\n", "\theight: 1.8em;\n", "}\n", "\n" ], "file_path": "src/vs/workbench/electron-browser/media/shell.css", "type": "add", "edit_start_line_idx": 71 }
{ "": [ "--------------------------------------------------------------------------------------------", "Copyright (c) Microsoft Corporation. All rights reserved.", "Licensed under the MIT License. See License.txt in the project root for license information.", "--------------------------------------------------------------------------------------------", "Do not edit this file. It is machine generated." ], "noResultWord": "Nem található a(z) '{0}' definíciója", "generic.noResults": "Definíció nem található", "meta.title": " – {0} definíció", "actions.goToDecl.label": "Ugrás a definícióra", "actions.goToDeclToSide.label": "Definíció megnyitása oldalt", "actions.previewDecl.label": "Betekintés a definícióba", "goToImplementation.noResultWord": "Nem található a(z) '{0}' implementációja", "goToImplementation.generic.noResults": "Implementáció nem található", "meta.implementations.title": " – {0} implementáció", "actions.goToImplementation.label": "Ugrás az implementációra", "actions.peekImplementation.label": "Betekintés az implementációba", "goToTypeDefinition.noResultWord": "Nem található a(z) '{0}' típusdefiníciója", "goToTypeDefinition.generic.noResults": "Típusdefiníció nem található", "meta.typeDefinitions.title": " – {0} típusdefiníció", "actions.goToTypeDefinition.label": "Ugrás a típusdefinícióra", "actions.peekTypeDefinition.label": "Betekintés a típusdefinícióba" }
i18n/hun/src/vs/editor/contrib/goToDeclaration/goToDeclarationCommands.i18n.json
0
https://github.com/microsoft/vscode/commit/26e5a55cd8452477bfb7a472ea9475761600adf0
[ 0.0001771274401107803, 0.00017424124234821647, 0.00017145754827652127, 0.00017413872410543263, 0.0000023158584099292057 ]
{ "id": 7, "code_window": [ ".monaco-shell .monaco-menu .monaco-action-bar.vertical {\n", "\tpadding: .5em 0;\n", "}\n", "\n", ".monaco-shell .monaco-menu .monaco-action-bar.vertical .action-label:not(.separator),\n", ".monaco-shell .monaco-menu .monaco-action-bar.vertical .keybinding {\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep" ], "after_edit": [ ".monaco-shell .monaco-menu .monaco-action-bar.vertical .action-menu-item {\n", "\theight: 1.8em;\n", "}\n", "\n" ], "file_path": "src/vs/workbench/electron-browser/media/shell.css", "type": "add", "edit_start_line_idx": 71 }
{ "": [ "--------------------------------------------------------------------------------------------", "Copyright (c) Microsoft Corporation. All rights reserved.", "Licensed under the MIT License. See License.txt in the project root for license information.", "--------------------------------------------------------------------------------------------", "Do not edit this file. It is machine generated." ], "internalConsoleOptions": "Controlla il comportamento della console di debug interna." }
i18n/ita/src/vs/workbench/parts/debug/common/debug.i18n.json
0
https://github.com/microsoft/vscode/commit/26e5a55cd8452477bfb7a472ea9475761600adf0
[ 0.00017660210141912103, 0.00017238847794942558, 0.00016817486903164536, 0.00017238847794942558, 0.000004213616193737835 ]
{ "id": 8, "code_window": [ ".monaco-shell .monaco-menu .monaco-action-bar.vertical .action-label:not(.separator),\n", ".monaco-shell .monaco-menu .monaco-action-bar.vertical .keybinding {\n", "\tpadding: 0.5em 2em;\n", "}\n", "\n", ".monaco-shell .monaco-menu .monaco-action-bar.vertical .action-label.separator {\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\tpadding: 0 1.5em;\n" ], "file_path": "src/vs/workbench/electron-browser/media/shell.css", "type": "replace", "edit_start_line_idx": 73 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ .monaco-menu .monaco-action-bar.vertical { margin-left: 0; overflow: visible; } .monaco-menu .monaco-action-bar.vertical .actions-container { display: block; } .monaco-menu .monaco-action-bar.vertical .action-item { padding: 0; -ms-transform: none; -webkit-transform: none; -moz-transform: none; -o-transform: none; transform: none; display: -ms-flexbox; display: flex; } .monaco-menu .monaco-action-bar.vertical .action-item.active { -ms-transform: none; -webkit-transform: none; -moz-transform: none; -o-transform: none; transform: none; } .monaco-menu .monaco-action-bar.vertical .action-item.focused { background-color: #E4E4E4; } .monaco-menu .monaco-action-bar.vertical .action-menu-item { -ms-flex: 1 1 auto; flex: 1 1 auto; display: -ms-flexbox; display: flex; } .monaco-menu .monaco-action-bar.vertical .action-label { -ms-flex: 1 1 auto; flex: 1 1 auto; text-decoration: none; padding: 0.8em 1em; line-height: 1.1em; background: none; } .monaco-menu .monaco-action-bar.vertical .keybinding, .monaco-menu .monaco-action-bar.vertical .submenu-indicator { display: inline-block; -ms-flex: 2 1 auto; flex: 2 1 auto; padding: 0.8em 1em; line-height: 1.1em; font-size: 12px; text-align: right; } .monaco-menu .monaco-action-bar.vertical .submenu-indicator { padding: 0.8em .5em; } .monaco-menu .monaco-action-bar.vertical .action-item.disabled .keybinding, .monaco-menu .monaco-action-bar.vertical .action-item.disabled .submenu-indicator { opacity: 0.4; } .monaco-menu .monaco-action-bar.vertical .action-label:not(.separator) { display: inline-block; -webkit-box-sizing: border-box; -o-box-sizing: border-box; -moz-box-sizing: border-box; -ms-box-sizing: border-box; box-sizing: border-box; margin: 0; } .monaco-menu .monaco-action-bar.vertical .action-label.separator { padding: 0.5em 0 0 0; margin-bottom: 0.5em; width: 100%; } .monaco-menu .monaco-action-bar.vertical .action-label.separator.text { padding: 0.7em 1em 0.1em 1em; font-weight: bold; opacity: 1; } .monaco-menu .monaco-action-bar.vertical .action-label:hover { color: inherit; } .monaco-menu .monaco-action-bar.vertical .action-label.checked:after { content: ' \2713'; } /* Context Menu */ .context-view.monaco-menu-container { font-family: "Segoe WPC", "Segoe UI", ".SFNSDisplay-Light", "SFUIText-Light", "HelveticaNeue-Light", sans-serif, "Droid Sans Fallback"; outline: 0; box-shadow: 0 2px 8px #A8A8A8; border: none; color: #646465; background-color: white; -webkit-animation: fadeIn 0.083s linear; -o-animation: fadeIn 0.083s linear; -moz-animation: fadeIn 0.083s linear; -ms-animation: fadeIn 0.083s linear; animation: fadeIn 0.083s linear; } .context-view.monaco-menu-container :focus { outline: 0; } .monaco-menu .monaco-action-bar.vertical .action-item { border: 1px solid transparent; /* prevents jumping behaviour on hover or focus */ } /* Dark theme */ .vs-dark .monaco-menu .monaco-action-bar.vertical .action-item.focused { background-color: #4B4C4D; } .vs-dark .context-view.monaco-menu-container { box-shadow: 0 2px 8px #000; color: #BBB; background-color: #2D2F31; } /* High Contrast Theming */ .hc-black .context-view.monaco-menu-container { border: 2px solid #6FC3DF; color: white; background-color: #0C141F; box-shadow: none; } .hc-black .monaco-menu .monaco-action-bar.vertical .action-item.focused { background: none; border: 1px dotted #f38518; }
src/vs/base/browser/ui/menu/menu.css
1
https://github.com/microsoft/vscode/commit/26e5a55cd8452477bfb7a472ea9475761600adf0
[ 0.024685509502887726, 0.005839031655341387, 0.0001860835764091462, 0.001337643014267087, 0.008022637106478214 ]
{ "id": 8, "code_window": [ ".monaco-shell .monaco-menu .monaco-action-bar.vertical .action-label:not(.separator),\n", ".monaco-shell .monaco-menu .monaco-action-bar.vertical .keybinding {\n", "\tpadding: 0.5em 2em;\n", "}\n", "\n", ".monaco-shell .monaco-menu .monaco-action-bar.vertical .action-label.separator {\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\tpadding: 0 1.5em;\n" ], "file_path": "src/vs/workbench/electron-browser/media/shell.css", "type": "replace", "edit_start_line_idx": 73 }
{ "": [ "--------------------------------------------------------------------------------------------", "Copyright (c) Microsoft Corporation. All rights reserved.", "Licensed under the MIT License. See License.txt in the project root for license information.", "--------------------------------------------------------------------------------------------", "Do not edit this file. It is machine generated." ], "sev.error": "Fehler", "sev.warning": "Warnung", "sev.info": "Info" }
i18n/deu/src/vs/base/common/severity.i18n.json
0
https://github.com/microsoft/vscode/commit/26e5a55cd8452477bfb7a472ea9475761600adf0
[ 0.00017714347632136196, 0.00017428849241696298, 0.00017143352306447923, 0.00017428849241696298, 0.0000028549766284413636 ]
{ "id": 8, "code_window": [ ".monaco-shell .monaco-menu .monaco-action-bar.vertical .action-label:not(.separator),\n", ".monaco-shell .monaco-menu .monaco-action-bar.vertical .keybinding {\n", "\tpadding: 0.5em 2em;\n", "}\n", "\n", ".monaco-shell .monaco-menu .monaco-action-bar.vertical .action-label.separator {\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\tpadding: 0 1.5em;\n" ], "file_path": "src/vs/workbench/electron-browser/media/shell.css", "type": "replace", "edit_start_line_idx": 73 }
{ "": [ "--------------------------------------------------------------------------------------------", "Copyright (c) Microsoft Corporation. All rights reserved.", "Licensed under the MIT License. See License.txt in the project root for license information.", "--------------------------------------------------------------------------------------------", "Do not edit this file. It is machine generated." ], "displayName": "Recursos da Linguagem HTML", "description": "Fornece suporte de linguagem rico para arquivos HTML, Razor e Handlebar.", "html.format.enable.desc": "Ativar/desativar o formatador HTML padrão", "html.format.wrapLineLength.desc": "Quantidade máxima de caracteres por linha (0 = desativar).", "html.format.unformatted.desc": "Lista de tags, separados por vírgula, que não deveria ser reformatada. o padrão é 'nulo' para todas as tags listadas em https://www.w3.org/TR/html5/dom.html#phrasing-content.", "html.format.contentUnformatted.desc": "Lista de tags, separada por vírgula, onde o conteúdo não deve ser reformatado. o padrão é 'nulo' para a tag 'pré'.", "html.format.indentInnerHtml.desc": "Indentar secões <head>e <body>.", "html.format.preserveNewLines.desc": "Se quebras de linha existentes antes de elementos deveriam ser preservadas. Só funciona antes de elementos, não dentro de rótulos ou para texto.", "html.format.maxPreserveNewLines.desc": "Número máximo de quebras de linha a serem preservadas em um bloco. Use 'null' para ilimitado.", "html.format.indentHandlebars.desc": "Formatar e indentar {{#foo}} e {{/ foo}}.", "html.format.endWithNewline.desc": "Finalizar com uma nova linha.", "html.format.extraLiners.desc": "Lista de rótulos, separados por vírgulas, que deveriam ter uma quebra de linha extra antes deles. 'null' admite o padrão \"head, body, /html\".", "html.format.wrapAttributes.desc": "Agrupar atributos.", "html.format.wrapAttributes.auto": "Agrupar atributos somente quando o tamanho da linha é excedido.", "html.format.wrapAttributes.force": "Agrupar cada atributo exceto o primeiro.", "html.format.wrapAttributes.forcealign": "Agrupar cada atributo, exceto o primeiro e manter alinhado.", "html.format.wrapAttributes.forcemultiline": "Agrupar cada atributo.", "html.suggest.angular1.desc": "Configura se o suporte da linguagem HTML interna sugere rótulos e propriedades do Angular V1.", "html.suggest.ionic.desc": "Configura se o suporte da linguagem HTML interna sugere rótulos, propriedades e valores Ionic.", "html.suggest.html5.desc": "Configura se o suporte da linguagem HTML interna sugere rótulos, propriedades e valores HTML5.", "html.trace.server.desc": "Rastrear a comunicação entre o VS Code e o servidor de linguagem HTML.", "html.validate.scripts": "Configura se o suporte da linguagem HTML interna valida scripts embutidos.", "html.validate.styles": "Configura se o suporte da linguagem HTML interna valida estilos embutidos.", "html.autoClosingTags": "Ativar/desativar o fechamento automático de tags HTML." }
i18n/ptb/extensions/html-language-features/package.i18n.json
0
https://github.com/microsoft/vscode/commit/26e5a55cd8452477bfb7a472ea9475761600adf0
[ 0.00017494821804575622, 0.00016987881099339575, 0.00016539565694984049, 0.00016958569176495075, 0.0000034716533718892606 ]
{ "id": 8, "code_window": [ ".monaco-shell .monaco-menu .monaco-action-bar.vertical .action-label:not(.separator),\n", ".monaco-shell .monaco-menu .monaco-action-bar.vertical .keybinding {\n", "\tpadding: 0.5em 2em;\n", "}\n", "\n", ".monaco-shell .monaco-menu .monaco-action-bar.vertical .action-label.separator {\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\tpadding: 0 1.5em;\n" ], "file_path": "src/vs/workbench/electron-browser/media/shell.css", "type": "replace", "edit_start_line_idx": 73 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "openChange": "開啟變更", "openFile": "開啟檔案", "init": "Init", "refresh": "重新整理", "stageChanges": "分段", "stageAllChanges": "全部分段", "confirmUndoMessage": "確定要清除所有變更嗎?", "confirmUndoAllOne": "{0} 個檔案中有取消暫存的變更。\n\n此動作無法回復!", "confirmUndoAllMultiple": "{0} 個檔案中有取消暫存的變更。\n\n此動作無法回復!", "cleanChangesLabel": "清除變更(&&C)", "confirmUndo": "確定要清除 '{0}' 中的變更嗎?", "irreversible": "此動作無法回復!", "undoChanges": "清除", "undoAllChanges": "全部清除", "unstage": "取消分段", "unstageAllChanges": "全部取消分段", "dirtyTreeCheckout": "無法簽出。請先認可或隱藏您的工作。", "commitStaged": "認可暫存", "commitStagedAmend": "認可暫存 (修改)", "commitStagedSignedOff": "認可暫存 (已登出)", "commit": "Commit", "commitMessage": "認可訊息", "commitAll": "全部認可", "commitAllSignedOff": "全部認可 (已登出)", "commitAll2": "全部認可", "commitStaged2": "認可暫存", "dirtyTreePull": "無法提取。請先認可或隱藏您的工作。", "authFailed": "Git 遠端的驗證失敗。", "pushToRemote": "推送至...", "pushToRemotePickMessage": "挑選遠端作為分支 '{0}' 的發送目標:", "publish": "發行", "confirmPublishMessage": "確定要將 '{0}' 發行至 '{1}' 嗎?", "confirmPublishMessageButton": "發行(&&P)", "publishPickMessage": "挑選要發行分支 '{0}' 的目標遠端:", "sync is unpredictable": "此動作會將認可發送至 '{0}' 及從中提取認可。", "ok": "確定", "cancel": "取消", "never again": "確定,不要再顯示", "undoLastCommit": "復原上次認可" }
i18n/cht/src/vs/workbench/parts/git/browser/gitActions.i18n.json
0
https://github.com/microsoft/vscode/commit/26e5a55cd8452477bfb7a472ea9475761600adf0
[ 0.00017375408788211644, 0.00017041995306499302, 0.00016857960144989192, 0.00016885483637452126, 0.000002163985755032627 ]
{ "id": 9, "code_window": [ "}\n", "\n", ".monaco-shell .monaco-menu .monaco-action-bar.vertical .submenu-indicator {\n", "\tpadding: 0.5em 1em;\n", "}\n", "\n", ".monaco-shell .monaco-menu .action-item {\n", "\tcursor: default;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tpadding: 0 1em;\n" ], "file_path": "src/vs/workbench/electron-browser/media/shell.css", "type": "replace", "edit_start_line_idx": 82 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ .monaco-menu .monaco-action-bar.vertical { margin-left: 0; overflow: visible; } .monaco-menu .monaco-action-bar.vertical .actions-container { display: block; } .monaco-menu .monaco-action-bar.vertical .action-item { padding: 0; -ms-transform: none; -webkit-transform: none; -moz-transform: none; -o-transform: none; transform: none; display: -ms-flexbox; display: flex; } .monaco-menu .monaco-action-bar.vertical .action-item.active { -ms-transform: none; -webkit-transform: none; -moz-transform: none; -o-transform: none; transform: none; } .monaco-menu .monaco-action-bar.vertical .action-item.focused { background-color: #E4E4E4; } .monaco-menu .monaco-action-bar.vertical .action-menu-item { -ms-flex: 1 1 auto; flex: 1 1 auto; display: -ms-flexbox; display: flex; } .monaco-menu .monaco-action-bar.vertical .action-label { -ms-flex: 1 1 auto; flex: 1 1 auto; text-decoration: none; padding: 0.8em 1em; line-height: 1.1em; background: none; } .monaco-menu .monaco-action-bar.vertical .keybinding, .monaco-menu .monaco-action-bar.vertical .submenu-indicator { display: inline-block; -ms-flex: 2 1 auto; flex: 2 1 auto; padding: 0.8em 1em; line-height: 1.1em; font-size: 12px; text-align: right; } .monaco-menu .monaco-action-bar.vertical .submenu-indicator { padding: 0.8em .5em; } .monaco-menu .monaco-action-bar.vertical .action-item.disabled .keybinding, .monaco-menu .monaco-action-bar.vertical .action-item.disabled .submenu-indicator { opacity: 0.4; } .monaco-menu .monaco-action-bar.vertical .action-label:not(.separator) { display: inline-block; -webkit-box-sizing: border-box; -o-box-sizing: border-box; -moz-box-sizing: border-box; -ms-box-sizing: border-box; box-sizing: border-box; margin: 0; } .monaco-menu .monaco-action-bar.vertical .action-label.separator { padding: 0.5em 0 0 0; margin-bottom: 0.5em; width: 100%; } .monaco-menu .monaco-action-bar.vertical .action-label.separator.text { padding: 0.7em 1em 0.1em 1em; font-weight: bold; opacity: 1; } .monaco-menu .monaco-action-bar.vertical .action-label:hover { color: inherit; } .monaco-menu .monaco-action-bar.vertical .action-label.checked:after { content: ' \2713'; } /* Context Menu */ .context-view.monaco-menu-container { font-family: "Segoe WPC", "Segoe UI", ".SFNSDisplay-Light", "SFUIText-Light", "HelveticaNeue-Light", sans-serif, "Droid Sans Fallback"; outline: 0; box-shadow: 0 2px 8px #A8A8A8; border: none; color: #646465; background-color: white; -webkit-animation: fadeIn 0.083s linear; -o-animation: fadeIn 0.083s linear; -moz-animation: fadeIn 0.083s linear; -ms-animation: fadeIn 0.083s linear; animation: fadeIn 0.083s linear; } .context-view.monaco-menu-container :focus { outline: 0; } .monaco-menu .monaco-action-bar.vertical .action-item { border: 1px solid transparent; /* prevents jumping behaviour on hover or focus */ } /* Dark theme */ .vs-dark .monaco-menu .monaco-action-bar.vertical .action-item.focused { background-color: #4B4C4D; } .vs-dark .context-view.monaco-menu-container { box-shadow: 0 2px 8px #000; color: #BBB; background-color: #2D2F31; } /* High Contrast Theming */ .hc-black .context-view.monaco-menu-container { border: 2px solid #6FC3DF; color: white; background-color: #0C141F; box-shadow: none; } .hc-black .monaco-menu .monaco-action-bar.vertical .action-item.focused { background: none; border: 1px dotted #f38518; }
src/vs/base/browser/ui/menu/menu.css
1
https://github.com/microsoft/vscode/commit/26e5a55cd8452477bfb7a472ea9475761600adf0
[ 0.01340772770345211, 0.004012702498584986, 0.0001725791225908324, 0.0027934368699789047, 0.0036314697936177254 ]
{ "id": 9, "code_window": [ "}\n", "\n", ".monaco-shell .monaco-menu .monaco-action-bar.vertical .submenu-indicator {\n", "\tpadding: 0.5em 1em;\n", "}\n", "\n", ".monaco-shell .monaco-menu .action-item {\n", "\tcursor: default;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tpadding: 0 1em;\n" ], "file_path": "src/vs/workbench/electron-browser/media/shell.css", "type": "replace", "edit_start_line_idx": 82 }
{ "": [ "--------------------------------------------------------------------------------------------", "Copyright (c) Microsoft Corporation. All rights reserved.", "Licensed under the MIT License. See License.txt in the project root for license information.", "--------------------------------------------------------------------------------------------", "Do not edit this file. It is machine generated." ], "authRequire": "Proxy Kimlik Doğrulaması Gerekli", "proxyauth": "{0} proxy'si kimlik doğrulama gerektiriyor." }
i18n/trk/src/vs/code/electron-main/auth.i18n.json
0
https://github.com/microsoft/vscode/commit/26e5a55cd8452477bfb7a472ea9475761600adf0
[ 0.00017703793128021061, 0.00017694875714369118, 0.00017685959755908698, 0.00017694875714369118, 8.916686056181788e-8 ]
{ "id": 9, "code_window": [ "}\n", "\n", ".monaco-shell .monaco-menu .monaco-action-bar.vertical .submenu-indicator {\n", "\tpadding: 0.5em 1em;\n", "}\n", "\n", ".monaco-shell .monaco-menu .action-item {\n", "\tcursor: default;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tpadding: 0 1em;\n" ], "file_path": "src/vs/workbench/electron-browser/media/shell.css", "type": "replace", "edit_start_line_idx": 82 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import { TPromise } from 'vs/base/common/winjs.base'; import * as mouse from 'vs/base/browser/mouseEvent'; import * as tree from 'vs/base/parts/tree/browser/tree'; import { MarkersModel, Marker, ResourceMarkers } from 'vs/workbench/parts/markers/electron-browser/markersModel'; import { IContextMenuService } from 'vs/platform/contextview/browser/contextView'; import { IMenuService, MenuId } from 'vs/platform/actions/common/actions'; import { IAction, Action } from 'vs/base/common/actions'; import { ActionItem, Separator } from 'vs/base/browser/ui/actionbar/actionbar'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; import { WorkbenchTree, WorkbenchTreeController } from 'vs/platform/list/browser/listService'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IBulkEditService } from 'vs/editor/browser/services/bulkEditService'; import { applyCodeAction } from 'vs/editor/contrib/codeAction/codeActionCommands'; import { ICommandService } from 'vs/platform/commands/common/commands'; import { IEditorService, ACTIVE_GROUP } from 'vs/workbench/services/editor/common/editorService'; import { localize } from 'vs/nls'; export class Controller extends WorkbenchTreeController { constructor( @IContextMenuService private contextMenuService: IContextMenuService, @IMenuService private menuService: IMenuService, @IKeybindingService private readonly _keybindingService: IKeybindingService, @IConfigurationService configurationService: IConfigurationService, @IBulkEditService private bulkEditService: IBulkEditService, @ICommandService private commandService: ICommandService, @IEditorService private editorService: IEditorService ) { super({}, configurationService); } protected onLeftClick(tree: tree.ITree, element: any, event: mouse.IMouseEvent): boolean { let currentFoucssed = tree.getFocus(); if (super.onLeftClick(tree, element, event)) { if (element instanceof MarkersModel) { if (currentFoucssed) { tree.setFocus(currentFoucssed); } else { tree.focusFirst(); } } return true; } return false; } public onContextMenu(tree: WorkbenchTree, element: any, event: tree.ContextMenuEvent): boolean { tree.setFocus(element, { preventOpenOnFocus: true }); const anchor = { x: event.posx, y: event.posy }; this.contextMenuService.showContextMenu({ getAnchor: () => anchor, getActions: () => TPromise.wrap(this._getMenuActions(tree, element)), getActionItem: (action) => { const keybinding = this._keybindingService.lookupKeybinding(action.id); if (keybinding) { return new ActionItem(action, action, { label: true, keybinding: keybinding.getLabel() }); } return null; }, onHide: (wasCancelled?: boolean) => { if (wasCancelled) { tree.domFocus(); } } }); return true; } private async _getMenuActions(tree: WorkbenchTree, element: any): Promise<IAction[]> { const result: IAction[] = []; if (element instanceof Marker) { const quickFixActions = await this._getQuickFixActions(tree, element); if (quickFixActions.length) { result.push(...quickFixActions); } else { result.push(new Action('problems.no.fixes', localize('no fixes available', "No fixes available"), void 0, false)); } result.push(new Separator()); } const menu = this.menuService.createMenu(MenuId.ProblemsPanelContext, tree.contextKeyService); const groups = menu.getActions(); menu.dispose(); for (let group of groups) { const [, actions] = group; result.push(...actions); result.push(new Separator()); } result.pop(); // remove last separator return result; } private async _getQuickFixActions(tree: WorkbenchTree, element: Marker): Promise<IAction[]> { const parent = tree.getNavigator(element).parent(); if (parent instanceof ResourceMarkers) { const codeActions = await parent.getFixes(element); return codeActions.map(codeAction => new Action( codeAction.command ? codeAction.command.id : codeAction.title, codeAction.title, void 0, true, () => { return this.openFileAtMarker(element) .then(() => applyCodeAction(codeAction, this.bulkEditService, this.commandService)); })); } return []; } public openFileAtMarker(element: Marker): TPromise<void> { const { resource, selection } = { resource: element.resource, selection: element.range }; return this.editorService.openEditor({ resource, options: { selection, preserveFocus: true, pinned: false, revealIfVisible: true }, }, ACTIVE_GROUP).then(() => null); } }
src/vs/workbench/parts/markers/electron-browser/markersTreeController.ts
0
https://github.com/microsoft/vscode/commit/26e5a55cd8452477bfb7a472ea9475761600adf0
[ 0.00019093218725174665, 0.00017102288256864995, 0.00016405557107646018, 0.0001701375877019018, 0.000006723806563968537 ]
{ "id": 9, "code_window": [ "}\n", "\n", ".monaco-shell .monaco-menu .monaco-action-bar.vertical .submenu-indicator {\n", "\tpadding: 0.5em 1em;\n", "}\n", "\n", ".monaco-shell .monaco-menu .action-item {\n", "\tcursor: default;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tpadding: 0 1em;\n" ], "file_path": "src/vs/workbench/electron-browser/media/shell.css", "type": "replace", "edit_start_line_idx": 82 }
// ATTENTION - THIS DIRECTORY CONTAINS THIRD PARTY OPEN SOURCE MATERIALS: [{ "name": "chjj-marked", "repositoryURL": "https://github.com/npmcomponent/chjj-marked", "version": "0.3.18", "license": "MIT" }]
src/vs/base/common/marked/OSSREADME.json
0
https://github.com/microsoft/vscode/commit/26e5a55cd8452477bfb7a472ea9475761600adf0
[ 0.0001665598392719403, 0.0001665598392719403, 0.0001665598392719403, 0.0001665598392719403, 0 ]
{ "id": 0, "code_window": [ "\t\tthis._onEditorsMoved.fire();\n", "\t}\n", "\n", "\tpublic moveEditor(input: EditorInput, from: EditorGroup, to: EditorGroup, index?: number): void;\n", "\tpublic moveEditor(input: EditorInput, from: Position, to: Position, index?: number): void;\n", "\tpublic moveEditor(input: EditorInput, arg2: any, arg3: any, index?: number): void {\n", "\t\tconst fromGroup = (typeof arg2 === 'number') ? this.stacks.groupAt(arg2) : arg2;\n", "\t\tif (!fromGroup) {\n", "\t\t\treturn;\n", "\t\t}\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tpublic moveEditor(input: EditorInput, from: EditorGroup, to: EditorGroup, index?: number, inactive?: boolean): void;\n", "\tpublic moveEditor(input: EditorInput, from: Position, to: Position, index?: number, inactive?: boolean): void;\n", "\tpublic moveEditor(input: EditorInput, arg2: any, arg3: any, index?: number, inactive?: boolean): void {\n" ], "file_path": "src/vs/workbench/browser/parts/editor/editorPart.ts", "type": "replace", "edit_start_line_idx": 810 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import 'vs/css!./media/editorpart'; import 'vs/workbench/browser/parts/editor/editor.contribution'; import { TPromise } from 'vs/base/common/winjs.base'; import { Registry } from 'vs/platform/platform'; import { Dimension, Builder, $ } from 'vs/base/browser/builder'; import nls = require('vs/nls'); import strings = require('vs/base/common/strings'); import arrays = require('vs/base/common/arrays'); import types = require('vs/base/common/types'); import errors = require('vs/base/common/errors'); import * as objects from 'vs/base/common/objects'; import { getCodeEditor } from 'vs/editor/common/services/codeEditorService'; import { toErrorMessage } from 'vs/base/common/errorMessage'; import { Scope as MementoScope } from 'vs/workbench/common/memento'; import { Part } from 'vs/workbench/browser/part'; import { BaseEditor, EditorDescriptor } from 'vs/workbench/browser/parts/editor/baseEditor'; import { IEditorRegistry, Extensions as EditorExtensions, EditorInput, EditorOptions, ConfirmResult, IWorkbenchEditorConfiguration, IEditorDescriptor, TextEditorOptions, SideBySideEditorInput, TextCompareEditorVisible, TEXT_DIFF_EDITOR_ID } from 'vs/workbench/common/editor'; import { EditorGroupsControl, Rochade, IEditorGroupsControl, ProgressState } from 'vs/workbench/browser/parts/editor/editorGroupsControl'; import { WorkbenchProgressService } from 'vs/workbench/services/progress/browser/progressService'; import { IEditorGroupService, GroupOrientation, GroupArrangement, ITabOptions } from 'vs/workbench/services/group/common/groupService'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IEditorPart } from 'vs/workbench/services/editor/browser/editorService'; import { IPartService } from 'vs/workbench/services/part/common/partService'; import { Position, POSITIONS, Direction } from 'vs/platform/editor/common/editor'; import { IStorageService } from 'vs/platform/storage/common/storage'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection'; import { IMessageService, IMessageWithAction, Severity } from 'vs/platform/message/common/message'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IProgressService } from 'vs/platform/progress/common/progress'; import { EditorStacksModel, EditorGroup, EditorIdentifier, GroupEvent } from 'vs/workbench/common/editor/editorStacksModel'; import Event, { Emitter } from 'vs/base/common/event'; import { IContextKey, IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; class ProgressMonitor { constructor(private _token: number, private progressPromise: TPromise<void>) { } public get token(): number { return this._token; } public cancel(): void { this.progressPromise.cancel(); } } interface IEditorPartUIState { ratio: number[]; groupOrientation: GroupOrientation; } interface IEditorReplacement extends EditorIdentifier { group: EditorGroup; editor: EditorInput; replaceWith: EditorInput; options?: EditorOptions; } /** * The editor part is the container for editors in the workbench. Based on the editor input being opened, it asks the registered * editor for the given input to show the contents. The editor part supports up to 3 side-by-side editors. */ export class EditorPart extends Part implements IEditorPart, IEditorGroupService { public _serviceBrand: any; private static GROUP_LEFT = nls.localize('groupOneVertical', "Left"); private static GROUP_CENTER = nls.localize('groupTwoVertical', "Center"); private static GROUP_RIGHT = nls.localize('groupThreeVertical', "Right"); private static GROUP_TOP = nls.localize('groupOneHorizontal', "Top"); private static GROUP_MIDDLE = nls.localize('groupTwoHorizontal', "Center"); private static GROUP_BOTTOM = nls.localize('groupThreeHorizontal', "Bottom"); private static EDITOR_PART_UI_STATE_STORAGE_KEY = 'editorpart.uiState'; private dimension: Dimension; private editorGroupsControl: IEditorGroupsControl; private memento: any; private stacks: EditorStacksModel; private tabOptions: ITabOptions; private forceHideTabs: boolean; private doNotFireTabOptionsChanged: boolean; private revealIfOpen: boolean; private _onEditorsChanged: Emitter<void>; private _onEditorsMoved: Emitter<void>; private _onEditorOpenFail: Emitter<EditorInput>; private _onGroupOrientationChanged: Emitter<void>; private _onTabOptionsChanged: Emitter<ITabOptions>; private textCompareEditorVisible: IContextKey<boolean>; // The following data structures are partitioned into array of Position as provided by Services.POSITION array private visibleEditors: BaseEditor[]; private instantiatedEditors: BaseEditor[][]; private mapEditorInstantiationPromiseToEditor: { [editorId: string]: TPromise<BaseEditor>; }[]; private editorOpenToken: number[]; private pendingEditorInputsToClose: EditorIdentifier[]; private pendingEditorInputCloseTimeout: number; private onLayoutEmitter = new Emitter<Dimension>(); public onLayout = this.onLayoutEmitter.event; constructor( id: string, restoreFromStorage: boolean, @IMessageService private messageService: IMessageService, @ITelemetryService private telemetryService: ITelemetryService, @IStorageService private storageService: IStorageService, @IPartService private partService: IPartService, @IConfigurationService private configurationService: IConfigurationService, @IContextKeyService contextKeyService: IContextKeyService, @IInstantiationService private instantiationService: IInstantiationService ) { super(id, { hasTitle: false }); this._onEditorsChanged = new Emitter<void>(); this._onEditorsMoved = new Emitter<void>(); this._onEditorOpenFail = new Emitter<EditorInput>(); this._onGroupOrientationChanged = new Emitter<void>(); this._onTabOptionsChanged = new Emitter<ITabOptions>(); this.visibleEditors = []; this.editorOpenToken = arrays.fill(POSITIONS.length, () => 0); this.instantiatedEditors = arrays.fill(POSITIONS.length, () => []); this.mapEditorInstantiationPromiseToEditor = arrays.fill(POSITIONS.length, () => Object.create(null)); this.pendingEditorInputsToClose = []; this.pendingEditorInputCloseTimeout = null; this.stacks = this.instantiationService.createInstance(EditorStacksModel, restoreFromStorage); this.textCompareEditorVisible = TextCompareEditorVisible.bindTo(contextKeyService); const config = configurationService.getConfiguration<IWorkbenchEditorConfiguration>(); if (config && config.workbench && config.workbench.editor) { const editorConfig = config.workbench.editor; this.tabOptions = { previewEditors: editorConfig.enablePreview, showIcons: editorConfig.showIcons, showTabs: editorConfig.showTabs, tabCloseButton: editorConfig.tabCloseButton }; this.revealIfOpen = editorConfig.revealIfOpen; this.telemetryService.publicLog('workbenchEditorConfiguration', editorConfig); } else { this.tabOptions = { previewEditors: true, showIcons: false, showTabs: true, tabCloseButton: 'right' }; this.revealIfOpen = false; } this.registerListeners(); } private registerListeners(): void { this.toUnbind.push(this.stacks.onEditorDirty(identifier => this.onEditorDirty(identifier))); this.toUnbind.push(this.stacks.onEditorDisposed(identifier => this.onEditorDisposed(identifier))); this.toUnbind.push(this.stacks.onEditorOpened(identifier => this.onEditorOpened(identifier))); this.toUnbind.push(this.stacks.onEditorClosed(event => this.onEditorClosed(event))); this.toUnbind.push(this.configurationService.onDidUpdateConfiguration(e => this.onConfigurationUpdated(e.config))); } private onConfigurationUpdated(configuration: IWorkbenchEditorConfiguration): void { if (configuration && configuration.workbench && configuration.workbench.editor) { const editorConfig = configuration.workbench.editor; // Pin all preview editors of the user chose to disable preview const newPreviewEditors = editorConfig.enablePreview; if (this.tabOptions.previewEditors !== newPreviewEditors && !newPreviewEditors) { this.stacks.groups.forEach(group => { if (group.previewEditor) { this.pinEditor(group, group.previewEditor); } }); } const oldTabOptions = objects.clone(this.tabOptions); this.tabOptions = { previewEditors: newPreviewEditors, showIcons: editorConfig.showIcons, tabCloseButton: editorConfig.tabCloseButton, showTabs: this.forceHideTabs ? false : editorConfig.showTabs }; if (!this.doNotFireTabOptionsChanged && !objects.equals(oldTabOptions, this.tabOptions)) { this._onTabOptionsChanged.fire(this.tabOptions); } this.revealIfOpen = editorConfig.revealIfOpen; } } private onEditorDirty(identifier: EditorIdentifier): void { // we pin every editor that becomes dirty this.pinEditor(identifier.group, identifier.editor); } private onEditorDisposed(identifier: EditorIdentifier): void { this.pendingEditorInputsToClose.push(identifier); this.startDelayedCloseEditorsFromInputDispose(); } private onEditorOpened(identifier: EditorIdentifier): void { this.telemetryService.publicLog('editorOpened', identifier.editor.getTelemetryDescriptor()); } private onEditorClosed(event: GroupEvent): void { this.telemetryService.publicLog('editorClosed', event.editor.getTelemetryDescriptor()); } public hideTabs(forceHide: boolean): void { this.forceHideTabs = forceHide; const config = this.configurationService.getConfiguration<IWorkbenchEditorConfiguration>(); this.tabOptions.showTabs = forceHide ? false : config && config.workbench && config.workbench.editor && config.workbench.editor.showTabs; this._onTabOptionsChanged.fire(this.tabOptions); } public get onEditorsChanged(): Event<void> { return this._onEditorsChanged.event; } public get onEditorsMoved(): Event<void> { return this._onEditorsMoved.event; } public get onEditorOpenFail(): Event<EditorInput> { return this._onEditorOpenFail.event; } public get onGroupOrientationChanged(): Event<void> { return this._onGroupOrientationChanged.event; } public get onTabOptionsChanged(): Event<ITabOptions> { return this._onTabOptionsChanged.event; } public getTabOptions(): ITabOptions { return this.tabOptions; } public openEditor(input: EditorInput, options?: EditorOptions, sideBySide?: boolean): TPromise<BaseEditor>; public openEditor(input: EditorInput, options?: EditorOptions, position?: Position, ratio?: number[]): TPromise<BaseEditor>; public openEditor(input: EditorInput, options?: EditorOptions, arg3?: any, ratio?: number[]): TPromise<BaseEditor> { // Normalize some values if (!options) { options = null; } // Determine position to open editor in (one, two, three) const position = this.findPosition(input, options, arg3, ratio); // Some conditions under which we prevent the request if ( !input || // no input position === null || // invalid position Object.keys(this.mapEditorInstantiationPromiseToEditor[position]).length > 0 || // pending editor load !this.editorGroupsControl || // too early this.editorGroupsControl.isDragging() // pending editor DND ) { return TPromise.as<BaseEditor>(null); } // We need an editor descriptor for the input const descriptor = Registry.as<IEditorRegistry>(EditorExtensions.Editors).getEditor(input); if (!descriptor) { return TPromise.wrapError(new Error(strings.format('Can not find a registered editor for the input {0}', input))); } // Opened to the side if (position !== Position.ONE) { this.telemetryService.publicLog('workbenchSideEditorOpened', { position: position }); } // Open through UI return this.doOpenEditor(position, descriptor, input, options, ratio); } private doOpenEditor(position: Position, descriptor: IEditorDescriptor, input: EditorInput, options: EditorOptions, ratio: number[]): TPromise<BaseEditor> { // Update stacks: We do this early on before the UI is there because we want our stacks model to have // a consistent view of the editor world and updating it later async after the UI is there will cause // issues (e.g. when a closeEditor call is made that expects the openEditor call to have updated the // stacks model). // This can however cause a race condition where the stacks model indicates the opened editor is there // while the UI is not yet ready. Clients have to deal with this fact and we have to make sure that the // stacks model gets updated if any of the UI updating fails with an error. const group = this.ensureGroup(position, !options || !options.preserveFocus); const pinned = !this.tabOptions.previewEditors || (options && (options.pinned || typeof options.index === 'number')) || input.isDirty(); const active = (group.count === 0) || !options || !options.inactive; group.openEditor(input, { active, pinned, index: options && options.index }); // Return early if the editor is to be open inactive and there are other editors in this group to show if (!active) { return TPromise.as<BaseEditor>(null); } // Progress Monitor & Ref Counting this.editorOpenToken[position]++; const editorOpenToken = this.editorOpenToken[position]; const monitor = new ProgressMonitor(editorOpenToken, TPromise.timeout(this.partService.isCreated() ? 800 : 3200 /* less ugly initial startup */).then(() => { const position = this.stacks.positionOfGroup(group); // might have changed due to a rochade meanwhile if (editorOpenToken === this.editorOpenToken[position]) { this.editorGroupsControl.updateProgress(position, ProgressState.INFINITE); } })); // Show editor return this.doShowEditor(group, descriptor, input, options, ratio, monitor).then(editor => { if (!editor) { return TPromise.as<BaseEditor>(null); // canceled or other error } // Set input to editor return this.doSetInput(group, editor, input, options, monitor); }); } private doShowEditor(group: EditorGroup, descriptor: IEditorDescriptor, input: EditorInput, options: EditorOptions, ratio: number[], monitor: ProgressMonitor): TPromise<BaseEditor> { const position = this.stacks.positionOfGroup(group); const editorAtPosition = this.visibleEditors[position]; // Return early if the currently visible editor can handle the input if (editorAtPosition && descriptor.describes(editorAtPosition)) { return TPromise.as(editorAtPosition); } // Hide active one first if (editorAtPosition) { this.doHideEditor(position, false); } // Create Editor return this.doCreateEditor(group, descriptor, monitor).then(editor => { const position = this.stacks.positionOfGroup(group); // might have changed due to a rochade meanwhile // Make sure that the user meanwhile did not open another editor or something went wrong if (!editor || !this.visibleEditors[position] || editor.getId() !== this.visibleEditors[position].getId()) { monitor.cancel(); return null; } // Show in side by side control this.editorGroupsControl.show(editor, position, options && options.preserveFocus, ratio); // Indicate to editor that it is now visible editor.setVisible(true, position); // Update text compare editor visible context this.updateTextCompareEditorVisible(); // Make sure the editor is layed out this.editorGroupsControl.layout(position); return editor; }, e => this.messageService.show(Severity.Error, types.isString(e) ? new Error(e) : e)); } private doCreateEditor(group: EditorGroup, descriptor: IEditorDescriptor, monitor: ProgressMonitor): TPromise<BaseEditor> { // Instantiate editor return this.doInstantiateEditor(group, descriptor).then(editor => { const position = this.stacks.positionOfGroup(group); // might have changed due to a rochade meanwhile // Make sure that the user meanwhile did not open another editor if (monitor.token !== this.editorOpenToken[position]) { monitor.cancel(); return null; } // Remember Editor at position this.visibleEditors[position] = editor; // Create editor as needed if (!editor.getContainer()) { editor.create($().div({ 'class': 'editor-container', 'role': 'tabpanel', id: descriptor.getId() })); } return editor; }); } private doInstantiateEditor(group: EditorGroup, descriptor: IEditorDescriptor): TPromise<BaseEditor> { const position = this.stacks.positionOfGroup(group); // Return early if already instantiated const instantiatedEditor = this.instantiatedEditors[position].filter(e => descriptor.describes(e))[0]; if (instantiatedEditor) { return TPromise.as(instantiatedEditor); } // Return early if editor is being instantiated at the same time from a previous call const pendingEditorInstantiate = this.mapEditorInstantiationPromiseToEditor[position][descriptor.getId()]; if (pendingEditorInstantiate) { return pendingEditorInstantiate; } // Otherwise instantiate const progressService = this.instantiationService.createInstance(WorkbenchProgressService, this.editorGroupsControl.getProgressBar(position), descriptor.getId(), true); const editorInstantiationService = this.editorGroupsControl.getInstantiationService(position).createChild(new ServiceCollection([IProgressService, progressService])); let loaded = false; const onInstantiate = (arg: BaseEditor | Error): TPromise<BaseEditor | Error> => { const position = this.stacks.positionOfGroup(group); // might have changed due to a rochade meanwhile loaded = true; delete this.mapEditorInstantiationPromiseToEditor[position][descriptor.getId()]; if (arg instanceof BaseEditor) { this.instantiatedEditors[position].push(arg); return TPromise.as(arg); } return TPromise.wrapError(arg); }; const instantiateEditorPromise = editorInstantiationService.createInstance(<EditorDescriptor>descriptor).then(onInstantiate, onInstantiate); if (!loaded) { this.mapEditorInstantiationPromiseToEditor[position][descriptor.getId()] = instantiateEditorPromise; } return instantiateEditorPromise.then(result => { progressService.dispose(); return result; }); } private doSetInput(group: EditorGroup, editor: BaseEditor, input: EditorInput, options: EditorOptions, monitor: ProgressMonitor): TPromise<BaseEditor> { // Emit Input-Changed Event as appropiate const previousInput = editor.input; const inputChanged = (!previousInput || !previousInput.matches(input) || (options && options.forceOpen)); // Call into Editor return editor.setInput(input, options).then(() => { // Stop loading promise if any monitor.cancel(); const position = this.stacks.positionOfGroup(group); // might have changed due to a rochade meanwhile if (position === -1) { return null; // in theory a call to editor.setInput() could have resulted in the editor being closed due to an error, so we guard against it here } // Focus (unless prevented) const focus = !options || !options.preserveFocus; if (focus) { editor.focus(); } // Progress Done this.editorGroupsControl.updateProgress(position, ProgressState.DONE); // Emit Change Event (if input changed) if (inputChanged) { this._onEditorsChanged.fire(); } // Fullfill promise with Editor that is being used return editor; }, e => this.doHandleSetInputError(e, group, editor, input, options, monitor)); } private doHandleSetInputError(e: Error | IMessageWithAction, group: EditorGroup, editor: BaseEditor, input: EditorInput, options: EditorOptions, monitor: ProgressMonitor): void { const position = this.stacks.positionOfGroup(group); // Stop loading promise if any monitor.cancel(); // Report error only if this was not us restoring previous error state if (this.partService.isCreated() && !errors.isPromiseCanceledError(e)) { const errorMessage = nls.localize('editorOpenError', "Unable to open '{0}': {1}.", input.getName(), toErrorMessage(e)); let error: any; if (e && (<IMessageWithAction>e).actions && (<IMessageWithAction>e).actions.length) { error = errors.create(errorMessage, { actions: (<IMessageWithAction>e).actions }); // Support error actions from thrower } else { error = errorMessage; } this.messageService.show(Severity.Error, types.isString(error) ? new Error(error) : error); } this.editorGroupsControl.updateProgress(position, ProgressState.DONE); // Event this._onEditorOpenFail.fire(input); // Recover by closing the active editor (if the input is still the active one) if (group.activeEditor === input) { this.doCloseActiveEditor(group); } } public closeEditor(position: Position, input: EditorInput): TPromise<void> { const group = this.stacks.groupAt(position); if (!group) { return TPromise.as<void>(null); } // Check for dirty and veto return this.handleDirty([{ group, editor: input }], true /* ignore if opened in other group */).then(veto => { if (veto) { return; } // Do close this.doCloseEditor(group, input); }); } private doCloseEditor(group: EditorGroup, input: EditorInput, focusNext = this.stacks.isActive(group)): void { // Closing the active editor of the group is a bit more work if (group.activeEditor && group.activeEditor.matches(input)) { this.doCloseActiveEditor(group, focusNext); } // Closing inactive editor is just a model update else { this.doCloseInactiveEditor(group, input); } } private doCloseActiveEditor(group: EditorGroup, focusNext = true): void { const position = this.stacks.positionOfGroup(group); // Update stacks model group.closeEditor(group.activeEditor); // Close group is this is the last editor in group if (group.count === 0) { this.doCloseGroup(group, focusNext); } // Otherwise open next active else { this.openEditor(group.activeEditor, !focusNext ? EditorOptions.create({ preserveFocus: true }) : null, position).done(null, errors.onUnexpectedError); } } private doCloseInactiveEditor(group: EditorGroup, input: EditorInput): void { // Closing inactive editor is just a model update group.closeEditor(input); } private doCloseGroup(group: EditorGroup, focusNext = true): void { const position = this.stacks.positionOfGroup(group); // Update stacks model this.modifyGroups(() => this.stacks.closeGroup(group)); // Hide Editor this.doHideEditor(position, true); // Emit Change Event this._onEditorsChanged.fire(); // Focus next group if we have an active one left const currentActiveGroup = this.stacks.activeGroup; if (currentActiveGroup) { if (focusNext) { this.focusGroup(currentActiveGroup); } else { this.activateGroup(currentActiveGroup); } // Explicitly trigger the focus changed handler because the side by side control will not trigger it unless // the user is actively changing focus with the mouse from left/top to right/bottom. this.onGroupFocusChanged(); } } private doHideEditor(position: Position, layoutAndRochade: boolean): void { const editor = this.visibleEditors[position]; // Hide in side by side control const rochade = this.editorGroupsControl.hide(editor, position, layoutAndRochade); // Clear any running Progress this.editorGroupsControl.updateProgress(position, ProgressState.STOP); // Indicate to Editor editor.clearInput(); editor.setVisible(false); // Update text compare editor visible context this.updateTextCompareEditorVisible(); // Clear active editor this.visibleEditors[position] = null; // Rochade as needed this.rochade(rochade); // Emit Editor move event if (rochade !== Rochade.NONE) { this._onEditorsMoved.fire(); } } private updateTextCompareEditorVisible(): void { this.textCompareEditorVisible.set(this.visibleEditors.some(e => e && e.isVisible() && e.getId() === TEXT_DIFF_EDITOR_ID)); } public closeAllEditors(except?: Position): TPromise<void> { let groups = this.stacks.groups.reverse(); // start from the end to prevent layout to happen through rochade // Remove position to exclude if we have any if (typeof except === 'number') { groups = groups.filter(group => this.stacks.positionOfGroup(group) !== except); } // Check for dirty and veto const editorsToClose = arrays.flatten(groups.map(group => group.getEditors().map(editor => { return { group, editor }; }))); return this.handleDirty(editorsToClose).then(veto => { if (veto) { return; } groups.forEach(group => this.doCloseEditors(group)); }); } public closeEditors(position: Position, except?: EditorInput, direction?: Direction): TPromise<void> { const group = this.stacks.groupAt(position); if (!group) { return TPromise.as<void>(null); } // Check for dirty and veto let editorsToClose: EditorInput[]; if (types.isUndefinedOrNull(direction)) { editorsToClose = group.getEditors().filter(e => !except || !e.matches(except)); } else { editorsToClose = (direction === Direction.LEFT) ? group.getEditors().slice(0, group.indexOf(except)) : group.getEditors().slice(group.indexOf(except) + 1); } return this.handleDirty(editorsToClose.map(editor => { return { group, editor }; }), true /* ignore if opened in other group */).then(veto => { if (veto) { return; } this.doCloseEditors(group, except, direction); }); } private doCloseEditors(group: EditorGroup, except?: EditorInput, direction?: Direction): void { // Close all editors in group if (!except) { // Update stacks model: remove all non active editors first to prevent opening the next editor in group group.closeEditors(group.activeEditor); // Now close active editor in group which will close the group this.doCloseActiveEditor(group); } // Close all editors in group except active one else if (except.matches(group.activeEditor)) { // Update stacks model: close non active editors supporting the direction group.closeEditors(group.activeEditor, direction); } // Finally: we are asked to close editors around a non-active editor // Thus we make the non-active one active and then close the others else { this.openEditor(except, null, this.stacks.positionOfGroup(group)).done(() => { // since the opening might have failed, we have to check again for the active editor // being the expected one, otherwise we end up in an endless loop trying to open the // editor if (except.matches(group.activeEditor)) { this.doCloseEditors(group, except, direction); } }, errors.onUnexpectedError); } } private handleDirty(identifiers: EditorIdentifier[], ignoreIfOpenedInOtherGroup?: boolean): TPromise<boolean /* veto */> { if (!identifiers.length) { return TPromise.as(false); // no veto } return this.doHandleDirty(identifiers.shift(), ignoreIfOpenedInOtherGroup).then(veto => { if (veto) { return veto; } return this.handleDirty(identifiers, ignoreIfOpenedInOtherGroup); }); } private doHandleDirty(identifier: EditorIdentifier, ignoreIfOpenedInOtherGroup?: boolean): TPromise<boolean /* veto */> { if (!identifier || !identifier.editor || !identifier.editor.isDirty() || (ignoreIfOpenedInOtherGroup && this.countEditors(identifier.editor) > 1 /* allow to close a dirty editor if it is opened in another group */)) { return TPromise.as(false); // no veto } const { editor } = identifier; const res = editor.confirmSave(); switch (res) { case ConfirmResult.SAVE: return editor.save().then(ok => !ok); case ConfirmResult.DONT_SAVE: return editor.revert().then(ok => !ok); case ConfirmResult.CANCEL: return TPromise.as(true); // veto } } private countEditors(editor: EditorInput): number { const editors = [editor]; if (editor instanceof SideBySideEditorInput) { editors.push(editor.master); } return editors.reduce((prev, e) => prev += this.stacks.count(e), 0); } public getStacksModel(): EditorStacksModel { return this.stacks; } public getActiveEditorInput(): EditorInput { const lastActiveEditor = this.getActiveEditor(); return lastActiveEditor ? lastActiveEditor.input : null; } public getActiveEditor(): BaseEditor { if (!this.editorGroupsControl) { return null; // too early } return this.editorGroupsControl.getActiveEditor(); } public getVisibleEditors(): BaseEditor[] { return this.visibleEditors ? this.visibleEditors.filter(editor => !!editor) : []; } public moveGroup(from: EditorGroup, to: EditorGroup): void; public moveGroup(from: Position, to: Position): void; public moveGroup(arg1: any, arg2: any): void { const fromGroup = (typeof arg1 === 'number') ? this.stacks.groupAt(arg1) : arg1; const toGroup = (typeof arg2 === 'number') ? this.stacks.groupAt(arg2) : arg2; if (!fromGroup || !toGroup || fromGroup === toGroup) { return; // Ignore if we cannot move } const fromPosition = this.stacks.positionOfGroup(fromGroup); const toPosition = this.stacks.positionOfGroup(toGroup); // Update stacks model this.modifyGroups(() => this.stacks.moveGroup(fromGroup, toPosition)); // Move widgets this.editorGroupsControl.move(fromPosition, toPosition); // Move data structures arrays.move(this.visibleEditors, fromPosition, toPosition); arrays.move(this.editorOpenToken, fromPosition, toPosition); arrays.move(this.mapEditorInstantiationPromiseToEditor, fromPosition, toPosition); arrays.move(this.instantiatedEditors, fromPosition, toPosition); // Restore focus this.focusGroup(fromGroup); // Events this._onEditorsMoved.fire(); } public moveEditor(input: EditorInput, from: EditorGroup, to: EditorGroup, index?: number): void; public moveEditor(input: EditorInput, from: Position, to: Position, index?: number): void; public moveEditor(input: EditorInput, arg2: any, arg3: any, index?: number): void { const fromGroup = (typeof arg2 === 'number') ? this.stacks.groupAt(arg2) : arg2; if (!fromGroup) { return; } // Move within group if (arg2 === arg3) { this.doMoveEditorInsideGroups(input, fromGroup, index); } // Move across groups else { const toPosition = (typeof arg3 === 'number') ? arg3 : this.stacks.positionOfGroup(arg3); this.doMoveEditorAcrossGroups(input, fromGroup, toPosition, index); } } private doMoveEditorInsideGroups(input: EditorInput, group: EditorGroup, toIndex: number): void { if (typeof toIndex !== 'number') { return; // do nothing if we move into same group without index } const currentIndex = group.indexOf(input); if (currentIndex === toIndex) { return; // do nothing if editor is already at the given index } // Update stacks model group.moveEditor(input, toIndex); group.pin(input); } private doMoveEditorAcrossGroups(input: EditorInput, fromGroup: EditorGroup, to: Position, index?: number): void { if (fromGroup.count === 1) { const toGroup = this.stacks.groupAt(to); if (!toGroup && this.stacks.positionOfGroup(fromGroup) < to) { return; // do nothing if the group to move only has one editor and is the last group already } } // When moving an editor, try to preserve as much view state as possible by checking // for th editor to be a text editor and creating the options accordingly if so let options = EditorOptions.create({ pinned: true, index }); const activeEditor = this.getActiveEditor(); const codeEditor = getCodeEditor(activeEditor); if (codeEditor && activeEditor.position === this.stacks.positionOfGroup(fromGroup) && input.matches(activeEditor.input)) { options = TextEditorOptions.create({ pinned: true, index }); (<TextEditorOptions>options).fromEditor(codeEditor); } // A move to another group is an open first... this.openEditor(input, options, to).done(null, errors.onUnexpectedError); // and a close afterwards... this.doCloseEditor(fromGroup, input, false /* do not activate next one behind if any */); } public arrangeGroups(arrangement: GroupArrangement): void { this.editorGroupsControl.arrangeGroups(arrangement); } public setGroupOrientation(orientation: GroupOrientation): void { this.editorGroupsControl.setGroupOrientation(orientation); this._onGroupOrientationChanged.fire(); // Rename groups when layout changes this.renameGroups(); } public getGroupOrientation(): GroupOrientation { return this.editorGroupsControl.getGroupOrientation(); } public createContentArea(parent: Builder): Builder { // Content Container const contentArea = $(parent) .div() .addClass('content'); // get settings this.memento = this.getMemento(this.storageService, MementoScope.WORKSPACE); // Side by Side Control const editorPartState: IEditorPartUIState = this.memento[EditorPart.EDITOR_PART_UI_STATE_STORAGE_KEY]; this.editorGroupsControl = this.instantiationService.createInstance(EditorGroupsControl, contentArea, editorPartState && editorPartState.groupOrientation); this.toUnbind.push(this.editorGroupsControl.onGroupFocusChanged(() => this.onGroupFocusChanged())); return contentArea; } private onGroupFocusChanged(): void { // Update stacks model const activePosition = this.editorGroupsControl.getActivePosition(); if (typeof activePosition === 'number') { this.stacks.setActive(this.stacks.groupAt(activePosition)); } // Emit as change event so that clients get aware of new active editor const activeEditor = this.editorGroupsControl.getActiveEditor(); if (activeEditor) { this._onEditorsChanged.fire(); } } public replaceEditors(editors: { toReplace: EditorInput, replaceWith: EditorInput, options?: EditorOptions }[], position?: Position): TPromise<BaseEditor[]> { const activeReplacements: IEditorReplacement[] = []; const hiddenReplacements: IEditorReplacement[] = []; // Find editors across groups to close editors.forEach(editor => { if (editor.toReplace.isDirty()) { return; // we do not handle dirty in this method, so ignore all dirty } // For each group this.stacks.groups.forEach(group => { if (position === void 0 || this.stacks.positionOfGroup(group) === position) { const index = group.indexOf(editor.toReplace); if (index >= 0) { if (editor.options) { editor.options.index = index; // make sure we respect the index of the editor to replace! } else { editor.options = EditorOptions.create({ index }); } const replacement = { group, editor: editor.toReplace, replaceWith: editor.replaceWith, options: editor.options }; if (group.activeEditor.matches(editor.toReplace)) { activeReplacements.push(replacement); } else { hiddenReplacements.push(replacement); } } } }); }); // Deal with hidden replacements first hiddenReplacements.forEach(replacement => { const group = replacement.group; group.openEditor(replacement.replaceWith, { active: false, pinned: true, index: replacement.options.index }); group.closeEditor(replacement.editor); }); // Now deal with active editors to be opened const res = this.openEditors(activeReplacements.map(replacement => { const group = replacement.group; return { input: replacement.replaceWith, position: this.stacks.positionOfGroup(group), options: replacement.options }; })); // Close active editors to be replaced now (they are no longer active) activeReplacements.forEach(replacement => { this.doCloseEditor(replacement.group, replacement.editor, false); }); return res; } public openEditors(editors: { input: EditorInput, position: Position, options?: EditorOptions }[]): TPromise<BaseEditor[]> { if (!editors.length) { return TPromise.as<BaseEditor[]>([]); } let activePosition: Position; if (this.stacks.activeGroup) { activePosition = this.stacks.positionOfGroup(this.stacks.activeGroup); } const ratio = this.editorGroupsControl.getRatio(); return this.doOpenEditors(editors, activePosition, ratio); } public restoreEditors(): TPromise<BaseEditor[]> { const editors = this.stacks.groups.map((group, index) => { return { input: group.activeEditor, position: index, options: group.isPinned(group.activeEditor) ? EditorOptions.create({ pinned: true }) : void 0 }; }); if (!editors.length) { return TPromise.as<BaseEditor[]>([]); } let activePosition: Position; if (this.stacks.groups.length) { activePosition = this.stacks.positionOfGroup(this.stacks.activeGroup); } const editorState: IEditorPartUIState = this.memento[EditorPart.EDITOR_PART_UI_STATE_STORAGE_KEY]; return this.doOpenEditors(editors, activePosition, editorState && editorState.ratio); } private doOpenEditors(editors: { input: EditorInput, position: Position, options?: EditorOptions }[], activePosition?: number, ratio?: number[]): TPromise<BaseEditor[]> { const positionOneEditors = editors.filter(e => e.position === Position.ONE); const positionTwoEditors = editors.filter(e => e.position === Position.TWO); const positionThreeEditors = editors.filter(e => e.position === Position.THREE); const groupOne = this.stacks.groupAt(Position.ONE); const groupTwo = this.stacks.groupAt(Position.TWO); const groupThree = this.stacks.groupAt(Position.THREE); // Compute the imaginary count if we const all editors open as the way requested const oneCount = positionOneEditors.length + (groupOne ? groupOne.count : 0); const twoCount = positionTwoEditors.length + (groupTwo ? groupTwo.count : 0); const threeCount = positionThreeEditors.length + (groupThree ? groupThree.count : 0); // Validate we do not produce empty groups given our imaginary count model if ((!oneCount && (twoCount || threeCount) || (!twoCount && threeCount))) { positionOneEditors.push(...positionTwoEditors); positionOneEditors.push(...positionThreeEditors); positionTwoEditors.splice(0, positionTwoEditors.length); positionThreeEditors.splice(0, positionThreeEditors.length); } // Validate active input if (typeof activePosition !== 'number') { activePosition = Position.ONE; } // Validate ratios const positions = positionThreeEditors.length ? 3 : positionTwoEditors.length ? 2 : 1; if (!ratio || ratio.length !== positions) { if (!this.getVisibleEditors().length) { ratio = (positions === 3) ? [0.33, 0.33, 0.34] : (positions === 2) ? [0.5, 0.5] : [1]; } else { ratio = void 0; } } let focusGroup = false; const activeGroup = this.stacks.groupAt(activePosition); if (!this.stacks.activeGroup || !activeGroup) { focusGroup = true; // always focus group if this is the first group or we are about to open a new group } else { focusGroup = editors.some(e => !e.options || (!e.options.inactive && !e.options.preserveFocus)); // only focus if the editors to open are not opening as inactive or preserveFocus } // Open each input respecting the options. Since there can only be one active editor in each // position, we have to pick the first input from each position and add the others as inactive const promises: TPromise<BaseEditor>[] = []; [positionOneEditors.shift(), positionTwoEditors.shift(), positionThreeEditors.shift()].forEach((editor, position) => { if (!editor) { return; // unused position } const input = editor.input; // Resolve editor options const preserveFocus = (activePosition !== position); let options: EditorOptions; if (editor.options) { options = editor.options; if (typeof options.preserveFocus !== 'boolean') { options.preserveFocus = preserveFocus; } } else { options = EditorOptions.create({ preserveFocus }); } promises.push(this.openEditor(input, options, position, ratio)); }); return TPromise.join(promises).then(editors => { // Adjust focus as needed if (focusGroup) { this.focusGroup(activePosition); } // Update stacks model for remaining inactive editors [positionOneEditors, positionTwoEditors, positionThreeEditors].forEach((editors, index) => { const group = this.stacks.groupAt(index); if (group) { editors.forEach(editor => group.openEditor(editor.input, { pinned: true })); // group could be null if one openeditor call failed! } }); // Full layout side by side this.editorGroupsControl.layout(this.dimension); return editors; }); } public activateGroup(group: EditorGroup): void; public activateGroup(position: Position): void; public activateGroup(arg1: any): void { const group = (typeof arg1 === 'number') ? this.stacks.groupAt(arg1) : arg1; if (group) { // Update stacks model this.stacks.setActive(group); // Update UI const editor = this.visibleEditors[this.stacks.positionOfGroup(group)]; if (editor) { this.editorGroupsControl.setActive(editor); } } } public focusGroup(group: EditorGroup): void; public focusGroup(position: Position): void; public focusGroup(arg1: any): void { const group = (typeof arg1 === 'number') ? this.stacks.groupAt(arg1) : arg1; if (group) { // Make active this.activateGroup(group); // Focus Editor const editor = this.visibleEditors[this.stacks.positionOfGroup(group)]; if (editor) { editor.focus(); } } } public pinEditor(group: EditorGroup, input: EditorInput): void; public pinEditor(position: Position, input: EditorInput): void; public pinEditor(arg1: any, input: EditorInput): void { const group = (typeof arg1 === 'number') ? this.stacks.groupAt(arg1) : arg1; if (group) { if (group.isPinned(input)) { return; } // Update stacks model group.pin(input); } } public unpinEditor(group: EditorGroup, input: EditorInput): void; public unpinEditor(position: Position, input: EditorInput): void; public unpinEditor(arg1: any, input: EditorInput): void { if (input.isDirty()) { return; // we do not allow to unpin dirty editors } const group = (typeof arg1 === 'number') ? this.stacks.groupAt(arg1) : arg1; if (group) { if (group.isPreview(input)) { return; } // Unpinning an editor closes the preview editor if we have any let handlePreviewEditor: TPromise<boolean> = TPromise.as(false); if (group.previewEditor) { handlePreviewEditor = this.handleDirty([{ group, editor: group.previewEditor }], true /* ignore if opened in other group */); } handlePreviewEditor.done(veto => { if (veto) { return; } // The active editor is the preview editor and we are asked to make // another editor the preview editor. So we need to take care of closing // the active editor first if (group.isPreview(group.activeEditor) && !group.activeEditor.matches(input)) { this.doCloseActiveEditor(group); } // Update stacks model group.unpin(input); }); } } public layout(dimension: Dimension): Dimension[] { // Pass to super const sizes = super.layout(dimension); // Pass to Side by Side Control this.dimension = sizes[1]; this.editorGroupsControl.layout(this.dimension); this.onLayoutEmitter.fire(dimension); return sizes; } public shutdown(): void { // Persist UI State const editorState: IEditorPartUIState = { ratio: this.editorGroupsControl.getRatio(), groupOrientation: this.editorGroupsControl.getGroupOrientation() }; this.memento[EditorPart.EDITOR_PART_UI_STATE_STORAGE_KEY] = editorState; // Unload all Instantiated Editors for (let i = 0; i < this.instantiatedEditors.length; i++) { for (let j = 0; j < this.instantiatedEditors[i].length; j++) { this.instantiatedEditors[i][j].shutdown(); } } // Pass to super super.shutdown(); } public dispose(): void { // Emitters this._onEditorsChanged.dispose(); this._onEditorsMoved.dispose(); this._onEditorOpenFail.dispose(); // Reset Tokens this.editorOpenToken = []; for (let i = 0; i < POSITIONS.length; i++) { this.editorOpenToken[i] = 0; } // Widgets this.editorGroupsControl.dispose(); // Pass to active editors this.visibleEditors.forEach(editor => { if (editor) { editor.dispose(); } }); // Pass to instantiated editors for (let i = 0; i < this.instantiatedEditors.length; i++) { for (let j = 0; j < this.instantiatedEditors[i].length; j++) { if (this.visibleEditors.some(editor => editor === this.instantiatedEditors[i][j])) { continue; } this.instantiatedEditors[i][j].dispose(); } } this.visibleEditors = null; // Pass to super super.dispose(); } private findPosition(input: EditorInput, options?: EditorOptions, sideBySide?: boolean, ratio?: number[]): Position; private findPosition(input: EditorInput, options?: EditorOptions, desiredPosition?: Position, ratio?: number[]): Position; private findPosition(input: EditorInput, options?: EditorOptions, arg1?: any, ratio?: number[]): Position { // With defined ratios, always trust the provided position if (ratio && types.isNumber(arg1)) { return arg1; } // No editor open const visibleEditors = this.getVisibleEditors(); const activeEditor = this.getActiveEditor(); if (visibleEditors.length === 0 || !activeEditor) { return Position.ONE; // can only be ONE } // Respect option to reveal an editor if it is already visible if (options && options.revealIfVisible) { const group = this.stacks.findGroup(input, true); if (group) { return this.stacks.positionOfGroup(group); } } // Respect option to reveal an editor if it is open (not necessarily visible) const skipRevealIfOpen = (options && options.index) || arg1; if (!skipRevealIfOpen && this.revealIfOpen) { const group = this.stacks.findGroup(input); if (group) { return this.stacks.positionOfGroup(group); } } // Position is unknown: pick last active or ONE if (types.isUndefinedOrNull(arg1) || arg1 === false) { const lastActivePosition = this.editorGroupsControl.getActivePosition(); return lastActivePosition || Position.ONE; } // Position is sideBySide: Find position relative to active editor if (arg1 === true) { switch (activeEditor.position) { case Position.ONE: return Position.TWO; case Position.TWO: return Position.THREE; case Position.THREE: return null; // Cannot open to the side of the right/bottom most editor } return null; // Prevent opening to the side } // Position is provided, validate it if (arg1 === Position.THREE && visibleEditors.length === 1) { return Position.TWO; } return arg1; } private startDelayedCloseEditorsFromInputDispose(): void { // To prevent race conditions, we call the close in a timeout because it can well be // that an input is being disposed with the intent to replace it with some other input // right after. if (this.pendingEditorInputCloseTimeout === null) { this.pendingEditorInputCloseTimeout = setTimeout(() => { // Split between visible and hidden editors const visibleEditors: EditorIdentifier[] = []; const hiddenEditors: EditorIdentifier[] = []; this.pendingEditorInputsToClose.forEach(identifier => { const { group, editor } = identifier; if (group.isActive(editor)) { visibleEditors.push(identifier); } else if (group.contains(editor)) { hiddenEditors.push(identifier); } }); // Close all hidden first hiddenEditors.forEach(hidden => this.doCloseEditor(<EditorGroup>hidden.group, hidden.editor, false)); // Close visible ones second visibleEditors .sort((a1, a2) => this.stacks.positionOfGroup(a2.group) - this.stacks.positionOfGroup(a1.group)) // reduce layout work by starting right/bottom first .forEach(visible => this.doCloseEditor(<EditorGroup>visible.group, visible.editor, false)); // Reset this.pendingEditorInputCloseTimeout = null; this.pendingEditorInputsToClose = []; }, 0); } } private rochade(rochade: Rochade): void; private rochade(from: Position, to: Position): void; private rochade(arg1: any, arg2?: any): void { if (types.isUndefinedOrNull(arg2)) { const rochade = <Rochade>arg1; switch (rochade) { case Rochade.TWO_TO_ONE: this.rochade(Position.TWO, Position.ONE); break; case Rochade.THREE_TO_TWO: this.rochade(Position.THREE, Position.TWO); break; case Rochade.TWO_AND_THREE_TO_ONE: this.rochade(Position.TWO, Position.ONE); this.rochade(Position.THREE, Position.TWO); } } else { const from = <Position>arg1; const to = <Position>arg2; this.doRochade(this.visibleEditors, from, to, null); this.doRochade(this.editorOpenToken, from, to, null); this.doRochade(this.mapEditorInstantiationPromiseToEditor, from, to, Object.create(null)); this.doRochade(this.instantiatedEditors, from, to, []); } } private doRochade(array: any[], from: Position, to: Position, empty: any): void { array[to] = array[from]; array[from] = empty; } private ensureGroup(position: Position, activate = true): EditorGroup { let group = this.stacks.groupAt(position); if (!group) { // Race condition: it could be that someone quickly opens editors one after // the other and we are asked to open an editor in position 2 before position // 1 was opened. Therefor we must ensure that all groups are created up to // the point where we are asked for. this.modifyGroups(() => { for (let i = 0; i < position; i++) { if (!this.hasGroup(i)) { this.stacks.openGroup('', false, i); } } group = this.stacks.openGroup('', activate, position); }); } else { this.renameGroups(); // ensure group labels are proper } if (activate) { this.stacks.setActive(group); } return group; } private modifyGroups(modification: () => void) { // Run the modification modification(); // Adjust group labels as needed this.renameGroups(); } private renameGroups(): void { const groups = this.stacks.groups; if (groups.length > 0) { const layoutVertically = (this.editorGroupsControl.getGroupOrientation() !== 'horizontal'); // ONE | TWO | THREE if (groups.length > 2) { this.stacks.renameGroup(this.stacks.groupAt(Position.ONE), layoutVertically ? EditorPart.GROUP_LEFT : EditorPart.GROUP_TOP); this.stacks.renameGroup(this.stacks.groupAt(Position.TWO), layoutVertically ? EditorPart.GROUP_CENTER : EditorPart.GROUP_MIDDLE); this.stacks.renameGroup(this.stacks.groupAt(Position.THREE), layoutVertically ? EditorPart.GROUP_RIGHT : EditorPart.GROUP_BOTTOM); } // ONE | TWO else if (groups.length > 1) { this.stacks.renameGroup(this.stacks.groupAt(Position.ONE), layoutVertically ? EditorPart.GROUP_LEFT : EditorPart.GROUP_TOP); this.stacks.renameGroup(this.stacks.groupAt(Position.TWO), layoutVertically ? EditorPart.GROUP_RIGHT : EditorPart.GROUP_BOTTOM); } // ONE else { this.stacks.renameGroup(this.stacks.groupAt(Position.ONE), layoutVertically ? EditorPart.GROUP_LEFT : EditorPart.GROUP_TOP); } } } private hasGroup(position: Position): boolean { return !!this.stacks.groupAt(position); } }
src/vs/workbench/browser/parts/editor/editorPart.ts
1
https://github.com/microsoft/vscode/commit/522c6e01711a50ab2c48e2efb11f837dce7ebab9
[ 0.9991959929466248, 0.08826174587011337, 0.00016505521489307284, 0.0004633502976503223, 0.2680758833885193 ]
{ "id": 0, "code_window": [ "\t\tthis._onEditorsMoved.fire();\n", "\t}\n", "\n", "\tpublic moveEditor(input: EditorInput, from: EditorGroup, to: EditorGroup, index?: number): void;\n", "\tpublic moveEditor(input: EditorInput, from: Position, to: Position, index?: number): void;\n", "\tpublic moveEditor(input: EditorInput, arg2: any, arg3: any, index?: number): void {\n", "\t\tconst fromGroup = (typeof arg2 === 'number') ? this.stacks.groupAt(arg2) : arg2;\n", "\t\tif (!fromGroup) {\n", "\t\t\treturn;\n", "\t\t}\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tpublic moveEditor(input: EditorInput, from: EditorGroup, to: EditorGroup, index?: number, inactive?: boolean): void;\n", "\tpublic moveEditor(input: EditorInput, from: Position, to: Position, index?: number, inactive?: boolean): void;\n", "\tpublic moveEditor(input: EditorInput, arg2: any, arg3: any, index?: number, inactive?: boolean): void {\n" ], "file_path": "src/vs/workbench/browser/parts/editor/editorPart.ts", "type": "replace", "edit_start_line_idx": 810 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "fileLink": "클릭하여 이동(측면에서 열려면 Ctrl 키를 누르고 클릭)", "fileLinkMac": "클릭하여 이동(측면에서 열려면 Cmd 키를 누르고 클릭)", "replExpressionAriaLabel": "{0} 식에 {1} 값이 있습니다. read–eval–print loop, 디버그", "replKeyValueOutputAriaLabel": "출력 변수 {0}에 값 {1}이(가) 있습니다. read–eval–print loop, 디버그", "replValueOutputAriaLabel": "{0}, read–eval–print loop, 디버그", "replVariableAriaLabel": "{0} 변수에 {1} 값이 있습니다. read–eval–print loop, 디버그", "stateCapture": "개체 상태는 첫 번재 평가에서 캡처됩니다." }
i18n/kor/src/vs/workbench/parts/debug/electron-browser/replViewer.i18n.json
0
https://github.com/microsoft/vscode/commit/522c6e01711a50ab2c48e2efb11f837dce7ebab9
[ 0.0001690692879492417, 0.0001689671480562538, 0.00016886500816326588, 0.0001689671480562538, 1.0213989298790693e-7 ]
{ "id": 0, "code_window": [ "\t\tthis._onEditorsMoved.fire();\n", "\t}\n", "\n", "\tpublic moveEditor(input: EditorInput, from: EditorGroup, to: EditorGroup, index?: number): void;\n", "\tpublic moveEditor(input: EditorInput, from: Position, to: Position, index?: number): void;\n", "\tpublic moveEditor(input: EditorInput, arg2: any, arg3: any, index?: number): void {\n", "\t\tconst fromGroup = (typeof arg2 === 'number') ? this.stacks.groupAt(arg2) : arg2;\n", "\t\tif (!fromGroup) {\n", "\t\t\treturn;\n", "\t\t}\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tpublic moveEditor(input: EditorInput, from: EditorGroup, to: EditorGroup, index?: number, inactive?: boolean): void;\n", "\tpublic moveEditor(input: EditorInput, from: Position, to: Position, index?: number, inactive?: boolean): void;\n", "\tpublic moveEditor(input: EditorInput, arg2: any, arg3: any, index?: number, inactive?: boolean): void {\n" ], "file_path": "src/vs/workbench/browser/parts/editor/editorPart.ts", "type": "replace", "edit_start_line_idx": 810 }
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16"><path d="M3 9v5h10v-5h-10z" fill="#424242"/><polygon points="7,8 9,8 9,5 11,7 11,5 8,2 5,5 5,7 7,5" fill="#00539C"/></svg>
src/vs/workbench/parts/git/browser/media/push.svg
0
https://github.com/microsoft/vscode/commit/522c6e01711a50ab2c48e2efb11f837dce7ebab9
[ 0.00017308306996710598, 0.00017308306996710598, 0.00017308306996710598, 0.00017308306996710598, 0 ]
{ "id": 0, "code_window": [ "\t\tthis._onEditorsMoved.fire();\n", "\t}\n", "\n", "\tpublic moveEditor(input: EditorInput, from: EditorGroup, to: EditorGroup, index?: number): void;\n", "\tpublic moveEditor(input: EditorInput, from: Position, to: Position, index?: number): void;\n", "\tpublic moveEditor(input: EditorInput, arg2: any, arg3: any, index?: number): void {\n", "\t\tconst fromGroup = (typeof arg2 === 'number') ? this.stacks.groupAt(arg2) : arg2;\n", "\t\tif (!fromGroup) {\n", "\t\t\treturn;\n", "\t\t}\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tpublic moveEditor(input: EditorInput, from: EditorGroup, to: EditorGroup, index?: number, inactive?: boolean): void;\n", "\tpublic moveEditor(input: EditorInput, from: Position, to: Position, index?: number, inactive?: boolean): void;\n", "\tpublic moveEditor(input: EditorInput, arg2: any, arg3: any, index?: number, inactive?: boolean): void {\n" ], "file_path": "src/vs/workbench/browser/parts/editor/editorPart.ts", "type": "replace", "edit_start_line_idx": 810 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "explorerSection": "Section de l'Explorateur de fichiers", "treeAriaLabel": "Explorateur de fichiers" }
i18n/fra/src/vs/workbench/parts/files/browser/views/explorerView.i18n.json
0
https://github.com/microsoft/vscode/commit/522c6e01711a50ab2c48e2efb11f837dce7ebab9
[ 0.00017550996562931687, 0.00017550996562931687, 0.00017550996562931687, 0.00017550996562931687, 0 ]
{ "id": 1, "code_window": [ "\t\telse {\n", "\t\t\tconst toPosition = (typeof arg3 === 'number') ? arg3 : this.stacks.positionOfGroup(arg3);\n", "\n", "\t\t\tthis.doMoveEditorAcrossGroups(input, fromGroup, toPosition, index);\n", "\t\t}\n", "\t}\n", "\n", "\tprivate doMoveEditorInsideGroups(input: EditorInput, group: EditorGroup, toIndex: number): void {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tthis.doMoveEditorAcrossGroups(input, fromGroup, toPosition, index, inactive);\n" ], "file_path": "src/vs/workbench/browser/parts/editor/editorPart.ts", "type": "replace", "edit_start_line_idx": 827 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import 'vs/css!./media/editorpart'; import 'vs/workbench/browser/parts/editor/editor.contribution'; import { TPromise } from 'vs/base/common/winjs.base'; import { Registry } from 'vs/platform/platform'; import { Dimension, Builder, $ } from 'vs/base/browser/builder'; import nls = require('vs/nls'); import strings = require('vs/base/common/strings'); import arrays = require('vs/base/common/arrays'); import types = require('vs/base/common/types'); import errors = require('vs/base/common/errors'); import * as objects from 'vs/base/common/objects'; import { getCodeEditor } from 'vs/editor/common/services/codeEditorService'; import { toErrorMessage } from 'vs/base/common/errorMessage'; import { Scope as MementoScope } from 'vs/workbench/common/memento'; import { Part } from 'vs/workbench/browser/part'; import { BaseEditor, EditorDescriptor } from 'vs/workbench/browser/parts/editor/baseEditor'; import { IEditorRegistry, Extensions as EditorExtensions, EditorInput, EditorOptions, ConfirmResult, IWorkbenchEditorConfiguration, IEditorDescriptor, TextEditorOptions, SideBySideEditorInput, TextCompareEditorVisible, TEXT_DIFF_EDITOR_ID } from 'vs/workbench/common/editor'; import { EditorGroupsControl, Rochade, IEditorGroupsControl, ProgressState } from 'vs/workbench/browser/parts/editor/editorGroupsControl'; import { WorkbenchProgressService } from 'vs/workbench/services/progress/browser/progressService'; import { IEditorGroupService, GroupOrientation, GroupArrangement, ITabOptions } from 'vs/workbench/services/group/common/groupService'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IEditorPart } from 'vs/workbench/services/editor/browser/editorService'; import { IPartService } from 'vs/workbench/services/part/common/partService'; import { Position, POSITIONS, Direction } from 'vs/platform/editor/common/editor'; import { IStorageService } from 'vs/platform/storage/common/storage'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection'; import { IMessageService, IMessageWithAction, Severity } from 'vs/platform/message/common/message'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IProgressService } from 'vs/platform/progress/common/progress'; import { EditorStacksModel, EditorGroup, EditorIdentifier, GroupEvent } from 'vs/workbench/common/editor/editorStacksModel'; import Event, { Emitter } from 'vs/base/common/event'; import { IContextKey, IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; class ProgressMonitor { constructor(private _token: number, private progressPromise: TPromise<void>) { } public get token(): number { return this._token; } public cancel(): void { this.progressPromise.cancel(); } } interface IEditorPartUIState { ratio: number[]; groupOrientation: GroupOrientation; } interface IEditorReplacement extends EditorIdentifier { group: EditorGroup; editor: EditorInput; replaceWith: EditorInput; options?: EditorOptions; } /** * The editor part is the container for editors in the workbench. Based on the editor input being opened, it asks the registered * editor for the given input to show the contents. The editor part supports up to 3 side-by-side editors. */ export class EditorPart extends Part implements IEditorPart, IEditorGroupService { public _serviceBrand: any; private static GROUP_LEFT = nls.localize('groupOneVertical', "Left"); private static GROUP_CENTER = nls.localize('groupTwoVertical', "Center"); private static GROUP_RIGHT = nls.localize('groupThreeVertical', "Right"); private static GROUP_TOP = nls.localize('groupOneHorizontal', "Top"); private static GROUP_MIDDLE = nls.localize('groupTwoHorizontal', "Center"); private static GROUP_BOTTOM = nls.localize('groupThreeHorizontal', "Bottom"); private static EDITOR_PART_UI_STATE_STORAGE_KEY = 'editorpart.uiState'; private dimension: Dimension; private editorGroupsControl: IEditorGroupsControl; private memento: any; private stacks: EditorStacksModel; private tabOptions: ITabOptions; private forceHideTabs: boolean; private doNotFireTabOptionsChanged: boolean; private revealIfOpen: boolean; private _onEditorsChanged: Emitter<void>; private _onEditorsMoved: Emitter<void>; private _onEditorOpenFail: Emitter<EditorInput>; private _onGroupOrientationChanged: Emitter<void>; private _onTabOptionsChanged: Emitter<ITabOptions>; private textCompareEditorVisible: IContextKey<boolean>; // The following data structures are partitioned into array of Position as provided by Services.POSITION array private visibleEditors: BaseEditor[]; private instantiatedEditors: BaseEditor[][]; private mapEditorInstantiationPromiseToEditor: { [editorId: string]: TPromise<BaseEditor>; }[]; private editorOpenToken: number[]; private pendingEditorInputsToClose: EditorIdentifier[]; private pendingEditorInputCloseTimeout: number; private onLayoutEmitter = new Emitter<Dimension>(); public onLayout = this.onLayoutEmitter.event; constructor( id: string, restoreFromStorage: boolean, @IMessageService private messageService: IMessageService, @ITelemetryService private telemetryService: ITelemetryService, @IStorageService private storageService: IStorageService, @IPartService private partService: IPartService, @IConfigurationService private configurationService: IConfigurationService, @IContextKeyService contextKeyService: IContextKeyService, @IInstantiationService private instantiationService: IInstantiationService ) { super(id, { hasTitle: false }); this._onEditorsChanged = new Emitter<void>(); this._onEditorsMoved = new Emitter<void>(); this._onEditorOpenFail = new Emitter<EditorInput>(); this._onGroupOrientationChanged = new Emitter<void>(); this._onTabOptionsChanged = new Emitter<ITabOptions>(); this.visibleEditors = []; this.editorOpenToken = arrays.fill(POSITIONS.length, () => 0); this.instantiatedEditors = arrays.fill(POSITIONS.length, () => []); this.mapEditorInstantiationPromiseToEditor = arrays.fill(POSITIONS.length, () => Object.create(null)); this.pendingEditorInputsToClose = []; this.pendingEditorInputCloseTimeout = null; this.stacks = this.instantiationService.createInstance(EditorStacksModel, restoreFromStorage); this.textCompareEditorVisible = TextCompareEditorVisible.bindTo(contextKeyService); const config = configurationService.getConfiguration<IWorkbenchEditorConfiguration>(); if (config && config.workbench && config.workbench.editor) { const editorConfig = config.workbench.editor; this.tabOptions = { previewEditors: editorConfig.enablePreview, showIcons: editorConfig.showIcons, showTabs: editorConfig.showTabs, tabCloseButton: editorConfig.tabCloseButton }; this.revealIfOpen = editorConfig.revealIfOpen; this.telemetryService.publicLog('workbenchEditorConfiguration', editorConfig); } else { this.tabOptions = { previewEditors: true, showIcons: false, showTabs: true, tabCloseButton: 'right' }; this.revealIfOpen = false; } this.registerListeners(); } private registerListeners(): void { this.toUnbind.push(this.stacks.onEditorDirty(identifier => this.onEditorDirty(identifier))); this.toUnbind.push(this.stacks.onEditorDisposed(identifier => this.onEditorDisposed(identifier))); this.toUnbind.push(this.stacks.onEditorOpened(identifier => this.onEditorOpened(identifier))); this.toUnbind.push(this.stacks.onEditorClosed(event => this.onEditorClosed(event))); this.toUnbind.push(this.configurationService.onDidUpdateConfiguration(e => this.onConfigurationUpdated(e.config))); } private onConfigurationUpdated(configuration: IWorkbenchEditorConfiguration): void { if (configuration && configuration.workbench && configuration.workbench.editor) { const editorConfig = configuration.workbench.editor; // Pin all preview editors of the user chose to disable preview const newPreviewEditors = editorConfig.enablePreview; if (this.tabOptions.previewEditors !== newPreviewEditors && !newPreviewEditors) { this.stacks.groups.forEach(group => { if (group.previewEditor) { this.pinEditor(group, group.previewEditor); } }); } const oldTabOptions = objects.clone(this.tabOptions); this.tabOptions = { previewEditors: newPreviewEditors, showIcons: editorConfig.showIcons, tabCloseButton: editorConfig.tabCloseButton, showTabs: this.forceHideTabs ? false : editorConfig.showTabs }; if (!this.doNotFireTabOptionsChanged && !objects.equals(oldTabOptions, this.tabOptions)) { this._onTabOptionsChanged.fire(this.tabOptions); } this.revealIfOpen = editorConfig.revealIfOpen; } } private onEditorDirty(identifier: EditorIdentifier): void { // we pin every editor that becomes dirty this.pinEditor(identifier.group, identifier.editor); } private onEditorDisposed(identifier: EditorIdentifier): void { this.pendingEditorInputsToClose.push(identifier); this.startDelayedCloseEditorsFromInputDispose(); } private onEditorOpened(identifier: EditorIdentifier): void { this.telemetryService.publicLog('editorOpened', identifier.editor.getTelemetryDescriptor()); } private onEditorClosed(event: GroupEvent): void { this.telemetryService.publicLog('editorClosed', event.editor.getTelemetryDescriptor()); } public hideTabs(forceHide: boolean): void { this.forceHideTabs = forceHide; const config = this.configurationService.getConfiguration<IWorkbenchEditorConfiguration>(); this.tabOptions.showTabs = forceHide ? false : config && config.workbench && config.workbench.editor && config.workbench.editor.showTabs; this._onTabOptionsChanged.fire(this.tabOptions); } public get onEditorsChanged(): Event<void> { return this._onEditorsChanged.event; } public get onEditorsMoved(): Event<void> { return this._onEditorsMoved.event; } public get onEditorOpenFail(): Event<EditorInput> { return this._onEditorOpenFail.event; } public get onGroupOrientationChanged(): Event<void> { return this._onGroupOrientationChanged.event; } public get onTabOptionsChanged(): Event<ITabOptions> { return this._onTabOptionsChanged.event; } public getTabOptions(): ITabOptions { return this.tabOptions; } public openEditor(input: EditorInput, options?: EditorOptions, sideBySide?: boolean): TPromise<BaseEditor>; public openEditor(input: EditorInput, options?: EditorOptions, position?: Position, ratio?: number[]): TPromise<BaseEditor>; public openEditor(input: EditorInput, options?: EditorOptions, arg3?: any, ratio?: number[]): TPromise<BaseEditor> { // Normalize some values if (!options) { options = null; } // Determine position to open editor in (one, two, three) const position = this.findPosition(input, options, arg3, ratio); // Some conditions under which we prevent the request if ( !input || // no input position === null || // invalid position Object.keys(this.mapEditorInstantiationPromiseToEditor[position]).length > 0 || // pending editor load !this.editorGroupsControl || // too early this.editorGroupsControl.isDragging() // pending editor DND ) { return TPromise.as<BaseEditor>(null); } // We need an editor descriptor for the input const descriptor = Registry.as<IEditorRegistry>(EditorExtensions.Editors).getEditor(input); if (!descriptor) { return TPromise.wrapError(new Error(strings.format('Can not find a registered editor for the input {0}', input))); } // Opened to the side if (position !== Position.ONE) { this.telemetryService.publicLog('workbenchSideEditorOpened', { position: position }); } // Open through UI return this.doOpenEditor(position, descriptor, input, options, ratio); } private doOpenEditor(position: Position, descriptor: IEditorDescriptor, input: EditorInput, options: EditorOptions, ratio: number[]): TPromise<BaseEditor> { // Update stacks: We do this early on before the UI is there because we want our stacks model to have // a consistent view of the editor world and updating it later async after the UI is there will cause // issues (e.g. when a closeEditor call is made that expects the openEditor call to have updated the // stacks model). // This can however cause a race condition where the stacks model indicates the opened editor is there // while the UI is not yet ready. Clients have to deal with this fact and we have to make sure that the // stacks model gets updated if any of the UI updating fails with an error. const group = this.ensureGroup(position, !options || !options.preserveFocus); const pinned = !this.tabOptions.previewEditors || (options && (options.pinned || typeof options.index === 'number')) || input.isDirty(); const active = (group.count === 0) || !options || !options.inactive; group.openEditor(input, { active, pinned, index: options && options.index }); // Return early if the editor is to be open inactive and there are other editors in this group to show if (!active) { return TPromise.as<BaseEditor>(null); } // Progress Monitor & Ref Counting this.editorOpenToken[position]++; const editorOpenToken = this.editorOpenToken[position]; const monitor = new ProgressMonitor(editorOpenToken, TPromise.timeout(this.partService.isCreated() ? 800 : 3200 /* less ugly initial startup */).then(() => { const position = this.stacks.positionOfGroup(group); // might have changed due to a rochade meanwhile if (editorOpenToken === this.editorOpenToken[position]) { this.editorGroupsControl.updateProgress(position, ProgressState.INFINITE); } })); // Show editor return this.doShowEditor(group, descriptor, input, options, ratio, monitor).then(editor => { if (!editor) { return TPromise.as<BaseEditor>(null); // canceled or other error } // Set input to editor return this.doSetInput(group, editor, input, options, monitor); }); } private doShowEditor(group: EditorGroup, descriptor: IEditorDescriptor, input: EditorInput, options: EditorOptions, ratio: number[], monitor: ProgressMonitor): TPromise<BaseEditor> { const position = this.stacks.positionOfGroup(group); const editorAtPosition = this.visibleEditors[position]; // Return early if the currently visible editor can handle the input if (editorAtPosition && descriptor.describes(editorAtPosition)) { return TPromise.as(editorAtPosition); } // Hide active one first if (editorAtPosition) { this.doHideEditor(position, false); } // Create Editor return this.doCreateEditor(group, descriptor, monitor).then(editor => { const position = this.stacks.positionOfGroup(group); // might have changed due to a rochade meanwhile // Make sure that the user meanwhile did not open another editor or something went wrong if (!editor || !this.visibleEditors[position] || editor.getId() !== this.visibleEditors[position].getId()) { monitor.cancel(); return null; } // Show in side by side control this.editorGroupsControl.show(editor, position, options && options.preserveFocus, ratio); // Indicate to editor that it is now visible editor.setVisible(true, position); // Update text compare editor visible context this.updateTextCompareEditorVisible(); // Make sure the editor is layed out this.editorGroupsControl.layout(position); return editor; }, e => this.messageService.show(Severity.Error, types.isString(e) ? new Error(e) : e)); } private doCreateEditor(group: EditorGroup, descriptor: IEditorDescriptor, monitor: ProgressMonitor): TPromise<BaseEditor> { // Instantiate editor return this.doInstantiateEditor(group, descriptor).then(editor => { const position = this.stacks.positionOfGroup(group); // might have changed due to a rochade meanwhile // Make sure that the user meanwhile did not open another editor if (monitor.token !== this.editorOpenToken[position]) { monitor.cancel(); return null; } // Remember Editor at position this.visibleEditors[position] = editor; // Create editor as needed if (!editor.getContainer()) { editor.create($().div({ 'class': 'editor-container', 'role': 'tabpanel', id: descriptor.getId() })); } return editor; }); } private doInstantiateEditor(group: EditorGroup, descriptor: IEditorDescriptor): TPromise<BaseEditor> { const position = this.stacks.positionOfGroup(group); // Return early if already instantiated const instantiatedEditor = this.instantiatedEditors[position].filter(e => descriptor.describes(e))[0]; if (instantiatedEditor) { return TPromise.as(instantiatedEditor); } // Return early if editor is being instantiated at the same time from a previous call const pendingEditorInstantiate = this.mapEditorInstantiationPromiseToEditor[position][descriptor.getId()]; if (pendingEditorInstantiate) { return pendingEditorInstantiate; } // Otherwise instantiate const progressService = this.instantiationService.createInstance(WorkbenchProgressService, this.editorGroupsControl.getProgressBar(position), descriptor.getId(), true); const editorInstantiationService = this.editorGroupsControl.getInstantiationService(position).createChild(new ServiceCollection([IProgressService, progressService])); let loaded = false; const onInstantiate = (arg: BaseEditor | Error): TPromise<BaseEditor | Error> => { const position = this.stacks.positionOfGroup(group); // might have changed due to a rochade meanwhile loaded = true; delete this.mapEditorInstantiationPromiseToEditor[position][descriptor.getId()]; if (arg instanceof BaseEditor) { this.instantiatedEditors[position].push(arg); return TPromise.as(arg); } return TPromise.wrapError(arg); }; const instantiateEditorPromise = editorInstantiationService.createInstance(<EditorDescriptor>descriptor).then(onInstantiate, onInstantiate); if (!loaded) { this.mapEditorInstantiationPromiseToEditor[position][descriptor.getId()] = instantiateEditorPromise; } return instantiateEditorPromise.then(result => { progressService.dispose(); return result; }); } private doSetInput(group: EditorGroup, editor: BaseEditor, input: EditorInput, options: EditorOptions, monitor: ProgressMonitor): TPromise<BaseEditor> { // Emit Input-Changed Event as appropiate const previousInput = editor.input; const inputChanged = (!previousInput || !previousInput.matches(input) || (options && options.forceOpen)); // Call into Editor return editor.setInput(input, options).then(() => { // Stop loading promise if any monitor.cancel(); const position = this.stacks.positionOfGroup(group); // might have changed due to a rochade meanwhile if (position === -1) { return null; // in theory a call to editor.setInput() could have resulted in the editor being closed due to an error, so we guard against it here } // Focus (unless prevented) const focus = !options || !options.preserveFocus; if (focus) { editor.focus(); } // Progress Done this.editorGroupsControl.updateProgress(position, ProgressState.DONE); // Emit Change Event (if input changed) if (inputChanged) { this._onEditorsChanged.fire(); } // Fullfill promise with Editor that is being used return editor; }, e => this.doHandleSetInputError(e, group, editor, input, options, monitor)); } private doHandleSetInputError(e: Error | IMessageWithAction, group: EditorGroup, editor: BaseEditor, input: EditorInput, options: EditorOptions, monitor: ProgressMonitor): void { const position = this.stacks.positionOfGroup(group); // Stop loading promise if any monitor.cancel(); // Report error only if this was not us restoring previous error state if (this.partService.isCreated() && !errors.isPromiseCanceledError(e)) { const errorMessage = nls.localize('editorOpenError', "Unable to open '{0}': {1}.", input.getName(), toErrorMessage(e)); let error: any; if (e && (<IMessageWithAction>e).actions && (<IMessageWithAction>e).actions.length) { error = errors.create(errorMessage, { actions: (<IMessageWithAction>e).actions }); // Support error actions from thrower } else { error = errorMessage; } this.messageService.show(Severity.Error, types.isString(error) ? new Error(error) : error); } this.editorGroupsControl.updateProgress(position, ProgressState.DONE); // Event this._onEditorOpenFail.fire(input); // Recover by closing the active editor (if the input is still the active one) if (group.activeEditor === input) { this.doCloseActiveEditor(group); } } public closeEditor(position: Position, input: EditorInput): TPromise<void> { const group = this.stacks.groupAt(position); if (!group) { return TPromise.as<void>(null); } // Check for dirty and veto return this.handleDirty([{ group, editor: input }], true /* ignore if opened in other group */).then(veto => { if (veto) { return; } // Do close this.doCloseEditor(group, input); }); } private doCloseEditor(group: EditorGroup, input: EditorInput, focusNext = this.stacks.isActive(group)): void { // Closing the active editor of the group is a bit more work if (group.activeEditor && group.activeEditor.matches(input)) { this.doCloseActiveEditor(group, focusNext); } // Closing inactive editor is just a model update else { this.doCloseInactiveEditor(group, input); } } private doCloseActiveEditor(group: EditorGroup, focusNext = true): void { const position = this.stacks.positionOfGroup(group); // Update stacks model group.closeEditor(group.activeEditor); // Close group is this is the last editor in group if (group.count === 0) { this.doCloseGroup(group, focusNext); } // Otherwise open next active else { this.openEditor(group.activeEditor, !focusNext ? EditorOptions.create({ preserveFocus: true }) : null, position).done(null, errors.onUnexpectedError); } } private doCloseInactiveEditor(group: EditorGroup, input: EditorInput): void { // Closing inactive editor is just a model update group.closeEditor(input); } private doCloseGroup(group: EditorGroup, focusNext = true): void { const position = this.stacks.positionOfGroup(group); // Update stacks model this.modifyGroups(() => this.stacks.closeGroup(group)); // Hide Editor this.doHideEditor(position, true); // Emit Change Event this._onEditorsChanged.fire(); // Focus next group if we have an active one left const currentActiveGroup = this.stacks.activeGroup; if (currentActiveGroup) { if (focusNext) { this.focusGroup(currentActiveGroup); } else { this.activateGroup(currentActiveGroup); } // Explicitly trigger the focus changed handler because the side by side control will not trigger it unless // the user is actively changing focus with the mouse from left/top to right/bottom. this.onGroupFocusChanged(); } } private doHideEditor(position: Position, layoutAndRochade: boolean): void { const editor = this.visibleEditors[position]; // Hide in side by side control const rochade = this.editorGroupsControl.hide(editor, position, layoutAndRochade); // Clear any running Progress this.editorGroupsControl.updateProgress(position, ProgressState.STOP); // Indicate to Editor editor.clearInput(); editor.setVisible(false); // Update text compare editor visible context this.updateTextCompareEditorVisible(); // Clear active editor this.visibleEditors[position] = null; // Rochade as needed this.rochade(rochade); // Emit Editor move event if (rochade !== Rochade.NONE) { this._onEditorsMoved.fire(); } } private updateTextCompareEditorVisible(): void { this.textCompareEditorVisible.set(this.visibleEditors.some(e => e && e.isVisible() && e.getId() === TEXT_DIFF_EDITOR_ID)); } public closeAllEditors(except?: Position): TPromise<void> { let groups = this.stacks.groups.reverse(); // start from the end to prevent layout to happen through rochade // Remove position to exclude if we have any if (typeof except === 'number') { groups = groups.filter(group => this.stacks.positionOfGroup(group) !== except); } // Check for dirty and veto const editorsToClose = arrays.flatten(groups.map(group => group.getEditors().map(editor => { return { group, editor }; }))); return this.handleDirty(editorsToClose).then(veto => { if (veto) { return; } groups.forEach(group => this.doCloseEditors(group)); }); } public closeEditors(position: Position, except?: EditorInput, direction?: Direction): TPromise<void> { const group = this.stacks.groupAt(position); if (!group) { return TPromise.as<void>(null); } // Check for dirty and veto let editorsToClose: EditorInput[]; if (types.isUndefinedOrNull(direction)) { editorsToClose = group.getEditors().filter(e => !except || !e.matches(except)); } else { editorsToClose = (direction === Direction.LEFT) ? group.getEditors().slice(0, group.indexOf(except)) : group.getEditors().slice(group.indexOf(except) + 1); } return this.handleDirty(editorsToClose.map(editor => { return { group, editor }; }), true /* ignore if opened in other group */).then(veto => { if (veto) { return; } this.doCloseEditors(group, except, direction); }); } private doCloseEditors(group: EditorGroup, except?: EditorInput, direction?: Direction): void { // Close all editors in group if (!except) { // Update stacks model: remove all non active editors first to prevent opening the next editor in group group.closeEditors(group.activeEditor); // Now close active editor in group which will close the group this.doCloseActiveEditor(group); } // Close all editors in group except active one else if (except.matches(group.activeEditor)) { // Update stacks model: close non active editors supporting the direction group.closeEditors(group.activeEditor, direction); } // Finally: we are asked to close editors around a non-active editor // Thus we make the non-active one active and then close the others else { this.openEditor(except, null, this.stacks.positionOfGroup(group)).done(() => { // since the opening might have failed, we have to check again for the active editor // being the expected one, otherwise we end up in an endless loop trying to open the // editor if (except.matches(group.activeEditor)) { this.doCloseEditors(group, except, direction); } }, errors.onUnexpectedError); } } private handleDirty(identifiers: EditorIdentifier[], ignoreIfOpenedInOtherGroup?: boolean): TPromise<boolean /* veto */> { if (!identifiers.length) { return TPromise.as(false); // no veto } return this.doHandleDirty(identifiers.shift(), ignoreIfOpenedInOtherGroup).then(veto => { if (veto) { return veto; } return this.handleDirty(identifiers, ignoreIfOpenedInOtherGroup); }); } private doHandleDirty(identifier: EditorIdentifier, ignoreIfOpenedInOtherGroup?: boolean): TPromise<boolean /* veto */> { if (!identifier || !identifier.editor || !identifier.editor.isDirty() || (ignoreIfOpenedInOtherGroup && this.countEditors(identifier.editor) > 1 /* allow to close a dirty editor if it is opened in another group */)) { return TPromise.as(false); // no veto } const { editor } = identifier; const res = editor.confirmSave(); switch (res) { case ConfirmResult.SAVE: return editor.save().then(ok => !ok); case ConfirmResult.DONT_SAVE: return editor.revert().then(ok => !ok); case ConfirmResult.CANCEL: return TPromise.as(true); // veto } } private countEditors(editor: EditorInput): number { const editors = [editor]; if (editor instanceof SideBySideEditorInput) { editors.push(editor.master); } return editors.reduce((prev, e) => prev += this.stacks.count(e), 0); } public getStacksModel(): EditorStacksModel { return this.stacks; } public getActiveEditorInput(): EditorInput { const lastActiveEditor = this.getActiveEditor(); return lastActiveEditor ? lastActiveEditor.input : null; } public getActiveEditor(): BaseEditor { if (!this.editorGroupsControl) { return null; // too early } return this.editorGroupsControl.getActiveEditor(); } public getVisibleEditors(): BaseEditor[] { return this.visibleEditors ? this.visibleEditors.filter(editor => !!editor) : []; } public moveGroup(from: EditorGroup, to: EditorGroup): void; public moveGroup(from: Position, to: Position): void; public moveGroup(arg1: any, arg2: any): void { const fromGroup = (typeof arg1 === 'number') ? this.stacks.groupAt(arg1) : arg1; const toGroup = (typeof arg2 === 'number') ? this.stacks.groupAt(arg2) : arg2; if (!fromGroup || !toGroup || fromGroup === toGroup) { return; // Ignore if we cannot move } const fromPosition = this.stacks.positionOfGroup(fromGroup); const toPosition = this.stacks.positionOfGroup(toGroup); // Update stacks model this.modifyGroups(() => this.stacks.moveGroup(fromGroup, toPosition)); // Move widgets this.editorGroupsControl.move(fromPosition, toPosition); // Move data structures arrays.move(this.visibleEditors, fromPosition, toPosition); arrays.move(this.editorOpenToken, fromPosition, toPosition); arrays.move(this.mapEditorInstantiationPromiseToEditor, fromPosition, toPosition); arrays.move(this.instantiatedEditors, fromPosition, toPosition); // Restore focus this.focusGroup(fromGroup); // Events this._onEditorsMoved.fire(); } public moveEditor(input: EditorInput, from: EditorGroup, to: EditorGroup, index?: number): void; public moveEditor(input: EditorInput, from: Position, to: Position, index?: number): void; public moveEditor(input: EditorInput, arg2: any, arg3: any, index?: number): void { const fromGroup = (typeof arg2 === 'number') ? this.stacks.groupAt(arg2) : arg2; if (!fromGroup) { return; } // Move within group if (arg2 === arg3) { this.doMoveEditorInsideGroups(input, fromGroup, index); } // Move across groups else { const toPosition = (typeof arg3 === 'number') ? arg3 : this.stacks.positionOfGroup(arg3); this.doMoveEditorAcrossGroups(input, fromGroup, toPosition, index); } } private doMoveEditorInsideGroups(input: EditorInput, group: EditorGroup, toIndex: number): void { if (typeof toIndex !== 'number') { return; // do nothing if we move into same group without index } const currentIndex = group.indexOf(input); if (currentIndex === toIndex) { return; // do nothing if editor is already at the given index } // Update stacks model group.moveEditor(input, toIndex); group.pin(input); } private doMoveEditorAcrossGroups(input: EditorInput, fromGroup: EditorGroup, to: Position, index?: number): void { if (fromGroup.count === 1) { const toGroup = this.stacks.groupAt(to); if (!toGroup && this.stacks.positionOfGroup(fromGroup) < to) { return; // do nothing if the group to move only has one editor and is the last group already } } // When moving an editor, try to preserve as much view state as possible by checking // for th editor to be a text editor and creating the options accordingly if so let options = EditorOptions.create({ pinned: true, index }); const activeEditor = this.getActiveEditor(); const codeEditor = getCodeEditor(activeEditor); if (codeEditor && activeEditor.position === this.stacks.positionOfGroup(fromGroup) && input.matches(activeEditor.input)) { options = TextEditorOptions.create({ pinned: true, index }); (<TextEditorOptions>options).fromEditor(codeEditor); } // A move to another group is an open first... this.openEditor(input, options, to).done(null, errors.onUnexpectedError); // and a close afterwards... this.doCloseEditor(fromGroup, input, false /* do not activate next one behind if any */); } public arrangeGroups(arrangement: GroupArrangement): void { this.editorGroupsControl.arrangeGroups(arrangement); } public setGroupOrientation(orientation: GroupOrientation): void { this.editorGroupsControl.setGroupOrientation(orientation); this._onGroupOrientationChanged.fire(); // Rename groups when layout changes this.renameGroups(); } public getGroupOrientation(): GroupOrientation { return this.editorGroupsControl.getGroupOrientation(); } public createContentArea(parent: Builder): Builder { // Content Container const contentArea = $(parent) .div() .addClass('content'); // get settings this.memento = this.getMemento(this.storageService, MementoScope.WORKSPACE); // Side by Side Control const editorPartState: IEditorPartUIState = this.memento[EditorPart.EDITOR_PART_UI_STATE_STORAGE_KEY]; this.editorGroupsControl = this.instantiationService.createInstance(EditorGroupsControl, contentArea, editorPartState && editorPartState.groupOrientation); this.toUnbind.push(this.editorGroupsControl.onGroupFocusChanged(() => this.onGroupFocusChanged())); return contentArea; } private onGroupFocusChanged(): void { // Update stacks model const activePosition = this.editorGroupsControl.getActivePosition(); if (typeof activePosition === 'number') { this.stacks.setActive(this.stacks.groupAt(activePosition)); } // Emit as change event so that clients get aware of new active editor const activeEditor = this.editorGroupsControl.getActiveEditor(); if (activeEditor) { this._onEditorsChanged.fire(); } } public replaceEditors(editors: { toReplace: EditorInput, replaceWith: EditorInput, options?: EditorOptions }[], position?: Position): TPromise<BaseEditor[]> { const activeReplacements: IEditorReplacement[] = []; const hiddenReplacements: IEditorReplacement[] = []; // Find editors across groups to close editors.forEach(editor => { if (editor.toReplace.isDirty()) { return; // we do not handle dirty in this method, so ignore all dirty } // For each group this.stacks.groups.forEach(group => { if (position === void 0 || this.stacks.positionOfGroup(group) === position) { const index = group.indexOf(editor.toReplace); if (index >= 0) { if (editor.options) { editor.options.index = index; // make sure we respect the index of the editor to replace! } else { editor.options = EditorOptions.create({ index }); } const replacement = { group, editor: editor.toReplace, replaceWith: editor.replaceWith, options: editor.options }; if (group.activeEditor.matches(editor.toReplace)) { activeReplacements.push(replacement); } else { hiddenReplacements.push(replacement); } } } }); }); // Deal with hidden replacements first hiddenReplacements.forEach(replacement => { const group = replacement.group; group.openEditor(replacement.replaceWith, { active: false, pinned: true, index: replacement.options.index }); group.closeEditor(replacement.editor); }); // Now deal with active editors to be opened const res = this.openEditors(activeReplacements.map(replacement => { const group = replacement.group; return { input: replacement.replaceWith, position: this.stacks.positionOfGroup(group), options: replacement.options }; })); // Close active editors to be replaced now (they are no longer active) activeReplacements.forEach(replacement => { this.doCloseEditor(replacement.group, replacement.editor, false); }); return res; } public openEditors(editors: { input: EditorInput, position: Position, options?: EditorOptions }[]): TPromise<BaseEditor[]> { if (!editors.length) { return TPromise.as<BaseEditor[]>([]); } let activePosition: Position; if (this.stacks.activeGroup) { activePosition = this.stacks.positionOfGroup(this.stacks.activeGroup); } const ratio = this.editorGroupsControl.getRatio(); return this.doOpenEditors(editors, activePosition, ratio); } public restoreEditors(): TPromise<BaseEditor[]> { const editors = this.stacks.groups.map((group, index) => { return { input: group.activeEditor, position: index, options: group.isPinned(group.activeEditor) ? EditorOptions.create({ pinned: true }) : void 0 }; }); if (!editors.length) { return TPromise.as<BaseEditor[]>([]); } let activePosition: Position; if (this.stacks.groups.length) { activePosition = this.stacks.positionOfGroup(this.stacks.activeGroup); } const editorState: IEditorPartUIState = this.memento[EditorPart.EDITOR_PART_UI_STATE_STORAGE_KEY]; return this.doOpenEditors(editors, activePosition, editorState && editorState.ratio); } private doOpenEditors(editors: { input: EditorInput, position: Position, options?: EditorOptions }[], activePosition?: number, ratio?: number[]): TPromise<BaseEditor[]> { const positionOneEditors = editors.filter(e => e.position === Position.ONE); const positionTwoEditors = editors.filter(e => e.position === Position.TWO); const positionThreeEditors = editors.filter(e => e.position === Position.THREE); const groupOne = this.stacks.groupAt(Position.ONE); const groupTwo = this.stacks.groupAt(Position.TWO); const groupThree = this.stacks.groupAt(Position.THREE); // Compute the imaginary count if we const all editors open as the way requested const oneCount = positionOneEditors.length + (groupOne ? groupOne.count : 0); const twoCount = positionTwoEditors.length + (groupTwo ? groupTwo.count : 0); const threeCount = positionThreeEditors.length + (groupThree ? groupThree.count : 0); // Validate we do not produce empty groups given our imaginary count model if ((!oneCount && (twoCount || threeCount) || (!twoCount && threeCount))) { positionOneEditors.push(...positionTwoEditors); positionOneEditors.push(...positionThreeEditors); positionTwoEditors.splice(0, positionTwoEditors.length); positionThreeEditors.splice(0, positionThreeEditors.length); } // Validate active input if (typeof activePosition !== 'number') { activePosition = Position.ONE; } // Validate ratios const positions = positionThreeEditors.length ? 3 : positionTwoEditors.length ? 2 : 1; if (!ratio || ratio.length !== positions) { if (!this.getVisibleEditors().length) { ratio = (positions === 3) ? [0.33, 0.33, 0.34] : (positions === 2) ? [0.5, 0.5] : [1]; } else { ratio = void 0; } } let focusGroup = false; const activeGroup = this.stacks.groupAt(activePosition); if (!this.stacks.activeGroup || !activeGroup) { focusGroup = true; // always focus group if this is the first group or we are about to open a new group } else { focusGroup = editors.some(e => !e.options || (!e.options.inactive && !e.options.preserveFocus)); // only focus if the editors to open are not opening as inactive or preserveFocus } // Open each input respecting the options. Since there can only be one active editor in each // position, we have to pick the first input from each position and add the others as inactive const promises: TPromise<BaseEditor>[] = []; [positionOneEditors.shift(), positionTwoEditors.shift(), positionThreeEditors.shift()].forEach((editor, position) => { if (!editor) { return; // unused position } const input = editor.input; // Resolve editor options const preserveFocus = (activePosition !== position); let options: EditorOptions; if (editor.options) { options = editor.options; if (typeof options.preserveFocus !== 'boolean') { options.preserveFocus = preserveFocus; } } else { options = EditorOptions.create({ preserveFocus }); } promises.push(this.openEditor(input, options, position, ratio)); }); return TPromise.join(promises).then(editors => { // Adjust focus as needed if (focusGroup) { this.focusGroup(activePosition); } // Update stacks model for remaining inactive editors [positionOneEditors, positionTwoEditors, positionThreeEditors].forEach((editors, index) => { const group = this.stacks.groupAt(index); if (group) { editors.forEach(editor => group.openEditor(editor.input, { pinned: true })); // group could be null if one openeditor call failed! } }); // Full layout side by side this.editorGroupsControl.layout(this.dimension); return editors; }); } public activateGroup(group: EditorGroup): void; public activateGroup(position: Position): void; public activateGroup(arg1: any): void { const group = (typeof arg1 === 'number') ? this.stacks.groupAt(arg1) : arg1; if (group) { // Update stacks model this.stacks.setActive(group); // Update UI const editor = this.visibleEditors[this.stacks.positionOfGroup(group)]; if (editor) { this.editorGroupsControl.setActive(editor); } } } public focusGroup(group: EditorGroup): void; public focusGroup(position: Position): void; public focusGroup(arg1: any): void { const group = (typeof arg1 === 'number') ? this.stacks.groupAt(arg1) : arg1; if (group) { // Make active this.activateGroup(group); // Focus Editor const editor = this.visibleEditors[this.stacks.positionOfGroup(group)]; if (editor) { editor.focus(); } } } public pinEditor(group: EditorGroup, input: EditorInput): void; public pinEditor(position: Position, input: EditorInput): void; public pinEditor(arg1: any, input: EditorInput): void { const group = (typeof arg1 === 'number') ? this.stacks.groupAt(arg1) : arg1; if (group) { if (group.isPinned(input)) { return; } // Update stacks model group.pin(input); } } public unpinEditor(group: EditorGroup, input: EditorInput): void; public unpinEditor(position: Position, input: EditorInput): void; public unpinEditor(arg1: any, input: EditorInput): void { if (input.isDirty()) { return; // we do not allow to unpin dirty editors } const group = (typeof arg1 === 'number') ? this.stacks.groupAt(arg1) : arg1; if (group) { if (group.isPreview(input)) { return; } // Unpinning an editor closes the preview editor if we have any let handlePreviewEditor: TPromise<boolean> = TPromise.as(false); if (group.previewEditor) { handlePreviewEditor = this.handleDirty([{ group, editor: group.previewEditor }], true /* ignore if opened in other group */); } handlePreviewEditor.done(veto => { if (veto) { return; } // The active editor is the preview editor and we are asked to make // another editor the preview editor. So we need to take care of closing // the active editor first if (group.isPreview(group.activeEditor) && !group.activeEditor.matches(input)) { this.doCloseActiveEditor(group); } // Update stacks model group.unpin(input); }); } } public layout(dimension: Dimension): Dimension[] { // Pass to super const sizes = super.layout(dimension); // Pass to Side by Side Control this.dimension = sizes[1]; this.editorGroupsControl.layout(this.dimension); this.onLayoutEmitter.fire(dimension); return sizes; } public shutdown(): void { // Persist UI State const editorState: IEditorPartUIState = { ratio: this.editorGroupsControl.getRatio(), groupOrientation: this.editorGroupsControl.getGroupOrientation() }; this.memento[EditorPart.EDITOR_PART_UI_STATE_STORAGE_KEY] = editorState; // Unload all Instantiated Editors for (let i = 0; i < this.instantiatedEditors.length; i++) { for (let j = 0; j < this.instantiatedEditors[i].length; j++) { this.instantiatedEditors[i][j].shutdown(); } } // Pass to super super.shutdown(); } public dispose(): void { // Emitters this._onEditorsChanged.dispose(); this._onEditorsMoved.dispose(); this._onEditorOpenFail.dispose(); // Reset Tokens this.editorOpenToken = []; for (let i = 0; i < POSITIONS.length; i++) { this.editorOpenToken[i] = 0; } // Widgets this.editorGroupsControl.dispose(); // Pass to active editors this.visibleEditors.forEach(editor => { if (editor) { editor.dispose(); } }); // Pass to instantiated editors for (let i = 0; i < this.instantiatedEditors.length; i++) { for (let j = 0; j < this.instantiatedEditors[i].length; j++) { if (this.visibleEditors.some(editor => editor === this.instantiatedEditors[i][j])) { continue; } this.instantiatedEditors[i][j].dispose(); } } this.visibleEditors = null; // Pass to super super.dispose(); } private findPosition(input: EditorInput, options?: EditorOptions, sideBySide?: boolean, ratio?: number[]): Position; private findPosition(input: EditorInput, options?: EditorOptions, desiredPosition?: Position, ratio?: number[]): Position; private findPosition(input: EditorInput, options?: EditorOptions, arg1?: any, ratio?: number[]): Position { // With defined ratios, always trust the provided position if (ratio && types.isNumber(arg1)) { return arg1; } // No editor open const visibleEditors = this.getVisibleEditors(); const activeEditor = this.getActiveEditor(); if (visibleEditors.length === 0 || !activeEditor) { return Position.ONE; // can only be ONE } // Respect option to reveal an editor if it is already visible if (options && options.revealIfVisible) { const group = this.stacks.findGroup(input, true); if (group) { return this.stacks.positionOfGroup(group); } } // Respect option to reveal an editor if it is open (not necessarily visible) const skipRevealIfOpen = (options && options.index) || arg1; if (!skipRevealIfOpen && this.revealIfOpen) { const group = this.stacks.findGroup(input); if (group) { return this.stacks.positionOfGroup(group); } } // Position is unknown: pick last active or ONE if (types.isUndefinedOrNull(arg1) || arg1 === false) { const lastActivePosition = this.editorGroupsControl.getActivePosition(); return lastActivePosition || Position.ONE; } // Position is sideBySide: Find position relative to active editor if (arg1 === true) { switch (activeEditor.position) { case Position.ONE: return Position.TWO; case Position.TWO: return Position.THREE; case Position.THREE: return null; // Cannot open to the side of the right/bottom most editor } return null; // Prevent opening to the side } // Position is provided, validate it if (arg1 === Position.THREE && visibleEditors.length === 1) { return Position.TWO; } return arg1; } private startDelayedCloseEditorsFromInputDispose(): void { // To prevent race conditions, we call the close in a timeout because it can well be // that an input is being disposed with the intent to replace it with some other input // right after. if (this.pendingEditorInputCloseTimeout === null) { this.pendingEditorInputCloseTimeout = setTimeout(() => { // Split between visible and hidden editors const visibleEditors: EditorIdentifier[] = []; const hiddenEditors: EditorIdentifier[] = []; this.pendingEditorInputsToClose.forEach(identifier => { const { group, editor } = identifier; if (group.isActive(editor)) { visibleEditors.push(identifier); } else if (group.contains(editor)) { hiddenEditors.push(identifier); } }); // Close all hidden first hiddenEditors.forEach(hidden => this.doCloseEditor(<EditorGroup>hidden.group, hidden.editor, false)); // Close visible ones second visibleEditors .sort((a1, a2) => this.stacks.positionOfGroup(a2.group) - this.stacks.positionOfGroup(a1.group)) // reduce layout work by starting right/bottom first .forEach(visible => this.doCloseEditor(<EditorGroup>visible.group, visible.editor, false)); // Reset this.pendingEditorInputCloseTimeout = null; this.pendingEditorInputsToClose = []; }, 0); } } private rochade(rochade: Rochade): void; private rochade(from: Position, to: Position): void; private rochade(arg1: any, arg2?: any): void { if (types.isUndefinedOrNull(arg2)) { const rochade = <Rochade>arg1; switch (rochade) { case Rochade.TWO_TO_ONE: this.rochade(Position.TWO, Position.ONE); break; case Rochade.THREE_TO_TWO: this.rochade(Position.THREE, Position.TWO); break; case Rochade.TWO_AND_THREE_TO_ONE: this.rochade(Position.TWO, Position.ONE); this.rochade(Position.THREE, Position.TWO); } } else { const from = <Position>arg1; const to = <Position>arg2; this.doRochade(this.visibleEditors, from, to, null); this.doRochade(this.editorOpenToken, from, to, null); this.doRochade(this.mapEditorInstantiationPromiseToEditor, from, to, Object.create(null)); this.doRochade(this.instantiatedEditors, from, to, []); } } private doRochade(array: any[], from: Position, to: Position, empty: any): void { array[to] = array[from]; array[from] = empty; } private ensureGroup(position: Position, activate = true): EditorGroup { let group = this.stacks.groupAt(position); if (!group) { // Race condition: it could be that someone quickly opens editors one after // the other and we are asked to open an editor in position 2 before position // 1 was opened. Therefor we must ensure that all groups are created up to // the point where we are asked for. this.modifyGroups(() => { for (let i = 0; i < position; i++) { if (!this.hasGroup(i)) { this.stacks.openGroup('', false, i); } } group = this.stacks.openGroup('', activate, position); }); } else { this.renameGroups(); // ensure group labels are proper } if (activate) { this.stacks.setActive(group); } return group; } private modifyGroups(modification: () => void) { // Run the modification modification(); // Adjust group labels as needed this.renameGroups(); } private renameGroups(): void { const groups = this.stacks.groups; if (groups.length > 0) { const layoutVertically = (this.editorGroupsControl.getGroupOrientation() !== 'horizontal'); // ONE | TWO | THREE if (groups.length > 2) { this.stacks.renameGroup(this.stacks.groupAt(Position.ONE), layoutVertically ? EditorPart.GROUP_LEFT : EditorPart.GROUP_TOP); this.stacks.renameGroup(this.stacks.groupAt(Position.TWO), layoutVertically ? EditorPart.GROUP_CENTER : EditorPart.GROUP_MIDDLE); this.stacks.renameGroup(this.stacks.groupAt(Position.THREE), layoutVertically ? EditorPart.GROUP_RIGHT : EditorPart.GROUP_BOTTOM); } // ONE | TWO else if (groups.length > 1) { this.stacks.renameGroup(this.stacks.groupAt(Position.ONE), layoutVertically ? EditorPart.GROUP_LEFT : EditorPart.GROUP_TOP); this.stacks.renameGroup(this.stacks.groupAt(Position.TWO), layoutVertically ? EditorPart.GROUP_RIGHT : EditorPart.GROUP_BOTTOM); } // ONE else { this.stacks.renameGroup(this.stacks.groupAt(Position.ONE), layoutVertically ? EditorPart.GROUP_LEFT : EditorPart.GROUP_TOP); } } } private hasGroup(position: Position): boolean { return !!this.stacks.groupAt(position); } }
src/vs/workbench/browser/parts/editor/editorPart.ts
1
https://github.com/microsoft/vscode/commit/522c6e01711a50ab2c48e2efb11f837dce7ebab9
[ 0.9984991550445557, 0.009648621082305908, 0.00016279648116324097, 0.00024168126401491463, 0.08260408788919449 ]
{ "id": 1, "code_window": [ "\t\telse {\n", "\t\t\tconst toPosition = (typeof arg3 === 'number') ? arg3 : this.stacks.positionOfGroup(arg3);\n", "\n", "\t\t\tthis.doMoveEditorAcrossGroups(input, fromGroup, toPosition, index);\n", "\t\t}\n", "\t}\n", "\n", "\tprivate doMoveEditorInsideGroups(input: EditorInput, group: EditorGroup, toIndex: number): void {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tthis.doMoveEditorAcrossGroups(input, fromGroup, toPosition, index, inactive);\n" ], "file_path": "src/vs/workbench/browser/parts/editor/editorPart.ts", "type": "replace", "edit_start_line_idx": 827 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "pleaseRestart": "開啟儲存機制的根目錄,以便存取 Git 功能。", "wrongRoot": "此目錄似乎包含在 Git 儲存機制中。" }
i18n/cht/src/vs/workbench/parts/git/browser/views/notroot/notrootView.i18n.json
0
https://github.com/microsoft/vscode/commit/522c6e01711a50ab2c48e2efb11f837dce7ebab9
[ 0.0001756961428327486, 0.0001756961428327486, 0.0001756961428327486, 0.0001756961428327486, 0 ]
{ "id": 1, "code_window": [ "\t\telse {\n", "\t\t\tconst toPosition = (typeof arg3 === 'number') ? arg3 : this.stacks.positionOfGroup(arg3);\n", "\n", "\t\t\tthis.doMoveEditorAcrossGroups(input, fromGroup, toPosition, index);\n", "\t\t}\n", "\t}\n", "\n", "\tprivate doMoveEditorInsideGroups(input: EditorInput, group: EditorGroup, toIndex: number): void {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tthis.doMoveEditorAcrossGroups(input, fromGroup, toPosition, index, inactive);\n" ], "file_path": "src/vs/workbench/browser/parts/editor/editorPart.ts", "type": "replace", "edit_start_line_idx": 827 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "diffLeftRightLabel": "{0} ⟷ {1}" }
i18n/jpn/src/vs/workbench/electron-browser/commands.i18n.json
0
https://github.com/microsoft/vscode/commit/522c6e01711a50ab2c48e2efb11f837dce7ebab9
[ 0.0001789407542673871, 0.0001789407542673871, 0.0001789407542673871, 0.0001789407542673871, 0 ]
{ "id": 1, "code_window": [ "\t\telse {\n", "\t\t\tconst toPosition = (typeof arg3 === 'number') ? arg3 : this.stacks.positionOfGroup(arg3);\n", "\n", "\t\t\tthis.doMoveEditorAcrossGroups(input, fromGroup, toPosition, index);\n", "\t\t}\n", "\t}\n", "\n", "\tprivate doMoveEditorInsideGroups(input: EditorInput, group: EditorGroup, toIndex: number): void {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tthis.doMoveEditorAcrossGroups(input, fromGroup, toPosition, index, inactive);\n" ], "file_path": "src/vs/workbench/browser/parts/editor/editorPart.ts", "type": "replace", "edit_start_line_idx": 827 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "fileAndTypeResults": "resultados de archivos y símbolos", "fileResults": "resultados de archivos" }
i18n/esn/src/vs/workbench/parts/search/browser/openAnythingHandler.i18n.json
0
https://github.com/microsoft/vscode/commit/522c6e01711a50ab2c48e2efb11f837dce7ebab9
[ 0.0001785036438377574, 0.0001785036438377574, 0.0001785036438377574, 0.0001785036438377574, 0 ]
{ "id": 2, "code_window": [ "\t\tgroup.moveEditor(input, toIndex);\n", "\t\tgroup.pin(input);\n", "\t}\n", "\n", "\tprivate doMoveEditorAcrossGroups(input: EditorInput, fromGroup: EditorGroup, to: Position, index?: number): void {\n", "\t\tif (fromGroup.count === 1) {\n", "\t\t\tconst toGroup = this.stacks.groupAt(to);\n", "\t\t\tif (!toGroup && this.stacks.positionOfGroup(fromGroup) < to) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\tprivate doMoveEditorAcrossGroups(input: EditorInput, fromGroup: EditorGroup, to: Position, index?: number, inactive?: boolean): void {\n" ], "file_path": "src/vs/workbench/browser/parts/editor/editorPart.ts", "type": "replace", "edit_start_line_idx": 846 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import 'vs/css!./media/editorpart'; import 'vs/workbench/browser/parts/editor/editor.contribution'; import { TPromise } from 'vs/base/common/winjs.base'; import { Registry } from 'vs/platform/platform'; import { Dimension, Builder, $ } from 'vs/base/browser/builder'; import nls = require('vs/nls'); import strings = require('vs/base/common/strings'); import arrays = require('vs/base/common/arrays'); import types = require('vs/base/common/types'); import errors = require('vs/base/common/errors'); import * as objects from 'vs/base/common/objects'; import { getCodeEditor } from 'vs/editor/common/services/codeEditorService'; import { toErrorMessage } from 'vs/base/common/errorMessage'; import { Scope as MementoScope } from 'vs/workbench/common/memento'; import { Part } from 'vs/workbench/browser/part'; import { BaseEditor, EditorDescriptor } from 'vs/workbench/browser/parts/editor/baseEditor'; import { IEditorRegistry, Extensions as EditorExtensions, EditorInput, EditorOptions, ConfirmResult, IWorkbenchEditorConfiguration, IEditorDescriptor, TextEditorOptions, SideBySideEditorInput, TextCompareEditorVisible, TEXT_DIFF_EDITOR_ID } from 'vs/workbench/common/editor'; import { EditorGroupsControl, Rochade, IEditorGroupsControl, ProgressState } from 'vs/workbench/browser/parts/editor/editorGroupsControl'; import { WorkbenchProgressService } from 'vs/workbench/services/progress/browser/progressService'; import { IEditorGroupService, GroupOrientation, GroupArrangement, ITabOptions } from 'vs/workbench/services/group/common/groupService'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IEditorPart } from 'vs/workbench/services/editor/browser/editorService'; import { IPartService } from 'vs/workbench/services/part/common/partService'; import { Position, POSITIONS, Direction } from 'vs/platform/editor/common/editor'; import { IStorageService } from 'vs/platform/storage/common/storage'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection'; import { IMessageService, IMessageWithAction, Severity } from 'vs/platform/message/common/message'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IProgressService } from 'vs/platform/progress/common/progress'; import { EditorStacksModel, EditorGroup, EditorIdentifier, GroupEvent } from 'vs/workbench/common/editor/editorStacksModel'; import Event, { Emitter } from 'vs/base/common/event'; import { IContextKey, IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; class ProgressMonitor { constructor(private _token: number, private progressPromise: TPromise<void>) { } public get token(): number { return this._token; } public cancel(): void { this.progressPromise.cancel(); } } interface IEditorPartUIState { ratio: number[]; groupOrientation: GroupOrientation; } interface IEditorReplacement extends EditorIdentifier { group: EditorGroup; editor: EditorInput; replaceWith: EditorInput; options?: EditorOptions; } /** * The editor part is the container for editors in the workbench. Based on the editor input being opened, it asks the registered * editor for the given input to show the contents. The editor part supports up to 3 side-by-side editors. */ export class EditorPart extends Part implements IEditorPart, IEditorGroupService { public _serviceBrand: any; private static GROUP_LEFT = nls.localize('groupOneVertical', "Left"); private static GROUP_CENTER = nls.localize('groupTwoVertical', "Center"); private static GROUP_RIGHT = nls.localize('groupThreeVertical', "Right"); private static GROUP_TOP = nls.localize('groupOneHorizontal', "Top"); private static GROUP_MIDDLE = nls.localize('groupTwoHorizontal', "Center"); private static GROUP_BOTTOM = nls.localize('groupThreeHorizontal', "Bottom"); private static EDITOR_PART_UI_STATE_STORAGE_KEY = 'editorpart.uiState'; private dimension: Dimension; private editorGroupsControl: IEditorGroupsControl; private memento: any; private stacks: EditorStacksModel; private tabOptions: ITabOptions; private forceHideTabs: boolean; private doNotFireTabOptionsChanged: boolean; private revealIfOpen: boolean; private _onEditorsChanged: Emitter<void>; private _onEditorsMoved: Emitter<void>; private _onEditorOpenFail: Emitter<EditorInput>; private _onGroupOrientationChanged: Emitter<void>; private _onTabOptionsChanged: Emitter<ITabOptions>; private textCompareEditorVisible: IContextKey<boolean>; // The following data structures are partitioned into array of Position as provided by Services.POSITION array private visibleEditors: BaseEditor[]; private instantiatedEditors: BaseEditor[][]; private mapEditorInstantiationPromiseToEditor: { [editorId: string]: TPromise<BaseEditor>; }[]; private editorOpenToken: number[]; private pendingEditorInputsToClose: EditorIdentifier[]; private pendingEditorInputCloseTimeout: number; private onLayoutEmitter = new Emitter<Dimension>(); public onLayout = this.onLayoutEmitter.event; constructor( id: string, restoreFromStorage: boolean, @IMessageService private messageService: IMessageService, @ITelemetryService private telemetryService: ITelemetryService, @IStorageService private storageService: IStorageService, @IPartService private partService: IPartService, @IConfigurationService private configurationService: IConfigurationService, @IContextKeyService contextKeyService: IContextKeyService, @IInstantiationService private instantiationService: IInstantiationService ) { super(id, { hasTitle: false }); this._onEditorsChanged = new Emitter<void>(); this._onEditorsMoved = new Emitter<void>(); this._onEditorOpenFail = new Emitter<EditorInput>(); this._onGroupOrientationChanged = new Emitter<void>(); this._onTabOptionsChanged = new Emitter<ITabOptions>(); this.visibleEditors = []; this.editorOpenToken = arrays.fill(POSITIONS.length, () => 0); this.instantiatedEditors = arrays.fill(POSITIONS.length, () => []); this.mapEditorInstantiationPromiseToEditor = arrays.fill(POSITIONS.length, () => Object.create(null)); this.pendingEditorInputsToClose = []; this.pendingEditorInputCloseTimeout = null; this.stacks = this.instantiationService.createInstance(EditorStacksModel, restoreFromStorage); this.textCompareEditorVisible = TextCompareEditorVisible.bindTo(contextKeyService); const config = configurationService.getConfiguration<IWorkbenchEditorConfiguration>(); if (config && config.workbench && config.workbench.editor) { const editorConfig = config.workbench.editor; this.tabOptions = { previewEditors: editorConfig.enablePreview, showIcons: editorConfig.showIcons, showTabs: editorConfig.showTabs, tabCloseButton: editorConfig.tabCloseButton }; this.revealIfOpen = editorConfig.revealIfOpen; this.telemetryService.publicLog('workbenchEditorConfiguration', editorConfig); } else { this.tabOptions = { previewEditors: true, showIcons: false, showTabs: true, tabCloseButton: 'right' }; this.revealIfOpen = false; } this.registerListeners(); } private registerListeners(): void { this.toUnbind.push(this.stacks.onEditorDirty(identifier => this.onEditorDirty(identifier))); this.toUnbind.push(this.stacks.onEditorDisposed(identifier => this.onEditorDisposed(identifier))); this.toUnbind.push(this.stacks.onEditorOpened(identifier => this.onEditorOpened(identifier))); this.toUnbind.push(this.stacks.onEditorClosed(event => this.onEditorClosed(event))); this.toUnbind.push(this.configurationService.onDidUpdateConfiguration(e => this.onConfigurationUpdated(e.config))); } private onConfigurationUpdated(configuration: IWorkbenchEditorConfiguration): void { if (configuration && configuration.workbench && configuration.workbench.editor) { const editorConfig = configuration.workbench.editor; // Pin all preview editors of the user chose to disable preview const newPreviewEditors = editorConfig.enablePreview; if (this.tabOptions.previewEditors !== newPreviewEditors && !newPreviewEditors) { this.stacks.groups.forEach(group => { if (group.previewEditor) { this.pinEditor(group, group.previewEditor); } }); } const oldTabOptions = objects.clone(this.tabOptions); this.tabOptions = { previewEditors: newPreviewEditors, showIcons: editorConfig.showIcons, tabCloseButton: editorConfig.tabCloseButton, showTabs: this.forceHideTabs ? false : editorConfig.showTabs }; if (!this.doNotFireTabOptionsChanged && !objects.equals(oldTabOptions, this.tabOptions)) { this._onTabOptionsChanged.fire(this.tabOptions); } this.revealIfOpen = editorConfig.revealIfOpen; } } private onEditorDirty(identifier: EditorIdentifier): void { // we pin every editor that becomes dirty this.pinEditor(identifier.group, identifier.editor); } private onEditorDisposed(identifier: EditorIdentifier): void { this.pendingEditorInputsToClose.push(identifier); this.startDelayedCloseEditorsFromInputDispose(); } private onEditorOpened(identifier: EditorIdentifier): void { this.telemetryService.publicLog('editorOpened', identifier.editor.getTelemetryDescriptor()); } private onEditorClosed(event: GroupEvent): void { this.telemetryService.publicLog('editorClosed', event.editor.getTelemetryDescriptor()); } public hideTabs(forceHide: boolean): void { this.forceHideTabs = forceHide; const config = this.configurationService.getConfiguration<IWorkbenchEditorConfiguration>(); this.tabOptions.showTabs = forceHide ? false : config && config.workbench && config.workbench.editor && config.workbench.editor.showTabs; this._onTabOptionsChanged.fire(this.tabOptions); } public get onEditorsChanged(): Event<void> { return this._onEditorsChanged.event; } public get onEditorsMoved(): Event<void> { return this._onEditorsMoved.event; } public get onEditorOpenFail(): Event<EditorInput> { return this._onEditorOpenFail.event; } public get onGroupOrientationChanged(): Event<void> { return this._onGroupOrientationChanged.event; } public get onTabOptionsChanged(): Event<ITabOptions> { return this._onTabOptionsChanged.event; } public getTabOptions(): ITabOptions { return this.tabOptions; } public openEditor(input: EditorInput, options?: EditorOptions, sideBySide?: boolean): TPromise<BaseEditor>; public openEditor(input: EditorInput, options?: EditorOptions, position?: Position, ratio?: number[]): TPromise<BaseEditor>; public openEditor(input: EditorInput, options?: EditorOptions, arg3?: any, ratio?: number[]): TPromise<BaseEditor> { // Normalize some values if (!options) { options = null; } // Determine position to open editor in (one, two, three) const position = this.findPosition(input, options, arg3, ratio); // Some conditions under which we prevent the request if ( !input || // no input position === null || // invalid position Object.keys(this.mapEditorInstantiationPromiseToEditor[position]).length > 0 || // pending editor load !this.editorGroupsControl || // too early this.editorGroupsControl.isDragging() // pending editor DND ) { return TPromise.as<BaseEditor>(null); } // We need an editor descriptor for the input const descriptor = Registry.as<IEditorRegistry>(EditorExtensions.Editors).getEditor(input); if (!descriptor) { return TPromise.wrapError(new Error(strings.format('Can not find a registered editor for the input {0}', input))); } // Opened to the side if (position !== Position.ONE) { this.telemetryService.publicLog('workbenchSideEditorOpened', { position: position }); } // Open through UI return this.doOpenEditor(position, descriptor, input, options, ratio); } private doOpenEditor(position: Position, descriptor: IEditorDescriptor, input: EditorInput, options: EditorOptions, ratio: number[]): TPromise<BaseEditor> { // Update stacks: We do this early on before the UI is there because we want our stacks model to have // a consistent view of the editor world and updating it later async after the UI is there will cause // issues (e.g. when a closeEditor call is made that expects the openEditor call to have updated the // stacks model). // This can however cause a race condition where the stacks model indicates the opened editor is there // while the UI is not yet ready. Clients have to deal with this fact and we have to make sure that the // stacks model gets updated if any of the UI updating fails with an error. const group = this.ensureGroup(position, !options || !options.preserveFocus); const pinned = !this.tabOptions.previewEditors || (options && (options.pinned || typeof options.index === 'number')) || input.isDirty(); const active = (group.count === 0) || !options || !options.inactive; group.openEditor(input, { active, pinned, index: options && options.index }); // Return early if the editor is to be open inactive and there are other editors in this group to show if (!active) { return TPromise.as<BaseEditor>(null); } // Progress Monitor & Ref Counting this.editorOpenToken[position]++; const editorOpenToken = this.editorOpenToken[position]; const monitor = new ProgressMonitor(editorOpenToken, TPromise.timeout(this.partService.isCreated() ? 800 : 3200 /* less ugly initial startup */).then(() => { const position = this.stacks.positionOfGroup(group); // might have changed due to a rochade meanwhile if (editorOpenToken === this.editorOpenToken[position]) { this.editorGroupsControl.updateProgress(position, ProgressState.INFINITE); } })); // Show editor return this.doShowEditor(group, descriptor, input, options, ratio, monitor).then(editor => { if (!editor) { return TPromise.as<BaseEditor>(null); // canceled or other error } // Set input to editor return this.doSetInput(group, editor, input, options, monitor); }); } private doShowEditor(group: EditorGroup, descriptor: IEditorDescriptor, input: EditorInput, options: EditorOptions, ratio: number[], monitor: ProgressMonitor): TPromise<BaseEditor> { const position = this.stacks.positionOfGroup(group); const editorAtPosition = this.visibleEditors[position]; // Return early if the currently visible editor can handle the input if (editorAtPosition && descriptor.describes(editorAtPosition)) { return TPromise.as(editorAtPosition); } // Hide active one first if (editorAtPosition) { this.doHideEditor(position, false); } // Create Editor return this.doCreateEditor(group, descriptor, monitor).then(editor => { const position = this.stacks.positionOfGroup(group); // might have changed due to a rochade meanwhile // Make sure that the user meanwhile did not open another editor or something went wrong if (!editor || !this.visibleEditors[position] || editor.getId() !== this.visibleEditors[position].getId()) { monitor.cancel(); return null; } // Show in side by side control this.editorGroupsControl.show(editor, position, options && options.preserveFocus, ratio); // Indicate to editor that it is now visible editor.setVisible(true, position); // Update text compare editor visible context this.updateTextCompareEditorVisible(); // Make sure the editor is layed out this.editorGroupsControl.layout(position); return editor; }, e => this.messageService.show(Severity.Error, types.isString(e) ? new Error(e) : e)); } private doCreateEditor(group: EditorGroup, descriptor: IEditorDescriptor, monitor: ProgressMonitor): TPromise<BaseEditor> { // Instantiate editor return this.doInstantiateEditor(group, descriptor).then(editor => { const position = this.stacks.positionOfGroup(group); // might have changed due to a rochade meanwhile // Make sure that the user meanwhile did not open another editor if (monitor.token !== this.editorOpenToken[position]) { monitor.cancel(); return null; } // Remember Editor at position this.visibleEditors[position] = editor; // Create editor as needed if (!editor.getContainer()) { editor.create($().div({ 'class': 'editor-container', 'role': 'tabpanel', id: descriptor.getId() })); } return editor; }); } private doInstantiateEditor(group: EditorGroup, descriptor: IEditorDescriptor): TPromise<BaseEditor> { const position = this.stacks.positionOfGroup(group); // Return early if already instantiated const instantiatedEditor = this.instantiatedEditors[position].filter(e => descriptor.describes(e))[0]; if (instantiatedEditor) { return TPromise.as(instantiatedEditor); } // Return early if editor is being instantiated at the same time from a previous call const pendingEditorInstantiate = this.mapEditorInstantiationPromiseToEditor[position][descriptor.getId()]; if (pendingEditorInstantiate) { return pendingEditorInstantiate; } // Otherwise instantiate const progressService = this.instantiationService.createInstance(WorkbenchProgressService, this.editorGroupsControl.getProgressBar(position), descriptor.getId(), true); const editorInstantiationService = this.editorGroupsControl.getInstantiationService(position).createChild(new ServiceCollection([IProgressService, progressService])); let loaded = false; const onInstantiate = (arg: BaseEditor | Error): TPromise<BaseEditor | Error> => { const position = this.stacks.positionOfGroup(group); // might have changed due to a rochade meanwhile loaded = true; delete this.mapEditorInstantiationPromiseToEditor[position][descriptor.getId()]; if (arg instanceof BaseEditor) { this.instantiatedEditors[position].push(arg); return TPromise.as(arg); } return TPromise.wrapError(arg); }; const instantiateEditorPromise = editorInstantiationService.createInstance(<EditorDescriptor>descriptor).then(onInstantiate, onInstantiate); if (!loaded) { this.mapEditorInstantiationPromiseToEditor[position][descriptor.getId()] = instantiateEditorPromise; } return instantiateEditorPromise.then(result => { progressService.dispose(); return result; }); } private doSetInput(group: EditorGroup, editor: BaseEditor, input: EditorInput, options: EditorOptions, monitor: ProgressMonitor): TPromise<BaseEditor> { // Emit Input-Changed Event as appropiate const previousInput = editor.input; const inputChanged = (!previousInput || !previousInput.matches(input) || (options && options.forceOpen)); // Call into Editor return editor.setInput(input, options).then(() => { // Stop loading promise if any monitor.cancel(); const position = this.stacks.positionOfGroup(group); // might have changed due to a rochade meanwhile if (position === -1) { return null; // in theory a call to editor.setInput() could have resulted in the editor being closed due to an error, so we guard against it here } // Focus (unless prevented) const focus = !options || !options.preserveFocus; if (focus) { editor.focus(); } // Progress Done this.editorGroupsControl.updateProgress(position, ProgressState.DONE); // Emit Change Event (if input changed) if (inputChanged) { this._onEditorsChanged.fire(); } // Fullfill promise with Editor that is being used return editor; }, e => this.doHandleSetInputError(e, group, editor, input, options, monitor)); } private doHandleSetInputError(e: Error | IMessageWithAction, group: EditorGroup, editor: BaseEditor, input: EditorInput, options: EditorOptions, monitor: ProgressMonitor): void { const position = this.stacks.positionOfGroup(group); // Stop loading promise if any monitor.cancel(); // Report error only if this was not us restoring previous error state if (this.partService.isCreated() && !errors.isPromiseCanceledError(e)) { const errorMessage = nls.localize('editorOpenError', "Unable to open '{0}': {1}.", input.getName(), toErrorMessage(e)); let error: any; if (e && (<IMessageWithAction>e).actions && (<IMessageWithAction>e).actions.length) { error = errors.create(errorMessage, { actions: (<IMessageWithAction>e).actions }); // Support error actions from thrower } else { error = errorMessage; } this.messageService.show(Severity.Error, types.isString(error) ? new Error(error) : error); } this.editorGroupsControl.updateProgress(position, ProgressState.DONE); // Event this._onEditorOpenFail.fire(input); // Recover by closing the active editor (if the input is still the active one) if (group.activeEditor === input) { this.doCloseActiveEditor(group); } } public closeEditor(position: Position, input: EditorInput): TPromise<void> { const group = this.stacks.groupAt(position); if (!group) { return TPromise.as<void>(null); } // Check for dirty and veto return this.handleDirty([{ group, editor: input }], true /* ignore if opened in other group */).then(veto => { if (veto) { return; } // Do close this.doCloseEditor(group, input); }); } private doCloseEditor(group: EditorGroup, input: EditorInput, focusNext = this.stacks.isActive(group)): void { // Closing the active editor of the group is a bit more work if (group.activeEditor && group.activeEditor.matches(input)) { this.doCloseActiveEditor(group, focusNext); } // Closing inactive editor is just a model update else { this.doCloseInactiveEditor(group, input); } } private doCloseActiveEditor(group: EditorGroup, focusNext = true): void { const position = this.stacks.positionOfGroup(group); // Update stacks model group.closeEditor(group.activeEditor); // Close group is this is the last editor in group if (group.count === 0) { this.doCloseGroup(group, focusNext); } // Otherwise open next active else { this.openEditor(group.activeEditor, !focusNext ? EditorOptions.create({ preserveFocus: true }) : null, position).done(null, errors.onUnexpectedError); } } private doCloseInactiveEditor(group: EditorGroup, input: EditorInput): void { // Closing inactive editor is just a model update group.closeEditor(input); } private doCloseGroup(group: EditorGroup, focusNext = true): void { const position = this.stacks.positionOfGroup(group); // Update stacks model this.modifyGroups(() => this.stacks.closeGroup(group)); // Hide Editor this.doHideEditor(position, true); // Emit Change Event this._onEditorsChanged.fire(); // Focus next group if we have an active one left const currentActiveGroup = this.stacks.activeGroup; if (currentActiveGroup) { if (focusNext) { this.focusGroup(currentActiveGroup); } else { this.activateGroup(currentActiveGroup); } // Explicitly trigger the focus changed handler because the side by side control will not trigger it unless // the user is actively changing focus with the mouse from left/top to right/bottom. this.onGroupFocusChanged(); } } private doHideEditor(position: Position, layoutAndRochade: boolean): void { const editor = this.visibleEditors[position]; // Hide in side by side control const rochade = this.editorGroupsControl.hide(editor, position, layoutAndRochade); // Clear any running Progress this.editorGroupsControl.updateProgress(position, ProgressState.STOP); // Indicate to Editor editor.clearInput(); editor.setVisible(false); // Update text compare editor visible context this.updateTextCompareEditorVisible(); // Clear active editor this.visibleEditors[position] = null; // Rochade as needed this.rochade(rochade); // Emit Editor move event if (rochade !== Rochade.NONE) { this._onEditorsMoved.fire(); } } private updateTextCompareEditorVisible(): void { this.textCompareEditorVisible.set(this.visibleEditors.some(e => e && e.isVisible() && e.getId() === TEXT_DIFF_EDITOR_ID)); } public closeAllEditors(except?: Position): TPromise<void> { let groups = this.stacks.groups.reverse(); // start from the end to prevent layout to happen through rochade // Remove position to exclude if we have any if (typeof except === 'number') { groups = groups.filter(group => this.stacks.positionOfGroup(group) !== except); } // Check for dirty and veto const editorsToClose = arrays.flatten(groups.map(group => group.getEditors().map(editor => { return { group, editor }; }))); return this.handleDirty(editorsToClose).then(veto => { if (veto) { return; } groups.forEach(group => this.doCloseEditors(group)); }); } public closeEditors(position: Position, except?: EditorInput, direction?: Direction): TPromise<void> { const group = this.stacks.groupAt(position); if (!group) { return TPromise.as<void>(null); } // Check for dirty and veto let editorsToClose: EditorInput[]; if (types.isUndefinedOrNull(direction)) { editorsToClose = group.getEditors().filter(e => !except || !e.matches(except)); } else { editorsToClose = (direction === Direction.LEFT) ? group.getEditors().slice(0, group.indexOf(except)) : group.getEditors().slice(group.indexOf(except) + 1); } return this.handleDirty(editorsToClose.map(editor => { return { group, editor }; }), true /* ignore if opened in other group */).then(veto => { if (veto) { return; } this.doCloseEditors(group, except, direction); }); } private doCloseEditors(group: EditorGroup, except?: EditorInput, direction?: Direction): void { // Close all editors in group if (!except) { // Update stacks model: remove all non active editors first to prevent opening the next editor in group group.closeEditors(group.activeEditor); // Now close active editor in group which will close the group this.doCloseActiveEditor(group); } // Close all editors in group except active one else if (except.matches(group.activeEditor)) { // Update stacks model: close non active editors supporting the direction group.closeEditors(group.activeEditor, direction); } // Finally: we are asked to close editors around a non-active editor // Thus we make the non-active one active and then close the others else { this.openEditor(except, null, this.stacks.positionOfGroup(group)).done(() => { // since the opening might have failed, we have to check again for the active editor // being the expected one, otherwise we end up in an endless loop trying to open the // editor if (except.matches(group.activeEditor)) { this.doCloseEditors(group, except, direction); } }, errors.onUnexpectedError); } } private handleDirty(identifiers: EditorIdentifier[], ignoreIfOpenedInOtherGroup?: boolean): TPromise<boolean /* veto */> { if (!identifiers.length) { return TPromise.as(false); // no veto } return this.doHandleDirty(identifiers.shift(), ignoreIfOpenedInOtherGroup).then(veto => { if (veto) { return veto; } return this.handleDirty(identifiers, ignoreIfOpenedInOtherGroup); }); } private doHandleDirty(identifier: EditorIdentifier, ignoreIfOpenedInOtherGroup?: boolean): TPromise<boolean /* veto */> { if (!identifier || !identifier.editor || !identifier.editor.isDirty() || (ignoreIfOpenedInOtherGroup && this.countEditors(identifier.editor) > 1 /* allow to close a dirty editor if it is opened in another group */)) { return TPromise.as(false); // no veto } const { editor } = identifier; const res = editor.confirmSave(); switch (res) { case ConfirmResult.SAVE: return editor.save().then(ok => !ok); case ConfirmResult.DONT_SAVE: return editor.revert().then(ok => !ok); case ConfirmResult.CANCEL: return TPromise.as(true); // veto } } private countEditors(editor: EditorInput): number { const editors = [editor]; if (editor instanceof SideBySideEditorInput) { editors.push(editor.master); } return editors.reduce((prev, e) => prev += this.stacks.count(e), 0); } public getStacksModel(): EditorStacksModel { return this.stacks; } public getActiveEditorInput(): EditorInput { const lastActiveEditor = this.getActiveEditor(); return lastActiveEditor ? lastActiveEditor.input : null; } public getActiveEditor(): BaseEditor { if (!this.editorGroupsControl) { return null; // too early } return this.editorGroupsControl.getActiveEditor(); } public getVisibleEditors(): BaseEditor[] { return this.visibleEditors ? this.visibleEditors.filter(editor => !!editor) : []; } public moveGroup(from: EditorGroup, to: EditorGroup): void; public moveGroup(from: Position, to: Position): void; public moveGroup(arg1: any, arg2: any): void { const fromGroup = (typeof arg1 === 'number') ? this.stacks.groupAt(arg1) : arg1; const toGroup = (typeof arg2 === 'number') ? this.stacks.groupAt(arg2) : arg2; if (!fromGroup || !toGroup || fromGroup === toGroup) { return; // Ignore if we cannot move } const fromPosition = this.stacks.positionOfGroup(fromGroup); const toPosition = this.stacks.positionOfGroup(toGroup); // Update stacks model this.modifyGroups(() => this.stacks.moveGroup(fromGroup, toPosition)); // Move widgets this.editorGroupsControl.move(fromPosition, toPosition); // Move data structures arrays.move(this.visibleEditors, fromPosition, toPosition); arrays.move(this.editorOpenToken, fromPosition, toPosition); arrays.move(this.mapEditorInstantiationPromiseToEditor, fromPosition, toPosition); arrays.move(this.instantiatedEditors, fromPosition, toPosition); // Restore focus this.focusGroup(fromGroup); // Events this._onEditorsMoved.fire(); } public moveEditor(input: EditorInput, from: EditorGroup, to: EditorGroup, index?: number): void; public moveEditor(input: EditorInput, from: Position, to: Position, index?: number): void; public moveEditor(input: EditorInput, arg2: any, arg3: any, index?: number): void { const fromGroup = (typeof arg2 === 'number') ? this.stacks.groupAt(arg2) : arg2; if (!fromGroup) { return; } // Move within group if (arg2 === arg3) { this.doMoveEditorInsideGroups(input, fromGroup, index); } // Move across groups else { const toPosition = (typeof arg3 === 'number') ? arg3 : this.stacks.positionOfGroup(arg3); this.doMoveEditorAcrossGroups(input, fromGroup, toPosition, index); } } private doMoveEditorInsideGroups(input: EditorInput, group: EditorGroup, toIndex: number): void { if (typeof toIndex !== 'number') { return; // do nothing if we move into same group without index } const currentIndex = group.indexOf(input); if (currentIndex === toIndex) { return; // do nothing if editor is already at the given index } // Update stacks model group.moveEditor(input, toIndex); group.pin(input); } private doMoveEditorAcrossGroups(input: EditorInput, fromGroup: EditorGroup, to: Position, index?: number): void { if (fromGroup.count === 1) { const toGroup = this.stacks.groupAt(to); if (!toGroup && this.stacks.positionOfGroup(fromGroup) < to) { return; // do nothing if the group to move only has one editor and is the last group already } } // When moving an editor, try to preserve as much view state as possible by checking // for th editor to be a text editor and creating the options accordingly if so let options = EditorOptions.create({ pinned: true, index }); const activeEditor = this.getActiveEditor(); const codeEditor = getCodeEditor(activeEditor); if (codeEditor && activeEditor.position === this.stacks.positionOfGroup(fromGroup) && input.matches(activeEditor.input)) { options = TextEditorOptions.create({ pinned: true, index }); (<TextEditorOptions>options).fromEditor(codeEditor); } // A move to another group is an open first... this.openEditor(input, options, to).done(null, errors.onUnexpectedError); // and a close afterwards... this.doCloseEditor(fromGroup, input, false /* do not activate next one behind if any */); } public arrangeGroups(arrangement: GroupArrangement): void { this.editorGroupsControl.arrangeGroups(arrangement); } public setGroupOrientation(orientation: GroupOrientation): void { this.editorGroupsControl.setGroupOrientation(orientation); this._onGroupOrientationChanged.fire(); // Rename groups when layout changes this.renameGroups(); } public getGroupOrientation(): GroupOrientation { return this.editorGroupsControl.getGroupOrientation(); } public createContentArea(parent: Builder): Builder { // Content Container const contentArea = $(parent) .div() .addClass('content'); // get settings this.memento = this.getMemento(this.storageService, MementoScope.WORKSPACE); // Side by Side Control const editorPartState: IEditorPartUIState = this.memento[EditorPart.EDITOR_PART_UI_STATE_STORAGE_KEY]; this.editorGroupsControl = this.instantiationService.createInstance(EditorGroupsControl, contentArea, editorPartState && editorPartState.groupOrientation); this.toUnbind.push(this.editorGroupsControl.onGroupFocusChanged(() => this.onGroupFocusChanged())); return contentArea; } private onGroupFocusChanged(): void { // Update stacks model const activePosition = this.editorGroupsControl.getActivePosition(); if (typeof activePosition === 'number') { this.stacks.setActive(this.stacks.groupAt(activePosition)); } // Emit as change event so that clients get aware of new active editor const activeEditor = this.editorGroupsControl.getActiveEditor(); if (activeEditor) { this._onEditorsChanged.fire(); } } public replaceEditors(editors: { toReplace: EditorInput, replaceWith: EditorInput, options?: EditorOptions }[], position?: Position): TPromise<BaseEditor[]> { const activeReplacements: IEditorReplacement[] = []; const hiddenReplacements: IEditorReplacement[] = []; // Find editors across groups to close editors.forEach(editor => { if (editor.toReplace.isDirty()) { return; // we do not handle dirty in this method, so ignore all dirty } // For each group this.stacks.groups.forEach(group => { if (position === void 0 || this.stacks.positionOfGroup(group) === position) { const index = group.indexOf(editor.toReplace); if (index >= 0) { if (editor.options) { editor.options.index = index; // make sure we respect the index of the editor to replace! } else { editor.options = EditorOptions.create({ index }); } const replacement = { group, editor: editor.toReplace, replaceWith: editor.replaceWith, options: editor.options }; if (group.activeEditor.matches(editor.toReplace)) { activeReplacements.push(replacement); } else { hiddenReplacements.push(replacement); } } } }); }); // Deal with hidden replacements first hiddenReplacements.forEach(replacement => { const group = replacement.group; group.openEditor(replacement.replaceWith, { active: false, pinned: true, index: replacement.options.index }); group.closeEditor(replacement.editor); }); // Now deal with active editors to be opened const res = this.openEditors(activeReplacements.map(replacement => { const group = replacement.group; return { input: replacement.replaceWith, position: this.stacks.positionOfGroup(group), options: replacement.options }; })); // Close active editors to be replaced now (they are no longer active) activeReplacements.forEach(replacement => { this.doCloseEditor(replacement.group, replacement.editor, false); }); return res; } public openEditors(editors: { input: EditorInput, position: Position, options?: EditorOptions }[]): TPromise<BaseEditor[]> { if (!editors.length) { return TPromise.as<BaseEditor[]>([]); } let activePosition: Position; if (this.stacks.activeGroup) { activePosition = this.stacks.positionOfGroup(this.stacks.activeGroup); } const ratio = this.editorGroupsControl.getRatio(); return this.doOpenEditors(editors, activePosition, ratio); } public restoreEditors(): TPromise<BaseEditor[]> { const editors = this.stacks.groups.map((group, index) => { return { input: group.activeEditor, position: index, options: group.isPinned(group.activeEditor) ? EditorOptions.create({ pinned: true }) : void 0 }; }); if (!editors.length) { return TPromise.as<BaseEditor[]>([]); } let activePosition: Position; if (this.stacks.groups.length) { activePosition = this.stacks.positionOfGroup(this.stacks.activeGroup); } const editorState: IEditorPartUIState = this.memento[EditorPart.EDITOR_PART_UI_STATE_STORAGE_KEY]; return this.doOpenEditors(editors, activePosition, editorState && editorState.ratio); } private doOpenEditors(editors: { input: EditorInput, position: Position, options?: EditorOptions }[], activePosition?: number, ratio?: number[]): TPromise<BaseEditor[]> { const positionOneEditors = editors.filter(e => e.position === Position.ONE); const positionTwoEditors = editors.filter(e => e.position === Position.TWO); const positionThreeEditors = editors.filter(e => e.position === Position.THREE); const groupOne = this.stacks.groupAt(Position.ONE); const groupTwo = this.stacks.groupAt(Position.TWO); const groupThree = this.stacks.groupAt(Position.THREE); // Compute the imaginary count if we const all editors open as the way requested const oneCount = positionOneEditors.length + (groupOne ? groupOne.count : 0); const twoCount = positionTwoEditors.length + (groupTwo ? groupTwo.count : 0); const threeCount = positionThreeEditors.length + (groupThree ? groupThree.count : 0); // Validate we do not produce empty groups given our imaginary count model if ((!oneCount && (twoCount || threeCount) || (!twoCount && threeCount))) { positionOneEditors.push(...positionTwoEditors); positionOneEditors.push(...positionThreeEditors); positionTwoEditors.splice(0, positionTwoEditors.length); positionThreeEditors.splice(0, positionThreeEditors.length); } // Validate active input if (typeof activePosition !== 'number') { activePosition = Position.ONE; } // Validate ratios const positions = positionThreeEditors.length ? 3 : positionTwoEditors.length ? 2 : 1; if (!ratio || ratio.length !== positions) { if (!this.getVisibleEditors().length) { ratio = (positions === 3) ? [0.33, 0.33, 0.34] : (positions === 2) ? [0.5, 0.5] : [1]; } else { ratio = void 0; } } let focusGroup = false; const activeGroup = this.stacks.groupAt(activePosition); if (!this.stacks.activeGroup || !activeGroup) { focusGroup = true; // always focus group if this is the first group or we are about to open a new group } else { focusGroup = editors.some(e => !e.options || (!e.options.inactive && !e.options.preserveFocus)); // only focus if the editors to open are not opening as inactive or preserveFocus } // Open each input respecting the options. Since there can only be one active editor in each // position, we have to pick the first input from each position and add the others as inactive const promises: TPromise<BaseEditor>[] = []; [positionOneEditors.shift(), positionTwoEditors.shift(), positionThreeEditors.shift()].forEach((editor, position) => { if (!editor) { return; // unused position } const input = editor.input; // Resolve editor options const preserveFocus = (activePosition !== position); let options: EditorOptions; if (editor.options) { options = editor.options; if (typeof options.preserveFocus !== 'boolean') { options.preserveFocus = preserveFocus; } } else { options = EditorOptions.create({ preserveFocus }); } promises.push(this.openEditor(input, options, position, ratio)); }); return TPromise.join(promises).then(editors => { // Adjust focus as needed if (focusGroup) { this.focusGroup(activePosition); } // Update stacks model for remaining inactive editors [positionOneEditors, positionTwoEditors, positionThreeEditors].forEach((editors, index) => { const group = this.stacks.groupAt(index); if (group) { editors.forEach(editor => group.openEditor(editor.input, { pinned: true })); // group could be null if one openeditor call failed! } }); // Full layout side by side this.editorGroupsControl.layout(this.dimension); return editors; }); } public activateGroup(group: EditorGroup): void; public activateGroup(position: Position): void; public activateGroup(arg1: any): void { const group = (typeof arg1 === 'number') ? this.stacks.groupAt(arg1) : arg1; if (group) { // Update stacks model this.stacks.setActive(group); // Update UI const editor = this.visibleEditors[this.stacks.positionOfGroup(group)]; if (editor) { this.editorGroupsControl.setActive(editor); } } } public focusGroup(group: EditorGroup): void; public focusGroup(position: Position): void; public focusGroup(arg1: any): void { const group = (typeof arg1 === 'number') ? this.stacks.groupAt(arg1) : arg1; if (group) { // Make active this.activateGroup(group); // Focus Editor const editor = this.visibleEditors[this.stacks.positionOfGroup(group)]; if (editor) { editor.focus(); } } } public pinEditor(group: EditorGroup, input: EditorInput): void; public pinEditor(position: Position, input: EditorInput): void; public pinEditor(arg1: any, input: EditorInput): void { const group = (typeof arg1 === 'number') ? this.stacks.groupAt(arg1) : arg1; if (group) { if (group.isPinned(input)) { return; } // Update stacks model group.pin(input); } } public unpinEditor(group: EditorGroup, input: EditorInput): void; public unpinEditor(position: Position, input: EditorInput): void; public unpinEditor(arg1: any, input: EditorInput): void { if (input.isDirty()) { return; // we do not allow to unpin dirty editors } const group = (typeof arg1 === 'number') ? this.stacks.groupAt(arg1) : arg1; if (group) { if (group.isPreview(input)) { return; } // Unpinning an editor closes the preview editor if we have any let handlePreviewEditor: TPromise<boolean> = TPromise.as(false); if (group.previewEditor) { handlePreviewEditor = this.handleDirty([{ group, editor: group.previewEditor }], true /* ignore if opened in other group */); } handlePreviewEditor.done(veto => { if (veto) { return; } // The active editor is the preview editor and we are asked to make // another editor the preview editor. So we need to take care of closing // the active editor first if (group.isPreview(group.activeEditor) && !group.activeEditor.matches(input)) { this.doCloseActiveEditor(group); } // Update stacks model group.unpin(input); }); } } public layout(dimension: Dimension): Dimension[] { // Pass to super const sizes = super.layout(dimension); // Pass to Side by Side Control this.dimension = sizes[1]; this.editorGroupsControl.layout(this.dimension); this.onLayoutEmitter.fire(dimension); return sizes; } public shutdown(): void { // Persist UI State const editorState: IEditorPartUIState = { ratio: this.editorGroupsControl.getRatio(), groupOrientation: this.editorGroupsControl.getGroupOrientation() }; this.memento[EditorPart.EDITOR_PART_UI_STATE_STORAGE_KEY] = editorState; // Unload all Instantiated Editors for (let i = 0; i < this.instantiatedEditors.length; i++) { for (let j = 0; j < this.instantiatedEditors[i].length; j++) { this.instantiatedEditors[i][j].shutdown(); } } // Pass to super super.shutdown(); } public dispose(): void { // Emitters this._onEditorsChanged.dispose(); this._onEditorsMoved.dispose(); this._onEditorOpenFail.dispose(); // Reset Tokens this.editorOpenToken = []; for (let i = 0; i < POSITIONS.length; i++) { this.editorOpenToken[i] = 0; } // Widgets this.editorGroupsControl.dispose(); // Pass to active editors this.visibleEditors.forEach(editor => { if (editor) { editor.dispose(); } }); // Pass to instantiated editors for (let i = 0; i < this.instantiatedEditors.length; i++) { for (let j = 0; j < this.instantiatedEditors[i].length; j++) { if (this.visibleEditors.some(editor => editor === this.instantiatedEditors[i][j])) { continue; } this.instantiatedEditors[i][j].dispose(); } } this.visibleEditors = null; // Pass to super super.dispose(); } private findPosition(input: EditorInput, options?: EditorOptions, sideBySide?: boolean, ratio?: number[]): Position; private findPosition(input: EditorInput, options?: EditorOptions, desiredPosition?: Position, ratio?: number[]): Position; private findPosition(input: EditorInput, options?: EditorOptions, arg1?: any, ratio?: number[]): Position { // With defined ratios, always trust the provided position if (ratio && types.isNumber(arg1)) { return arg1; } // No editor open const visibleEditors = this.getVisibleEditors(); const activeEditor = this.getActiveEditor(); if (visibleEditors.length === 0 || !activeEditor) { return Position.ONE; // can only be ONE } // Respect option to reveal an editor if it is already visible if (options && options.revealIfVisible) { const group = this.stacks.findGroup(input, true); if (group) { return this.stacks.positionOfGroup(group); } } // Respect option to reveal an editor if it is open (not necessarily visible) const skipRevealIfOpen = (options && options.index) || arg1; if (!skipRevealIfOpen && this.revealIfOpen) { const group = this.stacks.findGroup(input); if (group) { return this.stacks.positionOfGroup(group); } } // Position is unknown: pick last active or ONE if (types.isUndefinedOrNull(arg1) || arg1 === false) { const lastActivePosition = this.editorGroupsControl.getActivePosition(); return lastActivePosition || Position.ONE; } // Position is sideBySide: Find position relative to active editor if (arg1 === true) { switch (activeEditor.position) { case Position.ONE: return Position.TWO; case Position.TWO: return Position.THREE; case Position.THREE: return null; // Cannot open to the side of the right/bottom most editor } return null; // Prevent opening to the side } // Position is provided, validate it if (arg1 === Position.THREE && visibleEditors.length === 1) { return Position.TWO; } return arg1; } private startDelayedCloseEditorsFromInputDispose(): void { // To prevent race conditions, we call the close in a timeout because it can well be // that an input is being disposed with the intent to replace it with some other input // right after. if (this.pendingEditorInputCloseTimeout === null) { this.pendingEditorInputCloseTimeout = setTimeout(() => { // Split between visible and hidden editors const visibleEditors: EditorIdentifier[] = []; const hiddenEditors: EditorIdentifier[] = []; this.pendingEditorInputsToClose.forEach(identifier => { const { group, editor } = identifier; if (group.isActive(editor)) { visibleEditors.push(identifier); } else if (group.contains(editor)) { hiddenEditors.push(identifier); } }); // Close all hidden first hiddenEditors.forEach(hidden => this.doCloseEditor(<EditorGroup>hidden.group, hidden.editor, false)); // Close visible ones second visibleEditors .sort((a1, a2) => this.stacks.positionOfGroup(a2.group) - this.stacks.positionOfGroup(a1.group)) // reduce layout work by starting right/bottom first .forEach(visible => this.doCloseEditor(<EditorGroup>visible.group, visible.editor, false)); // Reset this.pendingEditorInputCloseTimeout = null; this.pendingEditorInputsToClose = []; }, 0); } } private rochade(rochade: Rochade): void; private rochade(from: Position, to: Position): void; private rochade(arg1: any, arg2?: any): void { if (types.isUndefinedOrNull(arg2)) { const rochade = <Rochade>arg1; switch (rochade) { case Rochade.TWO_TO_ONE: this.rochade(Position.TWO, Position.ONE); break; case Rochade.THREE_TO_TWO: this.rochade(Position.THREE, Position.TWO); break; case Rochade.TWO_AND_THREE_TO_ONE: this.rochade(Position.TWO, Position.ONE); this.rochade(Position.THREE, Position.TWO); } } else { const from = <Position>arg1; const to = <Position>arg2; this.doRochade(this.visibleEditors, from, to, null); this.doRochade(this.editorOpenToken, from, to, null); this.doRochade(this.mapEditorInstantiationPromiseToEditor, from, to, Object.create(null)); this.doRochade(this.instantiatedEditors, from, to, []); } } private doRochade(array: any[], from: Position, to: Position, empty: any): void { array[to] = array[from]; array[from] = empty; } private ensureGroup(position: Position, activate = true): EditorGroup { let group = this.stacks.groupAt(position); if (!group) { // Race condition: it could be that someone quickly opens editors one after // the other and we are asked to open an editor in position 2 before position // 1 was opened. Therefor we must ensure that all groups are created up to // the point where we are asked for. this.modifyGroups(() => { for (let i = 0; i < position; i++) { if (!this.hasGroup(i)) { this.stacks.openGroup('', false, i); } } group = this.stacks.openGroup('', activate, position); }); } else { this.renameGroups(); // ensure group labels are proper } if (activate) { this.stacks.setActive(group); } return group; } private modifyGroups(modification: () => void) { // Run the modification modification(); // Adjust group labels as needed this.renameGroups(); } private renameGroups(): void { const groups = this.stacks.groups; if (groups.length > 0) { const layoutVertically = (this.editorGroupsControl.getGroupOrientation() !== 'horizontal'); // ONE | TWO | THREE if (groups.length > 2) { this.stacks.renameGroup(this.stacks.groupAt(Position.ONE), layoutVertically ? EditorPart.GROUP_LEFT : EditorPart.GROUP_TOP); this.stacks.renameGroup(this.stacks.groupAt(Position.TWO), layoutVertically ? EditorPart.GROUP_CENTER : EditorPart.GROUP_MIDDLE); this.stacks.renameGroup(this.stacks.groupAt(Position.THREE), layoutVertically ? EditorPart.GROUP_RIGHT : EditorPart.GROUP_BOTTOM); } // ONE | TWO else if (groups.length > 1) { this.stacks.renameGroup(this.stacks.groupAt(Position.ONE), layoutVertically ? EditorPart.GROUP_LEFT : EditorPart.GROUP_TOP); this.stacks.renameGroup(this.stacks.groupAt(Position.TWO), layoutVertically ? EditorPart.GROUP_RIGHT : EditorPart.GROUP_BOTTOM); } // ONE else { this.stacks.renameGroup(this.stacks.groupAt(Position.ONE), layoutVertically ? EditorPart.GROUP_LEFT : EditorPart.GROUP_TOP); } } } private hasGroup(position: Position): boolean { return !!this.stacks.groupAt(position); } }
src/vs/workbench/browser/parts/editor/editorPart.ts
1
https://github.com/microsoft/vscode/commit/522c6e01711a50ab2c48e2efb11f837dce7ebab9
[ 0.9989317059516907, 0.03646375238895416, 0.00016323574527632445, 0.0004892269498668611, 0.18031689524650574 ]
{ "id": 2, "code_window": [ "\t\tgroup.moveEditor(input, toIndex);\n", "\t\tgroup.pin(input);\n", "\t}\n", "\n", "\tprivate doMoveEditorAcrossGroups(input: EditorInput, fromGroup: EditorGroup, to: Position, index?: number): void {\n", "\t\tif (fromGroup.count === 1) {\n", "\t\t\tconst toGroup = this.stacks.groupAt(to);\n", "\t\t\tif (!toGroup && this.stacks.positionOfGroup(fromGroup) < to) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\tprivate doMoveEditorAcrossGroups(input: EditorInput, fromGroup: EditorGroup, to: Position, index?: number, inactive?: boolean): void {\n" ], "file_path": "src/vs/workbench/browser/parts/editor/editorPart.ts", "type": "replace", "edit_start_line_idx": 846 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "files.backup.failSave": "No se pudo hacer una copia de seguridad de los archivos (Error: {0}). Intente guardar los archivos para salir." }
i18n/esn/src/vs/workbench/services/textfile/common/textFileService.i18n.json
0
https://github.com/microsoft/vscode/commit/522c6e01711a50ab2c48e2efb11f837dce7ebab9
[ 0.00017615410615690053, 0.00017615410615690053, 0.00017615410615690053, 0.00017615410615690053, 0 ]
{ "id": 2, "code_window": [ "\t\tgroup.moveEditor(input, toIndex);\n", "\t\tgroup.pin(input);\n", "\t}\n", "\n", "\tprivate doMoveEditorAcrossGroups(input: EditorInput, fromGroup: EditorGroup, to: Position, index?: number): void {\n", "\t\tif (fromGroup.count === 1) {\n", "\t\t\tconst toGroup = this.stacks.groupAt(to);\n", "\t\t\tif (!toGroup && this.stacks.positionOfGroup(fromGroup) < to) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\tprivate doMoveEditorAcrossGroups(input: EditorInput, fromGroup: EditorGroup, to: Position, index?: number, inactive?: boolean): void {\n" ], "file_path": "src/vs/workbench/browser/parts/editor/editorPart.ts", "type": "replace", "edit_start_line_idx": 846 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "smartSelect.jumpBracket": "Atteindre le crochet" }
i18n/fra/src/vs/editor/contrib/bracketMatching/common/bracketMatching.i18n.json
0
https://github.com/microsoft/vscode/commit/522c6e01711a50ab2c48e2efb11f837dce7ebab9
[ 0.00017890596063807607, 0.00017890596063807607, 0.00017890596063807607, 0.00017890596063807607, 0 ]
{ "id": 2, "code_window": [ "\t\tgroup.moveEditor(input, toIndex);\n", "\t\tgroup.pin(input);\n", "\t}\n", "\n", "\tprivate doMoveEditorAcrossGroups(input: EditorInput, fromGroup: EditorGroup, to: Position, index?: number): void {\n", "\t\tif (fromGroup.count === 1) {\n", "\t\t\tconst toGroup = this.stacks.groupAt(to);\n", "\t\t\tif (!toGroup && this.stacks.positionOfGroup(fromGroup) < to) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\tprivate doMoveEditorAcrossGroups(input: EditorInput, fromGroup: EditorGroup, to: Position, index?: number, inactive?: boolean): void {\n" ], "file_path": "src/vs/workbench/browser/parts/editor/editorPart.ts", "type": "replace", "edit_start_line_idx": 846 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; function* filter<T>(it: IterableIterator<T>, condition: (t: T, i: number) => boolean): IterableIterator<T> { let i = 0; for (let t of it) { if (condition(t, i++)) { yield t; } } } function* map<T, R>(it: IterableIterator<T>, fn: (t: T, i: number) => R): IterableIterator<R> { let i = 0; for (let t of it) { yield fn(t, i++); } } export interface FunctionalIterator<T> extends Iterable<T> { filter(condition: (t: T, i: number) => boolean): FunctionalIterator<T>; map<R>(fn: (t: T, i: number) => R): FunctionalIterator<R>; toArray(): T[]; } class FunctionalIteratorImpl<T> implements FunctionalIterator<T> { constructor(private iterator: IterableIterator<T>) { } filter(condition: (t: T, i: number) => boolean): FunctionalIterator<T> { return new FunctionalIteratorImpl(filter(this.iterator, condition)); } map<R>(fn: (t: T, i: number) => R): FunctionalIterator<R> { return new FunctionalIteratorImpl(map<T, R>(this.iterator, fn)); } toArray(): T[] { return Array.from(this.iterator); } [Symbol.iterator](): IterableIterator<T> { return this.iterator; } } export function iterate<T>(obj: T[] | IterableIterator<T>): FunctionalIterator<T> { if (Array.isArray(obj)) { return new FunctionalIteratorImpl(obj[Symbol.iterator]()); } return new FunctionalIteratorImpl(obj); }
extensions/git/src/iterators.ts
0
https://github.com/microsoft/vscode/commit/522c6e01711a50ab2c48e2efb11f837dce7ebab9
[ 0.00017736472364049405, 0.00017245027993340045, 0.00016552425222471356, 0.00017239214503206313, 0.0000036280287076806417 ]
{ "id": 3, "code_window": [ "\t\t}\n", "\n", "\t\t// When moving an editor, try to preserve as much view state as possible by checking\n", "\t\t// for th editor to be a text editor and creating the options accordingly if so\n", "\t\tlet options = EditorOptions.create({ pinned: true, index });\n", "\t\tconst activeEditor = this.getActiveEditor();\n", "\t\tconst codeEditor = getCodeEditor(activeEditor);\n", "\t\tif (codeEditor && activeEditor.position === this.stacks.positionOfGroup(fromGroup) && input.matches(activeEditor.input)) {\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\t// for the editor to be a text editor and creating the options accordingly if so\n", "\t\tlet options = EditorOptions.create({ pinned: true, index, inactive });\n" ], "file_path": "src/vs/workbench/browser/parts/editor/editorPart.ts", "type": "replace", "edit_start_line_idx": 855 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import { createDecorator, ServiceIdentifier } from 'vs/platform/instantiation/common/instantiation'; import { Position, IEditorInput } from 'vs/platform/editor/common/editor'; import { IEditorStacksModel, IEditorGroup } from 'vs/workbench/common/editor'; import Event from 'vs/base/common/event'; export enum GroupArrangement { MINIMIZE_OTHERS, EVEN } export type GroupOrientation = 'vertical' | 'horizontal'; export const IEditorGroupService = createDecorator<IEditorGroupService>('editorGroupService'); export interface ITabOptions { showTabs?: boolean; tabCloseButton?: 'left' | 'right' | 'off'; showIcons?: boolean; previewEditors?: boolean; }; /** * The editor service allows to open editors and work on the active * editor input and models. */ export interface IEditorGroupService { _serviceBrand: ServiceIdentifier<any>; /** * Emitted when editors or inputs change. Examples: opening, closing of editors. Active editor change. */ onEditorsChanged: Event<void>; /** * Emitted when opening an editor fails. */ onEditorOpenFail: Event<IEditorInput>; /** * Emitted when a editors are moved to another position. */ onEditorsMoved: Event<void>; /** * Emitted when the editor group orientation was changed. */ onGroupOrientationChanged: Event<void>; /** * Emitted when tab options changed. */ onTabOptionsChanged: Event<ITabOptions>; /** * Keyboard focus the editor group at the provided position. */ focusGroup(group: IEditorGroup): void; focusGroup(position: Position): void; /** * Activate the editor group at the provided position without moving focus. */ activateGroup(group: IEditorGroup): void; activateGroup(position: Position): void; /** * Allows to move the editor group from one position to another. */ moveGroup(from: IEditorGroup, to: IEditorGroup): void; moveGroup(from: Position, to: Position): void; /** * Allows to arrange editor groups according to the GroupArrangement enumeration. */ arrangeGroups(arrangement: GroupArrangement): void; /** * Changes the editor group layout between vertical and horizontal orientation. Only applies * if more than one editor is opened. */ setGroupOrientation(orientation: GroupOrientation): void; /** * Returns the current editor group layout. */ getGroupOrientation(): GroupOrientation; /** * Adds the pinned state to an editor, removing it from being a preview editor. */ pinEditor(group: IEditorGroup, input: IEditorInput): void; pinEditor(position: Position, input: IEditorInput): void; /** * Removes the pinned state of an editor making it a preview editor. */ unpinEditor(group: IEditorGroup, input: IEditorInput): void; unpinEditor(position: Position, input: IEditorInput): void; /** * Moves an editor from one group to another. The index in the group is optional. */ moveEditor(input: IEditorInput, from: IEditorGroup, to: IEditorGroup, index?: number): void; moveEditor(input: IEditorInput, from: Position, to: Position, index?: number): void; /** * Provides access to the editor stacks model */ getStacksModel(): IEditorStacksModel; /** * Returns tab options. */ getTabOptions(): ITabOptions; }
src/vs/workbench/services/group/common/groupService.ts
1
https://github.com/microsoft/vscode/commit/522c6e01711a50ab2c48e2efb11f837dce7ebab9
[ 0.0027218873146921396, 0.0005519202095456421, 0.00016581869567744434, 0.0001747538335621357, 0.0008042766130529344 ]
{ "id": 3, "code_window": [ "\t\t}\n", "\n", "\t\t// When moving an editor, try to preserve as much view state as possible by checking\n", "\t\t// for th editor to be a text editor and creating the options accordingly if so\n", "\t\tlet options = EditorOptions.create({ pinned: true, index });\n", "\t\tconst activeEditor = this.getActiveEditor();\n", "\t\tconst codeEditor = getCodeEditor(activeEditor);\n", "\t\tif (codeEditor && activeEditor.position === this.stacks.positionOfGroup(fromGroup) && input.matches(activeEditor.input)) {\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\t// for the editor to be a text editor and creating the options accordingly if so\n", "\t\tlet options = EditorOptions.create({ pinned: true, index, inactive });\n" ], "file_path": "src/vs/workbench/browser/parts/editor/editorPart.ts", "type": "replace", "edit_start_line_idx": 855 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import { Action } from 'vs/base/common/actions'; import { TPromise } from 'vs/base/common/winjs.base'; import { IWindowService } from 'vs/platform/windows/common/windows'; import { IMessageService } from 'vs/platform/message/common/message'; // tslint:disable import pkg from 'vs/platform/node/package'; // tslint:enable // Enable this by default for insiders function getDefaultValue(): boolean { const value = window.localStorage.getItem('enablePreviewSCM'); return /insider$/.test(pkg.version) ? value !== 'false' : value === 'true'; } export default class SCMPreview { private static readonly _enabled = getDefaultValue(); static get enabled(): boolean { return this._enabled; } static set enabled(enabled: boolean) { window.localStorage.setItem('enablePreviewSCM', enabled ? 'true' : 'false'); } } export class EnableSCMPreviewAction extends Action { static ID = 'enablescmpreview'; static LABEL = 'Enable Preview SCM'; constructor( id = EnableSCMPreviewAction.ID, label = EnableSCMPreviewAction.LABEL, @IWindowService private windowService: IWindowService, @IMessageService private messageService: IMessageService, ) { super(EnableSCMPreviewAction.ID, EnableSCMPreviewAction.LABEL, '', true); } run(): TPromise<void> { const message = 'This will reload this window, do you want to continue?'; const result = this.messageService.confirm({ message }); if (!result) { return undefined; } SCMPreview.enabled = true; return this.windowService.reloadWindow(); } } export class DisableSCMPreviewAction extends Action { static ID = 'disablescmpreview'; static LABEL = 'Disable Preview SCM'; constructor( id = DisableSCMPreviewAction.ID, label = DisableSCMPreviewAction.LABEL, @IWindowService private windowService: IWindowService, @IMessageService private messageService: IMessageService, ) { super(DisableSCMPreviewAction.ID, DisableSCMPreviewAction.LABEL, '', true); } run(): TPromise<void> { const message = 'This will reload this window, do you want to continue?'; const result = this.messageService.confirm({ message }); if (!result) { return undefined; } SCMPreview.enabled = false; return this.windowService.reloadWindow(); } }
src/vs/workbench/parts/scm/browser/scmPreview.ts
0
https://github.com/microsoft/vscode/commit/522c6e01711a50ab2c48e2efb11f837dce7ebab9
[ 0.00017775733431335539, 0.00017474127525929362, 0.00017156809917651117, 0.00017435387417208403, 0.0000020090978978259955 ]
{ "id": 3, "code_window": [ "\t\t}\n", "\n", "\t\t// When moving an editor, try to preserve as much view state as possible by checking\n", "\t\t// for th editor to be a text editor and creating the options accordingly if so\n", "\t\tlet options = EditorOptions.create({ pinned: true, index });\n", "\t\tconst activeEditor = this.getActiveEditor();\n", "\t\tconst codeEditor = getCodeEditor(activeEditor);\n", "\t\tif (codeEditor && activeEditor.position === this.stacks.positionOfGroup(fromGroup) && input.matches(activeEditor.input)) {\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\t// for the editor to be a text editor and creating the options accordingly if so\n", "\t\tlet options = EditorOptions.create({ pinned: true, index, inactive });\n" ], "file_path": "src/vs/workbench/browser/parts/editor/editorPart.ts", "type": "replace", "edit_start_line_idx": 855 }
<svg width="13" height="13" viewBox="0 0 13 13" xmlns="http://www.w3.org/2000/svg"><g fill="none" fill-rule="evenodd"><path d="M6.5 0C2.91 0 0 2.91 0 6.5S2.91 13 6.5 13 13 10.09 13 6.5 10.09 0 6.5 0zm3.9 9.1l-1.3 1.3-2.6-2.6-2.6 2.6-1.3-1.3 2.6-2.635L2.6 3.9l1.3-1.3 2.6 2.6 2.6-2.6 1.3 1.3-2.6 2.565L10.4 9.1z" fill="#fff"/></g></svg>
src/vs/workbench/parts/tasks/electron-browser/media/status-error.svg
0
https://github.com/microsoft/vscode/commit/522c6e01711a50ab2c48e2efb11f837dce7ebab9
[ 0.0001734220568323508, 0.0001734220568323508, 0.0001734220568323508, 0.0001734220568323508, 0 ]
{ "id": 3, "code_window": [ "\t\t}\n", "\n", "\t\t// When moving an editor, try to preserve as much view state as possible by checking\n", "\t\t// for th editor to be a text editor and creating the options accordingly if so\n", "\t\tlet options = EditorOptions.create({ pinned: true, index });\n", "\t\tconst activeEditor = this.getActiveEditor();\n", "\t\tconst codeEditor = getCodeEditor(activeEditor);\n", "\t\tif (codeEditor && activeEditor.position === this.stacks.positionOfGroup(fromGroup) && input.matches(activeEditor.input)) {\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\t// for the editor to be a text editor and creating the options accordingly if so\n", "\t\tlet options = EditorOptions.create({ pinned: true, index, inactive });\n" ], "file_path": "src/vs/workbench/browser/parts/editor/editorPart.ts", "type": "replace", "edit_start_line_idx": 855 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "titleLabel": "{0} ({1})" }
i18n/ita/src/vs/base/browser/ui/actionbar/actionbar.i18n.json
0
https://github.com/microsoft/vscode/commit/522c6e01711a50ab2c48e2efb11f837dce7ebab9
[ 0.00017688337538857013, 0.00017688337538857013, 0.00017688337538857013, 0.00017688337538857013, 0 ]
{ "id": 4, "code_window": [ "\t\tconst activeEditor = this.getActiveEditor();\n", "\t\tconst codeEditor = getCodeEditor(activeEditor);\n", "\t\tif (codeEditor && activeEditor.position === this.stacks.positionOfGroup(fromGroup) && input.matches(activeEditor.input)) {\n", "\t\t\toptions = TextEditorOptions.create({ pinned: true, index });\n", "\t\t\t(<TextEditorOptions>options).fromEditor(codeEditor);\n", "\t\t}\n", "\n", "\t\t// A move to another group is an open first...\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\toptions = TextEditorOptions.create({ pinned: true, index, inactive });\n" ], "file_path": "src/vs/workbench/browser/parts/editor/editorPart.ts", "type": "replace", "edit_start_line_idx": 860 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import { createDecorator, ServiceIdentifier } from 'vs/platform/instantiation/common/instantiation'; import { Position, IEditorInput } from 'vs/platform/editor/common/editor'; import { IEditorStacksModel, IEditorGroup } from 'vs/workbench/common/editor'; import Event from 'vs/base/common/event'; export enum GroupArrangement { MINIMIZE_OTHERS, EVEN } export type GroupOrientation = 'vertical' | 'horizontal'; export const IEditorGroupService = createDecorator<IEditorGroupService>('editorGroupService'); export interface ITabOptions { showTabs?: boolean; tabCloseButton?: 'left' | 'right' | 'off'; showIcons?: boolean; previewEditors?: boolean; }; /** * The editor service allows to open editors and work on the active * editor input and models. */ export interface IEditorGroupService { _serviceBrand: ServiceIdentifier<any>; /** * Emitted when editors or inputs change. Examples: opening, closing of editors. Active editor change. */ onEditorsChanged: Event<void>; /** * Emitted when opening an editor fails. */ onEditorOpenFail: Event<IEditorInput>; /** * Emitted when a editors are moved to another position. */ onEditorsMoved: Event<void>; /** * Emitted when the editor group orientation was changed. */ onGroupOrientationChanged: Event<void>; /** * Emitted when tab options changed. */ onTabOptionsChanged: Event<ITabOptions>; /** * Keyboard focus the editor group at the provided position. */ focusGroup(group: IEditorGroup): void; focusGroup(position: Position): void; /** * Activate the editor group at the provided position without moving focus. */ activateGroup(group: IEditorGroup): void; activateGroup(position: Position): void; /** * Allows to move the editor group from one position to another. */ moveGroup(from: IEditorGroup, to: IEditorGroup): void; moveGroup(from: Position, to: Position): void; /** * Allows to arrange editor groups according to the GroupArrangement enumeration. */ arrangeGroups(arrangement: GroupArrangement): void; /** * Changes the editor group layout between vertical and horizontal orientation. Only applies * if more than one editor is opened. */ setGroupOrientation(orientation: GroupOrientation): void; /** * Returns the current editor group layout. */ getGroupOrientation(): GroupOrientation; /** * Adds the pinned state to an editor, removing it from being a preview editor. */ pinEditor(group: IEditorGroup, input: IEditorInput): void; pinEditor(position: Position, input: IEditorInput): void; /** * Removes the pinned state of an editor making it a preview editor. */ unpinEditor(group: IEditorGroup, input: IEditorInput): void; unpinEditor(position: Position, input: IEditorInput): void; /** * Moves an editor from one group to another. The index in the group is optional. */ moveEditor(input: IEditorInput, from: IEditorGroup, to: IEditorGroup, index?: number): void; moveEditor(input: IEditorInput, from: Position, to: Position, index?: number): void; /** * Provides access to the editor stacks model */ getStacksModel(): IEditorStacksModel; /** * Returns tab options. */ getTabOptions(): ITabOptions; }
src/vs/workbench/services/group/common/groupService.ts
1
https://github.com/microsoft/vscode/commit/522c6e01711a50ab2c48e2efb11f837dce7ebab9
[ 0.002778573427349329, 0.0007060787174850702, 0.00016548889107070863, 0.00018130119133275002, 0.0009525853674858809 ]
{ "id": 4, "code_window": [ "\t\tconst activeEditor = this.getActiveEditor();\n", "\t\tconst codeEditor = getCodeEditor(activeEditor);\n", "\t\tif (codeEditor && activeEditor.position === this.stacks.positionOfGroup(fromGroup) && input.matches(activeEditor.input)) {\n", "\t\t\toptions = TextEditorOptions.create({ pinned: true, index });\n", "\t\t\t(<TextEditorOptions>options).fromEditor(codeEditor);\n", "\t\t}\n", "\n", "\t\t// A move to another group is an open first...\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\toptions = TextEditorOptions.create({ pinned: true, index, inactive });\n" ], "file_path": "src/vs/workbench/browser/parts/editor/editorPart.ts", "type": "replace", "edit_start_line_idx": 860 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "json.nugget.error.access": "Error de la solicitud a {0}: {1}", "json.nugget.error.indexaccess": "Error de la solicitud a {0}: {1}", "json.nugget.error.invalidformat": "{0} no es un documento JSON válido", "json.nugget.error.missingservice": "El documento de índices NuGet no tiene el servicio {0}.", "json.nugget.package.hover": "{0}", "json.nugget.version.hover": "Última versión: {0}", "json.project.default": "Project.json predeterminado" }
i18n/esn/extensions/json/server/out/jsoncontributions/projectJSONContribution.i18n.json
0
https://github.com/microsoft/vscode/commit/522c6e01711a50ab2c48e2efb11f837dce7ebab9
[ 0.0001755205012159422, 0.00017533099162392318, 0.0001751414965838194, 0.00017533099162392318, 1.8950231606140733e-7 ]
{ "id": 4, "code_window": [ "\t\tconst activeEditor = this.getActiveEditor();\n", "\t\tconst codeEditor = getCodeEditor(activeEditor);\n", "\t\tif (codeEditor && activeEditor.position === this.stacks.positionOfGroup(fromGroup) && input.matches(activeEditor.input)) {\n", "\t\t\toptions = TextEditorOptions.create({ pinned: true, index });\n", "\t\t\t(<TextEditorOptions>options).fromEditor(codeEditor);\n", "\t\t}\n", "\n", "\t\t// A move to another group is an open first...\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\toptions = TextEditorOptions.create({ pinned: true, index, inactive });\n" ], "file_path": "src/vs/workbench/browser/parts/editor/editorPart.ts", "type": "replace", "edit_start_line_idx": 860 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "fileLink": "Zum Öffnen klicken (STRG+KLICKEN für seitliche Anzeige)", "fileLinkMac": "Zum Öffnen klicken (CMD+KLICKEN für seitliche Anzeige)", "replExpressionAriaLabel": "Ausdruck {0} besitzt den Wert {1}, Read Eval Print-Loop, Debuggen", "replKeyValueOutputAriaLabel": "Ausgabevariable {0} besitzt den Wert {1}, Read Eval Print-Loop, Debuggen", "replValueOutputAriaLabel": "{0}, Read Eval Print-Loop, Debuggen", "replVariableAriaLabel": "Variable {0} besitzt den Wert {1}, Read Eval Print-Loop, Debuggen", "stateCapture": "Der Objektstatus wird aus der ersten Auswertung erfasst." }
i18n/deu/src/vs/workbench/parts/debug/electron-browser/replViewer.i18n.json
0
https://github.com/microsoft/vscode/commit/522c6e01711a50ab2c48e2efb11f837dce7ebab9
[ 0.00017614904209040105, 0.0001759210863383487, 0.00017569313058629632, 0.0001759210863383487, 2.2795575205236673e-7 ]
{ "id": 4, "code_window": [ "\t\tconst activeEditor = this.getActiveEditor();\n", "\t\tconst codeEditor = getCodeEditor(activeEditor);\n", "\t\tif (codeEditor && activeEditor.position === this.stacks.positionOfGroup(fromGroup) && input.matches(activeEditor.input)) {\n", "\t\t\toptions = TextEditorOptions.create({ pinned: true, index });\n", "\t\t\t(<TextEditorOptions>options).fromEditor(codeEditor);\n", "\t\t}\n", "\n", "\t\t// A move to another group is an open first...\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\toptions = TextEditorOptions.create({ pinned: true, index, inactive });\n" ], "file_path": "src/vs/workbench/browser/parts/editor/editorPart.ts", "type": "replace", "edit_start_line_idx": 860 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import * as assert from 'assert'; import { Range } from 'vs/editor/common/core/range'; import { testViewModel } from 'vs/editor/test/common/viewModel/testViewModel'; import * as editorCommon from 'vs/editor/common/editorCommon'; suite('ViewModelDecorations', () => { test('getDecorationsViewportData', () => { const text = [ 'hello world, this is a buffer that will be wrapped' ]; const opts: editorCommon.ICodeEditorWidgetCreationOptions = { wordWrap: 'wordWrapColumn', wordWrapColumn: 13 }; testViewModel(text, opts, (viewModel, model) => { assert.equal(viewModel.getLineContent(1), 'hello world, '); assert.equal(viewModel.getLineContent(2), 'this is a '); assert.equal(viewModel.getLineContent(3), 'buffer that '); assert.equal(viewModel.getLineContent(4), 'will be '); assert.equal(viewModel.getLineContent(5), 'wrapped'); let dec1: string; let dec2: string; let dec3: string; let dec4: string; let dec5: string; let dec6: string; let dec7: string; let dec8: string; let dec9: string; let dec10: string; let dec11: string; let dec12: string; let dec13: string; let dec14: string; let dec15: string; model.changeDecorations((accessor) => { let createOpts = (id: string) => { return { className: id, inlineClassName: 'i-' + id, beforeContentClassName: 'b-' + id, afterContentClassName: 'a-' + id }; }; // VIEWPORT will be (1,14) -> (1,36) // completely before viewport dec1 = accessor.addDecoration(new Range(1, 2, 1, 3), createOpts('dec1')); // starts before viewport, ends at viewport start dec2 = accessor.addDecoration(new Range(1, 2, 1, 14), createOpts('dec2')); // starts before viewport, ends inside viewport dec3 = accessor.addDecoration(new Range(1, 2, 1, 15), createOpts('dec3')); // starts before viewport, ends at viewport end dec4 = accessor.addDecoration(new Range(1, 2, 1, 36), createOpts('dec4')); // starts before viewport, ends after viewport dec5 = accessor.addDecoration(new Range(1, 2, 1, 51), createOpts('dec5')); // starts at viewport start, ends at viewport start dec6 = accessor.addDecoration(new Range(1, 14, 1, 14), createOpts('dec6')); // starts at viewport start, ends inside viewport dec7 = accessor.addDecoration(new Range(1, 14, 1, 16), createOpts('dec7')); // starts at viewport start, ends at viewport end dec8 = accessor.addDecoration(new Range(1, 14, 1, 36), createOpts('dec8')); // starts at viewport start, ends after viewport dec9 = accessor.addDecoration(new Range(1, 14, 1, 51), createOpts('dec9')); // starts inside viewport, ends inside viewport dec10 = accessor.addDecoration(new Range(1, 16, 1, 18), createOpts('dec10')); // starts inside viewport, ends at viewport end dec11 = accessor.addDecoration(new Range(1, 16, 1, 36), createOpts('dec11')); // starts inside viewport, ends after viewport dec12 = accessor.addDecoration(new Range(1, 16, 1, 51), createOpts('dec12')); // starts at viewport end, ends at viewport end dec13 = accessor.addDecoration(new Range(1, 36, 1, 36), createOpts('dec13')); // starts at viewport end, ends after viewport dec14 = accessor.addDecoration(new Range(1, 36, 1, 51), createOpts('dec14')); // starts after viewport, ends after viewport dec15 = accessor.addDecoration(new Range(1, 40, 1, 51), createOpts('dec15')); }); let actualDecorations = viewModel.getDecorationsInViewport( new Range(2, viewModel.getLineMinColumn(2), 3, viewModel.getLineMaxColumn(3)) ).map((dec) => { return dec.source.id; }); assert.deepEqual(actualDecorations, [ dec2, dec3, dec4, dec5, dec6, dec7, dec8, dec9, dec10, dec11, dec12, dec13, dec14, ]); let inlineDecorations1 = viewModel.getViewLineRenderingData( new Range(2, viewModel.getLineMinColumn(2), 3, viewModel.getLineMaxColumn(3)), 2 ).inlineDecorations; // view line 2: (1,14 -> 1,24) assert.deepEqual(inlineDecorations1, [ { range: new Range(1, 2, 2, 1), inlineClassName: 'i-dec2', insertsBeforeOrAfter: false }, { range: new Range(1, 2, 2, 2), inlineClassName: 'i-dec3', insertsBeforeOrAfter: false }, { range: new Range(2, 1, 2, 2), inlineClassName: 'a-dec3', insertsBeforeOrAfter: true }, { range: new Range(1, 2, 4, 1), inlineClassName: 'i-dec4', insertsBeforeOrAfter: false }, { range: new Range(1, 2, 5, 8), inlineClassName: 'i-dec5', insertsBeforeOrAfter: false }, { range: new Range(2, 1, 2, 1), inlineClassName: 'i-dec6', insertsBeforeOrAfter: false }, { range: new Range(2, 1, 2, 2), inlineClassName: 'b-dec6', insertsBeforeOrAfter: true }, { range: new Range(2, 1, 2, 3), inlineClassName: 'i-dec7', insertsBeforeOrAfter: false }, { range: new Range(2, 1, 2, 2), inlineClassName: 'b-dec7', insertsBeforeOrAfter: true }, { range: new Range(2, 2, 2, 3), inlineClassName: 'a-dec7', insertsBeforeOrAfter: true }, { range: new Range(2, 1, 4, 1), inlineClassName: 'i-dec8', insertsBeforeOrAfter: false }, { range: new Range(2, 1, 2, 2), inlineClassName: 'b-dec8', insertsBeforeOrAfter: true }, { range: new Range(2, 1, 5, 8), inlineClassName: 'i-dec9', insertsBeforeOrAfter: false }, { range: new Range(2, 1, 2, 2), inlineClassName: 'b-dec9', insertsBeforeOrAfter: true }, { range: new Range(2, 3, 2, 5), inlineClassName: 'i-dec10', insertsBeforeOrAfter: false }, { range: new Range(2, 3, 2, 4), inlineClassName: 'b-dec10', insertsBeforeOrAfter: true }, { range: new Range(2, 4, 2, 5), inlineClassName: 'a-dec10', insertsBeforeOrAfter: true }, { range: new Range(2, 3, 4, 1), inlineClassName: 'i-dec11', insertsBeforeOrAfter: false }, { range: new Range(2, 3, 2, 4), inlineClassName: 'b-dec11', insertsBeforeOrAfter: true }, { range: new Range(2, 3, 5, 8), inlineClassName: 'i-dec12', insertsBeforeOrAfter: false }, { range: new Range(2, 3, 2, 4), inlineClassName: 'b-dec12', insertsBeforeOrAfter: true }, ]); let inlineDecorations2 = viewModel.getViewLineRenderingData( new Range(2, viewModel.getLineMinColumn(2), 3, viewModel.getLineMaxColumn(3)), 3 ).inlineDecorations; // view line 3 (24 -> 36) assert.deepEqual(inlineDecorations2, [ { range: new Range(1, 2, 4, 1), inlineClassName: 'i-dec4', insertsBeforeOrAfter: false }, { range: new Range(1, 2, 5, 8), inlineClassName: 'i-dec5', insertsBeforeOrAfter: false }, { range: new Range(2, 1, 4, 1), inlineClassName: 'i-dec8', insertsBeforeOrAfter: false }, { range: new Range(2, 1, 5, 8), inlineClassName: 'i-dec9', insertsBeforeOrAfter: false }, { range: new Range(2, 3, 4, 1), inlineClassName: 'i-dec11', insertsBeforeOrAfter: false }, { range: new Range(2, 3, 5, 8), inlineClassName: 'i-dec12', insertsBeforeOrAfter: false }, ]); }); }); test('issue #17208: Problem scrolling in 1.8.0', () => { const text = [ 'hello world, this is a buffer that will be wrapped' ]; const opts: editorCommon.ICodeEditorWidgetCreationOptions = { wordWrap: 'wordWrapColumn', wordWrapColumn: 13 }; testViewModel(text, opts, (viewModel, model) => { assert.equal(viewModel.getLineContent(1), 'hello world, '); assert.equal(viewModel.getLineContent(2), 'this is a '); assert.equal(viewModel.getLineContent(3), 'buffer that '); assert.equal(viewModel.getLineContent(4), 'will be '); assert.equal(viewModel.getLineContent(5), 'wrapped'); let dec1: string; model.changeDecorations((accessor) => { dec1 = accessor.addDecoration( new Range(1, 50, 1, 51), { beforeContentClassName: 'dec1' } ); }); let decorations = viewModel.getDecorationsInViewport( new Range(2, viewModel.getLineMinColumn(2), 3, viewModel.getLineMaxColumn(3)) ); assert.deepEqual(decorations, []); let inlineDecorations1 = viewModel.getViewLineRenderingData( new Range(2, viewModel.getLineMinColumn(2), 3, viewModel.getLineMaxColumn(3)), 2 ).inlineDecorations; assert.deepEqual(inlineDecorations1, []); let inlineDecorations2 = viewModel.getViewLineRenderingData( new Range(2, viewModel.getLineMinColumn(2), 3, viewModel.getLineMaxColumn(3)), 3 ).inlineDecorations; assert.deepEqual(inlineDecorations2, []); }); }); });
src/vs/editor/test/common/viewModel/viewModelDecorations.test.ts
0
https://github.com/microsoft/vscode/commit/522c6e01711a50ab2c48e2efb11f837dce7ebab9
[ 0.0011631847592070699, 0.00020488437439780682, 0.00016255464288406074, 0.00017355987802147865, 0.00017213735554832965 ]
{ "id": 5, "code_window": [ "\t\toptions.preserveFocus = settings.preserveFocus;\n", "\t\toptions.forceOpen = settings.forceOpen;\n", "\t\toptions.revealIfVisible = settings.revealIfVisible;\n", "\t\toptions.pinned = settings.pinned;\n", "\t\toptions.index = settings.index;\n", "\n", "\t\tif (settings.selection) {\n", "\t\t\toptions.startLineNumber = settings.selection.startLineNumber;\n", "\t\t\toptions.startColumn = settings.selection.startColumn;\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\toptions.inactive = settings.inactive;\n" ], "file_path": "src/vs/workbench/common/editor.ts", "type": "add", "edit_start_line_idx": 644 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import { TPromise } from 'vs/base/common/winjs.base'; import Event, { Emitter, once } from 'vs/base/common/event'; import * as objects from 'vs/base/common/objects'; import types = require('vs/base/common/types'); import URI from 'vs/base/common/uri'; import { IDisposable, dispose, Disposable } from 'vs/base/common/lifecycle'; import { IEditor, ICommonCodeEditor, IEditorViewState, IEditorOptions as ICodeEditorOptions, IModel } from 'vs/editor/common/editorCommon'; import { IEditorInput, IEditorModel, IEditorOptions, ITextEditorOptions, IBaseResourceInput, Position, Verbosity } from 'vs/platform/editor/common/editor'; import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace'; import { IEditorGroupService } from 'vs/workbench/services/group/common/groupService'; import { SyncDescriptor, AsyncDescriptor } from 'vs/platform/instantiation/common/descriptors'; import { IInstantiationService, IConstructorSignature0 } from 'vs/platform/instantiation/common/instantiation'; import { RawContextKey } from 'vs/platform/contextkey/common/contextkey'; export const TextCompareEditorVisible = new RawContextKey<boolean>('textCompareEditorVisible', false); export enum ConfirmResult { SAVE, DONT_SAVE, CANCEL } export interface IEditorDescriptor { getId(): string; getName(): string; describes(obj: any): boolean; } export const Extensions = { Editors: 'workbench.contributions.editors' }; /** * Text diff editor id. */ export const TEXT_DIFF_EDITOR_ID = 'workbench.editors.textDiffEditor'; /** * Binary diff editor id. */ export const BINARY_DIFF_EDITOR_ID = 'workbench.editors.binaryResourceDiffEditor'; export interface IEditorRegistry { /** * Registers an editor to the platform for the given input type. The second parameter also supports an * array of input classes to be passed in. If the more than one editor is registered for the same editor * input, the input itself will be asked which editor it prefers if this method is provided. Otherwise * the first editor in the list will be returned. * * @param editorInputDescriptor a constructor function that returns an instance of EditorInput for which the * registered editor should be used for. */ registerEditor(descriptor: IEditorDescriptor, editorInputDescriptor: SyncDescriptor<EditorInput>): void; registerEditor(descriptor: IEditorDescriptor, editorInputDescriptor: SyncDescriptor<EditorInput>[]): void; /** * Returns the editor descriptor for the given input or null if none. */ getEditor(input: EditorInput): IEditorDescriptor; /** * Returns the editor descriptor for the given identifier or null if none. */ getEditorById(editorId: string): IEditorDescriptor; /** * Returns an array of registered editors known to the platform. */ getEditors(): IEditorDescriptor[]; /** * Registers the default input to be used for files in the workbench. * * @param editorInputDescriptor a descriptor that resolves to an instance of EditorInput that * should be used to handle file inputs. */ registerDefaultFileInput(editorInputDescriptor: AsyncDescriptor<IFileEditorInput>): void; /** * Returns a descriptor of the default input to be used for files in the workbench. * * @return a descriptor that resolves to an instance of EditorInput that should be used to handle * file inputs. */ getDefaultFileInput(): AsyncDescriptor<IFileEditorInput>; /** * Registers a editor input factory for the given editor input to the registry. An editor input factory * is capable of serializing and deserializing editor inputs from string data. * * @param editorInputId the identifier of the editor input * @param factory the editor input factory for serialization/deserialization */ registerEditorInputFactory(editorInputId: string, ctor: IConstructorSignature0<IEditorInputFactory>): void; /** * Returns the editor input factory for the given editor input. * * @param editorInputId the identifier of the editor input */ getEditorInputFactory(editorInputId: string): IEditorInputFactory; setInstantiationService(service: IInstantiationService): void; } export interface IEditorInputFactory { /** * Returns a string representation of the provided editor input that contains enough information * to deserialize back to the original editor input from the deserialize() method. */ serialize(editorInput: EditorInput): string; /** * Returns an editor input from the provided serialized form of the editor input. This form matches * the value returned from the serialize() method. */ deserialize(instantiationService: IInstantiationService, serializedEditorInput: string): EditorInput; } /** * Editor inputs are lightweight objects that can be passed to the workbench API to open inside the editor part. * Each editor input is mapped to an editor that is capable of opening it through the Platform facade. */ export abstract class EditorInput implements IEditorInput { private _onDispose: Emitter<void>; protected _onDidChangeDirty: Emitter<void>; protected _onDidChangeLabel: Emitter<void>; private disposed: boolean; constructor() { this._onDidChangeDirty = new Emitter<void>(); this._onDidChangeLabel = new Emitter<void>(); this._onDispose = new Emitter<void>(); this.disposed = false; } /** * Fired when the dirty state of this input changes. */ public get onDidChangeDirty(): Event<void> { return this._onDidChangeDirty.event; } /** * Fired when the label this input changes. */ public get onDidChangeLabel(): Event<void> { return this._onDidChangeLabel.event; } /** * Fired when the model gets disposed. */ public get onDispose(): Event<void> { return this._onDispose.event; } /** * Returns the name of this input that can be shown to the user. Examples include showing the name of the input * above the editor area when the input is shown. */ public getName(): string { return null; } /** * Returns the description of this input that can be shown to the user. Examples include showing the description of * the input above the editor area to the side of the name of the input. */ public getDescription(): string { return null; } public getTitle(verbosity?: Verbosity): string { return this.getName(); } /** * Returns the unique type identifier of this input. */ public abstract getTypeId(): string; /** * Returns the preferred editor for this input. A list of candidate editors is passed in that whee registered * for the input. This allows subclasses to decide late which editor to use for the input on a case by case basis. */ public getPreferredEditorId(candidates: string[]): string { if (candidates && candidates.length > 0) { return candidates[0]; } return null; } /** * Returns a descriptor suitable for telemetry events or null if none is available. * * Subclasses should extend if they can contribute. */ public getTelemetryDescriptor(): { [key: string]: any; } { return { typeId: this.getTypeId() }; } /** * Returns a type of EditorModel that represents the resolved input. Subclasses should * override to provide a meaningful model. The optional second argument allows to specify * if the EditorModel should be refreshed before returning it. Depending on the implementation * this could mean to refresh the editor model contents with the version from disk. */ public abstract resolve(refresh?: boolean): TPromise<IEditorModel>; /** * An editor that is dirty will be asked to be saved once it closes. */ public isDirty(): boolean { return false; } /** * Subclasses should bring up a proper dialog for the user if the editor is dirty and return the result. */ public confirmSave(): ConfirmResult { return ConfirmResult.DONT_SAVE; } /** * Saves the editor if it is dirty. Subclasses return a promise with a boolean indicating the success of the operation. */ public save(): TPromise<boolean> { return TPromise.as(true); } /** * Reverts the editor if it is dirty. Subclasses return a promise with a boolean indicating the success of the operation. */ public revert(): TPromise<boolean> { return TPromise.as(true); } /** * Called when this input is no longer opened in any editor. Subclasses can free resources as needed. */ public close(): void { this.dispose(); } /** * Subclasses can set this to false if it does not make sense to split the editor input. */ public supportsSplitEditor(): boolean { return true; } /** * Returns true if this input is identical to the otherInput. */ public matches(otherInput: any): boolean { return this === otherInput; } /** * Called when an editor input is no longer needed. Allows to free up any resources taken by * resolving the editor input. */ public dispose(): void { this.disposed = true; this._onDispose.fire(); this._onDidChangeDirty.dispose(); this._onDidChangeLabel.dispose(); this._onDispose.dispose(); } /** * Returns whether this input was disposed or not. */ public isDisposed(): boolean { return this.disposed; } } export enum EncodingMode { /** * Instructs the encoding support to encode the current input with the provided encoding */ Encode, /** * Instructs the encoding support to decode the current input with the provided encoding */ Decode } export interface IEncodingSupport { /** * Gets the encoding of the input if known. */ getEncoding(): string; /** * Sets the encoding for the input for saving. */ setEncoding(encoding: string, mode: EncodingMode): void; } /** * This is a tagging interface to declare an editor input being capable of dealing with files. It is only used in the editor registry * to register this kind of input to the platform. */ export interface IFileEditorInput extends IEditorInput, IEncodingSupport { /** * Gets the absolute file resource URI this input is about. */ getResource(): URI; /** * Sets the absolute file resource URI this input is about. */ setResource(resource: URI): void; /** * Sets the preferred encodingt to use for this input. */ setPreferredEncoding(encoding: string): void; } /** * Side by side editor inputs that have a master and details side. */ export class SideBySideEditorInput extends EditorInput { public static ID: string = 'workbench.editorinputs.sidebysideEditorInput'; private _toUnbind: IDisposable[]; constructor(private name: string, private description: string, private _details: EditorInput, private _master: EditorInput) { super(); this._toUnbind = []; this.registerListeners(); } get master(): EditorInput { return this._master; } get details(): EditorInput { return this._details; } public isDirty(): boolean { return this.master.isDirty(); } public confirmSave(): ConfirmResult { return this.master.confirmSave(); } public save(): TPromise<boolean> { return this.master.save(); } public revert(): TPromise<boolean> { return this.master.revert(); } public getTelemetryDescriptor(): { [key: string]: any; } { const descriptor = this.master.getTelemetryDescriptor(); return objects.assign(descriptor, super.getTelemetryDescriptor()); } private registerListeners(): void { // When the details or master input gets disposed, dispose this diff editor input const onceDetailsDisposed = once(this.details.onDispose); this._toUnbind.push(onceDetailsDisposed(() => { if (!this.isDisposed()) { this.dispose(); } })); const onceMasterDisposed = once(this.master.onDispose); this._toUnbind.push(onceMasterDisposed(() => { if (!this.isDisposed()) { this.dispose(); } })); // Reemit some events from the master side to the outside this._toUnbind.push(this.master.onDidChangeDirty(() => this._onDidChangeDirty.fire())); this._toUnbind.push(this.master.onDidChangeLabel(() => this._onDidChangeLabel.fire())); } public get toUnbind() { return this._toUnbind; } public resolve(refresh?: boolean): TPromise<EditorModel> { return TPromise.as(null); } getTypeId(): string { return SideBySideEditorInput.ID; } public getName(): string { return this.name; } public getDescription(): string { return this.description; } public supportsSplitEditor(): boolean { return false; } public matches(otherInput: any): boolean { if (super.matches(otherInput) === true) { return true; } if (otherInput) { if (!(otherInput instanceof SideBySideEditorInput)) { return false; } const otherDiffInput = <SideBySideEditorInput>otherInput; return this.details.matches(otherDiffInput.details) && this.master.matches(otherDiffInput.master); } return false; } public dispose(): void { this._toUnbind = dispose(this._toUnbind); super.dispose(); } } export interface ITextEditorModel extends IEditorModel { textEditorModel: IModel; } /** * The editor model is the heavyweight counterpart of editor input. Depending on the editor input, it * connects to the disk to retrieve content and may allow for saving it back or reverting it. Editor models * are typically cached for some while because they are expensive to construct. */ export class EditorModel extends Disposable implements IEditorModel { private _onDispose: Emitter<void>; constructor() { super(); this._onDispose = new Emitter<void>(); } /** * Fired when the model gets disposed. */ public get onDispose(): Event<void> { return this._onDispose.event; } /** * Causes this model to load returning a promise when loading is completed. */ public load(): TPromise<EditorModel> { return TPromise.as(this); } /** * Returns whether this model was loaded or not. */ public isResolved(): boolean { return true; } /** * Subclasses should implement to free resources that have been claimed through loading. */ public dispose(): void { this._onDispose.fire(); this._onDispose.dispose(); super.dispose(); } } /** * The editor options is the base class of options that can be passed in when opening an editor. */ export class EditorOptions implements IEditorOptions { /** * Helper to create EditorOptions inline. */ public static create(settings: IEditorOptions): EditorOptions { const options = new EditorOptions(); options.preserveFocus = settings.preserveFocus; options.forceOpen = settings.forceOpen; options.revealIfVisible = settings.revealIfVisible; options.pinned = settings.pinned; options.index = settings.index; options.inactive = settings.inactive; return options; } /** * Inherit all options from other EditorOptions instance. */ public mixin(other: IEditorOptions): void { if (other) { this.preserveFocus = other.preserveFocus; this.forceOpen = other.forceOpen; this.revealIfVisible = other.revealIfVisible; this.pinned = other.pinned; this.index = other.index; this.inactive = other.inactive; } } /** * Tells the editor to not receive keyboard focus when the editor is being opened. By default, * the editor will receive keyboard focus on open. */ public preserveFocus: boolean; /** * Tells the editor to replace the editor input in the editor even if it is identical to the one * already showing. By default, the editor will not replace the input if it is identical to the * one showing. */ public forceOpen: boolean; /** * Will reveal the editor if it is already opened and visible in any of the opened editor groups. */ public revealIfVisible: boolean; /** * An editor that is pinned remains in the editor stack even when another editor is being opened. * An editor that is not pinned will always get replaced by another editor that is not pinned. */ public pinned: boolean; /** * The index in the document stack where to insert the editor into when opening. */ public index: number; /** * An active editor that is opened will show its contents directly. Set to true to open an editor * in the background. */ public inactive: boolean; } /** * Base Text Editor Options. */ export class TextEditorOptions extends EditorOptions { protected startLineNumber: number; protected startColumn: number; protected endLineNumber: number; protected endColumn: number; private revealInCenterIfOutsideViewport: boolean; private editorViewState: IEditorViewState; private editorOptions: ICodeEditorOptions; public static from(input: IBaseResourceInput): TextEditorOptions { let options: TextEditorOptions = null; if (input && input.options) { if (input.options.selection || input.options.viewState || input.options.forceOpen || input.options.revealIfVisible || input.options.preserveFocus || input.options.pinned || input.options.inactive || typeof input.options.index === 'number') { options = new TextEditorOptions(); } if (input.options.selection) { const selection = input.options.selection; options.selection(selection.startLineNumber, selection.startColumn, selection.endLineNumber, selection.endColumn); } if (input.options.forceOpen) { options.forceOpen = true; } if (input.options.revealIfVisible) { options.revealIfVisible = true; } if (input.options.preserveFocus) { options.preserveFocus = true; } if (input.options.pinned) { options.pinned = true; } if (input.options.inactive) { options.inactive = true; } if (input.options.revealInCenterIfOutsideViewport) { options.revealInCenterIfOutsideViewport = true; } if (input.options.viewState) { options.editorViewState = input.options.viewState; } if (typeof input.options.index === 'number') { options.index = input.options.index; } } return options; } /** * Helper to create TextEditorOptions inline. */ public static create(settings: ITextEditorOptions): TextEditorOptions { const options = new TextEditorOptions(); options.preserveFocus = settings.preserveFocus; options.forceOpen = settings.forceOpen; options.revealIfVisible = settings.revealIfVisible; options.pinned = settings.pinned; options.index = settings.index; if (settings.selection) { options.startLineNumber = settings.selection.startLineNumber; options.startColumn = settings.selection.startColumn; options.endLineNumber = settings.selection.endLineNumber || settings.selection.startLineNumber; options.endColumn = settings.selection.endColumn || settings.selection.startColumn; } return options; } /** * Returns if this options object has objects defined for the editor. */ public hasOptionsDefined(): boolean { return !!this.editorViewState || (!types.isUndefinedOrNull(this.startLineNumber) && !types.isUndefinedOrNull(this.startColumn)); } /** * Tells the editor to set show the given selection when the editor is being opened. */ public selection(startLineNumber: number, startColumn: number, endLineNumber: number = startLineNumber, endColumn: number = startColumn): EditorOptions { this.startLineNumber = startLineNumber; this.startColumn = startColumn; this.endLineNumber = endLineNumber; this.endColumn = endColumn; return this; } /** * Sets the view state to be used when the editor is opening. */ public fromEditor(editor: IEditor): void { // View state this.editorViewState = editor.saveViewState(); // Selected editor options const codeEditor = <ICommonCodeEditor>editor; if (typeof codeEditor.getConfiguration === 'function') { const config = codeEditor.getConfiguration(); if (config && config.viewInfo && config.wrappingInfo) { this.editorOptions = Object.create(null); this.editorOptions.renderWhitespace = config.viewInfo.renderWhitespace; this.editorOptions.renderControlCharacters = config.viewInfo.renderControlCharacters; this.editorOptions.wordWrap = config.wrappingInfo.isViewportWrapping ? 'on' : 'off'; } } } /** * Apply the view state or selection to the given editor. * * @return if something was applied */ public apply(editor: IEditor): boolean { // Editor options if (this.editorOptions) { editor.updateOptions(this.editorOptions); } // View state return this.applyViewState(editor); } private applyViewState(editor: IEditor): boolean { let gotApplied = false; // First try viewstate if (this.editorViewState) { editor.restoreViewState(this.editorViewState); gotApplied = true; } // Otherwise check for selection else if (!types.isUndefinedOrNull(this.startLineNumber) && !types.isUndefinedOrNull(this.startColumn)) { // Select if (!types.isUndefinedOrNull(this.endLineNumber) && !types.isUndefinedOrNull(this.endColumn)) { const range = { startLineNumber: this.startLineNumber, startColumn: this.startColumn, endLineNumber: this.endLineNumber, endColumn: this.endColumn }; editor.setSelection(range); if (this.revealInCenterIfOutsideViewport) { editor.revealRangeInCenterIfOutsideViewport(range); } else { editor.revealRangeInCenter(range); } } // Reveal else { const pos = { lineNumber: this.startLineNumber, column: this.startColumn }; editor.setPosition(pos); if (this.revealInCenterIfOutsideViewport) { editor.revealPositionInCenterIfOutsideViewport(pos); } else { editor.revealPositionInCenter(pos); } } gotApplied = true; } return gotApplied; } } export interface ITextDiffEditorOptions extends ITextEditorOptions { /** * Whether to auto reveal the first change when the text editor is opened or not. By default * the first change will not be revealed. */ autoRevealFirstChange: boolean; } /** * Base Text Diff Editor Options. */ export class TextDiffEditorOptions extends TextEditorOptions { /** * Helper to create TextDiffEditorOptions inline. */ public static create(settings: ITextDiffEditorOptions): TextDiffEditorOptions { const options = new TextDiffEditorOptions(); options.autoRevealFirstChange = settings.autoRevealFirstChange; options.preserveFocus = settings.preserveFocus; options.forceOpen = settings.forceOpen; options.revealIfVisible = settings.revealIfVisible; options.pinned = settings.pinned; options.index = settings.index; if (settings.selection) { options.startLineNumber = settings.selection.startLineNumber; options.startColumn = settings.selection.startColumn; options.endLineNumber = settings.selection.endLineNumber || settings.selection.startLineNumber; options.endColumn = settings.selection.endColumn || settings.selection.startColumn; } return options; } /** * Whether to auto reveal the first change when the text editor is opened or not. By default * the first change will not be revealed. */ public autoRevealFirstChange: boolean; } /** * Helper to return all opened editors with resources not belonging to the currently opened workspace. */ export function getOutOfWorkspaceEditorResources(editorGroupService: IEditorGroupService, contextService: IWorkspaceContextService): URI[] { const resources: URI[] = []; editorGroupService.getStacksModel().groups.forEach(group => { const editors = group.getEditors(); editors.forEach(editor => { const fileResource = toResource(editor, { supportSideBySide: true, filter: 'file' }); if (fileResource && !contextService.isInsideWorkspace(fileResource)) { resources.push(fileResource); } }); }); return resources; } export interface IStacksModelChangeEvent { group: IEditorGroup; editor?: IEditorInput; structural?: boolean; } export interface IEditorStacksModel { onModelChanged: Event<IStacksModelChangeEvent>; onEditorClosed: Event<IGroupEvent>; groups: IEditorGroup[]; activeGroup: IEditorGroup; isActive(group: IEditorGroup): boolean; getGroup(id: GroupIdentifier): IEditorGroup; positionOfGroup(group: IEditorGroup): Position; groupAt(position: Position): IEditorGroup; next(jumpGroups: boolean): IEditorIdentifier; previous(jumpGroups: boolean): IEditorIdentifier; isOpen(editor: IEditorInput): boolean; isOpen(resource: URI): boolean; toString(): string; } export interface IEditorGroup { id: GroupIdentifier; label: string; count: number; activeEditor: IEditorInput; previewEditor: IEditorInput; getEditor(index: number): IEditorInput; getEditor(resource: URI): IEditorInput; indexOf(editor: IEditorInput): number; contains(editor: IEditorInput): boolean; contains(resource: URI): boolean; getEditors(mru?: boolean): IEditorInput[]; isActive(editor: IEditorInput): boolean; isPreview(editor: IEditorInput): boolean; isPinned(index: number): boolean; isPinned(editor: IEditorInput): boolean; } export interface IEditorIdentifier { group: IEditorGroup; editor: IEditorInput; } export interface IEditorContext extends IEditorIdentifier { event?: any; } export interface IGroupEvent { editor: IEditorInput; pinned: boolean; index: number; } export type GroupIdentifier = number; export const EditorOpenPositioning = { LEFT: 'left', RIGHT: 'right', FIRST: 'first', LAST: 'last' }; export interface IWorkbenchEditorConfiguration { workbench: { editor: { showTabs: boolean; tabCloseButton: 'left' | 'right' | 'off'; showIcons: boolean; enablePreview: boolean; enablePreviewFromQuickOpen: boolean; closeOnExternalFileDelete: boolean; openPositioning: 'left' | 'right' | 'first' | 'last'; revealIfOpen: boolean; } }; } export const ActiveEditorMovePositioning = { FIRST: 'first', LAST: 'last', LEFT: 'left', RIGHT: 'right', CENTER: 'center', POSITION: 'position', }; export const ActiveEditorMovePositioningBy = { TAB: 'tab', GROUP: 'group' }; export interface ActiveEditorMoveArguments { to?: string; by?: string; value?: number; } export const EditorCommands = { MoveActiveEditor: 'moveActiveEditor' }; export interface IResourceOptions { supportSideBySide?: boolean; filter?: 'file' | 'untitled' | ['file', 'untitled'] | ['untitled', 'file']; } export function hasResource(editor: IEditorInput, options?: IResourceOptions): boolean { return !!toResource(editor, options); } export function toResource(editor: IEditorInput, options?: IResourceOptions): URI { if (!editor) { return null; } // Check for side by side if we are asked to if (options && options.supportSideBySide && editor instanceof SideBySideEditorInput) { editor = editor.master; } const resource = doGetEditorResource(editor); if (!options || !options.filter) { return resource; // return early if no filter is specified } if (!resource) { return null; } let includeFiles: boolean; let includeUntitled: boolean; if (Array.isArray(options.filter)) { includeFiles = (options.filter.indexOf('file') >= 0); includeUntitled = (options.filter.indexOf('untitled') >= 0); } else { includeFiles = (options.filter === 'file'); includeUntitled = (options.filter === 'untitled'); } if (includeFiles && resource.scheme === 'file') { return resource; } if (includeUntitled && resource.scheme === 'untitled') { return resource; } return null; } // TODO@Ben every editor should have an associated resource function doGetEditorResource(editor: IEditorInput): URI { if (editor instanceof EditorInput && typeof (<any>editor).getResource === 'function') { const candidate = (<any>editor).getResource(); if (candidate instanceof URI) { return candidate; } } return null; }
src/vs/workbench/common/editor.ts
1
https://github.com/microsoft/vscode/commit/522c6e01711a50ab2c48e2efb11f837dce7ebab9
[ 0.9978893399238586, 0.03377673029899597, 0.0001623209100216627, 0.00017144651792477816, 0.17151185870170593 ]
{ "id": 5, "code_window": [ "\t\toptions.preserveFocus = settings.preserveFocus;\n", "\t\toptions.forceOpen = settings.forceOpen;\n", "\t\toptions.revealIfVisible = settings.revealIfVisible;\n", "\t\toptions.pinned = settings.pinned;\n", "\t\toptions.index = settings.index;\n", "\n", "\t\tif (settings.selection) {\n", "\t\t\toptions.startLineNumber = settings.selection.startLineNumber;\n", "\t\t\toptions.startColumn = settings.selection.startColumn;\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\toptions.inactive = settings.inactive;\n" ], "file_path": "src/vs/workbench/common/editor.ts", "type": "add", "edit_start_line_idx": 644 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "entryAriaLabel": "{0},檔案選擇器", "searchResults": "搜尋結果" }
i18n/cht/src/vs/workbench/parts/search/browser/openFileHandler.i18n.json
0
https://github.com/microsoft/vscode/commit/522c6e01711a50ab2c48e2efb11f837dce7ebab9
[ 0.00017184266471304, 0.00017184266471304, 0.00017184266471304, 0.00017184266471304, 0 ]
{ "id": 5, "code_window": [ "\t\toptions.preserveFocus = settings.preserveFocus;\n", "\t\toptions.forceOpen = settings.forceOpen;\n", "\t\toptions.revealIfVisible = settings.revealIfVisible;\n", "\t\toptions.pinned = settings.pinned;\n", "\t\toptions.index = settings.index;\n", "\n", "\t\tif (settings.selection) {\n", "\t\t\toptions.startLineNumber = settings.selection.startLineNumber;\n", "\t\t\toptions.startColumn = settings.selection.startColumn;\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\toptions.inactive = settings.inactive;\n" ], "file_path": "src/vs/workbench/common/editor.ts", "type": "add", "edit_start_line_idx": 644 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "evaluateMathExpression": "Emmet: Mathematischen Ausdruck auswerten" }
i18n/deu/src/vs/workbench/parts/emmet/node/actions/evaluateMath.i18n.json
0
https://github.com/microsoft/vscode/commit/522c6e01711a50ab2c48e2efb11f837dce7ebab9
[ 0.00017433575703762472, 0.00017433575703762472, 0.00017433575703762472, 0.00017433575703762472, 0 ]
{ "id": 5, "code_window": [ "\t\toptions.preserveFocus = settings.preserveFocus;\n", "\t\toptions.forceOpen = settings.forceOpen;\n", "\t\toptions.revealIfVisible = settings.revealIfVisible;\n", "\t\toptions.pinned = settings.pinned;\n", "\t\toptions.index = settings.index;\n", "\n", "\t\tif (settings.selection) {\n", "\t\t\toptions.startLineNumber = settings.selection.startLineNumber;\n", "\t\t\toptions.startColumn = settings.selection.startColumn;\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\toptions.inactive = settings.inactive;\n" ], "file_path": "src/vs/workbench/common/editor.ts", "type": "add", "edit_start_line_idx": 644 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "checkout": "체크 아웃...", "publish changes": "변경 내용 게시", "sync changes": "변경 내용 동기화", "syncing changes": "변경 내용을 동기화하는 중..." }
i18n/kor/extensions/git/out/statusbar.i18n.json
0
https://github.com/microsoft/vscode/commit/522c6e01711a50ab2c48e2efb11f837dce7ebab9
[ 0.00017240477609448135, 0.00017131143249571323, 0.0001702180743450299, 0.00017131143249571323, 0.0000010933508747257292 ]
{ "id": 6, "code_window": [ "\n", "\t/**\n", "\t * Moves an editor from one group to another. The index in the group is optional.\n", "\t */\n" ], "labels": [ "keep", "keep", "add", "keep" ], "after_edit": [ "\t * The inactive option is applied when moving across groups.\n" ], "file_path": "src/vs/workbench/services/group/common/groupService.ts", "type": "add", "edit_start_line_idx": 108 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import { createDecorator, ServiceIdentifier } from 'vs/platform/instantiation/common/instantiation'; import { Position, IEditorInput } from 'vs/platform/editor/common/editor'; import { IEditorStacksModel, IEditorGroup } from 'vs/workbench/common/editor'; import Event from 'vs/base/common/event'; export enum GroupArrangement { MINIMIZE_OTHERS, EVEN } export type GroupOrientation = 'vertical' | 'horizontal'; export const IEditorGroupService = createDecorator<IEditorGroupService>('editorGroupService'); export interface ITabOptions { showTabs?: boolean; tabCloseButton?: 'left' | 'right' | 'off'; showIcons?: boolean; previewEditors?: boolean; }; /** * The editor service allows to open editors and work on the active * editor input and models. */ export interface IEditorGroupService { _serviceBrand: ServiceIdentifier<any>; /** * Emitted when editors or inputs change. Examples: opening, closing of editors. Active editor change. */ onEditorsChanged: Event<void>; /** * Emitted when opening an editor fails. */ onEditorOpenFail: Event<IEditorInput>; /** * Emitted when a editors are moved to another position. */ onEditorsMoved: Event<void>; /** * Emitted when the editor group orientation was changed. */ onGroupOrientationChanged: Event<void>; /** * Emitted when tab options changed. */ onTabOptionsChanged: Event<ITabOptions>; /** * Keyboard focus the editor group at the provided position. */ focusGroup(group: IEditorGroup): void; focusGroup(position: Position): void; /** * Activate the editor group at the provided position without moving focus. */ activateGroup(group: IEditorGroup): void; activateGroup(position: Position): void; /** * Allows to move the editor group from one position to another. */ moveGroup(from: IEditorGroup, to: IEditorGroup): void; moveGroup(from: Position, to: Position): void; /** * Allows to arrange editor groups according to the GroupArrangement enumeration. */ arrangeGroups(arrangement: GroupArrangement): void; /** * Changes the editor group layout between vertical and horizontal orientation. Only applies * if more than one editor is opened. */ setGroupOrientation(orientation: GroupOrientation): void; /** * Returns the current editor group layout. */ getGroupOrientation(): GroupOrientation; /** * Adds the pinned state to an editor, removing it from being a preview editor. */ pinEditor(group: IEditorGroup, input: IEditorInput): void; pinEditor(position: Position, input: IEditorInput): void; /** * Removes the pinned state of an editor making it a preview editor. */ unpinEditor(group: IEditorGroup, input: IEditorInput): void; unpinEditor(position: Position, input: IEditorInput): void; /** * Moves an editor from one group to another. The index in the group is optional. */ moveEditor(input: IEditorInput, from: IEditorGroup, to: IEditorGroup, index?: number): void; moveEditor(input: IEditorInput, from: Position, to: Position, index?: number): void; /** * Provides access to the editor stacks model */ getStacksModel(): IEditorStacksModel; /** * Returns tab options. */ getTabOptions(): ITabOptions; }
src/vs/workbench/services/group/common/groupService.ts
1
https://github.com/microsoft/vscode/commit/522c6e01711a50ab2c48e2efb11f837dce7ebab9
[ 0.0018446064786985517, 0.00042426452273502946, 0.00016764570318628103, 0.00025816241395659745, 0.0004350011295173317 ]
{ "id": 6, "code_window": [ "\n", "\t/**\n", "\t * Moves an editor from one group to another. The index in the group is optional.\n", "\t */\n" ], "labels": [ "keep", "keep", "add", "keep" ], "after_edit": [ "\t * The inactive option is applied when moving across groups.\n" ], "file_path": "src/vs/workbench/services/group/common/groupService.ts", "type": "add", "edit_start_line_idx": 108 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import * as assert from 'assert'; import { Promise, TPromise } from 'vs/base/common/winjs.base'; import Async = require('vs/base/common/async'); suite('Async', () => { test('Throttler - non async', function (done) { let count = 0; let factory = () => { return TPromise.as(++count); }; let throttler = new Async.Throttler(); Promise.join([ throttler.queue(factory).then((result) => { assert.equal(result, 1); }), throttler.queue(factory).then((result) => { assert.equal(result, 2); }), throttler.queue(factory).then((result) => { assert.equal(result, 3); }), throttler.queue(factory).then((result) => { assert.equal(result, 4); }), throttler.queue(factory).then((result) => { assert.equal(result, 5); }) ]).done(() => done()); }); test('Throttler', function (done) { let count = 0; let factory = () => { return TPromise.timeout(0).then(() => { return ++count; }); }; let throttler = new Async.Throttler(); Promise.join([ throttler.queue(factory).then((result) => { assert.equal(result, 1); }), throttler.queue(factory).then((result) => { assert.equal(result, 2); }), throttler.queue(factory).then((result) => { assert.equal(result, 2); }), throttler.queue(factory).then((result) => { assert.equal(result, 2); }), throttler.queue(factory).then((result) => { assert.equal(result, 2); }) ]).done(() => { Promise.join([ throttler.queue(factory).then((result) => { assert.equal(result, 3); }), throttler.queue(factory).then((result) => { assert.equal(result, 4); }), throttler.queue(factory).then((result) => { assert.equal(result, 4); }), throttler.queue(factory).then((result) => { assert.equal(result, 4); }), throttler.queue(factory).then((result) => { assert.equal(result, 4); }) ]).done(() => done()); }); }); test('Throttler - cancel should not cancel other promises', function (done) { let count = 0; let factory = () => { return TPromise.timeout(0).then(() => { return ++count; }); }; let throttler = new Async.Throttler(); let p1: Promise; Promise.join([ p1 = throttler.queue(factory).then((result) => { assert(false, 'should not be here, 1'); }, () => { assert(true, 'yes, it was cancelled'); }), throttler.queue(factory).then((result) => { assert.equal(result, 1); }, () => { assert(false, 'should not be here, 2'); }), throttler.queue(factory).then((result) => { assert.equal(result, 1); }, () => { assert(false, 'should not be here, 3'); }), throttler.queue(factory).then((result) => { assert.equal(result, 1); }, () => { assert(false, 'should not be here, 4'); }) ]).done(() => done()); p1.cancel(); }); test('Throttler - cancel the first queued promise should not cancel other promises', function (done) { let count = 0; let factory = () => { return TPromise.timeout(0).then(() => { return ++count; }); }; let throttler = new Async.Throttler(); let p2: Promise; Promise.join([ throttler.queue(factory).then((result) => { assert.equal(result, 1); }, () => { assert(false, 'should not be here, 1'); }), p2 = throttler.queue(factory).then((result) => { assert(false, 'should not be here, 2'); }, () => { assert(true, 'yes, it was cancelled'); }), throttler.queue(factory).then((result) => { assert.equal(result, 2); }, () => { assert(false, 'should not be here, 3'); }), throttler.queue(factory).then((result) => { assert.equal(result, 2); }, () => { assert(false, 'should not be here, 4'); }) ]).done(() => done()); p2.cancel(); }); test('Throttler - cancel in the middle should not cancel other promises', function (done) { let count = 0; let factory = () => { return TPromise.timeout(0).then(() => { return ++count; }); }; let throttler = new Async.Throttler(); let p3: Promise; Promise.join([ throttler.queue(factory).then((result) => { assert.equal(result, 1); }, () => { assert(false, 'should not be here, 1'); }), throttler.queue(factory).then((result) => { assert.equal(result, 2); }, () => { assert(false, 'should not be here, 2'); }), p3 = throttler.queue(factory).then((result) => { assert(false, 'should not be here, 3'); }, () => { assert(true, 'yes, it was cancelled'); }), throttler.queue(factory).then((result) => { assert.equal(result, 2); }, () => { assert(false, 'should not be here, 4'); }) ]).done(() => done()); p3.cancel(); }); test('Throttler - last factory should be the one getting called', function (done) { let factoryFactory = (n: number) => () => { return TPromise.timeout(0).then(() => n); }; let throttler = new Async.Throttler(); let promises: Promise[] = []; promises.push(throttler.queue(factoryFactory(1)).then((n) => { assert.equal(n, 1); })); promises.push(throttler.queue(factoryFactory(2)).then((n) => { assert.equal(n, 3); })); promises.push(throttler.queue(factoryFactory(3)).then((n) => { assert.equal(n, 3); })); Promise.join(promises).done(() => done()); }); test('Throttler - progress should work', function (done) { let order = 0; let factory = () => new Promise((c, e, p) => { TPromise.timeout(0).done(() => { p(order++); c(true); }); }); let throttler = new Async.Throttler(); let promises: Promise[] = []; let progresses: any[][] = [[], [], []]; promises.push(throttler.queue(factory).then(null, null, (p) => progresses[0].push(p))); promises.push(throttler.queue(factory).then(null, null, (p) => progresses[1].push(p))); promises.push(throttler.queue(factory).then(null, null, (p) => progresses[2].push(p))); Promise.join(promises).done(() => { assert.deepEqual(progresses[0], [0]); assert.deepEqual(progresses[1], [0]); assert.deepEqual(progresses[2], [0]); done(); }); }); test('Delayer', function (done) { let count = 0; let factory = () => { return TPromise.as(++count); }; let delayer = new Async.Delayer(0); let promises: Promise[] = []; assert(!delayer.isTriggered()); promises.push(delayer.trigger(factory).then((result) => { assert.equal(result, 1); assert(!delayer.isTriggered()); })); assert(delayer.isTriggered()); promises.push(delayer.trigger(factory).then((result) => { assert.equal(result, 1); assert(!delayer.isTriggered()); })); assert(delayer.isTriggered()); promises.push(delayer.trigger(factory).then((result) => { assert.equal(result, 1); assert(!delayer.isTriggered()); })); assert(delayer.isTriggered()); Promise.join(promises).done(() => { assert(!delayer.isTriggered()); done(); }); }); test('Delayer - simple cancel', function (done) { let count = 0; let factory = () => { return TPromise.as(++count); }; let delayer = new Async.Delayer(0); assert(!delayer.isTriggered()); delayer.trigger(factory).then(() => { assert(false); }, () => { assert(true, 'yes, it was cancelled'); }).done(() => done()); assert(delayer.isTriggered()); delayer.cancel(); assert(!delayer.isTriggered()); }); test('Delayer - cancel should cancel all calls to trigger', function (done) { let count = 0; let factory = () => { return TPromise.as(++count); }; let delayer = new Async.Delayer(0); let promises: Promise[] = []; assert(!delayer.isTriggered()); promises.push(delayer.trigger(factory).then(null, () => { assert(true, 'yes, it was cancelled'); })); assert(delayer.isTriggered()); promises.push(delayer.trigger(factory).then(null, () => { assert(true, 'yes, it was cancelled'); })); assert(delayer.isTriggered()); promises.push(delayer.trigger(factory).then(null, () => { assert(true, 'yes, it was cancelled'); })); assert(delayer.isTriggered()); delayer.cancel(); Promise.join(promises).done(() => { assert(!delayer.isTriggered()); done(); }); }); test('Delayer - trigger, cancel, then trigger again', function (done) { let count = 0; let factory = () => { return TPromise.as(++count); }; let delayer = new Async.Delayer(0); let promises: Promise[] = []; assert(!delayer.isTriggered()); delayer.trigger(factory).then((result) => { assert.equal(result, 1); assert(!delayer.isTriggered()); promises.push(delayer.trigger(factory).then(null, () => { assert(true, 'yes, it was cancelled'); })); assert(delayer.isTriggered()); promises.push(delayer.trigger(factory).then(null, () => { assert(true, 'yes, it was cancelled'); })); assert(delayer.isTriggered()); delayer.cancel(); Promise.join(promises).then(() => { promises = []; assert(!delayer.isTriggered()); promises.push(delayer.trigger(factory).then(() => { assert.equal(result, 1); assert(!delayer.isTriggered()); })); assert(delayer.isTriggered()); promises.push(delayer.trigger(factory).then(() => { assert.equal(result, 1); assert(!delayer.isTriggered()); })); assert(delayer.isTriggered()); Promise.join(promises).then(() => { assert(!delayer.isTriggered()); done(); }); assert(delayer.isTriggered()); }); assert(delayer.isTriggered()); }); assert(delayer.isTriggered()); }); test('Delayer - last task should be the one getting called', function (done) { let factoryFactory = (n: number) => () => { return TPromise.as(n); }; let delayer = new Async.Delayer(0); let promises: Promise[] = []; assert(!delayer.isTriggered()); promises.push(delayer.trigger(factoryFactory(1)).then((n) => { assert.equal(n, 3); })); promises.push(delayer.trigger(factoryFactory(2)).then((n) => { assert.equal(n, 3); })); promises.push(delayer.trigger(factoryFactory(3)).then((n) => { assert.equal(n, 3); })); Promise.join(promises).then(() => { assert(!delayer.isTriggered()); done(); }); assert(delayer.isTriggered()); }); test('Delayer - progress should work', function (done) { let order = 0; let factory = () => new Promise((c, e, p) => { TPromise.timeout(0).done(() => { p(order++); c(true); }); }); let delayer = new Async.Delayer(0); let promises: Promise[] = []; let progresses: any[][] = [[], [], []]; promises.push(delayer.trigger(factory).then(null, null, (p) => progresses[0].push(p))); promises.push(delayer.trigger(factory).then(null, null, (p) => progresses[1].push(p))); promises.push(delayer.trigger(factory).then(null, null, (p) => progresses[2].push(p))); Promise.join(promises).done(() => { assert.deepEqual(progresses[0], [0]); assert.deepEqual(progresses[1], [0]); assert.deepEqual(progresses[2], [0]); done(); }); }); test('ThrottledDelayer - progress should work', function (done) { let order = 0; let factory = () => new Promise((c, e, p) => { TPromise.timeout(0).done(() => { p(order++); c(true); }); }); let delayer = new Async.ThrottledDelayer(0); let promises: Promise[] = []; let progresses: any[][] = [[], [], []]; promises.push(delayer.trigger(factory).then(null, null, (p) => progresses[0].push(p))); promises.push(delayer.trigger(factory).then(null, null, (p) => progresses[1].push(p))); promises.push(delayer.trigger(factory).then(null, null, (p) => progresses[2].push(p))); Promise.join(promises).done(() => { assert.deepEqual(progresses[0], [0]); assert.deepEqual(progresses[1], [0]); assert.deepEqual(progresses[2], [0]); done(); }); }); test('Sequence', function (done) { let factoryFactory = (n: number) => () => { return TPromise.as(n); }; Async.sequence([ factoryFactory(1), factoryFactory(2), factoryFactory(3), factoryFactory(4), factoryFactory(5), ]).then((result) => { assert.equal(5, result.length); assert.equal(1, result[0]); assert.equal(2, result[1]); assert.equal(3, result[2]); assert.equal(4, result[3]); assert.equal(5, result[4]); done(); }); }); test('Limiter - sync', function (done) { let factoryFactory = (n: number) => () => { return TPromise.as(n); }; let limiter = new Async.Limiter(1); let promises: Promise[] = []; [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].forEach(n => promises.push(limiter.queue(factoryFactory(n)))); Promise.join(promises).then((res) => { assert.equal(10, res.length); limiter = new Async.Limiter(100); promises = []; [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].forEach(n => promises.push(limiter.queue(factoryFactory(n)))); return Promise.join(promises).then((res) => { assert.equal(10, res.length); }); }).done(() => done()); }); test('Limiter - async', function (done) { let factoryFactory = (n: number) => () => { return TPromise.timeout(0).then(() => n); }; let limiter = new Async.Limiter(1); let promises: Promise[] = []; [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].forEach(n => promises.push(limiter.queue(factoryFactory(n)))); Promise.join(promises).then((res) => { assert.equal(10, res.length); limiter = new Async.Limiter(100); promises = []; [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].forEach(n => promises.push(limiter.queue(factoryFactory(n)))); Promise.join(promises).then((res) => { assert.equal(10, res.length); }); }).done(() => done()); }); test('Limiter - assert degree of paralellism', function (done) { let activePromises = 0; let factoryFactory = (n: number) => () => { activePromises++; assert(activePromises < 6); return TPromise.timeout(0).then(() => { activePromises--; return n; }); }; let limiter = new Async.Limiter(5); let promises: Promise[] = []; [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].forEach(n => promises.push(limiter.queue(factoryFactory(n)))); Promise.join(promises).then((res) => { assert.equal(10, res.length); assert.deepEqual([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], res); done(); }); }); test('Queue - simple', function (done) { let queue = new Async.Queue(); let syncPromise = false; let f1 = () => TPromise.as(true).then(() => syncPromise = true); let asyncPromise = false; let f2 = () => TPromise.timeout(10).then(() => asyncPromise = true); queue.queue(f1); queue.queue(f2).then(() => { assert.ok(syncPromise); assert.ok(asyncPromise); done(); }); }); test('Queue - order is kept', function (done) { let queue = new Async.Queue(); let res = []; let f1 = () => TPromise.as(true).then(() => res.push(1)); let f2 = () => TPromise.timeout(10).then(() => res.push(2)); let f3 = () => TPromise.as(true).then(() => res.push(3)); let f4 = () => TPromise.timeout(20).then(() => res.push(4)); let f5 = () => TPromise.timeout(0).then(() => res.push(5)); queue.queue(f1); queue.queue(f2); queue.queue(f3); queue.queue(f4); queue.queue(f5).then(() => { assert.equal(res[0], 1); assert.equal(res[1], 2); assert.equal(res[2], 3); assert.equal(res[3], 4); assert.equal(res[4], 5); done(); }); }); test('Queue - errors bubble individually but not cause stop', function (done) { let queue = new Async.Queue(); let res = []; let error = false; let f1 = () => TPromise.as(true).then(() => res.push(1)); let f2 = () => TPromise.timeout(10).then(() => res.push(2)); let f3 = () => TPromise.as(true).then(() => TPromise.wrapError('error')); let f4 = () => TPromise.timeout(20).then(() => res.push(4)); let f5 = () => TPromise.timeout(0).then(() => res.push(5)); queue.queue(f1); queue.queue(f2); queue.queue(f3).then(null, () => error = true); queue.queue(f4); queue.queue(f5).then(() => { assert.equal(res[0], 1); assert.equal(res[1], 2); assert.ok(error); assert.equal(res[2], 4); assert.equal(res[3], 5); done(); }); }); test('Queue - order is kept (chained)', function (done) { let queue = new Async.Queue(); let res = []; let f1 = () => TPromise.as(true).then(() => res.push(1)); let f2 = () => TPromise.timeout(10).then(() => res.push(2)); let f3 = () => TPromise.as(true).then(() => res.push(3)); let f4 = () => TPromise.timeout(20).then(() => res.push(4)); let f5 = () => TPromise.timeout(0).then(() => res.push(5)); queue.queue(f1).then(() => { queue.queue(f2).then(() => { queue.queue(f3).then(() => { queue.queue(f4).then(() => { queue.queue(f5).then(() => { assert.equal(res[0], 1); assert.equal(res[1], 2); assert.equal(res[2], 3); assert.equal(res[3], 4); assert.equal(res[4], 5); done(); }); }); }); }); }); }); test('Queue - events', function (done) { let queue = new Async.Queue(); let finished = false; queue.onFinished(() => { done(); }); let res = []; let f1 = () => TPromise.timeout(10).then(() => res.push(2)); let f2 = () => TPromise.timeout(20).then(() => res.push(4)); let f3 = () => TPromise.timeout(0).then(() => res.push(5)); const q1 = queue.queue(f1); const q2 = queue.queue(f2); queue.queue(f3); q1.then(() => { assert.ok(!finished); q2.then(() => { assert.ok(!finished); }); }); }); });
src/vs/base/test/common/async.test.ts
0
https://github.com/microsoft/vscode/commit/522c6e01711a50ab2c48e2efb11f837dce7ebab9
[ 0.0009025476756505668, 0.0001811372785596177, 0.0001648496399866417, 0.00016779803263489157, 0.000095591094577685 ]
{ "id": 6, "code_window": [ "\n", "\t/**\n", "\t * Moves an editor from one group to another. The index in the group is optional.\n", "\t */\n" ], "labels": [ "keep", "keep", "add", "keep" ], "after_edit": [ "\t * The inactive option is applied when moving across groups.\n" ], "file_path": "src/vs/workbench/services/group/common/groupService.ts", "type": "add", "edit_start_line_idx": 108 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "activityBarAriaLabel": "활성 뷰 전환기", "hideActivitBar": "작업 막대 숨기기" }
i18n/kor/src/vs/workbench/browser/parts/activitybar/activitybarPart.i18n.json
0
https://github.com/microsoft/vscode/commit/522c6e01711a50ab2c48e2efb11f837dce7ebab9
[ 0.0001682983711361885, 0.0001682983711361885, 0.0001682983711361885, 0.0001682983711361885, 0 ]
{ "id": 6, "code_window": [ "\n", "\t/**\n", "\t * Moves an editor from one group to another. The index in the group is optional.\n", "\t */\n" ], "labels": [ "keep", "keep", "add", "keep" ], "after_edit": [ "\t * The inactive option is applied when moving across groups.\n" ], "file_path": "src/vs/workbench/services/group/common/groupService.ts", "type": "add", "edit_start_line_idx": 108 }
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd" [ <!ENTITY ns_flows "http://ns.adobe.com/Flows/1.0/"> ]><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16"><polygon fill="#656565" points="10,2 7.414,2 8.414,3 9,3 9,3.586 9,4 9,4.414 9,6 12,6 12,13 4,13 4,8 3,8 3,14 13,14 13,5"/><polygon fill="#00539C" points="5,1 3,1 5,3 1,3 1,5 5,5 3,7 5,7 8,4"/></svg>
src/vs/workbench/parts/git/browser/media/OpenEditor.svg
0
https://github.com/microsoft/vscode/commit/522c6e01711a50ab2c48e2efb11f837dce7ebab9
[ 0.00016639521345496178, 0.00016639521345496178, 0.00016639521345496178, 0.00016639521345496178, 0 ]
{ "id": 7, "code_window": [ "\t */\n", "\tmoveEditor(input: IEditorInput, from: IEditorGroup, to: IEditorGroup, index?: number): void;\n", "\tmoveEditor(input: IEditorInput, from: Position, to: Position, index?: number): void;\n", "\n", "\t/**\n", "\t * Provides access to the editor stacks model\n", "\t */\n" ], "labels": [ "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tmoveEditor(input: IEditorInput, from: IEditorGroup, to: IEditorGroup, index?: number, inactive?: boolean): void;\n", "\tmoveEditor(input: IEditorInput, from: Position, to: Position, index?: number, inactive?: boolean): void;\n" ], "file_path": "src/vs/workbench/services/group/common/groupService.ts", "type": "replace", "edit_start_line_idx": 109 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import 'vs/css!./media/editorpart'; import 'vs/workbench/browser/parts/editor/editor.contribution'; import { TPromise } from 'vs/base/common/winjs.base'; import { Registry } from 'vs/platform/platform'; import { Dimension, Builder, $ } from 'vs/base/browser/builder'; import nls = require('vs/nls'); import strings = require('vs/base/common/strings'); import arrays = require('vs/base/common/arrays'); import types = require('vs/base/common/types'); import errors = require('vs/base/common/errors'); import * as objects from 'vs/base/common/objects'; import { getCodeEditor } from 'vs/editor/common/services/codeEditorService'; import { toErrorMessage } from 'vs/base/common/errorMessage'; import { Scope as MementoScope } from 'vs/workbench/common/memento'; import { Part } from 'vs/workbench/browser/part'; import { BaseEditor, EditorDescriptor } from 'vs/workbench/browser/parts/editor/baseEditor'; import { IEditorRegistry, Extensions as EditorExtensions, EditorInput, EditorOptions, ConfirmResult, IWorkbenchEditorConfiguration, IEditorDescriptor, TextEditorOptions, SideBySideEditorInput, TextCompareEditorVisible, TEXT_DIFF_EDITOR_ID } from 'vs/workbench/common/editor'; import { EditorGroupsControl, Rochade, IEditorGroupsControl, ProgressState } from 'vs/workbench/browser/parts/editor/editorGroupsControl'; import { WorkbenchProgressService } from 'vs/workbench/services/progress/browser/progressService'; import { IEditorGroupService, GroupOrientation, GroupArrangement, ITabOptions } from 'vs/workbench/services/group/common/groupService'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IEditorPart } from 'vs/workbench/services/editor/browser/editorService'; import { IPartService } from 'vs/workbench/services/part/common/partService'; import { Position, POSITIONS, Direction } from 'vs/platform/editor/common/editor'; import { IStorageService } from 'vs/platform/storage/common/storage'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection'; import { IMessageService, IMessageWithAction, Severity } from 'vs/platform/message/common/message'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IProgressService } from 'vs/platform/progress/common/progress'; import { EditorStacksModel, EditorGroup, EditorIdentifier, GroupEvent } from 'vs/workbench/common/editor/editorStacksModel'; import Event, { Emitter } from 'vs/base/common/event'; import { IContextKey, IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; class ProgressMonitor { constructor(private _token: number, private progressPromise: TPromise<void>) { } public get token(): number { return this._token; } public cancel(): void { this.progressPromise.cancel(); } } interface IEditorPartUIState { ratio: number[]; groupOrientation: GroupOrientation; } interface IEditorReplacement extends EditorIdentifier { group: EditorGroup; editor: EditorInput; replaceWith: EditorInput; options?: EditorOptions; } /** * The editor part is the container for editors in the workbench. Based on the editor input being opened, it asks the registered * editor for the given input to show the contents. The editor part supports up to 3 side-by-side editors. */ export class EditorPart extends Part implements IEditorPart, IEditorGroupService { public _serviceBrand: any; private static GROUP_LEFT = nls.localize('groupOneVertical', "Left"); private static GROUP_CENTER = nls.localize('groupTwoVertical', "Center"); private static GROUP_RIGHT = nls.localize('groupThreeVertical', "Right"); private static GROUP_TOP = nls.localize('groupOneHorizontal', "Top"); private static GROUP_MIDDLE = nls.localize('groupTwoHorizontal', "Center"); private static GROUP_BOTTOM = nls.localize('groupThreeHorizontal', "Bottom"); private static EDITOR_PART_UI_STATE_STORAGE_KEY = 'editorpart.uiState'; private dimension: Dimension; private editorGroupsControl: IEditorGroupsControl; private memento: any; private stacks: EditorStacksModel; private tabOptions: ITabOptions; private forceHideTabs: boolean; private doNotFireTabOptionsChanged: boolean; private revealIfOpen: boolean; private _onEditorsChanged: Emitter<void>; private _onEditorsMoved: Emitter<void>; private _onEditorOpenFail: Emitter<EditorInput>; private _onGroupOrientationChanged: Emitter<void>; private _onTabOptionsChanged: Emitter<ITabOptions>; private textCompareEditorVisible: IContextKey<boolean>; // The following data structures are partitioned into array of Position as provided by Services.POSITION array private visibleEditors: BaseEditor[]; private instantiatedEditors: BaseEditor[][]; private mapEditorInstantiationPromiseToEditor: { [editorId: string]: TPromise<BaseEditor>; }[]; private editorOpenToken: number[]; private pendingEditorInputsToClose: EditorIdentifier[]; private pendingEditorInputCloseTimeout: number; private onLayoutEmitter = new Emitter<Dimension>(); public onLayout = this.onLayoutEmitter.event; constructor( id: string, restoreFromStorage: boolean, @IMessageService private messageService: IMessageService, @ITelemetryService private telemetryService: ITelemetryService, @IStorageService private storageService: IStorageService, @IPartService private partService: IPartService, @IConfigurationService private configurationService: IConfigurationService, @IContextKeyService contextKeyService: IContextKeyService, @IInstantiationService private instantiationService: IInstantiationService ) { super(id, { hasTitle: false }); this._onEditorsChanged = new Emitter<void>(); this._onEditorsMoved = new Emitter<void>(); this._onEditorOpenFail = new Emitter<EditorInput>(); this._onGroupOrientationChanged = new Emitter<void>(); this._onTabOptionsChanged = new Emitter<ITabOptions>(); this.visibleEditors = []; this.editorOpenToken = arrays.fill(POSITIONS.length, () => 0); this.instantiatedEditors = arrays.fill(POSITIONS.length, () => []); this.mapEditorInstantiationPromiseToEditor = arrays.fill(POSITIONS.length, () => Object.create(null)); this.pendingEditorInputsToClose = []; this.pendingEditorInputCloseTimeout = null; this.stacks = this.instantiationService.createInstance(EditorStacksModel, restoreFromStorage); this.textCompareEditorVisible = TextCompareEditorVisible.bindTo(contextKeyService); const config = configurationService.getConfiguration<IWorkbenchEditorConfiguration>(); if (config && config.workbench && config.workbench.editor) { const editorConfig = config.workbench.editor; this.tabOptions = { previewEditors: editorConfig.enablePreview, showIcons: editorConfig.showIcons, showTabs: editorConfig.showTabs, tabCloseButton: editorConfig.tabCloseButton }; this.revealIfOpen = editorConfig.revealIfOpen; this.telemetryService.publicLog('workbenchEditorConfiguration', editorConfig); } else { this.tabOptions = { previewEditors: true, showIcons: false, showTabs: true, tabCloseButton: 'right' }; this.revealIfOpen = false; } this.registerListeners(); } private registerListeners(): void { this.toUnbind.push(this.stacks.onEditorDirty(identifier => this.onEditorDirty(identifier))); this.toUnbind.push(this.stacks.onEditorDisposed(identifier => this.onEditorDisposed(identifier))); this.toUnbind.push(this.stacks.onEditorOpened(identifier => this.onEditorOpened(identifier))); this.toUnbind.push(this.stacks.onEditorClosed(event => this.onEditorClosed(event))); this.toUnbind.push(this.configurationService.onDidUpdateConfiguration(e => this.onConfigurationUpdated(e.config))); } private onConfigurationUpdated(configuration: IWorkbenchEditorConfiguration): void { if (configuration && configuration.workbench && configuration.workbench.editor) { const editorConfig = configuration.workbench.editor; // Pin all preview editors of the user chose to disable preview const newPreviewEditors = editorConfig.enablePreview; if (this.tabOptions.previewEditors !== newPreviewEditors && !newPreviewEditors) { this.stacks.groups.forEach(group => { if (group.previewEditor) { this.pinEditor(group, group.previewEditor); } }); } const oldTabOptions = objects.clone(this.tabOptions); this.tabOptions = { previewEditors: newPreviewEditors, showIcons: editorConfig.showIcons, tabCloseButton: editorConfig.tabCloseButton, showTabs: this.forceHideTabs ? false : editorConfig.showTabs }; if (!this.doNotFireTabOptionsChanged && !objects.equals(oldTabOptions, this.tabOptions)) { this._onTabOptionsChanged.fire(this.tabOptions); } this.revealIfOpen = editorConfig.revealIfOpen; } } private onEditorDirty(identifier: EditorIdentifier): void { // we pin every editor that becomes dirty this.pinEditor(identifier.group, identifier.editor); } private onEditorDisposed(identifier: EditorIdentifier): void { this.pendingEditorInputsToClose.push(identifier); this.startDelayedCloseEditorsFromInputDispose(); } private onEditorOpened(identifier: EditorIdentifier): void { this.telemetryService.publicLog('editorOpened', identifier.editor.getTelemetryDescriptor()); } private onEditorClosed(event: GroupEvent): void { this.telemetryService.publicLog('editorClosed', event.editor.getTelemetryDescriptor()); } public hideTabs(forceHide: boolean): void { this.forceHideTabs = forceHide; const config = this.configurationService.getConfiguration<IWorkbenchEditorConfiguration>(); this.tabOptions.showTabs = forceHide ? false : config && config.workbench && config.workbench.editor && config.workbench.editor.showTabs; this._onTabOptionsChanged.fire(this.tabOptions); } public get onEditorsChanged(): Event<void> { return this._onEditorsChanged.event; } public get onEditorsMoved(): Event<void> { return this._onEditorsMoved.event; } public get onEditorOpenFail(): Event<EditorInput> { return this._onEditorOpenFail.event; } public get onGroupOrientationChanged(): Event<void> { return this._onGroupOrientationChanged.event; } public get onTabOptionsChanged(): Event<ITabOptions> { return this._onTabOptionsChanged.event; } public getTabOptions(): ITabOptions { return this.tabOptions; } public openEditor(input: EditorInput, options?: EditorOptions, sideBySide?: boolean): TPromise<BaseEditor>; public openEditor(input: EditorInput, options?: EditorOptions, position?: Position, ratio?: number[]): TPromise<BaseEditor>; public openEditor(input: EditorInput, options?: EditorOptions, arg3?: any, ratio?: number[]): TPromise<BaseEditor> { // Normalize some values if (!options) { options = null; } // Determine position to open editor in (one, two, three) const position = this.findPosition(input, options, arg3, ratio); // Some conditions under which we prevent the request if ( !input || // no input position === null || // invalid position Object.keys(this.mapEditorInstantiationPromiseToEditor[position]).length > 0 || // pending editor load !this.editorGroupsControl || // too early this.editorGroupsControl.isDragging() // pending editor DND ) { return TPromise.as<BaseEditor>(null); } // We need an editor descriptor for the input const descriptor = Registry.as<IEditorRegistry>(EditorExtensions.Editors).getEditor(input); if (!descriptor) { return TPromise.wrapError(new Error(strings.format('Can not find a registered editor for the input {0}', input))); } // Opened to the side if (position !== Position.ONE) { this.telemetryService.publicLog('workbenchSideEditorOpened', { position: position }); } // Open through UI return this.doOpenEditor(position, descriptor, input, options, ratio); } private doOpenEditor(position: Position, descriptor: IEditorDescriptor, input: EditorInput, options: EditorOptions, ratio: number[]): TPromise<BaseEditor> { // Update stacks: We do this early on before the UI is there because we want our stacks model to have // a consistent view of the editor world and updating it later async after the UI is there will cause // issues (e.g. when a closeEditor call is made that expects the openEditor call to have updated the // stacks model). // This can however cause a race condition where the stacks model indicates the opened editor is there // while the UI is not yet ready. Clients have to deal with this fact and we have to make sure that the // stacks model gets updated if any of the UI updating fails with an error. const group = this.ensureGroup(position, !options || !options.preserveFocus); const pinned = !this.tabOptions.previewEditors || (options && (options.pinned || typeof options.index === 'number')) || input.isDirty(); const active = (group.count === 0) || !options || !options.inactive; group.openEditor(input, { active, pinned, index: options && options.index }); // Return early if the editor is to be open inactive and there are other editors in this group to show if (!active) { return TPromise.as<BaseEditor>(null); } // Progress Monitor & Ref Counting this.editorOpenToken[position]++; const editorOpenToken = this.editorOpenToken[position]; const monitor = new ProgressMonitor(editorOpenToken, TPromise.timeout(this.partService.isCreated() ? 800 : 3200 /* less ugly initial startup */).then(() => { const position = this.stacks.positionOfGroup(group); // might have changed due to a rochade meanwhile if (editorOpenToken === this.editorOpenToken[position]) { this.editorGroupsControl.updateProgress(position, ProgressState.INFINITE); } })); // Show editor return this.doShowEditor(group, descriptor, input, options, ratio, monitor).then(editor => { if (!editor) { return TPromise.as<BaseEditor>(null); // canceled or other error } // Set input to editor return this.doSetInput(group, editor, input, options, monitor); }); } private doShowEditor(group: EditorGroup, descriptor: IEditorDescriptor, input: EditorInput, options: EditorOptions, ratio: number[], monitor: ProgressMonitor): TPromise<BaseEditor> { const position = this.stacks.positionOfGroup(group); const editorAtPosition = this.visibleEditors[position]; // Return early if the currently visible editor can handle the input if (editorAtPosition && descriptor.describes(editorAtPosition)) { return TPromise.as(editorAtPosition); } // Hide active one first if (editorAtPosition) { this.doHideEditor(position, false); } // Create Editor return this.doCreateEditor(group, descriptor, monitor).then(editor => { const position = this.stacks.positionOfGroup(group); // might have changed due to a rochade meanwhile // Make sure that the user meanwhile did not open another editor or something went wrong if (!editor || !this.visibleEditors[position] || editor.getId() !== this.visibleEditors[position].getId()) { monitor.cancel(); return null; } // Show in side by side control this.editorGroupsControl.show(editor, position, options && options.preserveFocus, ratio); // Indicate to editor that it is now visible editor.setVisible(true, position); // Update text compare editor visible context this.updateTextCompareEditorVisible(); // Make sure the editor is layed out this.editorGroupsControl.layout(position); return editor; }, e => this.messageService.show(Severity.Error, types.isString(e) ? new Error(e) : e)); } private doCreateEditor(group: EditorGroup, descriptor: IEditorDescriptor, monitor: ProgressMonitor): TPromise<BaseEditor> { // Instantiate editor return this.doInstantiateEditor(group, descriptor).then(editor => { const position = this.stacks.positionOfGroup(group); // might have changed due to a rochade meanwhile // Make sure that the user meanwhile did not open another editor if (monitor.token !== this.editorOpenToken[position]) { monitor.cancel(); return null; } // Remember Editor at position this.visibleEditors[position] = editor; // Create editor as needed if (!editor.getContainer()) { editor.create($().div({ 'class': 'editor-container', 'role': 'tabpanel', id: descriptor.getId() })); } return editor; }); } private doInstantiateEditor(group: EditorGroup, descriptor: IEditorDescriptor): TPromise<BaseEditor> { const position = this.stacks.positionOfGroup(group); // Return early if already instantiated const instantiatedEditor = this.instantiatedEditors[position].filter(e => descriptor.describes(e))[0]; if (instantiatedEditor) { return TPromise.as(instantiatedEditor); } // Return early if editor is being instantiated at the same time from a previous call const pendingEditorInstantiate = this.mapEditorInstantiationPromiseToEditor[position][descriptor.getId()]; if (pendingEditorInstantiate) { return pendingEditorInstantiate; } // Otherwise instantiate const progressService = this.instantiationService.createInstance(WorkbenchProgressService, this.editorGroupsControl.getProgressBar(position), descriptor.getId(), true); const editorInstantiationService = this.editorGroupsControl.getInstantiationService(position).createChild(new ServiceCollection([IProgressService, progressService])); let loaded = false; const onInstantiate = (arg: BaseEditor | Error): TPromise<BaseEditor | Error> => { const position = this.stacks.positionOfGroup(group); // might have changed due to a rochade meanwhile loaded = true; delete this.mapEditorInstantiationPromiseToEditor[position][descriptor.getId()]; if (arg instanceof BaseEditor) { this.instantiatedEditors[position].push(arg); return TPromise.as(arg); } return TPromise.wrapError(arg); }; const instantiateEditorPromise = editorInstantiationService.createInstance(<EditorDescriptor>descriptor).then(onInstantiate, onInstantiate); if (!loaded) { this.mapEditorInstantiationPromiseToEditor[position][descriptor.getId()] = instantiateEditorPromise; } return instantiateEditorPromise.then(result => { progressService.dispose(); return result; }); } private doSetInput(group: EditorGroup, editor: BaseEditor, input: EditorInput, options: EditorOptions, monitor: ProgressMonitor): TPromise<BaseEditor> { // Emit Input-Changed Event as appropiate const previousInput = editor.input; const inputChanged = (!previousInput || !previousInput.matches(input) || (options && options.forceOpen)); // Call into Editor return editor.setInput(input, options).then(() => { // Stop loading promise if any monitor.cancel(); const position = this.stacks.positionOfGroup(group); // might have changed due to a rochade meanwhile if (position === -1) { return null; // in theory a call to editor.setInput() could have resulted in the editor being closed due to an error, so we guard against it here } // Focus (unless prevented) const focus = !options || !options.preserveFocus; if (focus) { editor.focus(); } // Progress Done this.editorGroupsControl.updateProgress(position, ProgressState.DONE); // Emit Change Event (if input changed) if (inputChanged) { this._onEditorsChanged.fire(); } // Fullfill promise with Editor that is being used return editor; }, e => this.doHandleSetInputError(e, group, editor, input, options, monitor)); } private doHandleSetInputError(e: Error | IMessageWithAction, group: EditorGroup, editor: BaseEditor, input: EditorInput, options: EditorOptions, monitor: ProgressMonitor): void { const position = this.stacks.positionOfGroup(group); // Stop loading promise if any monitor.cancel(); // Report error only if this was not us restoring previous error state if (this.partService.isCreated() && !errors.isPromiseCanceledError(e)) { const errorMessage = nls.localize('editorOpenError', "Unable to open '{0}': {1}.", input.getName(), toErrorMessage(e)); let error: any; if (e && (<IMessageWithAction>e).actions && (<IMessageWithAction>e).actions.length) { error = errors.create(errorMessage, { actions: (<IMessageWithAction>e).actions }); // Support error actions from thrower } else { error = errorMessage; } this.messageService.show(Severity.Error, types.isString(error) ? new Error(error) : error); } this.editorGroupsControl.updateProgress(position, ProgressState.DONE); // Event this._onEditorOpenFail.fire(input); // Recover by closing the active editor (if the input is still the active one) if (group.activeEditor === input) { this.doCloseActiveEditor(group); } } public closeEditor(position: Position, input: EditorInput): TPromise<void> { const group = this.stacks.groupAt(position); if (!group) { return TPromise.as<void>(null); } // Check for dirty and veto return this.handleDirty([{ group, editor: input }], true /* ignore if opened in other group */).then(veto => { if (veto) { return; } // Do close this.doCloseEditor(group, input); }); } private doCloseEditor(group: EditorGroup, input: EditorInput, focusNext = this.stacks.isActive(group)): void { // Closing the active editor of the group is a bit more work if (group.activeEditor && group.activeEditor.matches(input)) { this.doCloseActiveEditor(group, focusNext); } // Closing inactive editor is just a model update else { this.doCloseInactiveEditor(group, input); } } private doCloseActiveEditor(group: EditorGroup, focusNext = true): void { const position = this.stacks.positionOfGroup(group); // Update stacks model group.closeEditor(group.activeEditor); // Close group is this is the last editor in group if (group.count === 0) { this.doCloseGroup(group, focusNext); } // Otherwise open next active else { this.openEditor(group.activeEditor, !focusNext ? EditorOptions.create({ preserveFocus: true }) : null, position).done(null, errors.onUnexpectedError); } } private doCloseInactiveEditor(group: EditorGroup, input: EditorInput): void { // Closing inactive editor is just a model update group.closeEditor(input); } private doCloseGroup(group: EditorGroup, focusNext = true): void { const position = this.stacks.positionOfGroup(group); // Update stacks model this.modifyGroups(() => this.stacks.closeGroup(group)); // Hide Editor this.doHideEditor(position, true); // Emit Change Event this._onEditorsChanged.fire(); // Focus next group if we have an active one left const currentActiveGroup = this.stacks.activeGroup; if (currentActiveGroup) { if (focusNext) { this.focusGroup(currentActiveGroup); } else { this.activateGroup(currentActiveGroup); } // Explicitly trigger the focus changed handler because the side by side control will not trigger it unless // the user is actively changing focus with the mouse from left/top to right/bottom. this.onGroupFocusChanged(); } } private doHideEditor(position: Position, layoutAndRochade: boolean): void { const editor = this.visibleEditors[position]; // Hide in side by side control const rochade = this.editorGroupsControl.hide(editor, position, layoutAndRochade); // Clear any running Progress this.editorGroupsControl.updateProgress(position, ProgressState.STOP); // Indicate to Editor editor.clearInput(); editor.setVisible(false); // Update text compare editor visible context this.updateTextCompareEditorVisible(); // Clear active editor this.visibleEditors[position] = null; // Rochade as needed this.rochade(rochade); // Emit Editor move event if (rochade !== Rochade.NONE) { this._onEditorsMoved.fire(); } } private updateTextCompareEditorVisible(): void { this.textCompareEditorVisible.set(this.visibleEditors.some(e => e && e.isVisible() && e.getId() === TEXT_DIFF_EDITOR_ID)); } public closeAllEditors(except?: Position): TPromise<void> { let groups = this.stacks.groups.reverse(); // start from the end to prevent layout to happen through rochade // Remove position to exclude if we have any if (typeof except === 'number') { groups = groups.filter(group => this.stacks.positionOfGroup(group) !== except); } // Check for dirty and veto const editorsToClose = arrays.flatten(groups.map(group => group.getEditors().map(editor => { return { group, editor }; }))); return this.handleDirty(editorsToClose).then(veto => { if (veto) { return; } groups.forEach(group => this.doCloseEditors(group)); }); } public closeEditors(position: Position, except?: EditorInput, direction?: Direction): TPromise<void> { const group = this.stacks.groupAt(position); if (!group) { return TPromise.as<void>(null); } // Check for dirty and veto let editorsToClose: EditorInput[]; if (types.isUndefinedOrNull(direction)) { editorsToClose = group.getEditors().filter(e => !except || !e.matches(except)); } else { editorsToClose = (direction === Direction.LEFT) ? group.getEditors().slice(0, group.indexOf(except)) : group.getEditors().slice(group.indexOf(except) + 1); } return this.handleDirty(editorsToClose.map(editor => { return { group, editor }; }), true /* ignore if opened in other group */).then(veto => { if (veto) { return; } this.doCloseEditors(group, except, direction); }); } private doCloseEditors(group: EditorGroup, except?: EditorInput, direction?: Direction): void { // Close all editors in group if (!except) { // Update stacks model: remove all non active editors first to prevent opening the next editor in group group.closeEditors(group.activeEditor); // Now close active editor in group which will close the group this.doCloseActiveEditor(group); } // Close all editors in group except active one else if (except.matches(group.activeEditor)) { // Update stacks model: close non active editors supporting the direction group.closeEditors(group.activeEditor, direction); } // Finally: we are asked to close editors around a non-active editor // Thus we make the non-active one active and then close the others else { this.openEditor(except, null, this.stacks.positionOfGroup(group)).done(() => { // since the opening might have failed, we have to check again for the active editor // being the expected one, otherwise we end up in an endless loop trying to open the // editor if (except.matches(group.activeEditor)) { this.doCloseEditors(group, except, direction); } }, errors.onUnexpectedError); } } private handleDirty(identifiers: EditorIdentifier[], ignoreIfOpenedInOtherGroup?: boolean): TPromise<boolean /* veto */> { if (!identifiers.length) { return TPromise.as(false); // no veto } return this.doHandleDirty(identifiers.shift(), ignoreIfOpenedInOtherGroup).then(veto => { if (veto) { return veto; } return this.handleDirty(identifiers, ignoreIfOpenedInOtherGroup); }); } private doHandleDirty(identifier: EditorIdentifier, ignoreIfOpenedInOtherGroup?: boolean): TPromise<boolean /* veto */> { if (!identifier || !identifier.editor || !identifier.editor.isDirty() || (ignoreIfOpenedInOtherGroup && this.countEditors(identifier.editor) > 1 /* allow to close a dirty editor if it is opened in another group */)) { return TPromise.as(false); // no veto } const { editor } = identifier; const res = editor.confirmSave(); switch (res) { case ConfirmResult.SAVE: return editor.save().then(ok => !ok); case ConfirmResult.DONT_SAVE: return editor.revert().then(ok => !ok); case ConfirmResult.CANCEL: return TPromise.as(true); // veto } } private countEditors(editor: EditorInput): number { const editors = [editor]; if (editor instanceof SideBySideEditorInput) { editors.push(editor.master); } return editors.reduce((prev, e) => prev += this.stacks.count(e), 0); } public getStacksModel(): EditorStacksModel { return this.stacks; } public getActiveEditorInput(): EditorInput { const lastActiveEditor = this.getActiveEditor(); return lastActiveEditor ? lastActiveEditor.input : null; } public getActiveEditor(): BaseEditor { if (!this.editorGroupsControl) { return null; // too early } return this.editorGroupsControl.getActiveEditor(); } public getVisibleEditors(): BaseEditor[] { return this.visibleEditors ? this.visibleEditors.filter(editor => !!editor) : []; } public moveGroup(from: EditorGroup, to: EditorGroup): void; public moveGroup(from: Position, to: Position): void; public moveGroup(arg1: any, arg2: any): void { const fromGroup = (typeof arg1 === 'number') ? this.stacks.groupAt(arg1) : arg1; const toGroup = (typeof arg2 === 'number') ? this.stacks.groupAt(arg2) : arg2; if (!fromGroup || !toGroup || fromGroup === toGroup) { return; // Ignore if we cannot move } const fromPosition = this.stacks.positionOfGroup(fromGroup); const toPosition = this.stacks.positionOfGroup(toGroup); // Update stacks model this.modifyGroups(() => this.stacks.moveGroup(fromGroup, toPosition)); // Move widgets this.editorGroupsControl.move(fromPosition, toPosition); // Move data structures arrays.move(this.visibleEditors, fromPosition, toPosition); arrays.move(this.editorOpenToken, fromPosition, toPosition); arrays.move(this.mapEditorInstantiationPromiseToEditor, fromPosition, toPosition); arrays.move(this.instantiatedEditors, fromPosition, toPosition); // Restore focus this.focusGroup(fromGroup); // Events this._onEditorsMoved.fire(); } public moveEditor(input: EditorInput, from: EditorGroup, to: EditorGroup, index?: number): void; public moveEditor(input: EditorInput, from: Position, to: Position, index?: number): void; public moveEditor(input: EditorInput, arg2: any, arg3: any, index?: number): void { const fromGroup = (typeof arg2 === 'number') ? this.stacks.groupAt(arg2) : arg2; if (!fromGroup) { return; } // Move within group if (arg2 === arg3) { this.doMoveEditorInsideGroups(input, fromGroup, index); } // Move across groups else { const toPosition = (typeof arg3 === 'number') ? arg3 : this.stacks.positionOfGroup(arg3); this.doMoveEditorAcrossGroups(input, fromGroup, toPosition, index); } } private doMoveEditorInsideGroups(input: EditorInput, group: EditorGroup, toIndex: number): void { if (typeof toIndex !== 'number') { return; // do nothing if we move into same group without index } const currentIndex = group.indexOf(input); if (currentIndex === toIndex) { return; // do nothing if editor is already at the given index } // Update stacks model group.moveEditor(input, toIndex); group.pin(input); } private doMoveEditorAcrossGroups(input: EditorInput, fromGroup: EditorGroup, to: Position, index?: number): void { if (fromGroup.count === 1) { const toGroup = this.stacks.groupAt(to); if (!toGroup && this.stacks.positionOfGroup(fromGroup) < to) { return; // do nothing if the group to move only has one editor and is the last group already } } // When moving an editor, try to preserve as much view state as possible by checking // for th editor to be a text editor and creating the options accordingly if so let options = EditorOptions.create({ pinned: true, index }); const activeEditor = this.getActiveEditor(); const codeEditor = getCodeEditor(activeEditor); if (codeEditor && activeEditor.position === this.stacks.positionOfGroup(fromGroup) && input.matches(activeEditor.input)) { options = TextEditorOptions.create({ pinned: true, index }); (<TextEditorOptions>options).fromEditor(codeEditor); } // A move to another group is an open first... this.openEditor(input, options, to).done(null, errors.onUnexpectedError); // and a close afterwards... this.doCloseEditor(fromGroup, input, false /* do not activate next one behind if any */); } public arrangeGroups(arrangement: GroupArrangement): void { this.editorGroupsControl.arrangeGroups(arrangement); } public setGroupOrientation(orientation: GroupOrientation): void { this.editorGroupsControl.setGroupOrientation(orientation); this._onGroupOrientationChanged.fire(); // Rename groups when layout changes this.renameGroups(); } public getGroupOrientation(): GroupOrientation { return this.editorGroupsControl.getGroupOrientation(); } public createContentArea(parent: Builder): Builder { // Content Container const contentArea = $(parent) .div() .addClass('content'); // get settings this.memento = this.getMemento(this.storageService, MementoScope.WORKSPACE); // Side by Side Control const editorPartState: IEditorPartUIState = this.memento[EditorPart.EDITOR_PART_UI_STATE_STORAGE_KEY]; this.editorGroupsControl = this.instantiationService.createInstance(EditorGroupsControl, contentArea, editorPartState && editorPartState.groupOrientation); this.toUnbind.push(this.editorGroupsControl.onGroupFocusChanged(() => this.onGroupFocusChanged())); return contentArea; } private onGroupFocusChanged(): void { // Update stacks model const activePosition = this.editorGroupsControl.getActivePosition(); if (typeof activePosition === 'number') { this.stacks.setActive(this.stacks.groupAt(activePosition)); } // Emit as change event so that clients get aware of new active editor const activeEditor = this.editorGroupsControl.getActiveEditor(); if (activeEditor) { this._onEditorsChanged.fire(); } } public replaceEditors(editors: { toReplace: EditorInput, replaceWith: EditorInput, options?: EditorOptions }[], position?: Position): TPromise<BaseEditor[]> { const activeReplacements: IEditorReplacement[] = []; const hiddenReplacements: IEditorReplacement[] = []; // Find editors across groups to close editors.forEach(editor => { if (editor.toReplace.isDirty()) { return; // we do not handle dirty in this method, so ignore all dirty } // For each group this.stacks.groups.forEach(group => { if (position === void 0 || this.stacks.positionOfGroup(group) === position) { const index = group.indexOf(editor.toReplace); if (index >= 0) { if (editor.options) { editor.options.index = index; // make sure we respect the index of the editor to replace! } else { editor.options = EditorOptions.create({ index }); } const replacement = { group, editor: editor.toReplace, replaceWith: editor.replaceWith, options: editor.options }; if (group.activeEditor.matches(editor.toReplace)) { activeReplacements.push(replacement); } else { hiddenReplacements.push(replacement); } } } }); }); // Deal with hidden replacements first hiddenReplacements.forEach(replacement => { const group = replacement.group; group.openEditor(replacement.replaceWith, { active: false, pinned: true, index: replacement.options.index }); group.closeEditor(replacement.editor); }); // Now deal with active editors to be opened const res = this.openEditors(activeReplacements.map(replacement => { const group = replacement.group; return { input: replacement.replaceWith, position: this.stacks.positionOfGroup(group), options: replacement.options }; })); // Close active editors to be replaced now (they are no longer active) activeReplacements.forEach(replacement => { this.doCloseEditor(replacement.group, replacement.editor, false); }); return res; } public openEditors(editors: { input: EditorInput, position: Position, options?: EditorOptions }[]): TPromise<BaseEditor[]> { if (!editors.length) { return TPromise.as<BaseEditor[]>([]); } let activePosition: Position; if (this.stacks.activeGroup) { activePosition = this.stacks.positionOfGroup(this.stacks.activeGroup); } const ratio = this.editorGroupsControl.getRatio(); return this.doOpenEditors(editors, activePosition, ratio); } public restoreEditors(): TPromise<BaseEditor[]> { const editors = this.stacks.groups.map((group, index) => { return { input: group.activeEditor, position: index, options: group.isPinned(group.activeEditor) ? EditorOptions.create({ pinned: true }) : void 0 }; }); if (!editors.length) { return TPromise.as<BaseEditor[]>([]); } let activePosition: Position; if (this.stacks.groups.length) { activePosition = this.stacks.positionOfGroup(this.stacks.activeGroup); } const editorState: IEditorPartUIState = this.memento[EditorPart.EDITOR_PART_UI_STATE_STORAGE_KEY]; return this.doOpenEditors(editors, activePosition, editorState && editorState.ratio); } private doOpenEditors(editors: { input: EditorInput, position: Position, options?: EditorOptions }[], activePosition?: number, ratio?: number[]): TPromise<BaseEditor[]> { const positionOneEditors = editors.filter(e => e.position === Position.ONE); const positionTwoEditors = editors.filter(e => e.position === Position.TWO); const positionThreeEditors = editors.filter(e => e.position === Position.THREE); const groupOne = this.stacks.groupAt(Position.ONE); const groupTwo = this.stacks.groupAt(Position.TWO); const groupThree = this.stacks.groupAt(Position.THREE); // Compute the imaginary count if we const all editors open as the way requested const oneCount = positionOneEditors.length + (groupOne ? groupOne.count : 0); const twoCount = positionTwoEditors.length + (groupTwo ? groupTwo.count : 0); const threeCount = positionThreeEditors.length + (groupThree ? groupThree.count : 0); // Validate we do not produce empty groups given our imaginary count model if ((!oneCount && (twoCount || threeCount) || (!twoCount && threeCount))) { positionOneEditors.push(...positionTwoEditors); positionOneEditors.push(...positionThreeEditors); positionTwoEditors.splice(0, positionTwoEditors.length); positionThreeEditors.splice(0, positionThreeEditors.length); } // Validate active input if (typeof activePosition !== 'number') { activePosition = Position.ONE; } // Validate ratios const positions = positionThreeEditors.length ? 3 : positionTwoEditors.length ? 2 : 1; if (!ratio || ratio.length !== positions) { if (!this.getVisibleEditors().length) { ratio = (positions === 3) ? [0.33, 0.33, 0.34] : (positions === 2) ? [0.5, 0.5] : [1]; } else { ratio = void 0; } } let focusGroup = false; const activeGroup = this.stacks.groupAt(activePosition); if (!this.stacks.activeGroup || !activeGroup) { focusGroup = true; // always focus group if this is the first group or we are about to open a new group } else { focusGroup = editors.some(e => !e.options || (!e.options.inactive && !e.options.preserveFocus)); // only focus if the editors to open are not opening as inactive or preserveFocus } // Open each input respecting the options. Since there can only be one active editor in each // position, we have to pick the first input from each position and add the others as inactive const promises: TPromise<BaseEditor>[] = []; [positionOneEditors.shift(), positionTwoEditors.shift(), positionThreeEditors.shift()].forEach((editor, position) => { if (!editor) { return; // unused position } const input = editor.input; // Resolve editor options const preserveFocus = (activePosition !== position); let options: EditorOptions; if (editor.options) { options = editor.options; if (typeof options.preserveFocus !== 'boolean') { options.preserveFocus = preserveFocus; } } else { options = EditorOptions.create({ preserveFocus }); } promises.push(this.openEditor(input, options, position, ratio)); }); return TPromise.join(promises).then(editors => { // Adjust focus as needed if (focusGroup) { this.focusGroup(activePosition); } // Update stacks model for remaining inactive editors [positionOneEditors, positionTwoEditors, positionThreeEditors].forEach((editors, index) => { const group = this.stacks.groupAt(index); if (group) { editors.forEach(editor => group.openEditor(editor.input, { pinned: true })); // group could be null if one openeditor call failed! } }); // Full layout side by side this.editorGroupsControl.layout(this.dimension); return editors; }); } public activateGroup(group: EditorGroup): void; public activateGroup(position: Position): void; public activateGroup(arg1: any): void { const group = (typeof arg1 === 'number') ? this.stacks.groupAt(arg1) : arg1; if (group) { // Update stacks model this.stacks.setActive(group); // Update UI const editor = this.visibleEditors[this.stacks.positionOfGroup(group)]; if (editor) { this.editorGroupsControl.setActive(editor); } } } public focusGroup(group: EditorGroup): void; public focusGroup(position: Position): void; public focusGroup(arg1: any): void { const group = (typeof arg1 === 'number') ? this.stacks.groupAt(arg1) : arg1; if (group) { // Make active this.activateGroup(group); // Focus Editor const editor = this.visibleEditors[this.stacks.positionOfGroup(group)]; if (editor) { editor.focus(); } } } public pinEditor(group: EditorGroup, input: EditorInput): void; public pinEditor(position: Position, input: EditorInput): void; public pinEditor(arg1: any, input: EditorInput): void { const group = (typeof arg1 === 'number') ? this.stacks.groupAt(arg1) : arg1; if (group) { if (group.isPinned(input)) { return; } // Update stacks model group.pin(input); } } public unpinEditor(group: EditorGroup, input: EditorInput): void; public unpinEditor(position: Position, input: EditorInput): void; public unpinEditor(arg1: any, input: EditorInput): void { if (input.isDirty()) { return; // we do not allow to unpin dirty editors } const group = (typeof arg1 === 'number') ? this.stacks.groupAt(arg1) : arg1; if (group) { if (group.isPreview(input)) { return; } // Unpinning an editor closes the preview editor if we have any let handlePreviewEditor: TPromise<boolean> = TPromise.as(false); if (group.previewEditor) { handlePreviewEditor = this.handleDirty([{ group, editor: group.previewEditor }], true /* ignore if opened in other group */); } handlePreviewEditor.done(veto => { if (veto) { return; } // The active editor is the preview editor and we are asked to make // another editor the preview editor. So we need to take care of closing // the active editor first if (group.isPreview(group.activeEditor) && !group.activeEditor.matches(input)) { this.doCloseActiveEditor(group); } // Update stacks model group.unpin(input); }); } } public layout(dimension: Dimension): Dimension[] { // Pass to super const sizes = super.layout(dimension); // Pass to Side by Side Control this.dimension = sizes[1]; this.editorGroupsControl.layout(this.dimension); this.onLayoutEmitter.fire(dimension); return sizes; } public shutdown(): void { // Persist UI State const editorState: IEditorPartUIState = { ratio: this.editorGroupsControl.getRatio(), groupOrientation: this.editorGroupsControl.getGroupOrientation() }; this.memento[EditorPart.EDITOR_PART_UI_STATE_STORAGE_KEY] = editorState; // Unload all Instantiated Editors for (let i = 0; i < this.instantiatedEditors.length; i++) { for (let j = 0; j < this.instantiatedEditors[i].length; j++) { this.instantiatedEditors[i][j].shutdown(); } } // Pass to super super.shutdown(); } public dispose(): void { // Emitters this._onEditorsChanged.dispose(); this._onEditorsMoved.dispose(); this._onEditorOpenFail.dispose(); // Reset Tokens this.editorOpenToken = []; for (let i = 0; i < POSITIONS.length; i++) { this.editorOpenToken[i] = 0; } // Widgets this.editorGroupsControl.dispose(); // Pass to active editors this.visibleEditors.forEach(editor => { if (editor) { editor.dispose(); } }); // Pass to instantiated editors for (let i = 0; i < this.instantiatedEditors.length; i++) { for (let j = 0; j < this.instantiatedEditors[i].length; j++) { if (this.visibleEditors.some(editor => editor === this.instantiatedEditors[i][j])) { continue; } this.instantiatedEditors[i][j].dispose(); } } this.visibleEditors = null; // Pass to super super.dispose(); } private findPosition(input: EditorInput, options?: EditorOptions, sideBySide?: boolean, ratio?: number[]): Position; private findPosition(input: EditorInput, options?: EditorOptions, desiredPosition?: Position, ratio?: number[]): Position; private findPosition(input: EditorInput, options?: EditorOptions, arg1?: any, ratio?: number[]): Position { // With defined ratios, always trust the provided position if (ratio && types.isNumber(arg1)) { return arg1; } // No editor open const visibleEditors = this.getVisibleEditors(); const activeEditor = this.getActiveEditor(); if (visibleEditors.length === 0 || !activeEditor) { return Position.ONE; // can only be ONE } // Respect option to reveal an editor if it is already visible if (options && options.revealIfVisible) { const group = this.stacks.findGroup(input, true); if (group) { return this.stacks.positionOfGroup(group); } } // Respect option to reveal an editor if it is open (not necessarily visible) const skipRevealIfOpen = (options && options.index) || arg1; if (!skipRevealIfOpen && this.revealIfOpen) { const group = this.stacks.findGroup(input); if (group) { return this.stacks.positionOfGroup(group); } } // Position is unknown: pick last active or ONE if (types.isUndefinedOrNull(arg1) || arg1 === false) { const lastActivePosition = this.editorGroupsControl.getActivePosition(); return lastActivePosition || Position.ONE; } // Position is sideBySide: Find position relative to active editor if (arg1 === true) { switch (activeEditor.position) { case Position.ONE: return Position.TWO; case Position.TWO: return Position.THREE; case Position.THREE: return null; // Cannot open to the side of the right/bottom most editor } return null; // Prevent opening to the side } // Position is provided, validate it if (arg1 === Position.THREE && visibleEditors.length === 1) { return Position.TWO; } return arg1; } private startDelayedCloseEditorsFromInputDispose(): void { // To prevent race conditions, we call the close in a timeout because it can well be // that an input is being disposed with the intent to replace it with some other input // right after. if (this.pendingEditorInputCloseTimeout === null) { this.pendingEditorInputCloseTimeout = setTimeout(() => { // Split between visible and hidden editors const visibleEditors: EditorIdentifier[] = []; const hiddenEditors: EditorIdentifier[] = []; this.pendingEditorInputsToClose.forEach(identifier => { const { group, editor } = identifier; if (group.isActive(editor)) { visibleEditors.push(identifier); } else if (group.contains(editor)) { hiddenEditors.push(identifier); } }); // Close all hidden first hiddenEditors.forEach(hidden => this.doCloseEditor(<EditorGroup>hidden.group, hidden.editor, false)); // Close visible ones second visibleEditors .sort((a1, a2) => this.stacks.positionOfGroup(a2.group) - this.stacks.positionOfGroup(a1.group)) // reduce layout work by starting right/bottom first .forEach(visible => this.doCloseEditor(<EditorGroup>visible.group, visible.editor, false)); // Reset this.pendingEditorInputCloseTimeout = null; this.pendingEditorInputsToClose = []; }, 0); } } private rochade(rochade: Rochade): void; private rochade(from: Position, to: Position): void; private rochade(arg1: any, arg2?: any): void { if (types.isUndefinedOrNull(arg2)) { const rochade = <Rochade>arg1; switch (rochade) { case Rochade.TWO_TO_ONE: this.rochade(Position.TWO, Position.ONE); break; case Rochade.THREE_TO_TWO: this.rochade(Position.THREE, Position.TWO); break; case Rochade.TWO_AND_THREE_TO_ONE: this.rochade(Position.TWO, Position.ONE); this.rochade(Position.THREE, Position.TWO); } } else { const from = <Position>arg1; const to = <Position>arg2; this.doRochade(this.visibleEditors, from, to, null); this.doRochade(this.editorOpenToken, from, to, null); this.doRochade(this.mapEditorInstantiationPromiseToEditor, from, to, Object.create(null)); this.doRochade(this.instantiatedEditors, from, to, []); } } private doRochade(array: any[], from: Position, to: Position, empty: any): void { array[to] = array[from]; array[from] = empty; } private ensureGroup(position: Position, activate = true): EditorGroup { let group = this.stacks.groupAt(position); if (!group) { // Race condition: it could be that someone quickly opens editors one after // the other and we are asked to open an editor in position 2 before position // 1 was opened. Therefor we must ensure that all groups are created up to // the point where we are asked for. this.modifyGroups(() => { for (let i = 0; i < position; i++) { if (!this.hasGroup(i)) { this.stacks.openGroup('', false, i); } } group = this.stacks.openGroup('', activate, position); }); } else { this.renameGroups(); // ensure group labels are proper } if (activate) { this.stacks.setActive(group); } return group; } private modifyGroups(modification: () => void) { // Run the modification modification(); // Adjust group labels as needed this.renameGroups(); } private renameGroups(): void { const groups = this.stacks.groups; if (groups.length > 0) { const layoutVertically = (this.editorGroupsControl.getGroupOrientation() !== 'horizontal'); // ONE | TWO | THREE if (groups.length > 2) { this.stacks.renameGroup(this.stacks.groupAt(Position.ONE), layoutVertically ? EditorPart.GROUP_LEFT : EditorPart.GROUP_TOP); this.stacks.renameGroup(this.stacks.groupAt(Position.TWO), layoutVertically ? EditorPart.GROUP_CENTER : EditorPart.GROUP_MIDDLE); this.stacks.renameGroup(this.stacks.groupAt(Position.THREE), layoutVertically ? EditorPart.GROUP_RIGHT : EditorPart.GROUP_BOTTOM); } // ONE | TWO else if (groups.length > 1) { this.stacks.renameGroup(this.stacks.groupAt(Position.ONE), layoutVertically ? EditorPart.GROUP_LEFT : EditorPart.GROUP_TOP); this.stacks.renameGroup(this.stacks.groupAt(Position.TWO), layoutVertically ? EditorPart.GROUP_RIGHT : EditorPart.GROUP_BOTTOM); } // ONE else { this.stacks.renameGroup(this.stacks.groupAt(Position.ONE), layoutVertically ? EditorPart.GROUP_LEFT : EditorPart.GROUP_TOP); } } } private hasGroup(position: Position): boolean { return !!this.stacks.groupAt(position); } }
src/vs/workbench/browser/parts/editor/editorPart.ts
1
https://github.com/microsoft/vscode/commit/522c6e01711a50ab2c48e2efb11f837dce7ebab9
[ 0.9963034391403198, 0.007012495305389166, 0.00016499243793077767, 0.00017163748270832002, 0.08187510818243027 ]
{ "id": 7, "code_window": [ "\t */\n", "\tmoveEditor(input: IEditorInput, from: IEditorGroup, to: IEditorGroup, index?: number): void;\n", "\tmoveEditor(input: IEditorInput, from: Position, to: Position, index?: number): void;\n", "\n", "\t/**\n", "\t * Provides access to the editor stacks model\n", "\t */\n" ], "labels": [ "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tmoveEditor(input: IEditorInput, from: IEditorGroup, to: IEditorGroup, index?: number, inactive?: boolean): void;\n", "\tmoveEditor(input: IEditorInput, from: Position, to: Position, index?: number, inactive?: boolean): void;\n" ], "file_path": "src/vs/workbench/services/group/common/groupService.ts", "type": "replace", "edit_start_line_idx": 109 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "toggleRenderWhitespace": "切换呈现空格" }
i18n/chs/src/vs/workbench/parts/codeEditor/electron-browser/toggleRenderWhitespace.i18n.json
0
https://github.com/microsoft/vscode/commit/522c6e01711a50ab2c48e2efb11f837dce7ebab9
[ 0.00017676636343821883, 0.00017676636343821883, 0.00017676636343821883, 0.00017676636343821883, 0 ]
{ "id": 7, "code_window": [ "\t */\n", "\tmoveEditor(input: IEditorInput, from: IEditorGroup, to: IEditorGroup, index?: number): void;\n", "\tmoveEditor(input: IEditorInput, from: Position, to: Position, index?: number): void;\n", "\n", "\t/**\n", "\t * Provides access to the editor stacks model\n", "\t */\n" ], "labels": [ "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tmoveEditor(input: IEditorInput, from: IEditorGroup, to: IEditorGroup, index?: number, inactive?: boolean): void;\n", "\tmoveEditor(input: IEditorInput, from: Position, to: Position, index?: number, inactive?: boolean): void;\n" ], "file_path": "src/vs/workbench/services/group/common/groupService.ts", "type": "replace", "edit_start_line_idx": 109 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import { IGitOperation, IRawStatus } from 'vs/workbench/parts/git/common/git'; import { TPromise } from 'vs/base/common/winjs.base'; export class GitOperation implements IGitOperation { id: string; constructor(id: string, private fn: () => TPromise<IRawStatus>) { this.id = id; } run(): TPromise<IRawStatus> { return this.fn(); } dispose(): void { // noop } }
src/vs/workbench/parts/git/browser/gitOperations.ts
0
https://github.com/microsoft/vscode/commit/522c6e01711a50ab2c48e2efb11f837dce7ebab9
[ 0.00017789214325603098, 0.0001746712950989604, 0.0001713214151095599, 0.00017480032693129033, 0.000002684039827727247 ]
{ "id": 7, "code_window": [ "\t */\n", "\tmoveEditor(input: IEditorInput, from: IEditorGroup, to: IEditorGroup, index?: number): void;\n", "\tmoveEditor(input: IEditorInput, from: Position, to: Position, index?: number): void;\n", "\n", "\t/**\n", "\t * Provides access to the editor stacks model\n", "\t */\n" ], "labels": [ "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tmoveEditor(input: IEditorInput, from: IEditorGroup, to: IEditorGroup, index?: number, inactive?: boolean): void;\n", "\tmoveEditor(input: IEditorInput, from: Position, to: Position, index?: number, inactive?: boolean): void;\n" ], "file_path": "src/vs/workbench/services/group/common/groupService.ts", "type": "replace", "edit_start_line_idx": 109 }
/*--------------------------------------------------------------------------------------------- * 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 { IJSONSchema } from 'vs/base/common/jsonSchema'; import { EXTENSION_IDENTIFIER_PATTERN } from 'vs/platform/extensionManagement/common/extensionManagement'; export const ExtensionsConfigurationSchemaId = 'vscode://schemas/extensions'; export const ExtensionsConfigurationSchema: IJSONSchema = { id: ExtensionsConfigurationSchemaId, type: 'object', title: localize('app.extensions.json.title', "Extensions"), properties: { recommendations: { type: 'array', description: localize('app.extensions.json.recommendations', "List of extensions recommendations. The identifier of an extension is always '${publisher}.${name}'. For example: 'vscode.csharp'."), items: { type: 'string', defaultSnippets: [{ label: 'Example', body: 'vscode.csharp' }], pattern: EXTENSION_IDENTIFIER_PATTERN, errorMessage: localize('app.extension.identifier.errorMessage', "Expected format '${publisher}.${name}'. Example: 'vscode.csharp'.") }, }, } }; export const ExtensionsConfigurationInitialContent: string = [ '{', '\t// See http://go.microsoft.com/fwlink/?LinkId=827846', '\t// for the documentation about the extensions.json format', '\t"recommendations": [', '\t\t// Extension identifier format: ${publisher}.${name}. Example: vscode.csharp', '\t\t', '\t]', '}' ].join('\n');
src/vs/workbench/parts/extensions/common/extensionsFileTemplate.ts
0
https://github.com/microsoft/vscode/commit/522c6e01711a50ab2c48e2efb11f837dce7ebab9
[ 0.00017513782950118184, 0.00017337869212497026, 0.00016998224600683898, 0.00017419736832380295, 0.000002003022245844477 ]
{ "id": 0, "code_window": [ "\tactiveTabIndex: number;\n", "\tconfigHelper: ITerminalConfigHelper;\n", "\tterminalInstances: ITerminalInstance[];\n", "\tterminalTabs: ITerminalTab[];\n", "\tisProcessSupportRegistered: boolean;\n", "\twillFocusNewTerminal: boolean;\n", "\treadonly connectionState: TerminalConnectionState;\n", "\n", "\tinitializeTerminals(): Promise<void>;\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/contrib/terminal/browser/terminal.ts", "type": "replace", "edit_start_line_idx": 85 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import type { Terminal as XTermTerminal } from 'xterm'; import type { SearchAddon as XTermSearchAddon } from 'xterm-addon-search'; import type { Unicode11Addon as XTermUnicode11Addon } from 'xterm-addon-unicode11'; import type { WebglAddon as XTermWebglAddon } from 'xterm-addon-webgl'; import { IWindowsShellHelper, ITerminalConfigHelper, ITerminalChildProcess, IShellLaunchConfig, IDefaultShellAndArgsRequest, ISpawnExtHostProcessRequest, IStartExtensionTerminalRequest, IAvailableShellsRequest, ITerminalProcessExtHostProxy, ICommandTracker, INavigationMode, TitleEventSource, ITerminalDimensions, ITerminalLaunchError, ITerminalNativeWindowsDelegate, LinuxDistro, IRemoteTerminalAttachTarget } from 'vs/workbench/contrib/terminal/common/terminal'; import { createDecorator } from 'vs/platform/instantiation/common/instantiation'; import { IProcessEnvironment, Platform } from 'vs/base/common/platform'; import { Event } from 'vs/base/common/event'; import { IDisposable } from 'vs/base/common/lifecycle'; import { FindReplaceState } from 'vs/editor/contrib/find/findState'; import { URI } from 'vs/base/common/uri'; export const ITerminalService = createDecorator<ITerminalService>('terminalService'); export const ITerminalInstanceService = createDecorator<ITerminalInstanceService>('terminalInstanceService'); export const IRemoteTerminalService = createDecorator<IRemoteTerminalService>('remoteTerminalService'); /** * A service used by TerminalInstance (and components owned by it) that allows it to break its * dependency on electron-browser and node layers, while at the same time avoiding a cyclic * dependency on ITerminalService. */ export interface ITerminalInstanceService { readonly _serviceBrand: undefined; // These events are optional as the requests they make are only needed on the browser side onRequestDefaultShellAndArgs?: Event<IDefaultShellAndArgsRequest>; getXtermConstructor(): Promise<typeof XTermTerminal>; getXtermSearchConstructor(): Promise<typeof XTermSearchAddon>; getXtermUnicode11Constructor(): Promise<typeof XTermUnicode11Addon>; getXtermWebglConstructor(): Promise<typeof XTermWebglAddon>; createWindowsShellHelper(shellProcessId: number, xterm: XTermTerminal): IWindowsShellHelper; createTerminalProcess(shellLaunchConfig: IShellLaunchConfig, cwd: string, cols: number, rows: number, env: IProcessEnvironment, windowsEnableConpty: boolean): ITerminalChildProcess; getDefaultShellAndArgs(useAutomationShell: boolean, platformOverride?: Platform): Promise<{ shell: string, args: string[] | string | undefined }>; getMainProcessParentEnv(): Promise<IProcessEnvironment>; } export interface IBrowserTerminalConfigHelper extends ITerminalConfigHelper { panelContainer: HTMLElement | undefined; } export const enum Direction { Left = 0, Right = 1, Up = 2, Down = 3 } export interface ITerminalTab { activeInstance: ITerminalInstance | null; terminalInstances: ITerminalInstance[]; title: string; onDisposed: Event<ITerminalTab>; onInstancesChanged: Event<void>; focusPreviousPane(): void; focusNextPane(): void; resizePane(direction: Direction): void; setActiveInstanceByIndex(index: number): void; attachToElement(element: HTMLElement): void; setVisible(visible: boolean): void; layout(width: number, height: number): void; addDisposable(disposable: IDisposable): void; split(shellLaunchConfig: IShellLaunchConfig): ITerminalInstance; } export const enum TerminalConnectionState { Connecting, Connected } export interface ITerminalService { readonly _serviceBrand: undefined; activeTabIndex: number; configHelper: ITerminalConfigHelper; terminalInstances: ITerminalInstance[]; terminalTabs: ITerminalTab[]; isProcessSupportRegistered: boolean; willFocusNewTerminal: boolean; readonly connectionState: TerminalConnectionState; initializeTerminals(): Promise<void>; onActiveTabChanged: Event<void>; onTabDisposed: Event<ITerminalTab>; onInstanceCreated: Event<ITerminalInstance>; onInstanceDisposed: Event<ITerminalInstance>; onInstanceProcessIdReady: Event<ITerminalInstance>; onInstanceDimensionsChanged: Event<ITerminalInstance>; onInstanceMaximumDimensionsChanged: Event<ITerminalInstance>; onInstanceRequestSpawnExtHostProcess: Event<ISpawnExtHostProcessRequest>; onInstanceRequestStartExtensionTerminal: Event<IStartExtensionTerminalRequest>; onInstancesChanged: Event<void>; onInstanceTitleChanged: Event<ITerminalInstance | undefined>; onActiveInstanceChanged: Event<ITerminalInstance | undefined>; onRequestAvailableShells: Event<IAvailableShellsRequest>; onDidRegisterProcessSupport: Event<void>; onDidChangeConnectionState: Event<void>; /** * Creates a terminal. * @param shell The shell launch configuration to use. */ createTerminal(shell?: IShellLaunchConfig): ITerminalInstance; /** * Creates a raw terminal instance, this should not be used outside of the terminal part. */ createInstance(container: HTMLElement | undefined, shellLaunchConfig: IShellLaunchConfig): ITerminalInstance; getInstanceFromId(terminalId: number): ITerminalInstance | undefined; getInstanceFromIndex(terminalIndex: number): ITerminalInstance; getTabLabels(): string[]; getActiveInstance(): ITerminalInstance | null; setActiveInstance(terminalInstance: ITerminalInstance): void; setActiveInstanceByIndex(terminalIndex: number): void; getActiveOrCreateInstance(): ITerminalInstance; splitInstance(instance: ITerminalInstance, shell?: IShellLaunchConfig): ITerminalInstance | null; /** * Perform an action with the active terminal instance, if the terminal does * not exist the callback will not be called. * @param callback The callback that fires with the active terminal */ doWithActiveInstance<T>(callback: (terminal: ITerminalInstance) => T): T | void; getActiveTab(): ITerminalTab | null; setActiveTabToNext(): void; setActiveTabToPrevious(): void; setActiveTabByIndex(tabIndex: number): void; /** * Fire the onActiveTabChanged event, this will trigger the terminal dropdown to be updated, * among other things. */ refreshActiveTab(): void; showPanel(focus?: boolean): Promise<void>; hidePanel(): void; focusFindWidget(): Promise<void>; hideFindWidget(): void; getFindState(): FindReplaceState; findNext(): void; findPrevious(): void; registerProcessSupport(isSupported: boolean): void; /** * Registers a link provider that enables integrators to add links to the terminal. * @param linkProvider When registered, the link provider is asked whenever a cell is hovered * for links at that position. This lets the terminal know all links at a given area and also * labels for what these links are going to do. */ registerLinkProvider(linkProvider: ITerminalExternalLinkProvider): IDisposable; selectDefaultShell(): Promise<void>; setContainers(panelContainer: HTMLElement, terminalContainer: HTMLElement): void; manageWorkspaceShellPermissions(): void; /** * Injects native Windows functionality into the service. */ setNativeWindowsDelegate(delegate: ITerminalNativeWindowsDelegate): void; setLinuxDistro(linuxDistro: LinuxDistro): void; /** * Takes a path and returns the properly escaped path to send to the terminal. * On Windows, this included trying to prepare the path for WSL if needed. * * @param executable The executable off the shellLaunchConfig * @param title The terminal's title * @param path The path to be escaped and formatted. * @returns An escaped version of the path to be execuded in the terminal. */ preparePathForTerminalAsync(path: string, executable: string | undefined, title: string, shellType: TerminalShellType): Promise<string>; extHostReady(remoteAuthority: string): void; requestSpawnExtHostProcess(proxy: ITerminalProcessExtHostProxy, shellLaunchConfig: IShellLaunchConfig, activeWorkspaceRootUri: URI | undefined, cols: number, rows: number, isWorkspaceShellAllowed: boolean): Promise<ITerminalLaunchError | undefined>; requestStartExtensionTerminal(proxy: ITerminalProcessExtHostProxy, cols: number, rows: number): Promise<ITerminalLaunchError | undefined>; } export interface IRemoteTerminalService { readonly _serviceBrand: undefined; dispose(): void; listTerminals(): Promise<IRemoteTerminalAttachTarget[]>; createRemoteTerminalProcess(terminalId: number, shellLaunchConfig: IShellLaunchConfig, activeWorkspaceRootUri: URI | undefined, cols: number, rows: number, configHelper: ITerminalConfigHelper,): Promise<ITerminalChildProcess>; } /** * Similar to xterm.js' ILinkProvider but using promises and hides xterm.js internals (like buffer * positions, decorations, etc.) from the rest of vscode. This is the interface to use for * workbench integrations. */ export interface ITerminalExternalLinkProvider { provideLinks(instance: ITerminalInstance, line: string): Promise<ITerminalLink[] | undefined>; } export interface ITerminalLink { /** 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; /** * Activates the link. * @param text The text of the link. */ activate(text: string): void; } export interface ISearchOptions { /** Whether the find should be done as a regex. */ regex?: boolean; /** Whether only whole words should match. */ wholeWord?: boolean; /** Whether find should pay attention to case. */ caseSensitive?: boolean; /** Whether the search should start at the current search position (not the next row). */ incremental?: boolean; } export enum WindowsShellType { CommandPrompt = 'cmd', PowerShell = 'pwsh', Wsl = 'wsl', GitBash = 'gitbash' } export type TerminalShellType = WindowsShellType | undefined; export interface ITerminalBeforeHandleLinkEvent { terminal?: ITerminalInstance; /** The text of the link */ link: string; /** Call with whether the link was handled by the interceptor */ resolve(wasHandled: boolean): void; } export interface ITerminalInstance { /** * The ID of the terminal instance, this is an arbitrary number only used to identify the * terminal instance. */ readonly id: number; readonly cols: number; readonly rows: number; readonly maxCols: number; readonly maxRows: number; /** * The process ID of the shell process, this is undefined when there is no process associated * with this terminal. */ processId: number | undefined; /** * An event that fires when the terminal instance's title changes. */ onTitleChanged: Event<ITerminalInstance>; /** * An event that fires when the terminal instance is disposed. */ onDisposed: Event<ITerminalInstance>; onFocused: Event<ITerminalInstance>; onProcessIdReady: Event<ITerminalInstance>; onLinksReady: Event<ITerminalInstance>; onRequestExtHostProcess: Event<ITerminalInstance>; onDimensionsChanged: Event<void>; onMaximumDimensionsChanged: Event<void>; onFocus: Event<ITerminalInstance>; /** * Attach a listener to the raw data stream coming from the pty, including ANSI escape * sequences. */ onData: Event<string>; /** * Attach a listener to listen for new lines added to this terminal instance. * * @param listener The listener function which takes new line strings added to the terminal, * excluding ANSI escape sequences. The line event will fire when an LF character is added to * the terminal (ie. the line is not wrapped). Note that this means that the line data will * not fire for the last line, until either the line is ended with a LF character of the process * is exited. The lineData string will contain the fully wrapped line, not containing any LF/CR * characters. */ onLineData: Event<string>; /** * Attach a listener that fires when the terminal's pty process exits. The number in the event * is the processes' exit code, an exit code of null means the process was killed as a result of * the ITerminalInstance being disposed. */ onExit: Event<number | undefined>; readonly exitCode: number | undefined; readonly areLinksReady: boolean; /** * Returns an array of data events that have fired within the first 10 seconds. If this is * called 10 seconds after the terminal has existed the result will be undefined. This is useful * when objects that depend on the data events have delayed initialization, like extension * hosts. */ readonly initialDataEvents: string[] | undefined; /** A promise that resolves when the terminal's pty/process have been created. */ processReady: Promise<void>; /** * The title of the terminal. This is either title or the process currently running or an * explicit name given to the terminal instance through the extension API. */ readonly title: string; /** * The shell type of the terminal. */ readonly shellType: TerminalShellType; /** * The focus state of the terminal before exiting. */ readonly hadFocusOnExit: boolean; /** * False when the title is set by an API or the user. We check this to make sure we * do not override the title when the process title changes in the terminal. */ isTitleSetByProcess: boolean; /** * The shell launch config used to launch the shell. */ readonly shellLaunchConfig: IShellLaunchConfig; /** * Whether to disable layout for the terminal. This is useful when the size of the terminal is * being manipulating (e.g. adding a split pane) and we want the terminal to ignore particular * resize events. */ disableLayout: boolean; /** * An object that tracks when commands are run and enables navigating and selecting between * them. */ readonly commandTracker: ICommandTracker | undefined; readonly navigationMode: INavigationMode | undefined; /** * Shows the environment information hover if the widget exists. */ showEnvironmentInfoHover(): void; /** * Dispose the terminal instance, removing it from the panel/service and freeing up resources. * * @param immediate Whether the kill should be immediate or not. Immediate should only be used * when VS Code is shutting down or in cases where the terminal dispose was user initiated. * The immediate===false exists to cover an edge case where the final output of the terminal can * get cut off. If immediate kill any terminal processes immediately. */ dispose(immediate?: boolean): void; /** * Forces the terminal to redraw its viewport. */ forceRedraw(): void; /** * Check if anything is selected in terminal. */ hasSelection(): boolean; /** * Copies the terminal selection to the clipboard. */ copySelection(): Promise<void>; /** * Current selection in the terminal. */ readonly selection: string | undefined; /** * Clear current selection. */ clearSelection(): void; /** * Select all text in the terminal. */ selectAll(): void; /** * Find the next instance of the term */ findNext(term: string, searchOptions: ISearchOptions): boolean; /** * Find the previous instance of the term */ findPrevious(term: string, searchOptions: ISearchOptions): boolean; /** * Notifies the terminal that the find widget's focus state has been changed. */ notifyFindWidgetFocusChanged(isFocused: boolean): void; /** * Focuses the terminal instance if it's able to (xterm.js instance exists). * * @param focus Force focus even if there is a selection. */ focus(force?: boolean): void; /** * Focuses the terminal instance when it's ready (the xterm.js instance is created). Use this * when the terminal is being shown. * * @param focus Force focus even if there is a selection. */ focusWhenReady(force?: boolean): Promise<void>; /** * Focuses and pastes the contents of the clipboard into the terminal instance. */ paste(): Promise<void>; /** * Send text to the terminal instance. The text is written to the stdin of the underlying pty * process (shell) of the terminal instance. * * @param text The text to send. * @param addNewLine Whether to add a new line to the text being sent, this is normally * required to run a command in the terminal. The character(s) added are \n or \r\n * depending on the platform. This defaults to `true`. */ sendText(text: string, addNewLine: boolean): void; /** Scroll the terminal buffer down 1 line. */ scrollDownLine(): void; /** Scroll the terminal buffer down 1 page. */ scrollDownPage(): void; /** Scroll the terminal buffer to the bottom. */ scrollToBottom(): void; /** Scroll the terminal buffer up 1 line. */ scrollUpLine(): void; /** Scroll the terminal buffer up 1 page. */ scrollUpPage(): void; /** Scroll the terminal buffer to the top. */ scrollToTop(): void; /** * Clears the terminal buffer, leaving only the prompt line. */ clear(): void; /** * Attaches the terminal instance to an element on the DOM, before this is called the terminal * instance process may run in the background but cannot be displayed on the UI. * * @param container The element to attach the terminal instance to. */ attachToElement(container: HTMLElement): void; /** * Configure the dimensions of the terminal instance. * * @param dimension The dimensions of the container. */ layout(dimension: { width: number, height: number }): void; /** * Sets whether the terminal instance's element is visible in the DOM. * * @param visible Whether the element is visible. */ setVisible(visible: boolean): void; /** * Immediately kills the terminal's current pty process and launches a new one to replace it. * * @param shell The new launch configuration. */ reuseTerminal(shell: IShellLaunchConfig): void; /** * Relaunches the terminal, killing it and reusing the launch config used initially. Any * environment variable changes will be recalculated when this happens. */ relaunch(): void; /** * Sets the title of the terminal instance. */ setTitle(title: string, eventSource: TitleEventSource): void; /** * Sets the shell type of the terminal instance. */ setShellType(shellType: TerminalShellType): void; waitForTitle(): Promise<string>; setDimensions(dimensions: ITerminalDimensions): void; addDisposable(disposable: IDisposable): void; toggleEscapeSequenceLogging(): void; getInitialCwd(): Promise<string>; getCwd(): Promise<string>; /** * @throws when called before xterm.js is ready. */ registerLinkProvider(provider: ITerminalExternalLinkProvider): IDisposable; }
src/vs/workbench/contrib/terminal/browser/terminal.ts
1
https://github.com/microsoft/vscode/commit/574ee2032cc24ed250ef15962ce100838d4e5e4a
[ 0.9940641522407532, 0.02308806963264942, 0.00016640601097606122, 0.0004782877513207495, 0.13374114036560059 ]
{ "id": 0, "code_window": [ "\tactiveTabIndex: number;\n", "\tconfigHelper: ITerminalConfigHelper;\n", "\tterminalInstances: ITerminalInstance[];\n", "\tterminalTabs: ITerminalTab[];\n", "\tisProcessSupportRegistered: boolean;\n", "\twillFocusNewTerminal: boolean;\n", "\treadonly connectionState: TerminalConnectionState;\n", "\n", "\tinitializeTerminals(): Promise<void>;\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/contrib/terminal/browser/terminal.ts", "type": "replace", "edit_start_line_idx": 85 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ .monaco-grid-view { position: relative; overflow: hidden; width: 100%; height: 100%; } .monaco-grid-branch-node { width: 100%; height: 100%; }
src/vs/base/browser/ui/grid/gridview.css
0
https://github.com/microsoft/vscode/commit/574ee2032cc24ed250ef15962ce100838d4e5e4a
[ 0.00017875334015116096, 0.00017543599824421108, 0.0001721186563372612, 0.00017543599824421108, 0.0000033173419069498777 ]
{ "id": 0, "code_window": [ "\tactiveTabIndex: number;\n", "\tconfigHelper: ITerminalConfigHelper;\n", "\tterminalInstances: ITerminalInstance[];\n", "\tterminalTabs: ITerminalTab[];\n", "\tisProcessSupportRegistered: boolean;\n", "\twillFocusNewTerminal: boolean;\n", "\treadonly connectionState: TerminalConnectionState;\n", "\n", "\tinitializeTerminals(): Promise<void>;\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/contrib/terminal/browser/terminal.ts", "type": "replace", "edit_start_line_idx": 85 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ const path = require('path'); const fs = require('fs'); function collect(location) { const element = { name: path.basename(location) }; const stat = fs.statSync(location); if (!stat.isDirectory()) { return { element, incompressible: true }; } const children = fs.readdirSync(location) .map(child => path.join(location, child)) .map(collect); return { element, children }; } console.log(JSON.stringify(collect(process.cwd())));
test/ui/tree/tree.js
0
https://github.com/microsoft/vscode/commit/574ee2032cc24ed250ef15962ce100838d4e5e4a
[ 0.00017863935499917716, 0.0001764010958140716, 0.0001738767314236611, 0.0001766871864674613, 0.0000019548288037185557 ]
{ "id": 0, "code_window": [ "\tactiveTabIndex: number;\n", "\tconfigHelper: ITerminalConfigHelper;\n", "\tterminalInstances: ITerminalInstance[];\n", "\tterminalTabs: ITerminalTab[];\n", "\tisProcessSupportRegistered: boolean;\n", "\twillFocusNewTerminal: boolean;\n", "\treadonly connectionState: TerminalConnectionState;\n", "\n", "\tinitializeTerminals(): Promise<void>;\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/contrib/terminal/browser/terminal.ts", "type": "replace", "edit_start_line_idx": 85 }
/*--------------------------------------------------------------------------------------------- * 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 { join } from 'path'; import * as vscode from 'vscode'; import { createRandomFile, testFs } from '../utils'; suite('vscode API - languages', () => { const isWindows = process.platform === 'win32'; function positionToString(p: vscode.Position) { return `[${p.character}/${p.line}]`; } function rangeToString(r: vscode.Range) { return `[${positionToString(r.start)}/${positionToString(r.end)}]`; } function assertEqualRange(actual: vscode.Range, expected: vscode.Range, message?: string) { assert.equal(rangeToString(actual), rangeToString(expected), message); } test('setTextDocumentLanguage -> close/open event', async function () { const file = await createRandomFile('foo\nbar\nbar'); const doc = await vscode.workspace.openTextDocument(file); const langIdNow = doc.languageId; let clock = 0; const disposables: vscode.Disposable[] = []; let close = new Promise<void>(resolve => { disposables.push(vscode.workspace.onDidCloseTextDocument(e => { if (e === doc) { assert.equal(doc.languageId, langIdNow); assert.equal(clock, 0); clock += 1; resolve(); } })); }); let open = new Promise<void>(resolve => { disposables.push(vscode.workspace.onDidOpenTextDocument(e => { if (e === doc) { // same instance! assert.equal(doc.languageId, 'json'); assert.equal(clock, 1); clock += 1; resolve(); } })); }); let change = vscode.languages.setTextDocumentLanguage(doc, 'json'); await Promise.all([change, close, open]); assert.equal(clock, 2); assert.equal(doc.languageId, 'json'); disposables.forEach(disposable => disposable.dispose()); disposables.length = 0; }); test('setTextDocumentLanguage -> error when language does not exist', async function () { const file = await createRandomFile('foo\nbar\nbar'); const doc = await vscode.workspace.openTextDocument(file); try { await vscode.languages.setTextDocumentLanguage(doc, 'fooLangDoesNotExist'); assert.ok(false); } catch (err) { assert.ok(err); } }); test('diagnostics, read & event', function () { let uri = vscode.Uri.file('/foo/bar.txt'); let col1 = vscode.languages.createDiagnosticCollection('foo1'); col1.set(uri, [new vscode.Diagnostic(new vscode.Range(0, 0, 0, 12), 'error1')]); let col2 = vscode.languages.createDiagnosticCollection('foo2'); col2.set(uri, [new vscode.Diagnostic(new vscode.Range(0, 0, 0, 12), 'error1')]); let diag = vscode.languages.getDiagnostics(uri); assert.equal(diag.length, 2); let tuples = vscode.languages.getDiagnostics(); let found = false; for (let [thisUri,] of tuples) { if (thisUri.toString() === uri.toString()) { found = true; break; } } assert.ok(tuples.length >= 1); assert.ok(found); }); test('link detector', async function () { const uri = await createRandomFile('class A { // http://a.com }', undefined, '.java'); const doc = await vscode.workspace.openTextDocument(uri); const target = vscode.Uri.file(isWindows ? 'c:\\foo\\bar' : '/foo/bar'); const range = new vscode.Range(new vscode.Position(0, 0), new vscode.Position(0, 5)); const linkProvider: vscode.DocumentLinkProvider = { provideDocumentLinks: _doc => { return [new vscode.DocumentLink(range, target)]; } }; vscode.languages.registerDocumentLinkProvider({ language: 'java', scheme: testFs.scheme }, linkProvider); const links = await vscode.commands.executeCommand<vscode.DocumentLink[]>('vscode.executeLinkProvider', doc.uri); assert.equal(2, links && links.length); let [link1, link2] = links!.sort((l1, l2) => l1.range.start.compareTo(l2.range.start)); assert.equal(target.toString(), link1.target && link1.target.toString()); assertEqualRange(range, link1.range); assert.equal('http://a.com/', link2.target && link2.target.toString()); assertEqualRange(new vscode.Range(new vscode.Position(0, 13), new vscode.Position(0, 25)), link2.range); }); test('diagnostics & CodeActionProvider', async function () { class D2 extends vscode.Diagnostic { customProp = { complex() { } }; constructor() { super(new vscode.Range(0, 2, 0, 7), 'sonntag'); } } let diag1 = new vscode.Diagnostic(new vscode.Range(0, 0, 0, 5), 'montag'); let diag2 = new D2(); let ran = false; let uri = vscode.Uri.parse('ttt:path.far'); let r1 = vscode.languages.registerCodeActionsProvider({ pattern: '*.far', scheme: 'ttt' }, { provideCodeActions(_document, _range, ctx): vscode.Command[] { assert.equal(ctx.diagnostics.length, 2); let [first, second] = ctx.diagnostics; assert.ok(first === diag1); assert.ok(second === diag2); assert.ok(diag2 instanceof D2); ran = true; return []; } }); let r2 = vscode.workspace.registerTextDocumentContentProvider('ttt', { provideTextDocumentContent() { return 'this is some text'; } }); let r3 = vscode.languages.createDiagnosticCollection(); r3.set(uri, [diag1]); let r4 = vscode.languages.createDiagnosticCollection(); r4.set(uri, [diag2]); await vscode.workspace.openTextDocument(uri); await vscode.commands.executeCommand('vscode.executeCodeActionProvider', uri, new vscode.Range(0, 0, 0, 10)); assert.ok(ran); vscode.Disposable.from(r1, r2, r3, r4).dispose(); }); test('completions with document filters', async function () { let ran = false; let uri = vscode.Uri.file(join(vscode.workspace.rootPath || '', './bower.json')); let jsonDocumentFilter = [{ language: 'json', pattern: '**/package.json' }, { language: 'json', pattern: '**/bower.json' }, { language: 'json', pattern: '**/.bower.json' }]; let r1 = vscode.languages.registerCompletionItemProvider(jsonDocumentFilter, { provideCompletionItems: (_document: vscode.TextDocument, _position: vscode.Position, _token: vscode.CancellationToken): vscode.CompletionItem[] => { let proposal = new vscode.CompletionItem('foo'); proposal.kind = vscode.CompletionItemKind.Property; ran = true; return [proposal]; } }); await vscode.workspace.openTextDocument(uri); const result = await vscode.commands.executeCommand<vscode.CompletionList>('vscode.executeCompletionItemProvider', uri, new vscode.Position(1, 0)); r1.dispose(); assert.ok(ran, 'Provider has not been invoked'); assert.ok(result!.items.some(i => i.label === 'foo'), 'Results do not include "foo"'); }); });
extensions/vscode-api-tests/src/singlefolder-tests/languages.test.ts
0
https://github.com/microsoft/vscode/commit/574ee2032cc24ed250ef15962ce100838d4e5e4a
[ 0.0001780098828021437, 0.00017516060324851424, 0.00016941090871114284, 0.0001754924887791276, 0.000002335075805603992 ]
{ "id": 1, "code_window": [ "\tprivate _configHelper: TerminalConfigHelper;\n", "\tprivate _terminalContainer: HTMLElement | undefined;\n", "\tprivate _nativeWindowsDelegate: ITerminalNativeWindowsDelegate | undefined;\n", "\tprivate _remoteTerminalsInitialized: Promise<void> | undefined;\n", "\tprivate _willFocusNewTerminal = false;\n", "\tprivate _connectionState: TerminalConnectionState;\n", "\n", "\tpublic get configHelper(): ITerminalConfigHelper { return this._configHelper; }\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/contrib/terminal/browser/terminalService.ts", "type": "replace", "edit_start_line_idx": 66 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import type { Terminal as XTermTerminal } from 'xterm'; import type { SearchAddon as XTermSearchAddon } from 'xterm-addon-search'; import type { Unicode11Addon as XTermUnicode11Addon } from 'xterm-addon-unicode11'; import type { WebglAddon as XTermWebglAddon } from 'xterm-addon-webgl'; import { IWindowsShellHelper, ITerminalConfigHelper, ITerminalChildProcess, IShellLaunchConfig, IDefaultShellAndArgsRequest, ISpawnExtHostProcessRequest, IStartExtensionTerminalRequest, IAvailableShellsRequest, ITerminalProcessExtHostProxy, ICommandTracker, INavigationMode, TitleEventSource, ITerminalDimensions, ITerminalLaunchError, ITerminalNativeWindowsDelegate, LinuxDistro, IRemoteTerminalAttachTarget } from 'vs/workbench/contrib/terminal/common/terminal'; import { createDecorator } from 'vs/platform/instantiation/common/instantiation'; import { IProcessEnvironment, Platform } from 'vs/base/common/platform'; import { Event } from 'vs/base/common/event'; import { IDisposable } from 'vs/base/common/lifecycle'; import { FindReplaceState } from 'vs/editor/contrib/find/findState'; import { URI } from 'vs/base/common/uri'; export const ITerminalService = createDecorator<ITerminalService>('terminalService'); export const ITerminalInstanceService = createDecorator<ITerminalInstanceService>('terminalInstanceService'); export const IRemoteTerminalService = createDecorator<IRemoteTerminalService>('remoteTerminalService'); /** * A service used by TerminalInstance (and components owned by it) that allows it to break its * dependency on electron-browser and node layers, while at the same time avoiding a cyclic * dependency on ITerminalService. */ export interface ITerminalInstanceService { readonly _serviceBrand: undefined; // These events are optional as the requests they make are only needed on the browser side onRequestDefaultShellAndArgs?: Event<IDefaultShellAndArgsRequest>; getXtermConstructor(): Promise<typeof XTermTerminal>; getXtermSearchConstructor(): Promise<typeof XTermSearchAddon>; getXtermUnicode11Constructor(): Promise<typeof XTermUnicode11Addon>; getXtermWebglConstructor(): Promise<typeof XTermWebglAddon>; createWindowsShellHelper(shellProcessId: number, xterm: XTermTerminal): IWindowsShellHelper; createTerminalProcess(shellLaunchConfig: IShellLaunchConfig, cwd: string, cols: number, rows: number, env: IProcessEnvironment, windowsEnableConpty: boolean): ITerminalChildProcess; getDefaultShellAndArgs(useAutomationShell: boolean, platformOverride?: Platform): Promise<{ shell: string, args: string[] | string | undefined }>; getMainProcessParentEnv(): Promise<IProcessEnvironment>; } export interface IBrowserTerminalConfigHelper extends ITerminalConfigHelper { panelContainer: HTMLElement | undefined; } export const enum Direction { Left = 0, Right = 1, Up = 2, Down = 3 } export interface ITerminalTab { activeInstance: ITerminalInstance | null; terminalInstances: ITerminalInstance[]; title: string; onDisposed: Event<ITerminalTab>; onInstancesChanged: Event<void>; focusPreviousPane(): void; focusNextPane(): void; resizePane(direction: Direction): void; setActiveInstanceByIndex(index: number): void; attachToElement(element: HTMLElement): void; setVisible(visible: boolean): void; layout(width: number, height: number): void; addDisposable(disposable: IDisposable): void; split(shellLaunchConfig: IShellLaunchConfig): ITerminalInstance; } export const enum TerminalConnectionState { Connecting, Connected } export interface ITerminalService { readonly _serviceBrand: undefined; activeTabIndex: number; configHelper: ITerminalConfigHelper; terminalInstances: ITerminalInstance[]; terminalTabs: ITerminalTab[]; isProcessSupportRegistered: boolean; willFocusNewTerminal: boolean; readonly connectionState: TerminalConnectionState; initializeTerminals(): Promise<void>; onActiveTabChanged: Event<void>; onTabDisposed: Event<ITerminalTab>; onInstanceCreated: Event<ITerminalInstance>; onInstanceDisposed: Event<ITerminalInstance>; onInstanceProcessIdReady: Event<ITerminalInstance>; onInstanceDimensionsChanged: Event<ITerminalInstance>; onInstanceMaximumDimensionsChanged: Event<ITerminalInstance>; onInstanceRequestSpawnExtHostProcess: Event<ISpawnExtHostProcessRequest>; onInstanceRequestStartExtensionTerminal: Event<IStartExtensionTerminalRequest>; onInstancesChanged: Event<void>; onInstanceTitleChanged: Event<ITerminalInstance | undefined>; onActiveInstanceChanged: Event<ITerminalInstance | undefined>; onRequestAvailableShells: Event<IAvailableShellsRequest>; onDidRegisterProcessSupport: Event<void>; onDidChangeConnectionState: Event<void>; /** * Creates a terminal. * @param shell The shell launch configuration to use. */ createTerminal(shell?: IShellLaunchConfig): ITerminalInstance; /** * Creates a raw terminal instance, this should not be used outside of the terminal part. */ createInstance(container: HTMLElement | undefined, shellLaunchConfig: IShellLaunchConfig): ITerminalInstance; getInstanceFromId(terminalId: number): ITerminalInstance | undefined; getInstanceFromIndex(terminalIndex: number): ITerminalInstance; getTabLabels(): string[]; getActiveInstance(): ITerminalInstance | null; setActiveInstance(terminalInstance: ITerminalInstance): void; setActiveInstanceByIndex(terminalIndex: number): void; getActiveOrCreateInstance(): ITerminalInstance; splitInstance(instance: ITerminalInstance, shell?: IShellLaunchConfig): ITerminalInstance | null; /** * Perform an action with the active terminal instance, if the terminal does * not exist the callback will not be called. * @param callback The callback that fires with the active terminal */ doWithActiveInstance<T>(callback: (terminal: ITerminalInstance) => T): T | void; getActiveTab(): ITerminalTab | null; setActiveTabToNext(): void; setActiveTabToPrevious(): void; setActiveTabByIndex(tabIndex: number): void; /** * Fire the onActiveTabChanged event, this will trigger the terminal dropdown to be updated, * among other things. */ refreshActiveTab(): void; showPanel(focus?: boolean): Promise<void>; hidePanel(): void; focusFindWidget(): Promise<void>; hideFindWidget(): void; getFindState(): FindReplaceState; findNext(): void; findPrevious(): void; registerProcessSupport(isSupported: boolean): void; /** * Registers a link provider that enables integrators to add links to the terminal. * @param linkProvider When registered, the link provider is asked whenever a cell is hovered * for links at that position. This lets the terminal know all links at a given area and also * labels for what these links are going to do. */ registerLinkProvider(linkProvider: ITerminalExternalLinkProvider): IDisposable; selectDefaultShell(): Promise<void>; setContainers(panelContainer: HTMLElement, terminalContainer: HTMLElement): void; manageWorkspaceShellPermissions(): void; /** * Injects native Windows functionality into the service. */ setNativeWindowsDelegate(delegate: ITerminalNativeWindowsDelegate): void; setLinuxDistro(linuxDistro: LinuxDistro): void; /** * Takes a path and returns the properly escaped path to send to the terminal. * On Windows, this included trying to prepare the path for WSL if needed. * * @param executable The executable off the shellLaunchConfig * @param title The terminal's title * @param path The path to be escaped and formatted. * @returns An escaped version of the path to be execuded in the terminal. */ preparePathForTerminalAsync(path: string, executable: string | undefined, title: string, shellType: TerminalShellType): Promise<string>; extHostReady(remoteAuthority: string): void; requestSpawnExtHostProcess(proxy: ITerminalProcessExtHostProxy, shellLaunchConfig: IShellLaunchConfig, activeWorkspaceRootUri: URI | undefined, cols: number, rows: number, isWorkspaceShellAllowed: boolean): Promise<ITerminalLaunchError | undefined>; requestStartExtensionTerminal(proxy: ITerminalProcessExtHostProxy, cols: number, rows: number): Promise<ITerminalLaunchError | undefined>; } export interface IRemoteTerminalService { readonly _serviceBrand: undefined; dispose(): void; listTerminals(): Promise<IRemoteTerminalAttachTarget[]>; createRemoteTerminalProcess(terminalId: number, shellLaunchConfig: IShellLaunchConfig, activeWorkspaceRootUri: URI | undefined, cols: number, rows: number, configHelper: ITerminalConfigHelper,): Promise<ITerminalChildProcess>; } /** * Similar to xterm.js' ILinkProvider but using promises and hides xterm.js internals (like buffer * positions, decorations, etc.) from the rest of vscode. This is the interface to use for * workbench integrations. */ export interface ITerminalExternalLinkProvider { provideLinks(instance: ITerminalInstance, line: string): Promise<ITerminalLink[] | undefined>; } export interface ITerminalLink { /** 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; /** * Activates the link. * @param text The text of the link. */ activate(text: string): void; } export interface ISearchOptions { /** Whether the find should be done as a regex. */ regex?: boolean; /** Whether only whole words should match. */ wholeWord?: boolean; /** Whether find should pay attention to case. */ caseSensitive?: boolean; /** Whether the search should start at the current search position (not the next row). */ incremental?: boolean; } export enum WindowsShellType { CommandPrompt = 'cmd', PowerShell = 'pwsh', Wsl = 'wsl', GitBash = 'gitbash' } export type TerminalShellType = WindowsShellType | undefined; export interface ITerminalBeforeHandleLinkEvent { terminal?: ITerminalInstance; /** The text of the link */ link: string; /** Call with whether the link was handled by the interceptor */ resolve(wasHandled: boolean): void; } export interface ITerminalInstance { /** * The ID of the terminal instance, this is an arbitrary number only used to identify the * terminal instance. */ readonly id: number; readonly cols: number; readonly rows: number; readonly maxCols: number; readonly maxRows: number; /** * The process ID of the shell process, this is undefined when there is no process associated * with this terminal. */ processId: number | undefined; /** * An event that fires when the terminal instance's title changes. */ onTitleChanged: Event<ITerminalInstance>; /** * An event that fires when the terminal instance is disposed. */ onDisposed: Event<ITerminalInstance>; onFocused: Event<ITerminalInstance>; onProcessIdReady: Event<ITerminalInstance>; onLinksReady: Event<ITerminalInstance>; onRequestExtHostProcess: Event<ITerminalInstance>; onDimensionsChanged: Event<void>; onMaximumDimensionsChanged: Event<void>; onFocus: Event<ITerminalInstance>; /** * Attach a listener to the raw data stream coming from the pty, including ANSI escape * sequences. */ onData: Event<string>; /** * Attach a listener to listen for new lines added to this terminal instance. * * @param listener The listener function which takes new line strings added to the terminal, * excluding ANSI escape sequences. The line event will fire when an LF character is added to * the terminal (ie. the line is not wrapped). Note that this means that the line data will * not fire for the last line, until either the line is ended with a LF character of the process * is exited. The lineData string will contain the fully wrapped line, not containing any LF/CR * characters. */ onLineData: Event<string>; /** * Attach a listener that fires when the terminal's pty process exits. The number in the event * is the processes' exit code, an exit code of null means the process was killed as a result of * the ITerminalInstance being disposed. */ onExit: Event<number | undefined>; readonly exitCode: number | undefined; readonly areLinksReady: boolean; /** * Returns an array of data events that have fired within the first 10 seconds. If this is * called 10 seconds after the terminal has existed the result will be undefined. This is useful * when objects that depend on the data events have delayed initialization, like extension * hosts. */ readonly initialDataEvents: string[] | undefined; /** A promise that resolves when the terminal's pty/process have been created. */ processReady: Promise<void>; /** * The title of the terminal. This is either title or the process currently running or an * explicit name given to the terminal instance through the extension API. */ readonly title: string; /** * The shell type of the terminal. */ readonly shellType: TerminalShellType; /** * The focus state of the terminal before exiting. */ readonly hadFocusOnExit: boolean; /** * False when the title is set by an API or the user. We check this to make sure we * do not override the title when the process title changes in the terminal. */ isTitleSetByProcess: boolean; /** * The shell launch config used to launch the shell. */ readonly shellLaunchConfig: IShellLaunchConfig; /** * Whether to disable layout for the terminal. This is useful when the size of the terminal is * being manipulating (e.g. adding a split pane) and we want the terminal to ignore particular * resize events. */ disableLayout: boolean; /** * An object that tracks when commands are run and enables navigating and selecting between * them. */ readonly commandTracker: ICommandTracker | undefined; readonly navigationMode: INavigationMode | undefined; /** * Shows the environment information hover if the widget exists. */ showEnvironmentInfoHover(): void; /** * Dispose the terminal instance, removing it from the panel/service and freeing up resources. * * @param immediate Whether the kill should be immediate or not. Immediate should only be used * when VS Code is shutting down or in cases where the terminal dispose was user initiated. * The immediate===false exists to cover an edge case where the final output of the terminal can * get cut off. If immediate kill any terminal processes immediately. */ dispose(immediate?: boolean): void; /** * Forces the terminal to redraw its viewport. */ forceRedraw(): void; /** * Check if anything is selected in terminal. */ hasSelection(): boolean; /** * Copies the terminal selection to the clipboard. */ copySelection(): Promise<void>; /** * Current selection in the terminal. */ readonly selection: string | undefined; /** * Clear current selection. */ clearSelection(): void; /** * Select all text in the terminal. */ selectAll(): void; /** * Find the next instance of the term */ findNext(term: string, searchOptions: ISearchOptions): boolean; /** * Find the previous instance of the term */ findPrevious(term: string, searchOptions: ISearchOptions): boolean; /** * Notifies the terminal that the find widget's focus state has been changed. */ notifyFindWidgetFocusChanged(isFocused: boolean): void; /** * Focuses the terminal instance if it's able to (xterm.js instance exists). * * @param focus Force focus even if there is a selection. */ focus(force?: boolean): void; /** * Focuses the terminal instance when it's ready (the xterm.js instance is created). Use this * when the terminal is being shown. * * @param focus Force focus even if there is a selection. */ focusWhenReady(force?: boolean): Promise<void>; /** * Focuses and pastes the contents of the clipboard into the terminal instance. */ paste(): Promise<void>; /** * Send text to the terminal instance. The text is written to the stdin of the underlying pty * process (shell) of the terminal instance. * * @param text The text to send. * @param addNewLine Whether to add a new line to the text being sent, this is normally * required to run a command in the terminal. The character(s) added are \n or \r\n * depending on the platform. This defaults to `true`. */ sendText(text: string, addNewLine: boolean): void; /** Scroll the terminal buffer down 1 line. */ scrollDownLine(): void; /** Scroll the terminal buffer down 1 page. */ scrollDownPage(): void; /** Scroll the terminal buffer to the bottom. */ scrollToBottom(): void; /** Scroll the terminal buffer up 1 line. */ scrollUpLine(): void; /** Scroll the terminal buffer up 1 page. */ scrollUpPage(): void; /** Scroll the terminal buffer to the top. */ scrollToTop(): void; /** * Clears the terminal buffer, leaving only the prompt line. */ clear(): void; /** * Attaches the terminal instance to an element on the DOM, before this is called the terminal * instance process may run in the background but cannot be displayed on the UI. * * @param container The element to attach the terminal instance to. */ attachToElement(container: HTMLElement): void; /** * Configure the dimensions of the terminal instance. * * @param dimension The dimensions of the container. */ layout(dimension: { width: number, height: number }): void; /** * Sets whether the terminal instance's element is visible in the DOM. * * @param visible Whether the element is visible. */ setVisible(visible: boolean): void; /** * Immediately kills the terminal's current pty process and launches a new one to replace it. * * @param shell The new launch configuration. */ reuseTerminal(shell: IShellLaunchConfig): void; /** * Relaunches the terminal, killing it and reusing the launch config used initially. Any * environment variable changes will be recalculated when this happens. */ relaunch(): void; /** * Sets the title of the terminal instance. */ setTitle(title: string, eventSource: TitleEventSource): void; /** * Sets the shell type of the terminal instance. */ setShellType(shellType: TerminalShellType): void; waitForTitle(): Promise<string>; setDimensions(dimensions: ITerminalDimensions): void; addDisposable(disposable: IDisposable): void; toggleEscapeSequenceLogging(): void; getInitialCwd(): Promise<string>; getCwd(): Promise<string>; /** * @throws when called before xterm.js is ready. */ registerLinkProvider(provider: ITerminalExternalLinkProvider): IDisposable; }
src/vs/workbench/contrib/terminal/browser/terminal.ts
1
https://github.com/microsoft/vscode/commit/574ee2032cc24ed250ef15962ce100838d4e5e4a
[ 0.9903212189674377, 0.029295094311237335, 0.000161743228090927, 0.0002278513857163489, 0.14197346568107605 ]
{ "id": 1, "code_window": [ "\tprivate _configHelper: TerminalConfigHelper;\n", "\tprivate _terminalContainer: HTMLElement | undefined;\n", "\tprivate _nativeWindowsDelegate: ITerminalNativeWindowsDelegate | undefined;\n", "\tprivate _remoteTerminalsInitialized: Promise<void> | undefined;\n", "\tprivate _willFocusNewTerminal = false;\n", "\tprivate _connectionState: TerminalConnectionState;\n", "\n", "\tpublic get configHelper(): ITerminalConfigHelper { return this._configHelper; }\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/contrib/terminal/browser/terminalService.ts", "type": "replace", "edit_start_line_idx": 66 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ .monaco-editor .selection-anchor { background-color: #007ACC; width: 2px !important; }
src/vs/editor/contrib/anchorSelect/anchorSelect.css
0
https://github.com/microsoft/vscode/commit/574ee2032cc24ed250ef15962ce100838d4e5e4a
[ 0.00017887713329400867, 0.00017887713329400867, 0.00017887713329400867, 0.00017887713329400867, 0 ]
{ "id": 1, "code_window": [ "\tprivate _configHelper: TerminalConfigHelper;\n", "\tprivate _terminalContainer: HTMLElement | undefined;\n", "\tprivate _nativeWindowsDelegate: ITerminalNativeWindowsDelegate | undefined;\n", "\tprivate _remoteTerminalsInitialized: Promise<void> | undefined;\n", "\tprivate _willFocusNewTerminal = false;\n", "\tprivate _connectionState: TerminalConnectionState;\n", "\n", "\tpublic get configHelper(): ITerminalConfigHelper { return this._configHelper; }\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/contrib/terminal/browser/terminalService.ts", "type": "replace", "edit_start_line_idx": 66 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Emitter, Event } from 'vs/base/common/event'; import { IDisposable } from 'vs/base/common/lifecycle'; class WindowManager { public static readonly INSTANCE = new WindowManager(); // --- Zoom Level private _zoomLevel: number = 0; private _lastZoomLevelChangeTime: number = 0; private readonly _onDidChangeZoomLevel = new Emitter<number>(); public readonly onDidChangeZoomLevel: Event<number> = this._onDidChangeZoomLevel.event; public getZoomLevel(): number { return this._zoomLevel; } public getTimeSinceLastZoomLevelChanged(): number { return Date.now() - this._lastZoomLevelChangeTime; } public setZoomLevel(zoomLevel: number, isTrusted: boolean): void { if (this._zoomLevel === zoomLevel) { return; } this._zoomLevel = zoomLevel; // See https://github.com/microsoft/vscode/issues/26151 this._lastZoomLevelChangeTime = isTrusted ? 0 : Date.now(); this._onDidChangeZoomLevel.fire(this._zoomLevel); } // --- Zoom Factor private _zoomFactor: number = 1; public getZoomFactor(): number { return this._zoomFactor; } public setZoomFactor(zoomFactor: number): void { this._zoomFactor = zoomFactor; } // --- Pixel Ratio public getPixelRatio(): number { let ctx: any = document.createElement('canvas').getContext('2d'); let dpr = window.devicePixelRatio || 1; let bsr = ctx.webkitBackingStorePixelRatio || ctx.mozBackingStorePixelRatio || ctx.msBackingStorePixelRatio || ctx.oBackingStorePixelRatio || ctx.backingStorePixelRatio || 1; return dpr / bsr; } // --- Fullscreen private _fullscreen: boolean = false; private readonly _onDidChangeFullscreen = new Emitter<void>(); public readonly onDidChangeFullscreen: Event<void> = this._onDidChangeFullscreen.event; public setFullscreen(fullscreen: boolean): void { if (this._fullscreen === fullscreen) { return; } this._fullscreen = fullscreen; this._onDidChangeFullscreen.fire(); } public isFullscreen(): boolean { return this._fullscreen; } } /** A zoom index, e.g. 1, 2, 3 */ export function setZoomLevel(zoomLevel: number, isTrusted: boolean): void { WindowManager.INSTANCE.setZoomLevel(zoomLevel, isTrusted); } export function getZoomLevel(): number { return WindowManager.INSTANCE.getZoomLevel(); } /** Returns the time (in ms) since the zoom level was changed */ export function getTimeSinceLastZoomLevelChanged(): number { return WindowManager.INSTANCE.getTimeSinceLastZoomLevelChanged(); } export function onDidChangeZoomLevel(callback: (zoomLevel: number) => void): IDisposable { return WindowManager.INSTANCE.onDidChangeZoomLevel(callback); } /** The zoom scale for an index, e.g. 1, 1.2, 1.4 */ export function getZoomFactor(): number { return WindowManager.INSTANCE.getZoomFactor(); } export function setZoomFactor(zoomFactor: number): void { WindowManager.INSTANCE.setZoomFactor(zoomFactor); } export function getPixelRatio(): number { return WindowManager.INSTANCE.getPixelRatio(); } export function setFullscreen(fullscreen: boolean): void { WindowManager.INSTANCE.setFullscreen(fullscreen); } export function isFullscreen(): boolean { return WindowManager.INSTANCE.isFullscreen(); } export const onDidChangeFullscreen = WindowManager.INSTANCE.onDidChangeFullscreen; const userAgent = navigator.userAgent; export const isEdge = (userAgent.indexOf('Edge/') >= 0); export const isOpera = (userAgent.indexOf('Opera') >= 0); export const isFirefox = (userAgent.indexOf('Firefox') >= 0); export const isWebKit = (userAgent.indexOf('AppleWebKit') >= 0); export const isChrome = (userAgent.indexOf('Chrome') >= 0); export const isSafari = (!isChrome && (userAgent.indexOf('Safari') >= 0)); export const isWebkitWebView = (!isChrome && !isSafari && isWebKit); export const isIPad = (userAgent.indexOf('iPad') >= 0 || (isSafari && navigator.maxTouchPoints > 0)); export const isEdgeWebView = isEdge && (userAgent.indexOf('WebView/') >= 0); export const isStandalone = (window.matchMedia && window.matchMedia('(display-mode: standalone)').matches);
src/vs/base/browser/browser.ts
0
https://github.com/microsoft/vscode/commit/574ee2032cc24ed250ef15962ce100838d4e5e4a
[ 0.00017717693117447197, 0.00017352191207464784, 0.00016822907491587102, 0.000174016720848158, 0.000002288992163812509 ]
{ "id": 1, "code_window": [ "\tprivate _configHelper: TerminalConfigHelper;\n", "\tprivate _terminalContainer: HTMLElement | undefined;\n", "\tprivate _nativeWindowsDelegate: ITerminalNativeWindowsDelegate | undefined;\n", "\tprivate _remoteTerminalsInitialized: Promise<void> | undefined;\n", "\tprivate _willFocusNewTerminal = false;\n", "\tprivate _connectionState: TerminalConnectionState;\n", "\n", "\tpublic get configHelper(): ITerminalConfigHelper { return this._configHelper; }\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/contrib/terminal/browser/terminalService.ts", "type": "replace", "edit_start_line_idx": 66 }
// ----------------------------------------------------------------------------------------- // ----------------------------------------------------------------------------------------- // This file overrides licenses only for OSS components which do not appear in `cgmanifest.json`. // i.e. for OSS components that are detected from `yarn.lock` or `Cargo.lock` files. // // DO NOT EDIT THIS FILE UNLESS THE OSS TOOL INDICATES THAT YOU SHOULD. // [ { // Reason: The license at https://github.com/aadsm/jschardet/blob/master/LICENSE // does not include a clear Copyright statement and does not credit authors. "name": "jschardet", "prependLicenseText": [ "Chardet was originally ported from C++ by Mark Pilgrim. It is now maintained", " by Dan Blanchard and Ian Cordasco, and was formerly maintained by Erik Rose.", " JSChardet was ported from python to JavaScript by António Afonso ", " (https://github.com/aadsm/jschardet) and transformed into an npm package by ", "Markus Ast (https://github.com/brainafk)" ] }, { // Reason: The license at https://github.com/microsoft/TypeScript/blob/master/LICENSE.txt // does not include a clear Copyright statement. "name": "typescript", "prependLicenseText": [ "Copyright (c) Microsoft Corporation. All rights reserved." ] }, { "name": "tunnel-agent", "prependLicenseText": [ "Copyright (c) tunnel-agent authors" ] }, { // Reason: Waiting for https://github.com/segmentio/noop-logger/issues/2 "name": "noop-logger", "fullLicenseText": [ "This project is licensed under the MIT license.", "Copyrights are respective of each contributor listed at the beginning of each definition file.", "", "Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:", "", "The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.", "", "THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE." ] }, { // Reason: The license at https://git.coolaj86.com/coolaj86/atob.js/src/branch/master/LICENSE // cannot be found by the OSS tool automatically. "name": "atob", "fullLicenseText": [ "The MIT License (MIT)", "", "Copyright (c) 2015 AJ ONeal", "", "Permission is hereby granted, free of charge, to any person obtaining a copy", "of this software and associated documentation files (the \"Software\"), to deal", "in the Software without restriction, including without limitation the rights", "to use, copy, modify, merge, publish, distribute, sublicense, and/or sell", "copies of the Software, and to permit persons to whom the Software is", "furnished to do so, subject to the following conditions:", "", "The above copyright notice and this permission notice shall be included in all", "copies or substantial portions of the Software.", "", "THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR", "IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,", "FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE", "AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER", "LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,", "OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE", "SOFTWARE." ] }, { // Reason: The license at https://github.com/microsoft/tslib/blob/master/LICENSE.txt // does not include a clear Copyright statement. "name": "tslib", "prependLicenseText": [ "Copyright (c) Microsoft Corporation. All rights reserved." ] }, { // Reason: The license at https://github.com/rbuckton/reflect-metadata/blob/master/LICENSE // does not include a clear Copyright statement (it's in https://github.com/rbuckton/reflect-metadata/blob/master/CopyrightNotice.txt). "name": "reflect-metadata", "prependLicenseText": [ "Copyright (c) Microsoft Corporation. All rights reserved." ] }, { // Reason: The license at https://github.com/reem/rust-unreachable/blob/master/LICENSE-MIT // cannot be found by the OSS tool automatically. "name": "reem/rust-unreachable", "fullLicenseText": [ "Copyright (c) 2015 The rust-unreachable Developers", "", "Permission is hereby granted, free of charge, to any person obtaining a copy", "of this software and associated documentation files (the \"Software\"), to deal", "in the Software without restriction, including without limitation the rights", "to use, copy, modify, merge, publish, distribute, sublicense, and/or sell", "copies of the Software, and to permit persons to whom the Software is", "furnished to do so, subject to the following conditions:", "", "The above copyright notice and this permission notice shall be included in all", "copies or substantial portions of the Software.", "", "THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR", "IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,", "FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE", "AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER", "LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,", "OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE", "SOFTWARE." ] }, { // Reason: The license at https://github.com/reem/rust-void/blob/master/LICENSE-MIT // cannot be found by the OSS tool automatically. "name": "reem/rust-void", "fullLicenseText": [ "Copyright (c) 2015 The rust-void Developers", "", "Permission is hereby granted, free of charge, to any person obtaining a copy", "of this software and associated documentation files (the \"Software\"), to deal", "in the Software without restriction, including without limitation the rights", "to use, copy, modify, merge, publish, distribute, sublicense, and/or sell", "copies of the Software, and to permit persons to whom the Software is", "furnished to do so, subject to the following conditions:", "", "The above copyright notice and this permission notice shall be included in all", "copies or substantial portions of the Software.", "", "THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR", "IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,", "FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE", "AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER", "LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,", "OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE", "SOFTWARE." ] }, { // Reason: The license at https://github.com/mrhooray/crc-rs/blob/master/LICENSE-MIT // cannot be found by the OSS tool automatically. "name": "mrhooray/crc-rs", "fullLicenseText": [ "MIT License", "", "Copyright (c) 2017 crc-rs Developers", "", "Permission is hereby granted, free of charge, to any person obtaining a copy", "of this software and associated documentation files (the \"Software\"), to deal", "in the Software without restriction, including without limitation the rights", "to use, copy, modify, merge, publish, distribute, sublicense, and/or sell", "copies of the Software, and to permit persons to whom the Software is", "furnished to do so, subject to the following conditions:", "", "The above copyright notice and this permission notice shall be included in all", "copies or substantial portions of the Software.", "", "THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR", "IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,", "FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE", "AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER", "LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,", "OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE", "SOFTWARE." ] }, { // Reason: The license at https://github.com/floatdrop/pinkie/blob/master/license // cannot be found by the OSS tool automatically. "name": "pinkie", "fullLicenseText": [ "The MIT License (MIT)", "", "Copyright (c) Vsevolod Strukchinsky <[email protected]> (github.com/floatdrop)", "", "Permission is hereby granted, free of charge, to any person obtaining a copy", "of this software and associated documentation files (the \"Software\"), to deal", "in the Software without restriction, including without limitation the rights", "to use, copy, modify, merge, publish, distribute, sublicense, and/or sell", "copies of the Software, and to permit persons to whom the Software is", "furnished to do so, subject to the following conditions:", "", "The above copyright notice and this permission notice shall be included in", "all copies or substantial portions of the Software.", "", "THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR", "IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,", "FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE", "AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER", "LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,", "OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN", "THE SOFTWARE." ] }, { "name": "big-integer", "prependLicenseText": [ "Copyright released to public domain" ] }, { // Reason: The license at https://github.com/justmoon/node-extend/blob/main/LICENSE // cannot be found by the OSS tool automatically. "name": "extend", "fullLicenseText": [ "The MIT License (MIT)", "", "Copyright (c) 2014 Stefan Thomas", "", "Permission is hereby granted, free of charge, to any person obtaining", "a copy of this software and associated documentation files (the", "\"Software\"), to deal in the Software without restriction, including", "without limitation the rights to use, copy, modify, merge, publish,", "distribute, sublicense, and/or sell copies of the Software, and to", "permit persons to whom the Software is furnished to do so, subject to", "the following conditions:", "", "The above copyright notice and this permission notice shall be", "included in all copies or substantial portions of the Software.", "", "THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,", "EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF", "MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND", "NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE", "LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION", "OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION", "WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE." ] }, { // Reason: The license at https://github.com/retep998/winapi-rs/blob/0.3/LICENSE-MIT // cannot be found by the OSS tool automatically. "name": "retep998/winapi-rs", "fullLicenseText": [ "Copyright (c) 2015-2018 The winapi-rs Developers", "", "Permission is hereby granted, free of charge, to any person obtaining a copy", "of this software and associated documentation files (the \"Software\"), to deal", "in the Software without restriction, including without limitation the rights", "to use, copy, modify, merge, publish, distribute, sublicense, and/or sell", "copies of the Software, and to permit persons to whom the Software is", "furnished to do so, subject to the following conditions:", "", "The above copyright notice and this permission notice shall be included in all", "copies or substantial portions of the Software.", "", "THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR", "IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,", "FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE", "AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER", "LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,", "OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE", "SOFTWARE." ] }, { // Reason: The license at https://github.com/digitaldesignlabs/es6-promisify/blob/main/LICENSE // cannot be found by the OSS tool automatically. "name": "es6-promisify", "fullLicenseText": [ "Copyright (c) 2014 Mike Hall / Digital Design Labs", "", "Permission is hereby granted, free of charge, to any person obtaining a copy", "of this software and associated documentation files (the \"Software\"), to deal", "in the Software without restriction, including without limitation the rights", "to use, copy, modify, merge, publish, distribute, sublicense, and/or sell", "copies of the Software, and to permit persons to whom the Software is", "furnished to do so, subject to the following conditions:", "", "The above copyright notice and this permission notice shall be included in all", "copies or substantial portions of the Software.", "", "THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR", "IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,", "FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE", "AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER", "LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,", "OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE", "SOFTWARE." ] }, { // Reason: The license at https://github.com/zkat/json-parse-better-errors/blob/latest/LICENSE.md // cannot be found by the OSS tool automatically. "name": "json-parse-better-errors", "fullLicenseText": [ "Copyright 2017 Kat Marchán", "", "Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the", "\"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute,", "sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following", "conditions:", "", "The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.", "", "THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE", "WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS", "OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR", "OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE." ] }, { // Reason: The license at https://github.com/time-rs/time/blob/main/LICENSE-MIT // cannot be found by the OSS tool automatically. "name": "time-rs/time", "fullLicenseText": [ "Copyright (c) 2019 Jacob Pratt", "", "Permission is hereby granted, free of charge, to any person obtaining a copy", "of this software and associated documentation files (the \"Software\"), to deal", "in the Software without restriction, including without limitation the rights", "to use, copy, modify, merge, publish, distribute, sublicense, and/or sell", "copies of the Software, and to permit persons to whom the Software is", "furnished to do so, subject to the following conditions:", "", "The above copyright notice and this permission notice shall be included in all", "copies or substantial portions of the Software.", "", "THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR", "IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,", "FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE", "AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER", "LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,", "OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE", "SOFTWARE." ] }, { // Reason: The license at https://github.com/colorjs/color-name/blob/master/LICENSE // cannot be found by the OSS tool automatically. "name": "color-name", "fullLicenseText": [ "The MIT License (MIT)", "Copyright (c) 2015 Dmitry Ivanov", "", "Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:", "", "The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.", "", "THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE." ] }, { // Reason: The license cannot be found by the tool due to access controls on the repository "name": "tas-client-umd", "fullLicenseText": [ "MIT License", "Copyright (c) 2020 - present Microsoft Corporation", "", "Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:", "", "The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.", "", "THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE." ] }, { // Reason: The license at https://github.com/acornjs/acorn/blob/master/acorn/LICENSE // cannot be found by the OSS tool automatically. "name": "acorn", "fullLicenseText": [ "MIT License", "Copyright (C) 2012-2018 by various contributors (see AUTHORS)", "", "Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:", "", "The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.", "", "THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE." ] }, { // Reason: The license at https://github.com/acornjs/acorn/blob/master/acorn-loose/LICENSE // cannot be found by the OSS tool automatically. "name": "acorn-loose", "fullLicenseText": [ "MIT License", "Copyright (C) 2012-2018 by various contributors (see AUTHORS)", "", "Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:", "", "The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.", "", "THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE." ] } ]
cglicenses.json
0
https://github.com/microsoft/vscode/commit/574ee2032cc24ed250ef15962ce100838d4e5e4a
[ 0.00017909062444232404, 0.00017492759798187762, 0.00017048706649802625, 0.00017458420188631862, 0.0000024562318685639184 ]
{ "id": 2, "code_window": [ "\tprivate readonly _onDidRegisterProcessSupport = new Emitter<void>();\n", "\tpublic get onDidRegisterProcessSupport(): Event<void> { return this._onDidRegisterProcessSupport.event; }\n", "\tprivate readonly _onDidChangeConnectionState = new Emitter<void>();\n", "\tpublic get onDidChangeConnectionState(): Event<void> { return this._onDidChangeConnectionState.event; }\n", "\tpublic get connectionState(): TerminalConnectionState { return this._connectionState; }\n", "\tpublic set willFocusNewTerminal(v: boolean) { this._willFocusNewTerminal = v; }\n", "\n", "\tconstructor(\n", "\t\t@IContextKeyService private _contextKeyService: IContextKeyService,\n", "\t\t@IWorkbenchLayoutService private _layoutService: IWorkbenchLayoutService,\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/contrib/terminal/browser/terminalService.ts", "type": "replace", "edit_start_line_idx": 104 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as dom from 'vs/base/browser/dom'; import * as nls from 'vs/nls'; import * as platform from 'vs/base/common/platform'; import { Action, IAction, Separator, IActionViewItem } from 'vs/base/common/actions'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IContextMenuService } from 'vs/platform/contextview/browser/contextView'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IThemeService, IColorTheme, registerThemingParticipant, ICssStyleCollector } from 'vs/platform/theme/common/themeService'; import { TerminalFindWidget } from 'vs/workbench/contrib/terminal/browser/terminalFindWidget'; import { KillTerminalAction, SwitchTerminalAction, SwitchTerminalActionViewItem, CopyTerminalSelectionAction, TerminalPasteAction, ClearTerminalAction, SelectAllTerminalAction, CreateNewTerminalAction, SplitTerminalAction } from 'vs/workbench/contrib/terminal/browser/terminalActions'; import { StandardMouseEvent } from 'vs/base/browser/mouseEvent'; import { URI } from 'vs/base/common/uri'; import { TERMINAL_BACKGROUND_COLOR, TERMINAL_BORDER_COLOR } from 'vs/workbench/contrib/terminal/common/terminalColorRegistry'; import { DataTransfers } from 'vs/base/browser/dnd'; import { INotificationService, IPromptChoice, Severity } from 'vs/platform/notification/common/notification'; import { ITerminalService } from 'vs/workbench/contrib/terminal/browser/terminal'; import { BrowserFeatures } from 'vs/base/browser/canIUse'; import { ViewPane, IViewPaneOptions } from 'vs/workbench/browser/parts/views/viewPaneContainer'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { IViewDescriptorService } from 'vs/workbench/common/views'; import { IOpenerService } from 'vs/platform/opener/common/opener'; import { PANEL_BACKGROUND, SIDE_BAR_BACKGROUND } from 'vs/workbench/common/theme'; import { Orientation } from 'vs/base/browser/ui/sash/sash'; const FIND_FOCUS_CLASS = 'find-focused'; export class TerminalViewPane extends ViewPane { private _actions: IAction[] | undefined; private _copyContextMenuAction: IAction | undefined; private _contextMenuActions: IAction[] | undefined; private _cancelContextMenu: boolean = false; private _fontStyleElement: HTMLElement | undefined; private _parentDomElement: HTMLElement | undefined; private _terminalContainer: HTMLElement | undefined; private _findWidget: TerminalFindWidget | undefined; private _splitTerminalAction: IAction | undefined; private _terminalsInitialized = false; private _bodyDimensions: { width: number, height: number } = { width: 0, height: 0 }; constructor( options: IViewPaneOptions, @IKeybindingService keybindingService: IKeybindingService, @IContextKeyService contextKeyService: IContextKeyService, @IViewDescriptorService viewDescriptorService: IViewDescriptorService, @IConfigurationService configurationService: IConfigurationService, @IContextMenuService private readonly _contextMenuService: IContextMenuService, @IInstantiationService private readonly _instantiationService: IInstantiationService, @ITerminalService private readonly _terminalService: ITerminalService, @IThemeService protected readonly themeService: IThemeService, @ITelemetryService telemetryService: ITelemetryService, @INotificationService private readonly _notificationService: INotificationService, @IOpenerService openerService: IOpenerService, ) { super(options, keybindingService, _contextMenuService, configurationService, contextKeyService, viewDescriptorService, _instantiationService, openerService, themeService, telemetryService); this._terminalService.onDidRegisterProcessSupport(() => { if (this._actions) { for (const action of this._actions) { action.enabled = true; } } this._onDidChangeViewWelcomeState.fire(); }); this._register(this.onDidBlur(() => { this._terminalService.willFocusNewTerminal = false; })); } protected renderBody(container: HTMLElement): void { super.renderBody(container); if (this.shouldShowWelcome()) { return; } this._parentDomElement = container; this._parentDomElement.classList.add('integrated-terminal'); this._fontStyleElement = document.createElement('style'); this._terminalContainer = document.createElement('div'); this._terminalContainer.classList.add('terminal-outer-container'); this._findWidget = this._instantiationService.createInstance(TerminalFindWidget, this._terminalService.getFindState()); this._findWidget.focusTracker.onDidFocus(() => this._terminalContainer!.classList.add(FIND_FOCUS_CLASS)); this._parentDomElement.appendChild(this._fontStyleElement); this._parentDomElement.appendChild(this._terminalContainer); this._parentDomElement.appendChild(this._findWidget.getDomNode()); this._attachEventListeners(this._parentDomElement, this._terminalContainer); this._terminalService.setContainers(container, this._terminalContainer); this._register(this.themeService.onDidColorThemeChange(theme => this._updateTheme(theme))); this._register(this.configurationService.onDidChangeConfiguration(e => { if (e.affectsConfiguration('terminal.integrated.fontFamily') || e.affectsConfiguration('editor.fontFamily')) { const configHelper = this._terminalService.configHelper; if (!configHelper.configFontIsMonospace()) { const choices: IPromptChoice[] = [{ label: nls.localize('terminal.useMonospace', "Use 'monospace'"), run: () => this.configurationService.updateValue('terminal.integrated.fontFamily', 'monospace'), }]; this._notificationService.prompt(Severity.Warning, nls.localize('terminal.monospaceOnly', "The terminal only supports monospace fonts. Be sure to restart VS Code if this is a newly installed font."), choices); } } })); this._updateTheme(); this._register(this.onDidChangeBodyVisibility(visible => { if (visible) { const hadTerminals = !!this._terminalService.terminalTabs.length; if (this._terminalsInitialized) { if (!hadTerminals) { this._terminalService.createTerminal(); } } else { this._terminalsInitialized = true; this._terminalService.initializeTerminals(); } this._updateTheme(); if (hadTerminals) { this._terminalService.getActiveTab()?.setVisible(visible); } else { // TODO@Tyriar - this call seems unnecessary this.layoutBody(this._bodyDimensions.height, this._bodyDimensions.width); } } else { this._terminalService.getActiveTab()?.setVisible(false); } })); // Force another layout (first is setContainers) since config has changed this.layoutBody(this._terminalContainer.offsetHeight, this._terminalContainer.offsetWidth); } protected layoutBody(height: number, width: number): void { super.layoutBody(height, width); if (this.shouldShowWelcome()) { return; } this._bodyDimensions.width = width; this._bodyDimensions.height = height; this._terminalService.terminalTabs.forEach(t => t.layout(width, height)); // Update orientation of split button icon if (this._splitTerminalAction) { this._splitTerminalAction.class = this.orientation === Orientation.HORIZONTAL ? SplitTerminalAction.HORIZONTAL_CLASS : SplitTerminalAction.VERTICAL_CLASS; } } public getActions(): IAction[] { if (!this._actions) { this._splitTerminalAction = this._instantiationService.createInstance(SplitTerminalAction, SplitTerminalAction.ID, SplitTerminalAction.LABEL); this._actions = [ this._instantiationService.createInstance(SwitchTerminalAction, SwitchTerminalAction.ID, SwitchTerminalAction.LABEL), this._instantiationService.createInstance(CreateNewTerminalAction, CreateNewTerminalAction.ID, CreateNewTerminalAction.SHORT_LABEL), this._splitTerminalAction, this._instantiationService.createInstance(KillTerminalAction, KillTerminalAction.ID, KillTerminalAction.PANEL_LABEL) ]; for (const action of this._actions) { if (!this._terminalService.isProcessSupportRegistered) { action.enabled = false; } this._register(action); } } return this._actions; } private _getContextMenuActions(): IAction[] { if (!this._contextMenuActions || !this._copyContextMenuAction) { this._copyContextMenuAction = this._instantiationService.createInstance(CopyTerminalSelectionAction, CopyTerminalSelectionAction.ID, CopyTerminalSelectionAction.SHORT_LABEL); const clipboardActions = []; if (BrowserFeatures.clipboard.writeText) { clipboardActions.push(this._copyContextMenuAction); } if (BrowserFeatures.clipboard.readText) { clipboardActions.push(this._instantiationService.createInstance(TerminalPasteAction, TerminalPasteAction.ID, TerminalPasteAction.SHORT_LABEL)); } clipboardActions.push(this._instantiationService.createInstance(SelectAllTerminalAction, SelectAllTerminalAction.ID, SelectAllTerminalAction.LABEL)); this._contextMenuActions = [ this._instantiationService.createInstance(CreateNewTerminalAction, CreateNewTerminalAction.ID, CreateNewTerminalAction.SHORT_LABEL), this._instantiationService.createInstance(SplitTerminalAction, SplitTerminalAction.ID, SplitTerminalAction.SHORT_LABEL), new Separator(), ...clipboardActions, new Separator(), this._instantiationService.createInstance(ClearTerminalAction, ClearTerminalAction.ID, ClearTerminalAction.LABEL), new Separator(), this._instantiationService.createInstance(KillTerminalAction, KillTerminalAction.ID, KillTerminalAction.PANEL_LABEL) ]; this._contextMenuActions.forEach(a => { this._register(a); }); } const activeInstance = this._terminalService.getActiveInstance(); this._copyContextMenuAction.enabled = !!activeInstance && activeInstance.hasSelection(); return this._contextMenuActions; } public getActionViewItem(action: Action): IActionViewItem | undefined { if (action.id === SwitchTerminalAction.ID) { return this._instantiationService.createInstance(SwitchTerminalActionViewItem, action); } return super.getActionViewItem(action); } public focus() { if (this._terminalService.getActiveInstance()) { this._terminalService.getActiveInstance()?.focusWhenReady(); } else { this._terminalService.willFocusNewTerminal = true; } } public focusFindWidget() { const activeInstance = this._terminalService.getActiveInstance(); if (activeInstance && activeInstance.hasSelection() && activeInstance.selection!.indexOf('\n') === -1) { this._findWidget!.reveal(activeInstance.selection); } else { this._findWidget!.reveal(); } } public hideFindWidget() { this._findWidget!.hide(); } public showFindWidget() { const activeInstance = this._terminalService.getActiveInstance(); if (activeInstance && activeInstance.hasSelection() && activeInstance.selection!.indexOf('\n') === -1) { this._findWidget!.show(activeInstance.selection); } else { this._findWidget!.show(); } } public getFindWidget(): TerminalFindWidget { return this._findWidget!; } private _attachEventListeners(parentDomElement: HTMLElement, terminalContainer: HTMLElement): void { this._register(dom.addDisposableListener(parentDomElement, 'mousedown', async (event: MouseEvent) => { if (this._terminalService.terminalInstances.length === 0) { return; } if (event.which === 2 && platform.isLinux) { // Drop selection and focus terminal on Linux to enable middle button paste when click // occurs on the selection itself. const terminal = this._terminalService.getActiveInstance(); if (terminal) { terminal.focus(); } } else if (event.which === 3) { const rightClickBehavior = this._terminalService.configHelper.config.rightClickBehavior; if (rightClickBehavior === 'copyPaste' || rightClickBehavior === 'paste') { const terminal = this._terminalService.getActiveInstance(); if (!terminal) { return; } // copyPaste: Shift+right click should open context menu if (rightClickBehavior === 'copyPaste' && event.shiftKey) { this._openContextMenu(event); return; } if (rightClickBehavior === 'copyPaste' && terminal.hasSelection()) { await terminal.copySelection(); terminal.clearSelection(); } else { terminal.paste(); } // Clear selection after all click event bubbling is finished on Mac to prevent // right-click selecting a word which is seemed cannot be disabled. There is a // flicker when pasting but this appears to give the best experience if the // setting is enabled. if (platform.isMacintosh) { setTimeout(() => { terminal.clearSelection(); }, 0); } this._cancelContextMenu = true; } } })); this._register(dom.addDisposableListener(parentDomElement, 'contextmenu', (event: MouseEvent) => { if (!this._cancelContextMenu) { this._openContextMenu(event); } event.preventDefault(); event.stopImmediatePropagation(); this._cancelContextMenu = false; })); this._register(dom.addDisposableListener(document, 'keydown', (event: KeyboardEvent) => { terminalContainer.classList.toggle('alt-active', !!event.altKey); })); this._register(dom.addDisposableListener(document, 'keyup', (event: KeyboardEvent) => { terminalContainer.classList.toggle('alt-active', !!event.altKey); })); this._register(dom.addDisposableListener(parentDomElement, 'keyup', (event: KeyboardEvent) => { if (event.keyCode === 27) { // Keep terminal open on escape event.stopPropagation(); } })); this._register(dom.addDisposableListener(parentDomElement, dom.EventType.DROP, async (e: DragEvent) => { if (e.target === this._parentDomElement || dom.isAncestor(e.target as HTMLElement, parentDomElement)) { if (!e.dataTransfer) { return; } // Check if files were dragged from the tree explorer let path: string | undefined; const resources = e.dataTransfer.getData(DataTransfers.RESOURCES); if (resources) { path = URI.parse(JSON.parse(resources)[0]).fsPath; } else if (e.dataTransfer.files.length > 0 && e.dataTransfer.files[0].path /* Electron only */) { // Check if the file was dragged from the filesystem path = URI.file(e.dataTransfer.files[0].path).fsPath; } if (!path) { return; } const terminal = this._terminalService.getActiveInstance(); if (terminal) { const preparedPath = await this._terminalService.preparePathForTerminalAsync(path, terminal.shellLaunchConfig.executable, terminal.title, terminal.shellType); terminal.sendText(preparedPath, false); terminal.focus(); } } })); } private _openContextMenu(event: MouseEvent): void { const standardEvent = new StandardMouseEvent(event); const anchor: { x: number, y: number } = { x: standardEvent.posx, y: standardEvent.posy }; this._contextMenuService.showContextMenu({ getAnchor: () => anchor, getActions: () => this._getContextMenuActions(), getActionsContext: () => this._parentDomElement }); } private _updateTheme(theme?: IColorTheme): void { if (!theme) { theme = this.themeService.getColorTheme(); } this._findWidget?.updateTheme(theme); } shouldShowWelcome(): boolean { return !this._terminalService.isProcessSupportRegistered; } } registerThemingParticipant((theme: IColorTheme, collector: ICssStyleCollector) => { const panelBackgroundColor = theme.getColor(TERMINAL_BACKGROUND_COLOR) || theme.getColor(PANEL_BACKGROUND); collector.addRule(`.monaco-workbench .part.panel .pane-body.integrated-terminal .terminal-outer-container { background-color: ${panelBackgroundColor ? panelBackgroundColor.toString() : ''}; }`); const sidebarBackgroundColor = theme.getColor(TERMINAL_BACKGROUND_COLOR) || theme.getColor(SIDE_BAR_BACKGROUND); collector.addRule(`.monaco-workbench .part.sidebar .pane-body.integrated-terminal .terminal-outer-container { background-color: ${sidebarBackgroundColor ? sidebarBackgroundColor.toString() : ''}; }`); const borderColor = theme.getColor(TERMINAL_BORDER_COLOR); if (borderColor) { collector.addRule(`.monaco-workbench .pane-body.integrated-terminal .split-view-view:not(:first-child) { border-color: ${borderColor.toString()}; }`); } });
src/vs/workbench/contrib/terminal/browser/terminalView.ts
1
https://github.com/microsoft/vscode/commit/574ee2032cc24ed250ef15962ce100838d4e5e4a
[ 0.9990585446357727, 0.07709190249443054, 0.00016322203737217933, 0.00017403977108187973, 0.2659817039966583 ]
{ "id": 2, "code_window": [ "\tprivate readonly _onDidRegisterProcessSupport = new Emitter<void>();\n", "\tpublic get onDidRegisterProcessSupport(): Event<void> { return this._onDidRegisterProcessSupport.event; }\n", "\tprivate readonly _onDidChangeConnectionState = new Emitter<void>();\n", "\tpublic get onDidChangeConnectionState(): Event<void> { return this._onDidChangeConnectionState.event; }\n", "\tpublic get connectionState(): TerminalConnectionState { return this._connectionState; }\n", "\tpublic set willFocusNewTerminal(v: boolean) { this._willFocusNewTerminal = v; }\n", "\n", "\tconstructor(\n", "\t\t@IContextKeyService private _contextKeyService: IContextKeyService,\n", "\t\t@IWorkbenchLayoutService private _layoutService: IWorkbenchLayoutService,\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/contrib/terminal/browser/terminalService.ts", "type": "replace", "edit_start_line_idx": 104 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { KeyboardLayoutContribution } from 'vs/workbench/services/keybinding/browser/keyboardLayouts/_.contribution'; KeyboardLayoutContribution.INSTANCE.registerKeyboardLayout({ layout: { name: '00000807', id: '', text: 'Swiss German' }, secondaryLayouts: [], mapping: { Sleep: [], WakeUp: [], KeyA: ['a', 'A', '', '', 0, 'VK_A'], KeyB: ['b', 'B', '', '', 0, 'VK_B'], KeyC: ['c', 'C', '', '', 0, 'VK_C'], KeyD: ['d', 'D', '', '', 0, 'VK_D'], KeyE: ['e', 'E', '€', '', 0, 'VK_E'], KeyF: ['f', 'F', '', '', 0, 'VK_F'], KeyG: ['g', 'G', '', '', 0, 'VK_G'], KeyH: ['h', 'H', '', '', 0, 'VK_H'], KeyI: ['i', 'I', '', '', 0, 'VK_I'], KeyJ: ['j', 'J', '', '', 0, 'VK_J'], KeyK: ['k', 'K', '', '', 0, 'VK_K'], KeyL: ['l', 'L', '', '', 0, 'VK_L'], KeyM: ['m', 'M', '', '', 0, 'VK_M'], KeyN: ['n', 'N', '', '', 0, 'VK_N'], KeyO: ['o', 'O', '', '', 0, 'VK_O'], KeyP: ['p', 'P', '', '', 0, 'VK_P'], KeyQ: ['q', 'Q', '', '', 0, 'VK_Q'], KeyR: ['r', 'R', '', '', 0, 'VK_R'], KeyS: ['s', 'S', '', '', 0, 'VK_S'], KeyT: ['t', 'T', '', '', 0, 'VK_T'], KeyU: ['u', 'U', '', '', 0, 'VK_U'], KeyV: ['v', 'V', '', '', 0, 'VK_V'], KeyW: ['w', 'W', '', '', 0, 'VK_W'], KeyX: ['x', 'X', '', '', 0, 'VK_X'], KeyY: ['z', 'Z', '', '', 0, 'VK_Z'], KeyZ: ['y', 'Y', '', '', 0, 'VK_Y'], Digit1: ['1', '+', '¦', '', 0, 'VK_1'], Digit2: ['2', '"', '@', '', 0, 'VK_2'], Digit3: ['3', '*', '#', '', 0, 'VK_3'], Digit4: ['4', 'ç', '°', '', 0, 'VK_4'], Digit5: ['5', '%', '§', '', 0, 'VK_5'], Digit6: ['6', '&', '¬', '', 0, 'VK_6'], Digit7: ['7', '/', '|', '', 0, 'VK_7'], Digit8: ['8', '(', '¢', '', 0, 'VK_8'], Digit9: ['9', ')', '', '', 0, 'VK_9'], Digit0: ['0', '=', '', '', 0, 'VK_0'], Enter: [], Escape: [], Backspace: [], Tab: [], Space: [' ', ' ', '', '', 0, 'VK_SPACE'], Minus: ['\'', '?', '´', '', 0, 'VK_OEM_4'], Equal: ['^', '`', '~', '', 0, 'VK_OEM_6'], BracketLeft: ['ü', 'è', '[', '', 0, 'VK_OEM_1'], BracketRight: ['¨', '!', ']', '', 0, 'VK_OEM_3'], Backslash: ['$', '£', '}', '', 0, 'VK_OEM_8'], Semicolon: ['ö', 'é', '', '', 0, 'VK_OEM_7'], Quote: ['ä', 'à', '{', '', 0, 'VK_OEM_5'], Backquote: ['§', '°', '', '', 0, 'VK_OEM_2'], Comma: [',', ';', '', '', 0, 'VK_OEM_COMMA'], Period: ['.', ':', '', '', 0, 'VK_OEM_PERIOD'], Slash: ['-', '_', '', '', 0, 'VK_OEM_MINUS'], CapsLock: [], F1: [], F2: [], F3: [], F4: [], F5: [], F6: [], F7: [], F8: [], F9: [], F10: [], F11: [], F12: [], PrintScreen: [], ScrollLock: [], Pause: [], Insert: [], Home: [], PageUp: [], Delete: [], End: [], PageDown: [], ArrowRight: [], ArrowLeft: [], ArrowDown: [], ArrowUp: [], NumLock: [], NumpadDivide: ['/', '/', '', '', 0, 'VK_DIVIDE'], NumpadMultiply: ['*', '*', '', '', 0, 'VK_MULTIPLY'], NumpadSubtract: ['-', '-', '', '', 0, 'VK_SUBTRACT'], NumpadAdd: ['+', '+', '', '', 0, 'VK_ADD'], NumpadEnter: [], Numpad1: [], Numpad2: [], Numpad3: [], Numpad4: [], Numpad5: [], Numpad6: [], Numpad7: [], Numpad8: [], Numpad9: [], Numpad0: [], NumpadDecimal: [], IntlBackslash: ['<', '>', '\\', '', 0, 'VK_OEM_102'], ContextMenu: [], Power: [], NumpadEqual: [], F13: [], F14: [], F15: [], F16: [], F17: [], F18: [], F19: [], F20: [], F21: [], F22: [], F23: [], F24: [], Help: [], Undo: [], Cut: [], Copy: [], Paste: [], AudioVolumeMute: [], AudioVolumeUp: [], AudioVolumeDown: [], NumpadComma: [], IntlRo: [], KanaMode: [], IntlYen: [], Convert: [], NonConvert: [], Lang1: [], Lang2: [], Lang3: [], Lang4: [], ControlLeft: [], ShiftLeft: [], AltLeft: [], MetaLeft: [], ControlRight: [], ShiftRight: [], AltRight: [], MetaRight: [], MediaTrackNext: [], MediaTrackPrevious: [], MediaStop: [], Eject: [], MediaPlayPause: [], MediaSelect: [], LaunchMail: [], LaunchApp2: [], LaunchApp1: [], BrowserSearch: [], BrowserHome: [], BrowserBack: [], BrowserForward: [], BrowserStop: [], BrowserRefresh: [], BrowserFavorites: [] } });
src/vs/workbench/services/keybinding/browser/keyboardLayouts/de-swiss.win.ts
0
https://github.com/microsoft/vscode/commit/574ee2032cc24ed250ef15962ce100838d4e5e4a
[ 0.00017582518921699375, 0.0001737499114824459, 0.00017057047807611525, 0.00017412575834896415, 0.0000014595609627576778 ]
{ "id": 2, "code_window": [ "\tprivate readonly _onDidRegisterProcessSupport = new Emitter<void>();\n", "\tpublic get onDidRegisterProcessSupport(): Event<void> { return this._onDidRegisterProcessSupport.event; }\n", "\tprivate readonly _onDidChangeConnectionState = new Emitter<void>();\n", "\tpublic get onDidChangeConnectionState(): Event<void> { return this._onDidChangeConnectionState.event; }\n", "\tpublic get connectionState(): TerminalConnectionState { return this._connectionState; }\n", "\tpublic set willFocusNewTerminal(v: boolean) { this._willFocusNewTerminal = v; }\n", "\n", "\tconstructor(\n", "\t\t@IContextKeyService private _contextKeyService: IContextKeyService,\n", "\t\t@IWorkbenchLayoutService private _layoutService: IWorkbenchLayoutService,\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/contrib/terminal/browser/terminalService.ts", "type": "replace", "edit_start_line_idx": 104 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as dom from 'vs/base/browser/dom'; import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent'; import * as aria from 'vs/base/browser/ui/aria/aria'; import { MessageType } from 'vs/base/browser/ui/inputbox/inputBox'; import { IIdentityProvider } from 'vs/base/browser/ui/list/list'; import { ITreeContextMenuEvent, ITreeElement } from 'vs/base/browser/ui/tree/tree'; import { IAction, ActionRunner } from 'vs/base/common/actions'; import { Delayer } from 'vs/base/common/async'; import * as errors from 'vs/base/common/errors'; import { Event } from 'vs/base/common/event'; import { Iterable } from 'vs/base/common/iterator'; import { KeyCode, KeyMod } from 'vs/base/common/keyCodes'; import { dispose, IDisposable } from 'vs/base/common/lifecycle'; import * as env from 'vs/base/common/platform'; import * as strings from 'vs/base/common/strings'; import { URI } from 'vs/base/common/uri'; import 'vs/css!./media/searchview'; import { ICodeEditor, isCodeEditor, isDiffEditor, getCodeEditor } from 'vs/editor/browser/editorBrowser'; import { IEditorOptions } from 'vs/editor/common/config/editorOptions'; import * as nls from 'vs/nls'; import { createAndFillInContextMenuActions } from 'vs/platform/actions/browser/menuEntryActionViewItem'; import { IMenu, IMenuService, MenuId } from 'vs/platform/actions/common/actions'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IContextKey, IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { IContextMenuService, IContextViewService } from 'vs/platform/contextview/browser/contextView'; import { IConfirmation, IDialogService } from 'vs/platform/dialogs/common/dialogs'; import { FileChangesEvent, FileChangeType, IFileService } from 'vs/platform/files/common/files'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { WorkbenchObjectTree, getSelectionKeyboardEvent } from 'vs/platform/list/browser/listService'; import { INotificationService } from 'vs/platform/notification/common/notification'; import { IProgressService, IProgressStep, IProgress } from 'vs/platform/progress/common/progress'; import { IPatternInfo, ISearchComplete, ISearchConfiguration, ISearchConfigurationProperties, ITextQuery, SearchSortOrder, SearchCompletionExitCode } from 'vs/workbench/services/search/common/search'; import { ISearchHistoryService, ISearchHistoryValues } from 'vs/workbench/contrib/search/common/searchHistoryService'; import { diffInserted, diffInsertedOutline, diffRemoved, diffRemovedOutline, editorFindMatchHighlight, editorFindMatchHighlightBorder, listActiveSelectionForeground, foreground } from 'vs/platform/theme/common/colorRegistry'; import { ICssStyleCollector, IColorTheme, IThemeService, registerThemingParticipant } from 'vs/platform/theme/common/themeService'; import { IWorkspaceContextService, WorkbenchState } from 'vs/platform/workspace/common/workspace'; import { OpenFileFolderAction, OpenFolderAction } from 'vs/workbench/browser/actions/workspaceActions'; import { ResourceLabels } from 'vs/workbench/browser/labels'; import { IEditorPane } from 'vs/workbench/common/editor'; import { ExcludePatternInputWidget, PatternInputWidget } from 'vs/workbench/contrib/search/browser/patternInputWidget'; import { CancelSearchAction, ClearSearchResultsAction, CollapseDeepestExpandedLevelAction, RefreshAction, IFindInFilesArgs, appendKeyBindingLabel, ExpandAllAction, ToggleCollapseAndExpandAction } from 'vs/workbench/contrib/search/browser/searchActions'; import { FileMatchRenderer, FolderMatchRenderer, MatchRenderer, SearchAccessibilityProvider, SearchDelegate, SearchDND } from 'vs/workbench/contrib/search/browser/searchResultsView'; import { ISearchWidgetOptions, SearchWidget } from 'vs/workbench/contrib/search/browser/searchWidget'; import * as Constants from 'vs/workbench/contrib/search/common/constants'; import { ITextQueryBuilderOptions, QueryBuilder } from 'vs/workbench/contrib/search/common/queryBuilder'; import { IReplaceService } from 'vs/workbench/contrib/search/common/replace'; import { getOutOfWorkspaceEditorResources } from 'vs/workbench/contrib/search/common/search'; import { FileMatch, FileMatchOrMatch, IChangeEvent, ISearchWorkbenchService, Match, RenderableMatch, searchMatchComparer, SearchModel, SearchResult, FolderMatch, FolderMatchWithResource } from 'vs/workbench/contrib/search/common/searchModel'; import { ACTIVE_GROUP, IEditorService, SIDE_GROUP } from 'vs/workbench/services/editor/common/editorService'; import { IPreferencesService, ISettingsEditorOptions } from 'vs/workbench/services/preferences/common/preferences'; import { ITextFileService } from 'vs/workbench/services/textfile/common/textfiles'; import { relativePath } from 'vs/base/common/resources'; import { IAccessibilityService } from 'vs/platform/accessibility/common/accessibility'; import { ViewPane, IViewPaneOptions } from 'vs/workbench/browser/parts/views/viewPaneContainer'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; import { Memento, MementoObject } from 'vs/workbench/common/memento'; import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage'; import { IOpenerService } from 'vs/platform/opener/common/opener'; import { MultiCursorSelectionController } from 'vs/editor/contrib/multicursor/multicursor'; import { Selection } from 'vs/editor/common/core/selection'; import { Color, RGBA } from 'vs/base/common/color'; import { IViewDescriptorService } from 'vs/workbench/common/views'; import { OpenSearchEditorAction, createEditorFromSearchResult } from 'vs/workbench/contrib/searchEditor/browser/searchEditorActions'; import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { Orientation } from 'vs/base/browser/ui/sash/sash'; import { searchDetailsIcon } from 'vs/workbench/contrib/search/browser/searchIcons'; const $ = dom.$; enum SearchUIState { Idle, Searching, SlowSearch } export enum SearchViewPosition { SideBar, Panel } const SEARCH_CANCELLED_MESSAGE = nls.localize('searchCanceled', "Search was canceled before any results could be found - "); export class SearchView extends ViewPane { private static readonly MAX_TEXT_RESULTS = 10000; private static readonly ACTIONS_RIGHT_CLASS_NAME = 'actions-right'; private isDisposed = false; private container!: HTMLElement; private queryBuilder: QueryBuilder; private viewModel: SearchModel; private memento: Memento; private viewletVisible: IContextKey<boolean>; private inputBoxFocused: IContextKey<boolean>; private inputPatternIncludesFocused: IContextKey<boolean>; private inputPatternExclusionsFocused: IContextKey<boolean>; private firstMatchFocused: IContextKey<boolean>; private fileMatchOrMatchFocused: IContextKey<boolean>; private fileMatchOrFolderMatchFocus: IContextKey<boolean>; private fileMatchOrFolderMatchWithResourceFocus: IContextKey<boolean>; private fileMatchFocused: IContextKey<boolean>; private folderMatchFocused: IContextKey<boolean>; private matchFocused: IContextKey<boolean>; private hasSearchResultsKey: IContextKey<boolean>; private lastFocusState: 'input' | 'tree' = 'input'; private state: SearchUIState = SearchUIState.Idle; private actions: Array<CollapseDeepestExpandedLevelAction | ClearSearchResultsAction | OpenSearchEditorAction> = []; private toggleCollapseAction: ToggleCollapseAndExpandAction; private cancelAction: CancelSearchAction; private refreshAction: RefreshAction; private contextMenu: IMenu | null = null; private tree!: WorkbenchObjectTree<RenderableMatch>; private treeLabels!: ResourceLabels; private viewletState: MementoObject; private messagesElement!: HTMLElement; private messageDisposables: IDisposable[] = []; private searchWidgetsContainerElement!: HTMLElement; private searchWidget!: SearchWidget; private size!: dom.Dimension; private queryDetails!: HTMLElement; private toggleQueryDetailsButton!: HTMLElement; private inputPatternExcludes!: ExcludePatternInputWidget; private inputPatternIncludes!: PatternInputWidget; private resultsElement!: HTMLElement; private currentSelectedFileMatch: FileMatch | undefined; private delayedRefresh: Delayer<void>; private changedWhileHidden: boolean = false; private updatedActionsWhileHidden = false; private searchWithoutFolderMessageElement: HTMLElement | undefined; private currentSearchQ = Promise.resolve(); private addToSearchHistoryDelayer: Delayer<void>; private toggleCollapseStateDelayer: Delayer<void>; private triggerQueryDelayer: Delayer<void>; private pauseSearching = false; private treeAccessibilityProvider: SearchAccessibilityProvider; constructor( options: IViewPaneOptions, @IFileService private readonly fileService: IFileService, @IEditorService private readonly editorService: IEditorService, @IProgressService private readonly progressService: IProgressService, @INotificationService private readonly notificationService: INotificationService, @IDialogService private readonly dialogService: IDialogService, @IContextViewService private readonly contextViewService: IContextViewService, @IInstantiationService instantiationService: IInstantiationService, @IViewDescriptorService viewDescriptorService: IViewDescriptorService, @IConfigurationService configurationService: IConfigurationService, @IWorkspaceContextService private readonly contextService: IWorkspaceContextService, @ISearchWorkbenchService private readonly searchWorkbenchService: ISearchWorkbenchService, @IContextKeyService readonly contextKeyService: IContextKeyService, @IReplaceService private readonly replaceService: IReplaceService, @ITextFileService private readonly textFileService: ITextFileService, @IPreferencesService private readonly preferencesService: IPreferencesService, @IThemeService themeService: IThemeService, @ISearchHistoryService private readonly searchHistoryService: ISearchHistoryService, @IContextMenuService contextMenuService: IContextMenuService, @IMenuService private readonly menuService: IMenuService, @IAccessibilityService private readonly accessibilityService: IAccessibilityService, @IKeybindingService keybindingService: IKeybindingService, @IStorageService storageService: IStorageService, @IOpenerService openerService: IOpenerService, @ITelemetryService telemetryService: ITelemetryService, ) { super(options, keybindingService, contextMenuService, configurationService, contextKeyService, viewDescriptorService, instantiationService, openerService, themeService, telemetryService); this.container = dom.$('.search-view'); // globals this.viewletVisible = Constants.SearchViewVisibleKey.bindTo(this.contextKeyService); this.firstMatchFocused = Constants.FirstMatchFocusKey.bindTo(this.contextKeyService); this.fileMatchOrMatchFocused = Constants.FileMatchOrMatchFocusKey.bindTo(this.contextKeyService); this.fileMatchOrFolderMatchFocus = Constants.FileMatchOrFolderMatchFocusKey.bindTo(this.contextKeyService); this.fileMatchOrFolderMatchWithResourceFocus = Constants.FileMatchOrFolderMatchWithResourceFocusKey.bindTo(this.contextKeyService); this.fileMatchFocused = Constants.FileFocusKey.bindTo(this.contextKeyService); this.folderMatchFocused = Constants.FolderFocusKey.bindTo(this.contextKeyService); this.hasSearchResultsKey = Constants.HasSearchResults.bindTo(this.contextKeyService); this.matchFocused = Constants.MatchFocusKey.bindTo(this.contextKeyService); // scoped this.contextKeyService = this._register(this.contextKeyService.createScoped(this.container)); Constants.SearchViewFocusedKey.bindTo(this.contextKeyService).set(true); this.inputBoxFocused = Constants.InputBoxFocusedKey.bindTo(this.contextKeyService); this.inputPatternIncludesFocused = Constants.PatternIncludesFocusedKey.bindTo(this.contextKeyService); this.inputPatternExclusionsFocused = Constants.PatternExcludesFocusedKey.bindTo(this.contextKeyService); this.instantiationService = this.instantiationService.createChild( new ServiceCollection([IContextKeyService, this.contextKeyService])); this.configurationService.onDidChangeConfiguration(e => { if (e.affectsConfiguration('search.sortOrder')) { if (this.searchConfig.sortOrder === SearchSortOrder.Modified) { // If changing away from modified, remove all fileStats // so that updated files are re-retrieved next time. this.removeFileStats(); } this.refreshTree(); } }); this.viewModel = this._register(this.searchWorkbenchService.searchModel); this.queryBuilder = this.instantiationService.createInstance(QueryBuilder); this.memento = new Memento(this.id, storageService); this.viewletState = this.memento.getMemento(StorageScope.WORKSPACE); this._register(this.fileService.onDidFilesChange(e => this.onFilesChanged(e))); this._register(this.textFileService.untitled.onDidDispose(model => this.onUntitledDidDispose(model.resource))); this._register(this.contextService.onDidChangeWorkbenchState(() => this.onDidChangeWorkbenchState())); this._register(this.searchHistoryService.onDidClearHistory(() => this.clearHistory())); this.delayedRefresh = this._register(new Delayer<void>(250)); this.addToSearchHistoryDelayer = this._register(new Delayer<void>(2000)); this.toggleCollapseStateDelayer = this._register(new Delayer<void>(100)); this.triggerQueryDelayer = this._register(new Delayer<void>(0)); const collapseDeepestExpandedLevelAction = this.instantiationService.createInstance(CollapseDeepestExpandedLevelAction, CollapseDeepestExpandedLevelAction.ID, CollapseDeepestExpandedLevelAction.LABEL); const expandAllAction = this.instantiationService.createInstance(ExpandAllAction, ExpandAllAction.ID, ExpandAllAction.LABEL); this.actions = [ this._register(this.instantiationService.createInstance(ClearSearchResultsAction, ClearSearchResultsAction.ID, ClearSearchResultsAction.LABEL)), this._register(this.instantiationService.createInstance(OpenSearchEditorAction, OpenSearchEditorAction.ID, OpenSearchEditorAction.LABEL)) ]; this.refreshAction = this._register(this.instantiationService.createInstance(RefreshAction, RefreshAction.ID, RefreshAction.LABEL)); this.cancelAction = this._register(this.instantiationService.createInstance(CancelSearchAction, CancelSearchAction.ID, CancelSearchAction.LABEL)); this.toggleCollapseAction = this._register(this.instantiationService.createInstance(ToggleCollapseAndExpandAction, ToggleCollapseAndExpandAction.ID, ToggleCollapseAndExpandAction.LABEL, collapseDeepestExpandedLevelAction, expandAllAction)); this.treeAccessibilityProvider = this.instantiationService.createInstance(SearchAccessibilityProvider, this.viewModel); } getContainer(): HTMLElement { return this.container; } get searchResult(): SearchResult { return this.viewModel && this.viewModel.searchResult; } private onDidChangeWorkbenchState(): void { if (this.contextService.getWorkbenchState() !== WorkbenchState.EMPTY && this.searchWithoutFolderMessageElement) { dom.hide(this.searchWithoutFolderMessageElement); } } renderBody(parent: HTMLElement): void { super.renderBody(parent); this.container = dom.append(parent, dom.$('.search-view')); this.searchWidgetsContainerElement = dom.append(this.container, $('.search-widgets-container')); this.createSearchWidget(this.searchWidgetsContainerElement); const history = this.searchHistoryService.load(); const filePatterns = this.viewletState['query.filePatterns'] || ''; const patternExclusions = this.viewletState['query.folderExclusions'] || ''; const patternExclusionsHistory: string[] = history.exclude || []; const patternIncludes = this.viewletState['query.folderIncludes'] || ''; const patternIncludesHistory: string[] = history.include || []; const queryDetailsExpanded = this.viewletState['query.queryDetailsExpanded'] || ''; const useExcludesAndIgnoreFiles = typeof this.viewletState['query.useExcludesAndIgnoreFiles'] === 'boolean' ? this.viewletState['query.useExcludesAndIgnoreFiles'] : true; this.queryDetails = dom.append(this.searchWidgetsContainerElement, $('.query-details')); // Toggle query details button this.toggleQueryDetailsButton = dom.append(this.queryDetails, $('.more' + searchDetailsIcon.cssSelector, { tabindex: 0, role: 'button', title: nls.localize('moreSearch', "Toggle Search Details") })); this._register(dom.addDisposableListener(this.toggleQueryDetailsButton, dom.EventType.CLICK, e => { dom.EventHelper.stop(e); this.toggleQueryDetails(!this.accessibilityService.isScreenReaderOptimized()); })); this._register(dom.addDisposableListener(this.toggleQueryDetailsButton, dom.EventType.KEY_UP, (e: KeyboardEvent) => { const event = new StandardKeyboardEvent(e); if (event.equals(KeyCode.Enter) || event.equals(KeyCode.Space)) { dom.EventHelper.stop(e); this.toggleQueryDetails(false); } })); this._register(dom.addDisposableListener(this.toggleQueryDetailsButton, dom.EventType.KEY_DOWN, (e: KeyboardEvent) => { const event = new StandardKeyboardEvent(e); if (event.equals(KeyMod.Shift | KeyCode.Tab)) { if (this.searchWidget.isReplaceActive()) { this.searchWidget.focusReplaceAllAction(); } else { this.searchWidget.isReplaceShown() ? this.searchWidget.replaceInput.focusOnPreserve() : this.searchWidget.focusRegexAction(); } dom.EventHelper.stop(e); } })); // folder includes list const folderIncludesList = dom.append(this.queryDetails, $('.file-types.includes')); const filesToIncludeTitle = nls.localize('searchScope.includes', "files to include"); dom.append(folderIncludesList, $('h4', undefined, filesToIncludeTitle)); this.inputPatternIncludes = this._register(this.instantiationService.createInstance(PatternInputWidget, folderIncludesList, this.contextViewService, { ariaLabel: nls.localize('label.includes', 'Search Include Patterns'), history: patternIncludesHistory, })); this.inputPatternIncludes.setValue(patternIncludes); this.inputPatternIncludes.onSubmit(triggeredOnType => this.triggerQueryChange({ triggeredOnType, delay: this.searchConfig.searchOnTypeDebouncePeriod })); this.inputPatternIncludes.onCancel(() => this.cancelSearch(false)); this.trackInputBox(this.inputPatternIncludes.inputFocusTracker, this.inputPatternIncludesFocused); // excludes list const excludesList = dom.append(this.queryDetails, $('.file-types.excludes')); const excludesTitle = nls.localize('searchScope.excludes', "files to exclude"); dom.append(excludesList, $('h4', undefined, excludesTitle)); this.inputPatternExcludes = this._register(this.instantiationService.createInstance(ExcludePatternInputWidget, excludesList, this.contextViewService, { ariaLabel: nls.localize('label.excludes', 'Search Exclude Patterns'), history: patternExclusionsHistory, })); this.inputPatternExcludes.setValue(patternExclusions); this.inputPatternExcludes.setUseExcludesAndIgnoreFiles(useExcludesAndIgnoreFiles); this.inputPatternExcludes.onSubmit(triggeredOnType => this.triggerQueryChange({ triggeredOnType, delay: this.searchConfig.searchOnTypeDebouncePeriod })); this.inputPatternExcludes.onCancel(() => this.cancelSearch(false)); this.inputPatternExcludes.onChangeIgnoreBox(() => this.triggerQueryChange()); this.trackInputBox(this.inputPatternExcludes.inputFocusTracker, this.inputPatternExclusionsFocused); this.messagesElement = dom.append(this.container, $('.messages')); if (this.contextService.getWorkbenchState() === WorkbenchState.EMPTY) { this.showSearchWithoutFolderMessage(); } this.createSearchResultsView(this.container); if (filePatterns !== '' || patternExclusions !== '' || patternIncludes !== '' || queryDetailsExpanded !== '' || !useExcludesAndIgnoreFiles) { this.toggleQueryDetails(true, true, true); } this._register(this.viewModel.searchResult.onChange((event) => this.onSearchResultsChanged(event))); this._register(this.searchWidget.searchInput.onInput(() => this.updateActions())); this._register(this.searchWidget.replaceInput.onInput(() => this.updateActions())); this._register(this.onDidChangeBodyVisibility(visible => this.onVisibilityChanged(visible))); } private onVisibilityChanged(visible: boolean): void { this.viewletVisible.set(visible); if (visible) { if (this.changedWhileHidden) { // Render if results changed while viewlet was hidden - #37818 this.refreshAndUpdateCount(); this.changedWhileHidden = false; } if (this.updatedActionsWhileHidden) { // The actions can only run or update their enablement when the view is visible, // because they can only access the view when it's visible this.updateActions(); this.updatedActionsWhileHidden = false; } } else { // Reset last focus to input to preserve opening the viewlet always focusing the query editor. this.lastFocusState = 'input'; } // Enable highlights if there are searchresults if (this.viewModel) { this.viewModel.searchResult.toggleHighlights(visible); } } get searchAndReplaceWidget(): SearchWidget { return this.searchWidget; } get searchIncludePattern(): PatternInputWidget { return this.inputPatternIncludes; } get searchExcludePattern(): PatternInputWidget { return this.inputPatternExcludes; } /** * Warning: a bit expensive due to updating the view title */ protected updateActions(): void { if (!this.isVisible()) { this.updatedActionsWhileHidden = true; } for (const action of this.actions) { action.update(); } this.refreshAction.update(); this.cancelAction.update(); this.toggleCollapseAction.update(); super.updateActions(); } private createSearchWidget(container: HTMLElement): void { const contentPattern = this.viewletState['query.contentPattern'] || ''; const replaceText = this.viewletState['query.replaceText'] || ''; const isRegex = this.viewletState['query.regex'] === true; const isWholeWords = this.viewletState['query.wholeWords'] === true; const isCaseSensitive = this.viewletState['query.caseSensitive'] === true; const history = this.searchHistoryService.load(); const searchHistory = history.search || this.viewletState['query.searchHistory'] || []; const replaceHistory = history.replace || this.viewletState['query.replaceHistory'] || []; const showReplace = typeof this.viewletState['view.showReplace'] === 'boolean' ? this.viewletState['view.showReplace'] : true; const preserveCase = this.viewletState['query.preserveCase'] === true; this.searchWidget = this._register(this.instantiationService.createInstance(SearchWidget, container, <ISearchWidgetOptions>{ value: contentPattern, replaceValue: replaceText, isRegex: isRegex, isCaseSensitive: isCaseSensitive, isWholeWords: isWholeWords, searchHistory: searchHistory, replaceHistory: replaceHistory, preserveCase: preserveCase })); if (showReplace) { this.searchWidget.toggleReplace(true); } this._register(this.searchWidget.onSearchSubmit(options => this.triggerQueryChange(options))); this._register(this.searchWidget.onSearchCancel(({ focus }) => this.cancelSearch(focus))); this._register(this.searchWidget.searchInput.onDidOptionChange(() => this.triggerQueryChange())); this._register(this.searchWidget.onDidHeightChange(() => this.reLayout())); this._register(this.searchWidget.onReplaceToggled(() => this.reLayout())); this._register(this.searchWidget.onReplaceStateChange((state) => { this.viewModel.replaceActive = state; this.refreshTree(); })); this._register(this.searchWidget.onPreserveCaseChange((state) => { this.viewModel.preserveCase = state; this.refreshTree(); })); this._register(this.searchWidget.onReplaceValueChanged(() => { this.viewModel.replaceString = this.searchWidget.getReplaceValue(); this.delayedRefresh.trigger(() => this.refreshTree()); })); this._register(this.searchWidget.onBlur(() => { this.toggleQueryDetailsButton.focus(); })); this._register(this.searchWidget.onReplaceAll(() => this.replaceAll())); this.trackInputBox(this.searchWidget.searchInputFocusTracker); this.trackInputBox(this.searchWidget.replaceInputFocusTracker); } private trackInputBox(inputFocusTracker: dom.IFocusTracker, contextKey?: IContextKey<boolean>): void { this._register(inputFocusTracker.onDidFocus(() => { this.lastFocusState = 'input'; this.inputBoxFocused.set(true); if (contextKey) { contextKey.set(true); } })); this._register(inputFocusTracker.onDidBlur(() => { this.inputBoxFocused.set(this.searchWidget.searchInputHasFocus() || this.searchWidget.replaceInputHasFocus() || this.inputPatternIncludes.inputHasFocus() || this.inputPatternExcludes.inputHasFocus()); if (contextKey) { contextKey.set(false); } })); } private onSearchResultsChanged(event?: IChangeEvent): void { if (this.isVisible()) { return this.refreshAndUpdateCount(event); } else { this.changedWhileHidden = true; } } private refreshAndUpdateCount(event?: IChangeEvent): void { this.searchWidget.setReplaceAllActionState(!this.viewModel.searchResult.isEmpty()); this.updateSearchResultCount(this.viewModel.searchResult.query!.userDisabledExcludesAndIgnoreFiles); return this.refreshTree(event); } refreshTree(event?: IChangeEvent): void { const collapseResults = this.searchConfig.collapseResults; if (!event || event.added || event.removed) { // Refresh whole tree if (this.searchConfig.sortOrder === SearchSortOrder.Modified) { // Ensure all matches have retrieved their file stat this.retrieveFileStats() .then(() => this.tree.setChildren(null, this.createResultIterator(collapseResults))); } else { this.tree.setChildren(null, this.createResultIterator(collapseResults)); } } else { // If updated counts affect our search order, re-sort the view. if (this.searchConfig.sortOrder === SearchSortOrder.CountAscending || this.searchConfig.sortOrder === SearchSortOrder.CountDescending) { this.tree.setChildren(null, this.createResultIterator(collapseResults)); } else { // FileMatch modified, refresh those elements event.elements.forEach(element => { this.tree.setChildren(element, this.createIterator(element, collapseResults)); this.tree.rerender(element); }); } } } private createResultIterator(collapseResults: ISearchConfigurationProperties['collapseResults']): Iterable<ITreeElement<RenderableMatch>> { const folderMatches = this.searchResult.folderMatches() .filter(fm => !fm.isEmpty()) .sort(searchMatchComparer); if (folderMatches.length === 1) { return this.createFolderIterator(folderMatches[0], collapseResults); } return Iterable.map(folderMatches, folderMatch => { const children = this.createFolderIterator(folderMatch, collapseResults); return <ITreeElement<RenderableMatch>>{ element: folderMatch, children }; }); } private createFolderIterator(folderMatch: FolderMatch, collapseResults: ISearchConfigurationProperties['collapseResults']): Iterable<ITreeElement<RenderableMatch>> { const sortOrder = this.searchConfig.sortOrder; const matches = folderMatch.matches().sort((a, b) => searchMatchComparer(a, b, sortOrder)); return Iterable.map(matches, fileMatch => { const children = this.createFileIterator(fileMatch); let nodeExists = true; try { this.tree.getNode(fileMatch); } catch (e) { nodeExists = false; } const collapsed = nodeExists ? undefined : (collapseResults === 'alwaysCollapse' || (fileMatch.matches().length > 10 && collapseResults !== 'alwaysExpand')); return <ITreeElement<RenderableMatch>>{ element: fileMatch, children, collapsed }; }); } private createFileIterator(fileMatch: FileMatch): Iterable<ITreeElement<RenderableMatch>> { const matches = fileMatch.matches().sort(searchMatchComparer); return Iterable.map(matches, r => (<ITreeElement<RenderableMatch>>{ element: r })); } private createIterator(match: FolderMatch | FileMatch | SearchResult, collapseResults: ISearchConfigurationProperties['collapseResults']): Iterable<ITreeElement<RenderableMatch>> { return match instanceof SearchResult ? this.createResultIterator(collapseResults) : match instanceof FolderMatch ? this.createFolderIterator(match, collapseResults) : this.createFileIterator(match); } private replaceAll(): void { if (this.viewModel.searchResult.count() === 0) { return; } const occurrences = this.viewModel.searchResult.count(); const fileCount = this.viewModel.searchResult.fileCount(); const replaceValue = this.searchWidget.getReplaceValue() || ''; const afterReplaceAllMessage = this.buildAfterReplaceAllMessage(occurrences, fileCount, replaceValue); let progressComplete: () => void; let progressReporter: IProgress<IProgressStep>; this.progressService.withProgress({ location: this.getProgressLocation(), delay: 100, total: occurrences }, p => { progressReporter = p; return new Promise<void>(resolve => progressComplete = resolve); }); const confirmation: IConfirmation = { title: nls.localize('replaceAll.confirmation.title', "Replace All"), message: this.buildReplaceAllConfirmationMessage(occurrences, fileCount, replaceValue), primaryButton: nls.localize('replaceAll.confirm.button', "&&Replace"), type: 'question' }; this.dialogService.confirm(confirmation).then(res => { if (res.confirmed) { this.searchWidget.setReplaceAllActionState(false); this.viewModel.searchResult.replaceAll(progressReporter).then(() => { progressComplete(); const messageEl = this.clearMessage(); dom.append(messageEl, $('p', undefined, afterReplaceAllMessage)); this.reLayout(); }, (error) => { progressComplete(); errors.isPromiseCanceledError(error); this.notificationService.error(error); }); } }); } private buildAfterReplaceAllMessage(occurrences: number, fileCount: number, replaceValue?: string) { if (occurrences === 1) { if (fileCount === 1) { if (replaceValue) { return nls.localize('replaceAll.occurrence.file.message', "Replaced {0} occurrence across {1} file with '{2}'.", occurrences, fileCount, replaceValue); } return nls.localize('removeAll.occurrence.file.message', "Replaced {0} occurrence across {1} file.", occurrences, fileCount); } if (replaceValue) { return nls.localize('replaceAll.occurrence.files.message', "Replaced {0} occurrence across {1} files with '{2}'.", occurrences, fileCount, replaceValue); } return nls.localize('removeAll.occurrence.files.message', "Replaced {0} occurrence across {1} files.", occurrences, fileCount); } if (fileCount === 1) { if (replaceValue) { return nls.localize('replaceAll.occurrences.file.message', "Replaced {0} occurrences across {1} file with '{2}'.", occurrences, fileCount, replaceValue); } return nls.localize('removeAll.occurrences.file.message', "Replaced {0} occurrences across {1} file.", occurrences, fileCount); } if (replaceValue) { return nls.localize('replaceAll.occurrences.files.message', "Replaced {0} occurrences across {1} files with '{2}'.", occurrences, fileCount, replaceValue); } return nls.localize('removeAll.occurrences.files.message', "Replaced {0} occurrences across {1} files.", occurrences, fileCount); } private buildReplaceAllConfirmationMessage(occurrences: number, fileCount: number, replaceValue?: string) { if (occurrences === 1) { if (fileCount === 1) { if (replaceValue) { return nls.localize('removeAll.occurrence.file.confirmation.message', "Replace {0} occurrence across {1} file with '{2}'?", occurrences, fileCount, replaceValue); } return nls.localize('replaceAll.occurrence.file.confirmation.message', "Replace {0} occurrence across {1} file?", occurrences, fileCount); } if (replaceValue) { return nls.localize('removeAll.occurrence.files.confirmation.message', "Replace {0} occurrence across {1} files with '{2}'?", occurrences, fileCount, replaceValue); } return nls.localize('replaceAll.occurrence.files.confirmation.message', "Replace {0} occurrence across {1} files?", occurrences, fileCount); } if (fileCount === 1) { if (replaceValue) { return nls.localize('removeAll.occurrences.file.confirmation.message', "Replace {0} occurrences across {1} file with '{2}'?", occurrences, fileCount, replaceValue); } return nls.localize('replaceAll.occurrences.file.confirmation.message', "Replace {0} occurrences across {1} file?", occurrences, fileCount); } if (replaceValue) { return nls.localize('removeAll.occurrences.files.confirmation.message', "Replace {0} occurrences across {1} files with '{2}'?", occurrences, fileCount, replaceValue); } return nls.localize('replaceAll.occurrences.files.confirmation.message', "Replace {0} occurrences across {1} files?", occurrences, fileCount); } private clearMessage(): HTMLElement { this.searchWithoutFolderMessageElement = undefined; dom.clearNode(this.messagesElement); dom.show(this.messagesElement); dispose(this.messageDisposables); this.messageDisposables = []; return dom.append(this.messagesElement, $('.message')); } private createSearchResultsView(container: HTMLElement): void { this.resultsElement = dom.append(container, $('.results.show-file-icons')); const delegate = this.instantiationService.createInstance(SearchDelegate); const identityProvider: IIdentityProvider<RenderableMatch> = { getId(element: RenderableMatch) { return element.id(); } }; this.treeLabels = this._register(this.instantiationService.createInstance(ResourceLabels, { onDidChangeVisibility: this.onDidChangeBodyVisibility })); this.tree = this._register(<WorkbenchObjectTree<RenderableMatch>>this.instantiationService.createInstance(WorkbenchObjectTree, 'SearchView', this.resultsElement, delegate, [ this._register(this.instantiationService.createInstance(FolderMatchRenderer, this.viewModel, this, this.treeLabels)), this._register(this.instantiationService.createInstance(FileMatchRenderer, this.viewModel, this, this.treeLabels)), this._register(this.instantiationService.createInstance(MatchRenderer, this.viewModel, this)), ], { identityProvider, accessibilityProvider: this.treeAccessibilityProvider, dnd: this.instantiationService.createInstance(SearchDND), multipleSelectionSupport: false, openOnFocus: true, overrideStyles: { listBackground: this.getBackgroundColor() } })); this._register(this.tree.onContextMenu(e => this.onContextMenu(e))); this._register(this.tree.onDidChangeCollapseState(() => this.toggleCollapseStateDelayer.trigger(() => this.toggleCollapseAction.onTreeCollapseStateChange()) )); this._register(Event.debounce(this.tree.onDidOpen, (last, event) => event, 75, true)(options => { if (options.element instanceof Match) { const selectedMatch: Match = options.element; if (this.currentSelectedFileMatch) { this.currentSelectedFileMatch.setSelectedMatch(null); } this.currentSelectedFileMatch = selectedMatch.parent(); this.currentSelectedFileMatch.setSelectedMatch(selectedMatch); this.onFocus(selectedMatch, options.editorOptions.preserveFocus, options.sideBySide, options.editorOptions.pinned); } })); this._register(Event.any<any>(this.tree.onDidFocus, this.tree.onDidChangeFocus)(() => { if (this.tree.isDOMFocused()) { const focus = this.tree.getFocus()[0]; this.firstMatchFocused.set(this.tree.navigate().first() === focus); this.fileMatchOrMatchFocused.set(!!focus); this.fileMatchFocused.set(focus instanceof FileMatch); this.folderMatchFocused.set(focus instanceof FolderMatch); this.matchFocused.set(focus instanceof Match); this.fileMatchOrFolderMatchFocus.set(focus instanceof FileMatch || focus instanceof FolderMatch); this.fileMatchOrFolderMatchWithResourceFocus.set(focus instanceof FileMatch || focus instanceof FolderMatchWithResource); this.lastFocusState = 'tree'; } })); this._register(this.tree.onDidBlur(() => { this.firstMatchFocused.reset(); this.fileMatchOrMatchFocused.reset(); this.fileMatchFocused.reset(); this.folderMatchFocused.reset(); this.matchFocused.reset(); this.fileMatchOrFolderMatchFocus.reset(); this.fileMatchOrFolderMatchWithResourceFocus.reset(); })); } private onContextMenu(e: ITreeContextMenuEvent<RenderableMatch | null>): void { if (!this.contextMenu) { this.contextMenu = this._register(this.menuService.createMenu(MenuId.SearchContext, this.contextKeyService)); } e.browserEvent.preventDefault(); e.browserEvent.stopPropagation(); const actions: IAction[] = []; const actionsDisposable = createAndFillInContextMenuActions(this.contextMenu, { shouldForwardArgs: true }, actions); this.contextMenuService.showContextMenu({ getAnchor: () => e.anchor, getActions: () => actions, getActionsContext: () => e.element, onHide: () => dispose(actionsDisposable) }); } selectNextMatch(): void { if (!this.hasSearchResults()) { return; } const [selected] = this.tree.getSelection(); // Expand the initial selected node, if needed if (selected && !(selected instanceof Match)) { if (this.tree.isCollapsed(selected)) { this.tree.expand(selected); } } const navigator = this.tree.navigate(selected); let next = navigator.next(); if (!next) { next = navigator.first(); } // Expand until first child is a Match while (next && !(next instanceof Match)) { if (this.tree.isCollapsed(next)) { this.tree.expand(next); } // Select the first child next = navigator.next(); } // Reveal the newly selected element if (next) { if (next === selected) { this.tree.setFocus([]); } this.tree.setFocus([next], getSelectionKeyboardEvent(undefined, false)); this.tree.reveal(next); const ariaLabel = this.treeAccessibilityProvider.getAriaLabel(next); if (ariaLabel) { aria.alert(ariaLabel); } } } selectPreviousMatch(): void { if (!this.hasSearchResults()) { return; } const [selected] = this.tree.getSelection(); let navigator = this.tree.navigate(selected); let prev = navigator.previous(); // Select previous until find a Match or a collapsed item while (!prev || (!(prev instanceof Match) && !this.tree.isCollapsed(prev))) { const nextPrev = prev ? navigator.previous() : navigator.last(); if (!prev && !nextPrev) { return; } prev = nextPrev; } // Expand until last child is a Match while (!(prev instanceof Match)) { const nextItem = navigator.next(); this.tree.expand(prev); navigator = this.tree.navigate(nextItem); // recreate navigator because modifying the tree can invalidate it prev = nextItem ? navigator.previous() : navigator.last(); // select last child } // Reveal the newly selected element if (prev) { if (prev === selected) { this.tree.setFocus([]); } this.tree.setFocus([prev], getSelectionKeyboardEvent(undefined, false)); this.tree.reveal(prev); const ariaLabel = this.treeAccessibilityProvider.getAriaLabel(prev); if (ariaLabel) { aria.alert(ariaLabel); } } } moveFocusToResults(): void { this.tree.domFocus(); } focus(): void { super.focus(); if (this.lastFocusState === 'input' || !this.hasSearchResults()) { const updatedText = this.searchConfig.seedOnFocus ? this.updateTextFromSelection({ allowSearchOnType: false }) : false; this.searchWidget.focus(undefined, undefined, updatedText); } else { this.tree.domFocus(); } } updateTextFromSelection({ allowUnselectedWord = true, allowSearchOnType = true }): boolean { let updatedText = false; const seedSearchStringFromSelection = this.configurationService.getValue<IEditorOptions>('editor').find!.seedSearchStringFromSelection; if (seedSearchStringFromSelection) { let selectedText = this.getSearchTextFromEditor(allowUnselectedWord); if (selectedText) { if (this.searchWidget.searchInput.getRegex()) { selectedText = strings.escapeRegExpCharacters(selectedText); } if (allowSearchOnType && !this.viewModel.searchResult.isDirty) { this.searchWidget.setValue(selectedText); } else { this.pauseSearching = true; this.searchWidget.setValue(selectedText); this.pauseSearching = false; } updatedText = true; } } return updatedText; } focusNextInputBox(): void { if (this.searchWidget.searchInputHasFocus()) { if (this.searchWidget.isReplaceShown()) { this.searchWidget.focus(true, true); } else { this.moveFocusFromSearchOrReplace(); } return; } if (this.searchWidget.replaceInputHasFocus()) { this.moveFocusFromSearchOrReplace(); return; } if (this.inputPatternIncludes.inputHasFocus()) { this.inputPatternExcludes.focus(); this.inputPatternExcludes.select(); return; } if (this.inputPatternExcludes.inputHasFocus()) { this.selectTreeIfNotSelected(); return; } } private moveFocusFromSearchOrReplace() { if (this.showsFileTypes()) { this.toggleQueryDetails(true, this.showsFileTypes()); } else { this.selectTreeIfNotSelected(); } } focusPreviousInputBox(): void { if (this.searchWidget.searchInputHasFocus()) { return; } if (this.searchWidget.replaceInputHasFocus()) { this.searchWidget.focus(true); return; } if (this.inputPatternIncludes.inputHasFocus()) { this.searchWidget.focus(true, true); return; } if (this.inputPatternExcludes.inputHasFocus()) { this.inputPatternIncludes.focus(); this.inputPatternIncludes.select(); return; } if (this.tree.isDOMFocused()) { this.moveFocusFromResults(); return; } } private moveFocusFromResults(): void { if (this.showsFileTypes()) { this.toggleQueryDetails(true, true, false, true); } else { this.searchWidget.focus(true, true); } } private reLayout(): void { if (this.isDisposed || !this.size) { return; } const actionsPosition = this.searchConfig.actionsPosition; this.getContainer().classList.toggle(SearchView.ACTIONS_RIGHT_CLASS_NAME, actionsPosition === 'right'); this.searchWidget.setWidth(this.size.width - 28 /* container margin */); this.inputPatternExcludes.setWidth(this.size.width - 28 /* container margin */); this.inputPatternIncludes.setWidth(this.size.width - 28 /* container margin */); const messagesSize = this.messagesElement.style.display === 'none' ? 0 : dom.getTotalHeight(this.messagesElement); const searchResultContainerHeight = this.size.height - messagesSize - dom.getTotalHeight(this.searchWidgetsContainerElement); this.resultsElement.style.height = searchResultContainerHeight + 'px'; this.tree.layout(searchResultContainerHeight, this.size.width); } protected layoutBody(height: number, width: number): void { super.layoutBody(height, width); this.size = new dom.Dimension(width, height); this.reLayout(); } getControl() { return this.tree; } isSlowSearch(): boolean { return this.state === SearchUIState.SlowSearch; } allSearchFieldsClear(): boolean { return this.searchWidget.getReplaceValue() === '' && this.searchWidget.searchInput.getValue() === ''; } allFilePatternFieldsClear(): boolean { return this.searchExcludePattern.getValue() === '' && this.searchIncludePattern.getValue() === ''; } hasSearchResults(): boolean { return !this.viewModel.searchResult.isEmpty(); } hasSearchPattern(): boolean { return this.searchWidget && this.searchWidget.searchInput.getValue().length > 0; } clearSearchResults(clearInput = true): void { this.viewModel.searchResult.clear(); this.showEmptyStage(true); if (this.contextService.getWorkbenchState() === WorkbenchState.EMPTY) { this.showSearchWithoutFolderMessage(); } if (clearInput) { if (this.allSearchFieldsClear()) { this.clearFilePatternFields(); } this.searchWidget.clear(); } this.viewModel.cancelSearch(); this.updateActions(); this.tree.ariaLabel = nls.localize('emptySearch', "Empty Search"); aria.status(nls.localize('ariaSearchResultsClearStatus', "The search results have been cleared")); } clearFilePatternFields(): void { this.searchExcludePattern.clear(); this.searchIncludePattern.clear(); } cancelSearch(focus: boolean = true): boolean { if (this.viewModel.cancelSearch()) { if (focus) { this.searchWidget.focus(); } return true; } return false; } private selectTreeIfNotSelected(): void { if (this.tree.getNode(null)) { this.tree.domFocus(); const selection = this.tree.getSelection(); if (selection.length === 0) { this.tree.focusNext(); } } } private getSearchTextFromEditor(allowUnselectedWord: boolean): string | null { if (!this.editorService.activeEditor) { return null; } if (dom.isAncestor(document.activeElement, this.getContainer())) { return null; } let activeTextEditorControl = this.editorService.activeTextEditorControl; if (isDiffEditor(activeTextEditorControl)) { if (activeTextEditorControl.getOriginalEditor().hasTextFocus()) { activeTextEditorControl = activeTextEditorControl.getOriginalEditor(); } else { activeTextEditorControl = activeTextEditorControl.getModifiedEditor(); } } if (!isCodeEditor(activeTextEditorControl) || !activeTextEditorControl.hasModel()) { return null; } const range = activeTextEditorControl.getSelection(); if (!range) { return null; } if (range.isEmpty() && this.searchConfig.seedWithNearestWord && allowUnselectedWord) { const wordAtPosition = activeTextEditorControl.getModel().getWordAtPosition(range.getStartPosition()); if (wordAtPosition) { return wordAtPosition.word; } } if (!range.isEmpty()) { let searchText = ''; for (let i = range.startLineNumber; i <= range.endLineNumber; i++) { let lineText = activeTextEditorControl.getModel().getLineContent(i); if (i === range.endLineNumber) { lineText = lineText.substring(0, range.endColumn - 1); } if (i === range.startLineNumber) { lineText = lineText.substring(range.startColumn - 1); } if (i !== range.startLineNumber) { lineText = '\n' + lineText; } searchText += lineText; } return searchText; } return null; } private showsFileTypes(): boolean { return this.queryDetails.classList.contains('more'); } toggleCaseSensitive(): void { this.searchWidget.searchInput.setCaseSensitive(!this.searchWidget.searchInput.getCaseSensitive()); this.triggerQueryChange(); } toggleWholeWords(): void { this.searchWidget.searchInput.setWholeWords(!this.searchWidget.searchInput.getWholeWords()); this.triggerQueryChange(); } toggleRegex(): void { this.searchWidget.searchInput.setRegex(!this.searchWidget.searchInput.getRegex()); this.triggerQueryChange(); } togglePreserveCase(): void { this.searchWidget.replaceInput.setPreserveCase(!this.searchWidget.replaceInput.getPreserveCase()); this.triggerQueryChange(); } setSearchParameters(args: IFindInFilesArgs = {}): void { if (typeof args.isCaseSensitive === 'boolean') { this.searchWidget.searchInput.setCaseSensitive(args.isCaseSensitive); } if (typeof args.matchWholeWord === 'boolean') { this.searchWidget.searchInput.setWholeWords(args.matchWholeWord); } if (typeof args.isRegex === 'boolean') { this.searchWidget.searchInput.setRegex(args.isRegex); } if (typeof args.filesToInclude === 'string') { this.searchIncludePattern.setValue(String(args.filesToInclude)); } if (typeof args.filesToExclude === 'string') { this.searchExcludePattern.setValue(String(args.filesToExclude)); } if (typeof args.query === 'string') { this.searchWidget.searchInput.setValue(args.query); } if (typeof args.replace === 'string') { this.searchWidget.replaceInput.setValue(args.replace); } else { if (this.searchWidget.replaceInput.getValue() !== '') { this.searchWidget.replaceInput.setValue(''); } } if (typeof args.triggerSearch === 'boolean' && args.triggerSearch) { this.triggerQueryChange(); } if (typeof args.preserveCase === 'boolean') { this.searchWidget.replaceInput.setPreserveCase(args.preserveCase); } if (typeof args.useExcludeSettingsAndIgnoreFiles === 'boolean') { this.inputPatternExcludes.setUseExcludesAndIgnoreFiles(args.useExcludeSettingsAndIgnoreFiles); } } toggleQueryDetails(moveFocus = true, show?: boolean, skipLayout?: boolean, reverse?: boolean): void { const cls = 'more'; show = typeof show === 'undefined' ? !this.queryDetails.classList.contains(cls) : Boolean(show); this.viewletState['query.queryDetailsExpanded'] = show; skipLayout = Boolean(skipLayout); if (show) { this.toggleQueryDetailsButton.setAttribute('aria-expanded', 'true'); this.queryDetails.classList.add(cls); if (moveFocus) { if (reverse) { this.inputPatternExcludes.focus(); this.inputPatternExcludes.select(); } else { this.inputPatternIncludes.focus(); this.inputPatternIncludes.select(); } } } else { this.toggleQueryDetailsButton.setAttribute('aria-expanded', 'false'); this.queryDetails.classList.remove(cls); if (moveFocus) { this.searchWidget.focus(); } } if (!skipLayout && this.size) { this.layout(this._orientation === Orientation.VERTICAL ? this.size.height : this.size.width); } } searchInFolders(resources?: URI[]): void { const folderPaths: string[] = []; const workspace = this.contextService.getWorkspace(); if (resources) { resources.forEach(resource => { let folderPath: string | undefined; if (this.contextService.getWorkbenchState() === WorkbenchState.FOLDER) { // Show relative path from the root for single-root mode folderPath = relativePath(workspace.folders[0].uri, resource); // always uses forward slashes if (folderPath && folderPath !== '.') { folderPath = './' + folderPath; } } else { const owningFolder = this.contextService.getWorkspaceFolder(resource); if (owningFolder) { const owningRootName = owningFolder.name; // If this root is the only one with its basename, use a relative ./ path. If there is another, use an absolute path const isUniqueFolder = workspace.folders.filter(folder => folder.name === owningRootName).length === 1; if (isUniqueFolder) { const relPath = relativePath(owningFolder.uri, resource); // always uses forward slashes if (relPath === '') { folderPath = `./${owningFolder.name}`; } else { folderPath = `./${owningFolder.name}/${relPath}`; } } else { folderPath = resource.fsPath; // TODO rob: handle on-file URIs } } } if (folderPath) { folderPaths.push(folderPath); } }); } if (!folderPaths.length || folderPaths.some(folderPath => folderPath === '.')) { this.inputPatternIncludes.setValue(''); this.searchWidget.focus(); return; } // Show 'files to include' box if (!this.showsFileTypes()) { this.toggleQueryDetails(true, true); } this.inputPatternIncludes.setValue(folderPaths.join(', ')); this.searchWidget.focus(false); } triggerQueryChange(_options?: { preserveFocus?: boolean, triggeredOnType?: boolean, delay?: number }) { const options = { preserveFocus: true, triggeredOnType: false, delay: 0, ..._options }; if (!this.pauseSearching) { this.triggerQueryDelayer.trigger(() => { this._onQueryChanged(options.preserveFocus, options.triggeredOnType); }, options.delay); } } private _onQueryChanged(preserveFocus: boolean, triggeredOnType = false): void { if (!this.searchWidget.searchInput.inputBox.isInputValid()) { return; } const isRegex = this.searchWidget.searchInput.getRegex(); const isWholeWords = this.searchWidget.searchInput.getWholeWords(); const isCaseSensitive = this.searchWidget.searchInput.getCaseSensitive(); const contentPattern = this.searchWidget.searchInput.getValue(); const excludePatternText = this.inputPatternExcludes.getValue().trim(); const includePatternText = this.inputPatternIncludes.getValue().trim(); const useExcludesAndIgnoreFiles = this.inputPatternExcludes.useExcludesAndIgnoreFiles(); if (contentPattern.length === 0) { this.clearSearchResults(false); this.clearMessage(); return; } const content: IPatternInfo = { pattern: contentPattern, isRegExp: isRegex, isCaseSensitive: isCaseSensitive, isWordMatch: isWholeWords }; const excludePattern = this.inputPatternExcludes.getValue(); const includePattern = this.inputPatternIncludes.getValue(); // Need the full match line to correctly calculate replace text, if this is a search/replace with regex group references ($1, $2, ...). // 10000 chars is enough to avoid sending huge amounts of text around, if you do a replace with a longer match, it may or may not resolve the group refs correctly. // https://github.com/microsoft/vscode/issues/58374 const charsPerLine = content.isRegExp ? 10000 : 1000; const options: ITextQueryBuilderOptions = { _reason: 'searchView', extraFileResources: this.instantiationService.invokeFunction(getOutOfWorkspaceEditorResources), maxResults: SearchView.MAX_TEXT_RESULTS, disregardIgnoreFiles: !useExcludesAndIgnoreFiles || undefined, disregardExcludeSettings: !useExcludesAndIgnoreFiles || undefined, excludePattern, includePattern, previewOptions: { matchLines: 1, charsPerLine }, isSmartCase: this.searchConfig.smartCase, expandPatterns: true }; const folderResources = this.contextService.getWorkspace().folders; const onQueryValidationError = (err: Error) => { this.searchWidget.searchInput.showMessage({ content: err.message, type: MessageType.ERROR }); this.viewModel.searchResult.clear(); }; let query: ITextQuery; try { query = this.queryBuilder.text(content, folderResources.map(folder => folder.uri), options); } catch (err) { onQueryValidationError(err); return; } this.validateQuery(query).then(() => { this.onQueryTriggered(query, options, excludePatternText, includePatternText, triggeredOnType); if (!preserveFocus) { this.searchWidget.focus(false, undefined, true); // focus back to input field } }, onQueryValidationError); } private validateQuery(query: ITextQuery): Promise<void> { // Validate folderQueries const folderQueriesExistP = query.folderQueries.map(fq => { return this.fileService.exists(fq.folder); }); return Promise.all(folderQueriesExistP).then(existResults => { // If no folders exist, show an error message about the first one const existingFolderQueries = query.folderQueries.filter((folderQuery, i) => existResults[i]); if (!query.folderQueries.length || existingFolderQueries.length) { query.folderQueries = existingFolderQueries; } else { const nonExistantPath = query.folderQueries[0].folder.fsPath; const searchPathNotFoundError = nls.localize('searchPathNotFoundError', "Search path not found: {0}", nonExistantPath); return Promise.reject(new Error(searchPathNotFoundError)); } return undefined; }); } private onQueryTriggered(query: ITextQuery, options: ITextQueryBuilderOptions, excludePatternText: string, includePatternText: string, triggeredOnType: boolean): void { this.addToSearchHistoryDelayer.trigger(() => { this.searchWidget.searchInput.onSearchSubmit(); this.inputPatternExcludes.onSearchSubmit(); this.inputPatternIncludes.onSearchSubmit(); }); this.viewModel.cancelSearch(true); this.currentSearchQ = this.currentSearchQ .then(() => this.doSearch(query, excludePatternText, includePatternText, triggeredOnType)) .then(() => undefined, () => undefined); } private doSearch(query: ITextQuery, excludePatternText: string, includePatternText: string, triggeredOnType: boolean): Thenable<void> { let progressComplete: () => void; this.progressService.withProgress({ location: this.getProgressLocation(), delay: triggeredOnType ? 300 : 0 }, _progress => { return new Promise<void>(resolve => progressComplete = resolve); }); this.searchWidget.searchInput.clearMessage(); this.state = SearchUIState.Searching; this.showEmptyStage(); const slowTimer = setTimeout(() => { this.state = SearchUIState.SlowSearch; this.updateActions(); }, 2000); const onComplete = (completed?: ISearchComplete) => { clearTimeout(slowTimer); this.state = SearchUIState.Idle; // Complete up to 100% as needed progressComplete(); // Do final render, then expand if just 1 file with less than 50 matches this.onSearchResultsChanged(); const collapseResults = this.searchConfig.collapseResults; if (collapseResults !== 'alwaysCollapse' && this.viewModel.searchResult.matches().length === 1) { const onlyMatch = this.viewModel.searchResult.matches()[0]; if (onlyMatch.count() < 50) { this.tree.expand(onlyMatch); } } this.viewModel.replaceString = this.searchWidget.getReplaceValue(); this.updateActions(); const hasResults = !this.viewModel.searchResult.isEmpty(); if (completed?.exit === SearchCompletionExitCode.NewSearchStarted) { return; } if (completed && completed.limitHit) { this.searchWidget.searchInput.showMessage({ content: nls.localize('searchMaxResultsWarning', "The result set only contains a subset of all matches. Please be more specific in your search to narrow down the results."), type: MessageType.WARNING }); } if (!hasResults) { const hasExcludes = !!excludePatternText; const hasIncludes = !!includePatternText; let message: string; if (!completed) { message = SEARCH_CANCELLED_MESSAGE; } else if (hasIncludes && hasExcludes) { message = nls.localize('noResultsIncludesExcludes', "No results found in '{0}' excluding '{1}' - ", includePatternText, excludePatternText); } else if (hasIncludes) { message = nls.localize('noResultsIncludes', "No results found in '{0}' - ", includePatternText); } else if (hasExcludes) { message = nls.localize('noResultsExcludes', "No results found excluding '{0}' - ", excludePatternText); } else { message = nls.localize('noResultsFound', "No results found. Review your settings for configured exclusions and check your gitignore files - "); } // Indicate as status to ARIA aria.status(message); const messageEl = this.clearMessage(); const p = dom.append(messageEl, $('p', undefined, message)); if (!completed) { const searchAgainLink = dom.append(p, $('a.pointer.prominent', undefined, nls.localize('rerunSearch.message', "Search again"))); this.messageDisposables.push(dom.addDisposableListener(searchAgainLink, dom.EventType.CLICK, (e: MouseEvent) => { dom.EventHelper.stop(e, false); this.triggerQueryChange({ preserveFocus: false }); })); } else if (hasIncludes || hasExcludes) { const searchAgainLink = dom.append(p, $('a.pointer.prominent', { tabindex: 0 }, nls.localize('rerunSearchInAll.message', "Search again in all files"))); this.messageDisposables.push(dom.addDisposableListener(searchAgainLink, dom.EventType.CLICK, (e: MouseEvent) => { dom.EventHelper.stop(e, false); this.inputPatternExcludes.setValue(''); this.inputPatternIncludes.setValue(''); this.triggerQueryChange({ preserveFocus: false }); })); } else { const openSettingsLink = dom.append(p, $('a.pointer.prominent', { tabindex: 0 }, nls.localize('openSettings.message', "Open Settings"))); this.addClickEvents(openSettingsLink, this.onOpenSettings); } if (completed) { dom.append(p, $('span', undefined, ' - ')); const learnMoreLink = dom.append(p, $('a.pointer.prominent', { tabindex: 0 }, nls.localize('openSettings.learnMore', "Learn More"))); this.addClickEvents(learnMoreLink, this.onLearnMore); } if (this.contextService.getWorkbenchState() === WorkbenchState.EMPTY) { this.showSearchWithoutFolderMessage(); } this.reLayout(); } else { this.viewModel.searchResult.toggleHighlights(this.isVisible()); // show highlights // Indicate final search result count for ARIA aria.status(nls.localize('ariaSearchResultsStatus', "Search returned {0} results in {1} files", this.viewModel.searchResult.count(), this.viewModel.searchResult.fileCount())); } }; const onError = (e: any) => { clearTimeout(slowTimer); this.state = SearchUIState.Idle; if (errors.isPromiseCanceledError(e)) { return onComplete(undefined); } else { this.updateActions(); progressComplete(); this.searchWidget.searchInput.showMessage({ content: e.message, type: MessageType.ERROR }); this.viewModel.searchResult.clear(); return Promise.resolve(); } }; let visibleMatches = 0; let updatedActionsForFileCount = false; // Handle UI updates in an interval to show frequent progress and results const uiRefreshHandle: any = setInterval(() => { if (this.state === SearchUIState.Idle) { window.clearInterval(uiRefreshHandle); return; } // Search result tree update const fileCount = this.viewModel.searchResult.fileCount(); if (visibleMatches !== fileCount) { visibleMatches = fileCount; this.refreshAndUpdateCount(); } if (fileCount > 0 && !updatedActionsForFileCount) { updatedActionsForFileCount = true; this.updateActions(); } }, 100); this.searchWidget.setReplaceAllActionState(false); return this.viewModel.search(query) .then(onComplete, onError); } private addClickEvents = (element: HTMLElement, handler: (event: any) => void): void => { this.messageDisposables.push(dom.addDisposableListener(element, dom.EventType.CLICK, handler)); this.messageDisposables.push(dom.addDisposableListener(element, dom.EventType.KEY_DOWN, e => { const event = new StandardKeyboardEvent(e); let eventHandled = true; if (event.equals(KeyCode.Space) || event.equals(KeyCode.Enter)) { handler(e); } else { eventHandled = false; } if (eventHandled) { event.preventDefault(); event.stopPropagation(); } })); }; private onOpenSettings = (e: dom.EventLike): void => { dom.EventHelper.stop(e, false); this.openSettings('.exclude'); }; private openSettings(query: string): Promise<IEditorPane | undefined> { const options: ISettingsEditorOptions = { query }; return this.contextService.getWorkbenchState() !== WorkbenchState.EMPTY ? this.preferencesService.openWorkspaceSettings(undefined, options) : this.preferencesService.openGlobalSettings(undefined, options); } private onLearnMore = (e: MouseEvent): void => { dom.EventHelper.stop(e, false); this.openerService.open(URI.parse('https://go.microsoft.com/fwlink/?linkid=853977')); }; private updateSearchResultCount(disregardExcludesAndIgnores?: boolean): void { const fileCount = this.viewModel.searchResult.fileCount(); this.hasSearchResultsKey.set(fileCount > 0); const msgWasHidden = this.messagesElement.style.display === 'none'; const messageEl = this.clearMessage(); let resultMsg = this.buildResultCountMessage(this.viewModel.searchResult.count(), fileCount); this.tree.ariaLabel = resultMsg + nls.localize('forTerm', " - Search: {0}", this.searchResult.query?.contentPattern.pattern ?? ''); if (fileCount > 0) { if (disregardExcludesAndIgnores) { resultMsg += nls.localize('useIgnoresAndExcludesDisabled', " - exclude settings and ignore files are disabled"); } dom.append(messageEl, $('span', undefined, resultMsg + ' - ')); const span = dom.append(messageEl, $('span')); const openInEditorLink = dom.append(span, $('a.pointer.prominent', undefined, nls.localize('openInEditor.message', "Open in editor"))); openInEditorLink.title = appendKeyBindingLabel( nls.localize('openInEditor.tooltip', "Copy current search results to an editor"), this.keybindingService.lookupKeybinding(Constants.OpenInEditorCommandId), this.keybindingService); this.messageDisposables.push(dom.addDisposableListener(openInEditorLink, dom.EventType.CLICK, (e: MouseEvent) => { dom.EventHelper.stop(e, false); this.instantiationService.invokeFunction(createEditorFromSearchResult, this.searchResult, this.searchIncludePattern.getValue(), this.searchExcludePattern.getValue()); })); this.reLayout(); } else if (!msgWasHidden) { dom.hide(this.messagesElement); } } private buildResultCountMessage(resultCount: number, fileCount: number): string { if (resultCount === 1 && fileCount === 1) { return nls.localize('search.file.result', "{0} result in {1} file", resultCount, fileCount); } else if (resultCount === 1) { return nls.localize('search.files.result', "{0} result in {1} files", resultCount, fileCount); } else if (fileCount === 1) { return nls.localize('search.file.results', "{0} results in {1} file", resultCount, fileCount); } else { return nls.localize('search.files.results', "{0} results in {1} files", resultCount, fileCount); } } private showSearchWithoutFolderMessage(): void { this.searchWithoutFolderMessageElement = this.clearMessage(); const textEl = dom.append(this.searchWithoutFolderMessageElement, $('p', undefined, nls.localize('searchWithoutFolder', "You have not opened or specified a folder. Only open files are currently searched - "))); const openFolderLink = dom.append(textEl, $('a.pointer.prominent', { tabindex: 0 }, nls.localize('openFolder', "Open Folder"))); const actionRunner = new ActionRunner(); this.messageDisposables.push(dom.addDisposableListener(openFolderLink, dom.EventType.CLICK, (e: MouseEvent) => { dom.EventHelper.stop(e, false); const action = env.isMacintosh ? this.instantiationService.createInstance(OpenFileFolderAction, OpenFileFolderAction.ID, OpenFileFolderAction.LABEL) : this.instantiationService.createInstance(OpenFolderAction, OpenFolderAction.ID, OpenFolderAction.LABEL); actionRunner.run(action).then(() => { action.dispose(); }, err => { action.dispose(); errors.onUnexpectedError(err); }); })); } private showEmptyStage(forceHideMessages = false): void { // disable 'result'-actions this.updateActions(); const showingCancelled = (this.messagesElement.firstChild?.textContent?.indexOf(SEARCH_CANCELLED_MESSAGE) ?? -1) > -1; // clean up ui // this.replaceService.disposeAllReplacePreviews(); if (showingCancelled || forceHideMessages || !this.configurationService.getValue<ISearchConfiguration>().search.searchOnType) { // when in search to type, don't preemptively hide, as it causes flickering and shifting of the live results dom.hide(this.messagesElement); } dom.show(this.resultsElement); this.currentSelectedFileMatch = undefined; } private onFocus(lineMatch: Match, preserveFocus?: boolean, sideBySide?: boolean, pinned?: boolean): Promise<any> { const useReplacePreview = this.configurationService.getValue<ISearchConfiguration>().search.useReplacePreview; return (useReplacePreview && this.viewModel.isReplaceActive() && !!this.viewModel.replaceString) ? this.replaceService.openReplacePreview(lineMatch, preserveFocus, sideBySide, pinned) : this.open(lineMatch, preserveFocus, sideBySide, pinned); } open(element: FileMatchOrMatch, preserveFocus?: boolean, sideBySide?: boolean, pinned?: boolean): Promise<void> { const selection = this.getSelectionFrom(element); const resource = element instanceof Match ? element.parent().resource : (<FileMatch>element).resource; return this.editorService.openEditor({ resource: resource, options: { preserveFocus, pinned, selection, revealIfVisible: true } }, sideBySide ? SIDE_GROUP : ACTIVE_GROUP).then(editor => { if (element instanceof Match && preserveFocus && isCodeEditor(editor)) { this.viewModel.searchResult.rangeHighlightDecorations.highlightRange( (<ICodeEditor>editor.getControl()).getModel()!, element.range() ); } else { this.viewModel.searchResult.rangeHighlightDecorations.removeHighlightRange(); } }, errors.onUnexpectedError); } openEditorWithMultiCursor(element: FileMatchOrMatch): Promise<void> { const resource = element instanceof Match ? element.parent().resource : (<FileMatch>element).resource; return this.editorService.openEditor({ resource: resource, options: { preserveFocus: false, pinned: true, revealIfVisible: true } }).then(editor => { if (editor) { let fileMatch = null; if (element instanceof FileMatch) { fileMatch = element; } else if (element instanceof Match) { fileMatch = element.parent(); } if (fileMatch) { const selections = fileMatch.matches().map(m => new Selection(m.range().startLineNumber, m.range().startColumn, m.range().endLineNumber, m.range().endColumn)); const codeEditor = getCodeEditor(editor.getControl()); if (codeEditor) { const multiCursorController = MultiCursorSelectionController.get(codeEditor); multiCursorController.selectAllUsingSelections(selections); } } } this.viewModel.searchResult.rangeHighlightDecorations.removeHighlightRange(); }, errors.onUnexpectedError); } private getSelectionFrom(element: FileMatchOrMatch): any { let match: Match | null = null; if (element instanceof Match) { match = element; } if (element instanceof FileMatch && element.count() > 0) { match = element.matches()[element.matches().length - 1]; } if (match) { const range = match.range(); if (this.viewModel.isReplaceActive() && !!this.viewModel.replaceString) { const replaceString = match.replaceString; return { startLineNumber: range.startLineNumber, startColumn: range.startColumn, endLineNumber: range.startLineNumber, endColumn: range.startColumn + replaceString.length }; } return range; } return undefined; } private onUntitledDidDispose(resource: URI): void { if (!this.viewModel) { return; } // remove search results from this resource as it got disposed const matches = this.viewModel.searchResult.matches(); for (let i = 0, len = matches.length; i < len; i++) { if (resource.toString() === matches[i].resource.toString()) { this.viewModel.searchResult.remove(matches[i]); } } } private onFilesChanged(e: FileChangesEvent): void { if (!this.viewModel || (this.searchConfig.sortOrder !== SearchSortOrder.Modified && !e.gotDeleted())) { return; } const matches = this.viewModel.searchResult.matches(); if (e.gotDeleted()) { const deletedMatches = matches.filter(m => e.contains(m.resource, FileChangeType.DELETED)); this.viewModel.searchResult.remove(deletedMatches); } else { // Check if the changed file contained matches const changedMatches = matches.filter(m => e.contains(m.resource)); if (changedMatches.length && this.searchConfig.sortOrder === SearchSortOrder.Modified) { // No matches need to be removed, but modified files need to have their file stat updated. this.updateFileStats(changedMatches).then(() => this.refreshTree()); } } } getActions(): IAction[] { return [ this.state === SearchUIState.SlowSearch ? this.cancelAction : this.refreshAction, ...this.actions, this.toggleCollapseAction ]; } private get searchConfig(): ISearchConfigurationProperties { return this.configurationService.getValue<ISearchConfigurationProperties>('search'); } private clearHistory(): void { this.searchWidget.clearHistory(); this.inputPatternExcludes.clearHistory(); this.inputPatternIncludes.clearHistory(); } public saveState(): void { const isRegex = this.searchWidget.searchInput.getRegex(); const isWholeWords = this.searchWidget.searchInput.getWholeWords(); const isCaseSensitive = this.searchWidget.searchInput.getCaseSensitive(); const contentPattern = this.searchWidget.searchInput.getValue(); const patternExcludes = this.inputPatternExcludes.getValue().trim(); const patternIncludes = this.inputPatternIncludes.getValue().trim(); const useExcludesAndIgnoreFiles = this.inputPatternExcludes.useExcludesAndIgnoreFiles(); const preserveCase = this.viewModel.preserveCase; this.viewletState['query.contentPattern'] = contentPattern; this.viewletState['query.regex'] = isRegex; this.viewletState['query.wholeWords'] = isWholeWords; this.viewletState['query.caseSensitive'] = isCaseSensitive; this.viewletState['query.folderExclusions'] = patternExcludes; this.viewletState['query.folderIncludes'] = patternIncludes; this.viewletState['query.useExcludesAndIgnoreFiles'] = useExcludesAndIgnoreFiles; this.viewletState['query.preserveCase'] = preserveCase; const isReplaceShown = this.searchAndReplaceWidget.isReplaceShown(); this.viewletState['view.showReplace'] = isReplaceShown; this.viewletState['query.replaceText'] = isReplaceShown && this.searchWidget.getReplaceValue(); const history: ISearchHistoryValues = Object.create(null); const searchHistory = this.searchWidget.getSearchHistory(); if (searchHistory && searchHistory.length) { history.search = searchHistory; } const replaceHistory = this.searchWidget.getReplaceHistory(); if (replaceHistory && replaceHistory.length) { history.replace = replaceHistory; } const patternExcludesHistory = this.inputPatternExcludes.getHistory(); if (patternExcludesHistory && patternExcludesHistory.length) { history.exclude = patternExcludesHistory; } const patternIncludesHistory = this.inputPatternIncludes.getHistory(); if (patternIncludesHistory && patternIncludesHistory.length) { history.include = patternIncludesHistory; } this.searchHistoryService.save(history); this.memento.saveMemento(); super.saveState(); } private async retrieveFileStats(): Promise<void> { const files = this.searchResult.matches().filter(f => !f.fileStat).map(f => f.resolveFileStat(this.fileService)); await Promise.all(files); } private async updateFileStats(elements: FileMatch[]): Promise<void> { const files = elements.map(f => f.resolveFileStat(this.fileService)); await Promise.all(files); } private removeFileStats(): void { for (const fileMatch of this.searchResult.matches()) { fileMatch.fileStat = undefined; } } dispose(): void { this.isDisposed = true; this.saveState(); super.dispose(); } } registerThemingParticipant((theme: IColorTheme, collector: ICssStyleCollector) => { const matchHighlightColor = theme.getColor(editorFindMatchHighlight); if (matchHighlightColor) { collector.addRule(`.monaco-workbench .search-view .findInFileMatch { background-color: ${matchHighlightColor}; }`); } const diffInsertedColor = theme.getColor(diffInserted); if (diffInsertedColor) { collector.addRule(`.monaco-workbench .search-view .replaceMatch { background-color: ${diffInsertedColor}; }`); } const diffRemovedColor = theme.getColor(diffRemoved); if (diffRemovedColor) { collector.addRule(`.monaco-workbench .search-view .replace.findInFileMatch { background-color: ${diffRemovedColor}; }`); } const diffInsertedOutlineColor = theme.getColor(diffInsertedOutline); if (diffInsertedOutlineColor) { collector.addRule(`.monaco-workbench .search-view .replaceMatch:not(:empty) { border: 1px ${theme.type === 'hc' ? 'dashed' : 'solid'} ${diffInsertedOutlineColor}; }`); } const diffRemovedOutlineColor = theme.getColor(diffRemovedOutline); if (diffRemovedOutlineColor) { collector.addRule(`.monaco-workbench .search-view .replace.findInFileMatch { border: 1px ${theme.type === 'hc' ? 'dashed' : 'solid'} ${diffRemovedOutlineColor}; }`); } const findMatchHighlightBorder = theme.getColor(editorFindMatchHighlightBorder); if (findMatchHighlightBorder) { collector.addRule(`.monaco-workbench .search-view .findInFileMatch { border: 1px ${theme.type === 'hc' ? 'dashed' : 'solid'} ${findMatchHighlightBorder}; }`); } const outlineSelectionColor = theme.getColor(listActiveSelectionForeground); if (outlineSelectionColor) { collector.addRule(`.monaco-workbench .search-view .monaco-list.element-focused .monaco-list-row.focused.selected:not(.highlighted) .action-label:focus { outline-color: ${outlineSelectionColor} }`); } if (theme.type === 'dark') { const foregroundColor = theme.getColor(foreground); if (foregroundColor) { const fgWithOpacity = new Color(new RGBA(foregroundColor.rgba.r, foregroundColor.rgba.g, foregroundColor.rgba.b, 0.65)); collector.addRule(`.search-view .message { color: ${fgWithOpacity}; }`); } } });
src/vs/workbench/contrib/search/browser/searchView.ts
0
https://github.com/microsoft/vscode/commit/574ee2032cc24ed250ef15962ce100838d4e5e4a
[ 0.7614365816116333, 0.004154278431087732, 0.00016225871513597667, 0.00017346101230941713, 0.05423438921570778 ]
{ "id": 2, "code_window": [ "\tprivate readonly _onDidRegisterProcessSupport = new Emitter<void>();\n", "\tpublic get onDidRegisterProcessSupport(): Event<void> { return this._onDidRegisterProcessSupport.event; }\n", "\tprivate readonly _onDidChangeConnectionState = new Emitter<void>();\n", "\tpublic get onDidChangeConnectionState(): Event<void> { return this._onDidChangeConnectionState.event; }\n", "\tpublic get connectionState(): TerminalConnectionState { return this._connectionState; }\n", "\tpublic set willFocusNewTerminal(v: boolean) { this._willFocusNewTerminal = v; }\n", "\n", "\tconstructor(\n", "\t\t@IContextKeyService private _contextKeyService: IContextKeyService,\n", "\t\t@IWorkbenchLayoutService private _layoutService: IWorkbenchLayoutService,\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/contrib/terminal/browser/terminalService.ts", "type": "replace", "edit_start_line_idx": 104 }
/*--------------------------------------------------------------------------------------------- * 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 * as uuid from 'vs/base/common/uuid'; suite('UUID', () => { test('generation', () => { const asHex = uuid.generateUuid(); assert.equal(asHex.length, 36); assert.equal(asHex[14], '4'); assert.ok(asHex[19] === '8' || asHex[19] === '9' || asHex[19] === 'a' || asHex[19] === 'b'); }); test('self-check', function () { const t1 = Date.now(); while (Date.now() - t1 < 50) { const value = uuid.generateUuid(); assert.ok(uuid.isUUID(value)); } }); });
src/vs/base/test/common/uuid.test.ts
0
https://github.com/microsoft/vscode/commit/574ee2032cc24ed250ef15962ce100838d4e5e4a
[ 0.00017722288612276316, 0.00017554167425259948, 0.00017390474386047572, 0.00017549740732647479, 0.0000013549876030083396 ]
{ "id": 3, "code_window": [ "\t\tthis._terminalTabs.push(terminalTab);\n", "\n", "\t\tconst instance = terminalTab.terminalInstances[0];\n", "\t\tif (this._willFocusNewTerminal) {\n", "\t\t\tinstance.focusWhenReady();\n", "\t\t\tthis._willFocusNewTerminal = false;\n", "\t\t}\n", "\n", "\t\tterminalTab.addDisposable(terminalTab.onDisposed(this._onTabDisposed.fire, this._onTabDisposed));\n", "\t\tterminalTab.addDisposable(terminalTab.onInstancesChanged(this._onInstancesChanged.fire, this._onInstancesChanged));\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/contrib/terminal/browser/terminalService.ts", "type": "replace", "edit_start_line_idx": 686 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as dom from 'vs/base/browser/dom'; import * as nls from 'vs/nls'; import * as platform from 'vs/base/common/platform'; import { Action, IAction, Separator, IActionViewItem } from 'vs/base/common/actions'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IContextMenuService } from 'vs/platform/contextview/browser/contextView'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IThemeService, IColorTheme, registerThemingParticipant, ICssStyleCollector } from 'vs/platform/theme/common/themeService'; import { TerminalFindWidget } from 'vs/workbench/contrib/terminal/browser/terminalFindWidget'; import { KillTerminalAction, SwitchTerminalAction, SwitchTerminalActionViewItem, CopyTerminalSelectionAction, TerminalPasteAction, ClearTerminalAction, SelectAllTerminalAction, CreateNewTerminalAction, SplitTerminalAction } from 'vs/workbench/contrib/terminal/browser/terminalActions'; import { StandardMouseEvent } from 'vs/base/browser/mouseEvent'; import { URI } from 'vs/base/common/uri'; import { TERMINAL_BACKGROUND_COLOR, TERMINAL_BORDER_COLOR } from 'vs/workbench/contrib/terminal/common/terminalColorRegistry'; import { DataTransfers } from 'vs/base/browser/dnd'; import { INotificationService, IPromptChoice, Severity } from 'vs/platform/notification/common/notification'; import { ITerminalService } from 'vs/workbench/contrib/terminal/browser/terminal'; import { BrowserFeatures } from 'vs/base/browser/canIUse'; import { ViewPane, IViewPaneOptions } from 'vs/workbench/browser/parts/views/viewPaneContainer'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { IViewDescriptorService } from 'vs/workbench/common/views'; import { IOpenerService } from 'vs/platform/opener/common/opener'; import { PANEL_BACKGROUND, SIDE_BAR_BACKGROUND } from 'vs/workbench/common/theme'; import { Orientation } from 'vs/base/browser/ui/sash/sash'; const FIND_FOCUS_CLASS = 'find-focused'; export class TerminalViewPane extends ViewPane { private _actions: IAction[] | undefined; private _copyContextMenuAction: IAction | undefined; private _contextMenuActions: IAction[] | undefined; private _cancelContextMenu: boolean = false; private _fontStyleElement: HTMLElement | undefined; private _parentDomElement: HTMLElement | undefined; private _terminalContainer: HTMLElement | undefined; private _findWidget: TerminalFindWidget | undefined; private _splitTerminalAction: IAction | undefined; private _terminalsInitialized = false; private _bodyDimensions: { width: number, height: number } = { width: 0, height: 0 }; constructor( options: IViewPaneOptions, @IKeybindingService keybindingService: IKeybindingService, @IContextKeyService contextKeyService: IContextKeyService, @IViewDescriptorService viewDescriptorService: IViewDescriptorService, @IConfigurationService configurationService: IConfigurationService, @IContextMenuService private readonly _contextMenuService: IContextMenuService, @IInstantiationService private readonly _instantiationService: IInstantiationService, @ITerminalService private readonly _terminalService: ITerminalService, @IThemeService protected readonly themeService: IThemeService, @ITelemetryService telemetryService: ITelemetryService, @INotificationService private readonly _notificationService: INotificationService, @IOpenerService openerService: IOpenerService, ) { super(options, keybindingService, _contextMenuService, configurationService, contextKeyService, viewDescriptorService, _instantiationService, openerService, themeService, telemetryService); this._terminalService.onDidRegisterProcessSupport(() => { if (this._actions) { for (const action of this._actions) { action.enabled = true; } } this._onDidChangeViewWelcomeState.fire(); }); this._register(this.onDidBlur(() => { this._terminalService.willFocusNewTerminal = false; })); } protected renderBody(container: HTMLElement): void { super.renderBody(container); if (this.shouldShowWelcome()) { return; } this._parentDomElement = container; this._parentDomElement.classList.add('integrated-terminal'); this._fontStyleElement = document.createElement('style'); this._terminalContainer = document.createElement('div'); this._terminalContainer.classList.add('terminal-outer-container'); this._findWidget = this._instantiationService.createInstance(TerminalFindWidget, this._terminalService.getFindState()); this._findWidget.focusTracker.onDidFocus(() => this._terminalContainer!.classList.add(FIND_FOCUS_CLASS)); this._parentDomElement.appendChild(this._fontStyleElement); this._parentDomElement.appendChild(this._terminalContainer); this._parentDomElement.appendChild(this._findWidget.getDomNode()); this._attachEventListeners(this._parentDomElement, this._terminalContainer); this._terminalService.setContainers(container, this._terminalContainer); this._register(this.themeService.onDidColorThemeChange(theme => this._updateTheme(theme))); this._register(this.configurationService.onDidChangeConfiguration(e => { if (e.affectsConfiguration('terminal.integrated.fontFamily') || e.affectsConfiguration('editor.fontFamily')) { const configHelper = this._terminalService.configHelper; if (!configHelper.configFontIsMonospace()) { const choices: IPromptChoice[] = [{ label: nls.localize('terminal.useMonospace', "Use 'monospace'"), run: () => this.configurationService.updateValue('terminal.integrated.fontFamily', 'monospace'), }]; this._notificationService.prompt(Severity.Warning, nls.localize('terminal.monospaceOnly', "The terminal only supports monospace fonts. Be sure to restart VS Code if this is a newly installed font."), choices); } } })); this._updateTheme(); this._register(this.onDidChangeBodyVisibility(visible => { if (visible) { const hadTerminals = !!this._terminalService.terminalTabs.length; if (this._terminalsInitialized) { if (!hadTerminals) { this._terminalService.createTerminal(); } } else { this._terminalsInitialized = true; this._terminalService.initializeTerminals(); } this._updateTheme(); if (hadTerminals) { this._terminalService.getActiveTab()?.setVisible(visible); } else { // TODO@Tyriar - this call seems unnecessary this.layoutBody(this._bodyDimensions.height, this._bodyDimensions.width); } } else { this._terminalService.getActiveTab()?.setVisible(false); } })); // Force another layout (first is setContainers) since config has changed this.layoutBody(this._terminalContainer.offsetHeight, this._terminalContainer.offsetWidth); } protected layoutBody(height: number, width: number): void { super.layoutBody(height, width); if (this.shouldShowWelcome()) { return; } this._bodyDimensions.width = width; this._bodyDimensions.height = height; this._terminalService.terminalTabs.forEach(t => t.layout(width, height)); // Update orientation of split button icon if (this._splitTerminalAction) { this._splitTerminalAction.class = this.orientation === Orientation.HORIZONTAL ? SplitTerminalAction.HORIZONTAL_CLASS : SplitTerminalAction.VERTICAL_CLASS; } } public getActions(): IAction[] { if (!this._actions) { this._splitTerminalAction = this._instantiationService.createInstance(SplitTerminalAction, SplitTerminalAction.ID, SplitTerminalAction.LABEL); this._actions = [ this._instantiationService.createInstance(SwitchTerminalAction, SwitchTerminalAction.ID, SwitchTerminalAction.LABEL), this._instantiationService.createInstance(CreateNewTerminalAction, CreateNewTerminalAction.ID, CreateNewTerminalAction.SHORT_LABEL), this._splitTerminalAction, this._instantiationService.createInstance(KillTerminalAction, KillTerminalAction.ID, KillTerminalAction.PANEL_LABEL) ]; for (const action of this._actions) { if (!this._terminalService.isProcessSupportRegistered) { action.enabled = false; } this._register(action); } } return this._actions; } private _getContextMenuActions(): IAction[] { if (!this._contextMenuActions || !this._copyContextMenuAction) { this._copyContextMenuAction = this._instantiationService.createInstance(CopyTerminalSelectionAction, CopyTerminalSelectionAction.ID, CopyTerminalSelectionAction.SHORT_LABEL); const clipboardActions = []; if (BrowserFeatures.clipboard.writeText) { clipboardActions.push(this._copyContextMenuAction); } if (BrowserFeatures.clipboard.readText) { clipboardActions.push(this._instantiationService.createInstance(TerminalPasteAction, TerminalPasteAction.ID, TerminalPasteAction.SHORT_LABEL)); } clipboardActions.push(this._instantiationService.createInstance(SelectAllTerminalAction, SelectAllTerminalAction.ID, SelectAllTerminalAction.LABEL)); this._contextMenuActions = [ this._instantiationService.createInstance(CreateNewTerminalAction, CreateNewTerminalAction.ID, CreateNewTerminalAction.SHORT_LABEL), this._instantiationService.createInstance(SplitTerminalAction, SplitTerminalAction.ID, SplitTerminalAction.SHORT_LABEL), new Separator(), ...clipboardActions, new Separator(), this._instantiationService.createInstance(ClearTerminalAction, ClearTerminalAction.ID, ClearTerminalAction.LABEL), new Separator(), this._instantiationService.createInstance(KillTerminalAction, KillTerminalAction.ID, KillTerminalAction.PANEL_LABEL) ]; this._contextMenuActions.forEach(a => { this._register(a); }); } const activeInstance = this._terminalService.getActiveInstance(); this._copyContextMenuAction.enabled = !!activeInstance && activeInstance.hasSelection(); return this._contextMenuActions; } public getActionViewItem(action: Action): IActionViewItem | undefined { if (action.id === SwitchTerminalAction.ID) { return this._instantiationService.createInstance(SwitchTerminalActionViewItem, action); } return super.getActionViewItem(action); } public focus() { if (this._terminalService.getActiveInstance()) { this._terminalService.getActiveInstance()?.focusWhenReady(); } else { this._terminalService.willFocusNewTerminal = true; } } public focusFindWidget() { const activeInstance = this._terminalService.getActiveInstance(); if (activeInstance && activeInstance.hasSelection() && activeInstance.selection!.indexOf('\n') === -1) { this._findWidget!.reveal(activeInstance.selection); } else { this._findWidget!.reveal(); } } public hideFindWidget() { this._findWidget!.hide(); } public showFindWidget() { const activeInstance = this._terminalService.getActiveInstance(); if (activeInstance && activeInstance.hasSelection() && activeInstance.selection!.indexOf('\n') === -1) { this._findWidget!.show(activeInstance.selection); } else { this._findWidget!.show(); } } public getFindWidget(): TerminalFindWidget { return this._findWidget!; } private _attachEventListeners(parentDomElement: HTMLElement, terminalContainer: HTMLElement): void { this._register(dom.addDisposableListener(parentDomElement, 'mousedown', async (event: MouseEvent) => { if (this._terminalService.terminalInstances.length === 0) { return; } if (event.which === 2 && platform.isLinux) { // Drop selection and focus terminal on Linux to enable middle button paste when click // occurs on the selection itself. const terminal = this._terminalService.getActiveInstance(); if (terminal) { terminal.focus(); } } else if (event.which === 3) { const rightClickBehavior = this._terminalService.configHelper.config.rightClickBehavior; if (rightClickBehavior === 'copyPaste' || rightClickBehavior === 'paste') { const terminal = this._terminalService.getActiveInstance(); if (!terminal) { return; } // copyPaste: Shift+right click should open context menu if (rightClickBehavior === 'copyPaste' && event.shiftKey) { this._openContextMenu(event); return; } if (rightClickBehavior === 'copyPaste' && terminal.hasSelection()) { await terminal.copySelection(); terminal.clearSelection(); } else { terminal.paste(); } // Clear selection after all click event bubbling is finished on Mac to prevent // right-click selecting a word which is seemed cannot be disabled. There is a // flicker when pasting but this appears to give the best experience if the // setting is enabled. if (platform.isMacintosh) { setTimeout(() => { terminal.clearSelection(); }, 0); } this._cancelContextMenu = true; } } })); this._register(dom.addDisposableListener(parentDomElement, 'contextmenu', (event: MouseEvent) => { if (!this._cancelContextMenu) { this._openContextMenu(event); } event.preventDefault(); event.stopImmediatePropagation(); this._cancelContextMenu = false; })); this._register(dom.addDisposableListener(document, 'keydown', (event: KeyboardEvent) => { terminalContainer.classList.toggle('alt-active', !!event.altKey); })); this._register(dom.addDisposableListener(document, 'keyup', (event: KeyboardEvent) => { terminalContainer.classList.toggle('alt-active', !!event.altKey); })); this._register(dom.addDisposableListener(parentDomElement, 'keyup', (event: KeyboardEvent) => { if (event.keyCode === 27) { // Keep terminal open on escape event.stopPropagation(); } })); this._register(dom.addDisposableListener(parentDomElement, dom.EventType.DROP, async (e: DragEvent) => { if (e.target === this._parentDomElement || dom.isAncestor(e.target as HTMLElement, parentDomElement)) { if (!e.dataTransfer) { return; } // Check if files were dragged from the tree explorer let path: string | undefined; const resources = e.dataTransfer.getData(DataTransfers.RESOURCES); if (resources) { path = URI.parse(JSON.parse(resources)[0]).fsPath; } else if (e.dataTransfer.files.length > 0 && e.dataTransfer.files[0].path /* Electron only */) { // Check if the file was dragged from the filesystem path = URI.file(e.dataTransfer.files[0].path).fsPath; } if (!path) { return; } const terminal = this._terminalService.getActiveInstance(); if (terminal) { const preparedPath = await this._terminalService.preparePathForTerminalAsync(path, terminal.shellLaunchConfig.executable, terminal.title, terminal.shellType); terminal.sendText(preparedPath, false); terminal.focus(); } } })); } private _openContextMenu(event: MouseEvent): void { const standardEvent = new StandardMouseEvent(event); const anchor: { x: number, y: number } = { x: standardEvent.posx, y: standardEvent.posy }; this._contextMenuService.showContextMenu({ getAnchor: () => anchor, getActions: () => this._getContextMenuActions(), getActionsContext: () => this._parentDomElement }); } private _updateTheme(theme?: IColorTheme): void { if (!theme) { theme = this.themeService.getColorTheme(); } this._findWidget?.updateTheme(theme); } shouldShowWelcome(): boolean { return !this._terminalService.isProcessSupportRegistered; } } registerThemingParticipant((theme: IColorTheme, collector: ICssStyleCollector) => { const panelBackgroundColor = theme.getColor(TERMINAL_BACKGROUND_COLOR) || theme.getColor(PANEL_BACKGROUND); collector.addRule(`.monaco-workbench .part.panel .pane-body.integrated-terminal .terminal-outer-container { background-color: ${panelBackgroundColor ? panelBackgroundColor.toString() : ''}; }`); const sidebarBackgroundColor = theme.getColor(TERMINAL_BACKGROUND_COLOR) || theme.getColor(SIDE_BAR_BACKGROUND); collector.addRule(`.monaco-workbench .part.sidebar .pane-body.integrated-terminal .terminal-outer-container { background-color: ${sidebarBackgroundColor ? sidebarBackgroundColor.toString() : ''}; }`); const borderColor = theme.getColor(TERMINAL_BORDER_COLOR); if (borderColor) { collector.addRule(`.monaco-workbench .pane-body.integrated-terminal .split-view-view:not(:first-child) { border-color: ${borderColor.toString()}; }`); } });
src/vs/workbench/contrib/terminal/browser/terminalView.ts
1
https://github.com/microsoft/vscode/commit/574ee2032cc24ed250ef15962ce100838d4e5e4a
[ 0.05776282772421837, 0.0027344776317477226, 0.00016313786909449846, 0.0002275713050039485, 0.009632982313632965 ]
{ "id": 3, "code_window": [ "\t\tthis._terminalTabs.push(terminalTab);\n", "\n", "\t\tconst instance = terminalTab.terminalInstances[0];\n", "\t\tif (this._willFocusNewTerminal) {\n", "\t\t\tinstance.focusWhenReady();\n", "\t\t\tthis._willFocusNewTerminal = false;\n", "\t\t}\n", "\n", "\t\tterminalTab.addDisposable(terminalTab.onDisposed(this._onTabDisposed.fire, this._onTabDisposed));\n", "\t\tterminalTab.addDisposable(terminalTab.onInstancesChanged(this._onInstancesChanged.fire, this._onInstancesChanged));\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/contrib/terminal/browser/terminalService.ts", "type": "replace", "edit_start_line_idx": 686 }
/*--------------------------------------------------------------------------------------------- * 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 { Emitter } from 'vs/base/common/event'; import { TelemetryService, ITelemetryServiceConfig } from 'vs/platform/telemetry/common/telemetryService'; import ErrorTelemetry from 'vs/platform/telemetry/browser/errorTelemetry'; import { NullAppender, ITelemetryAppender } from 'vs/platform/telemetry/common/telemetryUtils'; import * as Errors from 'vs/base/common/errors'; import * as sinon from 'sinon'; import { ITelemetryData } from 'vs/platform/telemetry/common/telemetry'; import { TestConfigurationService } from 'vs/platform/configuration/test/common/testConfigurationService'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; class TestTelemetryAppender implements ITelemetryAppender { public events: any[]; public isDisposed: boolean; constructor() { this.events = []; this.isDisposed = false; } public log(eventName: string, data?: any): void { this.events.push({ eventName, data }); } public getEventsCount() { return this.events.length; } public flush(): Promise<any> { this.isDisposed = true; return Promise.resolve(null); } } class ErrorTestingSettings { public personalInfo: string; public importantInfo: string; public filePrefix: string; public dangerousPathWithoutImportantInfo: string; public dangerousPathWithImportantInfo: string; public missingModelPrefix: string; public missingModelMessage: string; public noSuchFilePrefix: string; public noSuchFileMessage: string; public stack: string[]; public randomUserFile: string = 'a/path/that/doe_snt/con-tain/code/names.js'; public anonymizedRandomUserFile: string = '<REDACTED: user-file-path>'; public nodeModulePathToRetain: string = 'node_modules/path/that/shouldbe/retained/names.js:14:15854'; public nodeModuleAsarPathToRetain: string = 'node_modules.asar/path/that/shouldbe/retained/names.js:14:12354'; constructor() { this.personalInfo = 'DANGEROUS/PATH'; this.importantInfo = 'important/information'; this.filePrefix = 'file:///'; this.dangerousPathWithImportantInfo = this.filePrefix + this.personalInfo + '/resources/app/' + this.importantInfo; this.dangerousPathWithoutImportantInfo = this.filePrefix + this.personalInfo; this.missingModelPrefix = 'Received model events for missing model '; this.missingModelMessage = this.missingModelPrefix + ' ' + this.dangerousPathWithoutImportantInfo; this.noSuchFilePrefix = 'ENOENT: no such file or directory'; this.noSuchFileMessage = this.noSuchFilePrefix + ' \'' + this.personalInfo + '\''; this.stack = [`at e._modelEvents (${this.randomUserFile}:11:7309)`, ` at t.AllWorkers (${this.randomUserFile}:6:8844)`, ` at e.(anonymous function) [as _modelEvents] (${this.randomUserFile}:5:29552)`, ` at Function.<anonymous> (${this.randomUserFile}:6:8272)`, ` at e.dispatch (${this.randomUserFile}:5:26931)`, ` at e.request (/${this.nodeModuleAsarPathToRetain})`, ` at t._handleMessage (${this.nodeModuleAsarPathToRetain})`, ` at t._onmessage (/${this.nodeModulePathToRetain})`, ` at t.onmessage (${this.nodeModulePathToRetain})`, ` at DedicatedWorkerGlobalScope.self.onmessage`, this.dangerousPathWithImportantInfo, this.dangerousPathWithoutImportantInfo, this.missingModelMessage, this.noSuchFileMessage]; } } suite('TelemetryService', () => { test('Disposing', sinon.test(function () { let testAppender = new TestTelemetryAppender(); let service = new TelemetryService({ appender: testAppender }, undefined!); return service.publicLog('testPrivateEvent').then(() => { assert.equal(testAppender.getEventsCount(), 1); service.dispose(); assert.equal(!testAppender.isDisposed, true); }); })); // event reporting test('Simple event', sinon.test(function () { let testAppender = new TestTelemetryAppender(); let service = new TelemetryService({ appender: testAppender }, undefined!); return service.publicLog('testEvent').then(_ => { assert.equal(testAppender.getEventsCount(), 1); assert.equal(testAppender.events[0].eventName, 'testEvent'); assert.notEqual(testAppender.events[0].data, null); service.dispose(); }); })); test('Event with data', sinon.test(function () { let testAppender = new TestTelemetryAppender(); let service = new TelemetryService({ appender: testAppender }, undefined!); return service.publicLog('testEvent', { 'stringProp': 'property', 'numberProp': 1, 'booleanProp': true, 'complexProp': { 'value': 0 } }).then(() => { assert.equal(testAppender.getEventsCount(), 1); assert.equal(testAppender.events[0].eventName, 'testEvent'); assert.notEqual(testAppender.events[0].data, null); assert.equal(testAppender.events[0].data['stringProp'], 'property'); assert.equal(testAppender.events[0].data['numberProp'], 1); assert.equal(testAppender.events[0].data['booleanProp'], true); assert.equal(testAppender.events[0].data['complexProp'].value, 0); service.dispose(); }); })); test('common properties added to *all* events, simple event', function () { let testAppender = new TestTelemetryAppender(); let service = new TelemetryService({ appender: testAppender, commonProperties: Promise.resolve({ foo: 'JA!', get bar() { return Math.random(); } }) }, undefined!); return service.publicLog('testEvent').then(_ => { let [first] = testAppender.events; assert.equal(Object.keys(first.data).length, 2); assert.equal(typeof first.data['foo'], 'string'); assert.equal(typeof first.data['bar'], 'number'); service.dispose(); }); }); test('common properties added to *all* events, event with data', function () { let testAppender = new TestTelemetryAppender(); let service = new TelemetryService({ appender: testAppender, commonProperties: Promise.resolve({ foo: 'JA!', get bar() { return Math.random(); } }) }, undefined!); return service.publicLog('testEvent', { hightower: 'xl', price: 8000 }).then(_ => { let [first] = testAppender.events; assert.equal(Object.keys(first.data).length, 4); assert.equal(typeof first.data['foo'], 'string'); assert.equal(typeof first.data['bar'], 'number'); assert.equal(typeof first.data['hightower'], 'string'); assert.equal(typeof first.data['price'], 'number'); service.dispose(); }); }); test('TelemetryInfo comes from properties', function () { let service = new TelemetryService({ appender: NullAppender, commonProperties: Promise.resolve({ sessionID: 'one', ['common.instanceId']: 'two', ['common.machineId']: 'three', }) }, undefined!); return service.getTelemetryInfo().then(info => { assert.equal(info.sessionId, 'one'); assert.equal(info.instanceId, 'two'); assert.equal(info.machineId, 'three'); service.dispose(); }); }); test('enableTelemetry on by default', sinon.test(function () { let testAppender = new TestTelemetryAppender(); let service = new TelemetryService({ appender: testAppender }, undefined!); return service.publicLog('testEvent').then(() => { assert.equal(testAppender.getEventsCount(), 1); assert.equal(testAppender.events[0].eventName, 'testEvent'); service.dispose(); }); })); class JoinableTelemetryService extends TelemetryService { private readonly promises: Promise<void>[] = []; constructor(config: ITelemetryServiceConfig, configurationService: IConfigurationService) { super({ ...config, sendErrorTelemetry: true }, configurationService); } join(): Promise<any> { return Promise.all(this.promises); } publicLog(eventName: string, data?: ITelemetryData, anonymizeFilePaths?: boolean): Promise<void> { let p = super.publicLog(eventName, data, anonymizeFilePaths); this.promises.push(p); return p; } } test('Error events', sinon.test(async function (this: any) { let origErrorHandler = Errors.errorHandler.getUnexpectedErrorHandler(); Errors.setUnexpectedErrorHandler(() => { }); try { let testAppender = new TestTelemetryAppender(); let service = new JoinableTelemetryService({ appender: testAppender }, undefined!); const errorTelemetry = new ErrorTelemetry(service); let e: any = new Error('This is a test.'); // for Phantom if (!e.stack) { e.stack = 'blah'; } Errors.onUnexpectedError(e); this.clock.tick(ErrorTelemetry.ERROR_FLUSH_TIMEOUT); await service.join(); assert.equal(testAppender.getEventsCount(), 1); assert.equal(testAppender.events[0].eventName, 'UnhandledError'); assert.equal(testAppender.events[0].data.msg, 'This is a test.'); errorTelemetry.dispose(); service.dispose(); } finally { Errors.setUnexpectedErrorHandler(origErrorHandler); } })); // test('Unhandled Promise Error events', sinon.test(function() { // // let origErrorHandler = Errors.errorHandler.getUnexpectedErrorHandler(); // Errors.setUnexpectedErrorHandler(() => {}); // // try { // let service = new MainTelemetryService(); // let testAppender = new TestTelemetryAppender(); // service.addTelemetryAppender(testAppender); // // winjs.Promise.wrapError(new Error('This should not get logged')); // winjs.TPromise.as(true).then(() => { // throw new Error('This should get logged'); // }); // // prevent console output from failing the test // this.stub(console, 'log'); // // allow for the promise to finish // this.clock.tick(MainErrorTelemetry.ERROR_FLUSH_TIMEOUT); // // assert.equal(testAppender.getEventsCount(), 1); // assert.equal(testAppender.events[0].eventName, 'UnhandledError'); // assert.equal(testAppender.events[0].data.msg, 'This should get logged'); // // service.dispose(); // } finally { // Errors.setUnexpectedErrorHandler(origErrorHandler); // } // })); test('Handle global errors', sinon.test(async function (this: any) { let errorStub = sinon.stub(); window.onerror = errorStub; let testAppender = new TestTelemetryAppender(); let service = new JoinableTelemetryService({ appender: testAppender }, undefined!); const errorTelemetry = new ErrorTelemetry(service); let testError = new Error('test'); (<any>window.onerror)('Error Message', 'file.js', 2, 42, testError); this.clock.tick(ErrorTelemetry.ERROR_FLUSH_TIMEOUT); await service.join(); assert.equal(errorStub.alwaysCalledWithExactly('Error Message', 'file.js', 2, 42, testError), true); assert.equal(errorStub.callCount, 1); assert.equal(testAppender.getEventsCount(), 1); assert.equal(testAppender.events[0].eventName, 'UnhandledError'); assert.equal(testAppender.events[0].data.msg, 'Error Message'); assert.equal(testAppender.events[0].data.file, 'file.js'); assert.equal(testAppender.events[0].data.line, 2); assert.equal(testAppender.events[0].data.column, 42); assert.equal(testAppender.events[0].data.uncaught_error_msg, 'test'); errorTelemetry.dispose(); service.dispose(); })); test('Error Telemetry removes PII from filename with spaces', sinon.test(async function (this: any) { let errorStub = sinon.stub(); window.onerror = errorStub; let settings = new ErrorTestingSettings(); let testAppender = new TestTelemetryAppender(); let service = new JoinableTelemetryService({ appender: testAppender }, undefined!); const errorTelemetry = new ErrorTelemetry(service); let personInfoWithSpaces = settings.personalInfo.slice(0, 2) + ' ' + settings.personalInfo.slice(2); let dangerousFilenameError: any = new Error('dangerousFilename'); dangerousFilenameError.stack = settings.stack; (<any>window.onerror)('dangerousFilename', settings.dangerousPathWithImportantInfo.replace(settings.personalInfo, personInfoWithSpaces) + '/test.js', 2, 42, dangerousFilenameError); this.clock.tick(ErrorTelemetry.ERROR_FLUSH_TIMEOUT); await service.join(); assert.equal(errorStub.callCount, 1); assert.equal(testAppender.events[0].data.file.indexOf(settings.dangerousPathWithImportantInfo.replace(settings.personalInfo, personInfoWithSpaces)), -1); assert.equal(testAppender.events[0].data.file, settings.importantInfo + '/test.js'); errorTelemetry.dispose(); service.dispose(); })); test('Uncaught Error Telemetry removes PII from filename', sinon.test(function (this: any) { let clock = this.clock; let errorStub = sinon.stub(); window.onerror = errorStub; let settings = new ErrorTestingSettings(); let testAppender = new TestTelemetryAppender(); let service = new JoinableTelemetryService({ appender: testAppender }, undefined!); const errorTelemetry = new ErrorTelemetry(service); let dangerousFilenameError: any = new Error('dangerousFilename'); dangerousFilenameError.stack = settings.stack; (<any>window.onerror)('dangerousFilename', settings.dangerousPathWithImportantInfo + '/test.js', 2, 42, dangerousFilenameError); clock.tick(ErrorTelemetry.ERROR_FLUSH_TIMEOUT); return service.join().then(() => { assert.equal(errorStub.callCount, 1); assert.equal(testAppender.events[0].data.file.indexOf(settings.dangerousPathWithImportantInfo), -1); dangerousFilenameError = new Error('dangerousFilename'); dangerousFilenameError.stack = settings.stack; (<any>window.onerror)('dangerousFilename', settings.dangerousPathWithImportantInfo + '/test.js', 2, 42, dangerousFilenameError); clock.tick(ErrorTelemetry.ERROR_FLUSH_TIMEOUT); return service.join(); }).then(() => { assert.equal(errorStub.callCount, 2); assert.equal(testAppender.events[0].data.file.indexOf(settings.dangerousPathWithImportantInfo), -1); assert.equal(testAppender.events[0].data.file, settings.importantInfo + '/test.js'); errorTelemetry.dispose(); service.dispose(); }); })); test('Unexpected Error Telemetry removes PII', sinon.test(async function (this: any) { let origErrorHandler = Errors.errorHandler.getUnexpectedErrorHandler(); Errors.setUnexpectedErrorHandler(() => { }); try { let settings = new ErrorTestingSettings(); let testAppender = new TestTelemetryAppender(); let service = new JoinableTelemetryService({ appender: testAppender }, undefined!); const errorTelemetry = new ErrorTelemetry(service); let dangerousPathWithoutImportantInfoError: any = new Error(settings.dangerousPathWithoutImportantInfo); dangerousPathWithoutImportantInfoError.stack = settings.stack; Errors.onUnexpectedError(dangerousPathWithoutImportantInfoError); this.clock.tick(ErrorTelemetry.ERROR_FLUSH_TIMEOUT); await service.join(); assert.equal(testAppender.events[0].data.msg.indexOf(settings.personalInfo), -1); assert.equal(testAppender.events[0].data.msg.indexOf(settings.filePrefix), -1); assert.equal(testAppender.events[0].data.callstack.indexOf(settings.personalInfo), -1); assert.equal(testAppender.events[0].data.callstack.indexOf(settings.filePrefix), -1); assert.notEqual(testAppender.events[0].data.callstack.indexOf(settings.stack[4].replace(settings.randomUserFile, settings.anonymizedRandomUserFile)), -1); assert.equal(testAppender.events[0].data.callstack.split('\n').length, settings.stack.length); errorTelemetry.dispose(); service.dispose(); } finally { Errors.setUnexpectedErrorHandler(origErrorHandler); } })); test('Uncaught Error Telemetry removes PII', sinon.test(async function (this: any) { let errorStub = sinon.stub(); window.onerror = errorStub; let settings = new ErrorTestingSettings(); let testAppender = new TestTelemetryAppender(); let service = new JoinableTelemetryService({ appender: testAppender }, undefined!); const errorTelemetry = new ErrorTelemetry(service); let dangerousPathWithoutImportantInfoError: any = new Error('dangerousPathWithoutImportantInfo'); dangerousPathWithoutImportantInfoError.stack = settings.stack; (<any>window.onerror)(settings.dangerousPathWithoutImportantInfo, 'test.js', 2, 42, dangerousPathWithoutImportantInfoError); this.clock.tick(ErrorTelemetry.ERROR_FLUSH_TIMEOUT); await service.join(); assert.equal(errorStub.callCount, 1); // Test that no file information remains, esp. personal info assert.equal(testAppender.events[0].data.msg.indexOf(settings.personalInfo), -1); assert.equal(testAppender.events[0].data.msg.indexOf(settings.filePrefix), -1); assert.equal(testAppender.events[0].data.callstack.indexOf(settings.personalInfo), -1); assert.equal(testAppender.events[0].data.callstack.indexOf(settings.filePrefix), -1); assert.notEqual(testAppender.events[0].data.callstack.indexOf(settings.stack[4].replace(settings.randomUserFile, settings.anonymizedRandomUserFile)), -1); assert.equal(testAppender.events[0].data.callstack.split('\n').length, settings.stack.length); errorTelemetry.dispose(); service.dispose(); })); test('Unexpected Error Telemetry removes PII but preserves Code file path', sinon.test(async function (this: any) { let origErrorHandler = Errors.errorHandler.getUnexpectedErrorHandler(); Errors.setUnexpectedErrorHandler(() => { }); try { let settings = new ErrorTestingSettings(); let testAppender = new TestTelemetryAppender(); let service = new JoinableTelemetryService({ appender: testAppender }, undefined!); const errorTelemetry = new ErrorTelemetry(service); let dangerousPathWithImportantInfoError: any = new Error(settings.dangerousPathWithImportantInfo); dangerousPathWithImportantInfoError.stack = settings.stack; // Test that important information remains but personal info does not Errors.onUnexpectedError(dangerousPathWithImportantInfoError); this.clock.tick(ErrorTelemetry.ERROR_FLUSH_TIMEOUT); await service.join(); assert.notEqual(testAppender.events[0].data.msg.indexOf(settings.importantInfo), -1); assert.equal(testAppender.events[0].data.msg.indexOf(settings.personalInfo), -1); assert.equal(testAppender.events[0].data.msg.indexOf(settings.filePrefix), -1); assert.notEqual(testAppender.events[0].data.callstack.indexOf(settings.importantInfo), -1); assert.equal(testAppender.events[0].data.callstack.indexOf(settings.personalInfo), -1); assert.equal(testAppender.events[0].data.callstack.indexOf(settings.filePrefix), -1); assert.notEqual(testAppender.events[0].data.callstack.indexOf(settings.stack[4].replace(settings.randomUserFile, settings.anonymizedRandomUserFile)), -1); assert.equal(testAppender.events[0].data.callstack.split('\n').length, settings.stack.length); errorTelemetry.dispose(); service.dispose(); } finally { Errors.setUnexpectedErrorHandler(origErrorHandler); } })); test('Uncaught Error Telemetry removes PII but preserves Code file path', sinon.test(async function (this: any) { let errorStub = sinon.stub(); window.onerror = errorStub; let settings = new ErrorTestingSettings(); let testAppender = new TestTelemetryAppender(); let service = new JoinableTelemetryService({ appender: testAppender }, undefined!); const errorTelemetry = new ErrorTelemetry(service); let dangerousPathWithImportantInfoError: any = new Error('dangerousPathWithImportantInfo'); dangerousPathWithImportantInfoError.stack = settings.stack; (<any>window.onerror)(settings.dangerousPathWithImportantInfo, 'test.js', 2, 42, dangerousPathWithImportantInfoError); this.clock.tick(ErrorTelemetry.ERROR_FLUSH_TIMEOUT); await service.join(); assert.equal(errorStub.callCount, 1); // Test that important information remains but personal info does not assert.notEqual(testAppender.events[0].data.msg.indexOf(settings.importantInfo), -1); assert.equal(testAppender.events[0].data.msg.indexOf(settings.personalInfo), -1); assert.equal(testAppender.events[0].data.msg.indexOf(settings.filePrefix), -1); assert.notEqual(testAppender.events[0].data.callstack.indexOf(settings.importantInfo), -1); assert.equal(testAppender.events[0].data.callstack.indexOf(settings.personalInfo), -1); assert.equal(testAppender.events[0].data.callstack.indexOf(settings.filePrefix), -1); assert.notEqual(testAppender.events[0].data.callstack.indexOf(settings.stack[4].replace(settings.randomUserFile, settings.anonymizedRandomUserFile)), -1); assert.equal(testAppender.events[0].data.callstack.split('\n').length, settings.stack.length); errorTelemetry.dispose(); service.dispose(); })); test('Unexpected Error Telemetry removes PII but preserves Code file path with node modules', sinon.test(async function (this: any) { let origErrorHandler = Errors.errorHandler.getUnexpectedErrorHandler(); Errors.setUnexpectedErrorHandler(() => { }); try { let settings = new ErrorTestingSettings(); let testAppender = new TestTelemetryAppender(); let service = new JoinableTelemetryService({ appender: testAppender }, undefined!); const errorTelemetry = new ErrorTelemetry(service); let dangerousPathWithImportantInfoError: any = new Error(settings.dangerousPathWithImportantInfo); dangerousPathWithImportantInfoError.stack = settings.stack; Errors.onUnexpectedError(dangerousPathWithImportantInfoError); this.clock.tick(ErrorTelemetry.ERROR_FLUSH_TIMEOUT); await service.join(); assert.notEqual(testAppender.events[0].data.callstack.indexOf('(' + settings.nodeModuleAsarPathToRetain), -1); assert.notEqual(testAppender.events[0].data.callstack.indexOf('(' + settings.nodeModulePathToRetain), -1); assert.notEqual(testAppender.events[0].data.callstack.indexOf('(/' + settings.nodeModuleAsarPathToRetain), -1); assert.notEqual(testAppender.events[0].data.callstack.indexOf('(/' + settings.nodeModulePathToRetain), -1); errorTelemetry.dispose(); service.dispose(); } finally { Errors.setUnexpectedErrorHandler(origErrorHandler); } })); test('Uncaught Error Telemetry removes PII but preserves Code file path', sinon.test(async function (this: any) { let errorStub = sinon.stub(); window.onerror = errorStub; let settings = new ErrorTestingSettings(); let testAppender = new TestTelemetryAppender(); let service = new JoinableTelemetryService({ appender: testAppender }, undefined!); const errorTelemetry = new ErrorTelemetry(service); let dangerousPathWithImportantInfoError: any = new Error('dangerousPathWithImportantInfo'); dangerousPathWithImportantInfoError.stack = settings.stack; (<any>window.onerror)(settings.dangerousPathWithImportantInfo, 'test.js', 2, 42, dangerousPathWithImportantInfoError); this.clock.tick(ErrorTelemetry.ERROR_FLUSH_TIMEOUT); await service.join(); assert.equal(errorStub.callCount, 1); assert.notEqual(testAppender.events[0].data.callstack.indexOf('(' + settings.nodeModuleAsarPathToRetain), -1); assert.notEqual(testAppender.events[0].data.callstack.indexOf('(' + settings.nodeModulePathToRetain), -1); assert.notEqual(testAppender.events[0].data.callstack.indexOf('(/' + settings.nodeModuleAsarPathToRetain), -1); assert.notEqual(testAppender.events[0].data.callstack.indexOf('(/' + settings.nodeModulePathToRetain), -1); errorTelemetry.dispose(); service.dispose(); })); test('Unexpected Error Telemetry removes PII but preserves Code file path when PIIPath is configured', sinon.test(async function (this: any) { let origErrorHandler = Errors.errorHandler.getUnexpectedErrorHandler(); Errors.setUnexpectedErrorHandler(() => { }); try { let settings = new ErrorTestingSettings(); let testAppender = new TestTelemetryAppender(); let service = new JoinableTelemetryService({ appender: testAppender, piiPaths: [settings.personalInfo + '/resources/app/'] }, undefined!); const errorTelemetry = new ErrorTelemetry(service); let dangerousPathWithImportantInfoError: any = new Error(settings.dangerousPathWithImportantInfo); dangerousPathWithImportantInfoError.stack = settings.stack; // Test that important information remains but personal info does not Errors.onUnexpectedError(dangerousPathWithImportantInfoError); this.clock.tick(ErrorTelemetry.ERROR_FLUSH_TIMEOUT); await service.join(); assert.notEqual(testAppender.events[0].data.msg.indexOf(settings.importantInfo), -1); assert.equal(testAppender.events[0].data.msg.indexOf(settings.personalInfo), -1); assert.equal(testAppender.events[0].data.msg.indexOf(settings.filePrefix), -1); assert.notEqual(testAppender.events[0].data.callstack.indexOf(settings.importantInfo), -1); assert.equal(testAppender.events[0].data.callstack.indexOf(settings.personalInfo), -1); assert.equal(testAppender.events[0].data.callstack.indexOf(settings.filePrefix), -1); assert.notEqual(testAppender.events[0].data.callstack.indexOf(settings.stack[4].replace(settings.randomUserFile, settings.anonymizedRandomUserFile)), -1); assert.equal(testAppender.events[0].data.callstack.split('\n').length, settings.stack.length); errorTelemetry.dispose(); service.dispose(); } finally { Errors.setUnexpectedErrorHandler(origErrorHandler); } })); test('Uncaught Error Telemetry removes PII but preserves Code file path when PIIPath is configured', sinon.test(async function (this: any) { let errorStub = sinon.stub(); window.onerror = errorStub; let settings = new ErrorTestingSettings(); let testAppender = new TestTelemetryAppender(); let service = new JoinableTelemetryService({ appender: testAppender, piiPaths: [settings.personalInfo + '/resources/app/'] }, undefined!); const errorTelemetry = new ErrorTelemetry(service); let dangerousPathWithImportantInfoError: any = new Error('dangerousPathWithImportantInfo'); dangerousPathWithImportantInfoError.stack = settings.stack; (<any>window.onerror)(settings.dangerousPathWithImportantInfo, 'test.js', 2, 42, dangerousPathWithImportantInfoError); this.clock.tick(ErrorTelemetry.ERROR_FLUSH_TIMEOUT); await service.join(); assert.equal(errorStub.callCount, 1); // Test that important information remains but personal info does not assert.notEqual(testAppender.events[0].data.msg.indexOf(settings.importantInfo), -1); assert.equal(testAppender.events[0].data.msg.indexOf(settings.personalInfo), -1); assert.equal(testAppender.events[0].data.msg.indexOf(settings.filePrefix), -1); assert.notEqual(testAppender.events[0].data.callstack.indexOf(settings.importantInfo), -1); assert.equal(testAppender.events[0].data.callstack.indexOf(settings.personalInfo), -1); assert.equal(testAppender.events[0].data.callstack.indexOf(settings.filePrefix), -1); assert.notEqual(testAppender.events[0].data.callstack.indexOf(settings.stack[4].replace(settings.randomUserFile, settings.anonymizedRandomUserFile)), -1); assert.equal(testAppender.events[0].data.callstack.split('\n').length, settings.stack.length); errorTelemetry.dispose(); service.dispose(); })); test('Unexpected Error Telemetry removes PII but preserves Missing Model error message', sinon.test(async function (this: any) { let origErrorHandler = Errors.errorHandler.getUnexpectedErrorHandler(); Errors.setUnexpectedErrorHandler(() => { }); try { let settings = new ErrorTestingSettings(); let testAppender = new TestTelemetryAppender(); let service = new JoinableTelemetryService({ appender: testAppender }, undefined!); const errorTelemetry = new ErrorTelemetry(service); let missingModelError: any = new Error(settings.missingModelMessage); missingModelError.stack = settings.stack; // Test that no file information remains, but this particular // error message does (Received model events for missing model) Errors.onUnexpectedError(missingModelError); this.clock.tick(ErrorTelemetry.ERROR_FLUSH_TIMEOUT); await service.join(); assert.notEqual(testAppender.events[0].data.msg.indexOf(settings.missingModelPrefix), -1); assert.equal(testAppender.events[0].data.msg.indexOf(settings.personalInfo), -1); assert.equal(testAppender.events[0].data.msg.indexOf(settings.filePrefix), -1); assert.notEqual(testAppender.events[0].data.callstack.indexOf(settings.missingModelPrefix), -1); assert.equal(testAppender.events[0].data.callstack.indexOf(settings.personalInfo), -1); assert.equal(testAppender.events[0].data.callstack.indexOf(settings.filePrefix), -1); assert.notEqual(testAppender.events[0].data.callstack.indexOf(settings.stack[4].replace(settings.randomUserFile, settings.anonymizedRandomUserFile)), -1); assert.equal(testAppender.events[0].data.callstack.split('\n').length, settings.stack.length); errorTelemetry.dispose(); service.dispose(); } finally { Errors.setUnexpectedErrorHandler(origErrorHandler); } })); test('Uncaught Error Telemetry removes PII but preserves Missing Model error message', sinon.test(async function (this: any) { let errorStub = sinon.stub(); window.onerror = errorStub; let settings = new ErrorTestingSettings(); let testAppender = new TestTelemetryAppender(); let service = new JoinableTelemetryService({ appender: testAppender }, undefined!); const errorTelemetry = new ErrorTelemetry(service); let missingModelError: any = new Error('missingModelMessage'); missingModelError.stack = settings.stack; (<any>window.onerror)(settings.missingModelMessage, 'test.js', 2, 42, missingModelError); this.clock.tick(ErrorTelemetry.ERROR_FLUSH_TIMEOUT); await service.join(); assert.equal(errorStub.callCount, 1); // Test that no file information remains, but this particular // error message does (Received model events for missing model) assert.notEqual(testAppender.events[0].data.msg.indexOf(settings.missingModelPrefix), -1); assert.equal(testAppender.events[0].data.msg.indexOf(settings.personalInfo), -1); assert.equal(testAppender.events[0].data.msg.indexOf(settings.filePrefix), -1); assert.notEqual(testAppender.events[0].data.callstack.indexOf(settings.missingModelPrefix), -1); assert.equal(testAppender.events[0].data.callstack.indexOf(settings.personalInfo), -1); assert.equal(testAppender.events[0].data.callstack.indexOf(settings.filePrefix), -1); assert.notEqual(testAppender.events[0].data.callstack.indexOf(settings.stack[4].replace(settings.randomUserFile, settings.anonymizedRandomUserFile)), -1); assert.equal(testAppender.events[0].data.callstack.split('\n').length, settings.stack.length); errorTelemetry.dispose(); service.dispose(); })); test('Unexpected Error Telemetry removes PII but preserves No Such File error message', sinon.test(async function (this: any) { let origErrorHandler = Errors.errorHandler.getUnexpectedErrorHandler(); Errors.setUnexpectedErrorHandler(() => { }); try { let settings = new ErrorTestingSettings(); let testAppender = new TestTelemetryAppender(); let service = new JoinableTelemetryService({ appender: testAppender }, undefined!); const errorTelemetry = new ErrorTelemetry(service); let noSuchFileError: any = new Error(settings.noSuchFileMessage); noSuchFileError.stack = settings.stack; // Test that no file information remains, but this particular // error message does (ENOENT: no such file or directory) Errors.onUnexpectedError(noSuchFileError); this.clock.tick(ErrorTelemetry.ERROR_FLUSH_TIMEOUT); await service.join(); assert.notEqual(testAppender.events[0].data.msg.indexOf(settings.noSuchFilePrefix), -1); assert.equal(testAppender.events[0].data.msg.indexOf(settings.personalInfo), -1); assert.equal(testAppender.events[0].data.msg.indexOf(settings.filePrefix), -1); assert.notEqual(testAppender.events[0].data.callstack.indexOf(settings.noSuchFilePrefix), -1); assert.equal(testAppender.events[0].data.callstack.indexOf(settings.personalInfo), -1); assert.equal(testAppender.events[0].data.callstack.indexOf(settings.filePrefix), -1); assert.notEqual(testAppender.events[0].data.callstack.indexOf(settings.stack[4].replace(settings.randomUserFile, settings.anonymizedRandomUserFile)), -1); assert.equal(testAppender.events[0].data.callstack.split('\n').length, settings.stack.length); errorTelemetry.dispose(); service.dispose(); } finally { Errors.setUnexpectedErrorHandler(origErrorHandler); } })); test('Uncaught Error Telemetry removes PII but preserves No Such File error message', sinon.test(async function (this: any) { let origErrorHandler = Errors.errorHandler.getUnexpectedErrorHandler(); Errors.setUnexpectedErrorHandler(() => { }); try { let errorStub = sinon.stub(); window.onerror = errorStub; let settings = new ErrorTestingSettings(); let testAppender = new TestTelemetryAppender(); let service = new JoinableTelemetryService({ appender: testAppender }, undefined!); const errorTelemetry = new ErrorTelemetry(service); let noSuchFileError: any = new Error('noSuchFileMessage'); noSuchFileError.stack = settings.stack; (<any>window.onerror)(settings.noSuchFileMessage, 'test.js', 2, 42, noSuchFileError); this.clock.tick(ErrorTelemetry.ERROR_FLUSH_TIMEOUT); await service.join(); assert.equal(errorStub.callCount, 1); // Test that no file information remains, but this particular // error message does (ENOENT: no such file or directory) Errors.onUnexpectedError(noSuchFileError); assert.notEqual(testAppender.events[0].data.msg.indexOf(settings.noSuchFilePrefix), -1); assert.equal(testAppender.events[0].data.msg.indexOf(settings.personalInfo), -1); assert.equal(testAppender.events[0].data.msg.indexOf(settings.filePrefix), -1); assert.notEqual(testAppender.events[0].data.callstack.indexOf(settings.noSuchFilePrefix), -1); assert.equal(testAppender.events[0].data.callstack.indexOf(settings.personalInfo), -1); assert.equal(testAppender.events[0].data.callstack.indexOf(settings.filePrefix), -1); assert.notEqual(testAppender.events[0].data.callstack.indexOf(settings.stack[4].replace(settings.randomUserFile, settings.anonymizedRandomUserFile)), -1); assert.equal(testAppender.events[0].data.callstack.split('\n').length, settings.stack.length); errorTelemetry.dispose(); service.dispose(); } finally { Errors.setUnexpectedErrorHandler(origErrorHandler); } })); test('Telemetry Service sends events when enableTelemetry is on', sinon.test(function () { let testAppender = new TestTelemetryAppender(); let service = new TelemetryService({ appender: testAppender }, undefined!); return service.publicLog('testEvent').then(() => { assert.equal(testAppender.getEventsCount(), 1); service.dispose(); }); })); test('Telemetry Service checks with config service', function () { let enableTelemetry = false; let emitter = new Emitter<any>(); let testAppender = new TestTelemetryAppender(); let service = new TelemetryService({ appender: testAppender }, new class extends TestConfigurationService { onDidChangeConfiguration = emitter.event; getValue() { return { enableTelemetry: enableTelemetry } as any; } }()); assert.equal(service.isOptedIn, false); enableTelemetry = true; emitter.fire({}); assert.equal(service.isOptedIn, true); enableTelemetry = false; emitter.fire({}); assert.equal(service.isOptedIn, false); service.dispose(); }); });
src/vs/platform/telemetry/test/browser/telemetryService.test.ts
0
https://github.com/microsoft/vscode/commit/574ee2032cc24ed250ef15962ce100838d4e5e4a
[ 0.00017636096163187176, 0.00017236541316378862, 0.00016188040899578482, 0.00017257931176573038, 0.000002522865543141961 ]
{ "id": 3, "code_window": [ "\t\tthis._terminalTabs.push(terminalTab);\n", "\n", "\t\tconst instance = terminalTab.terminalInstances[0];\n", "\t\tif (this._willFocusNewTerminal) {\n", "\t\t\tinstance.focusWhenReady();\n", "\t\t\tthis._willFocusNewTerminal = false;\n", "\t\t}\n", "\n", "\t\tterminalTab.addDisposable(terminalTab.onDisposed(this._onTabDisposed.fire, this._onTabDisposed));\n", "\t\tterminalTab.addDisposable(terminalTab.onInstancesChanged(this._onInstancesChanged.fire, this._onInstancesChanged));\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/contrib/terminal/browser/terminalService.ts", "type": "replace", "edit_start_line_idx": 686 }
/*--------------------------------------------------------------------------------------------- * 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 { ICodeEditor } from 'vs/editor/browser/editorBrowser'; import { EditorAction, ServicesAccessor, registerEditorAction } from 'vs/editor/browser/editorExtensions'; import { EditorZoom } from 'vs/editor/common/config/editorZoom'; class EditorFontZoomIn extends EditorAction { constructor() { super({ id: 'editor.action.fontZoomIn', label: nls.localize('EditorFontZoomIn.label', "Editor Font Zoom In"), alias: 'Editor Font Zoom In', precondition: undefined }); } public run(accessor: ServicesAccessor, editor: ICodeEditor): void { EditorZoom.setZoomLevel(EditorZoom.getZoomLevel() + 1); } } class EditorFontZoomOut extends EditorAction { constructor() { super({ id: 'editor.action.fontZoomOut', label: nls.localize('EditorFontZoomOut.label', "Editor Font Zoom Out"), alias: 'Editor Font Zoom Out', precondition: undefined }); } public run(accessor: ServicesAccessor, editor: ICodeEditor): void { EditorZoom.setZoomLevel(EditorZoom.getZoomLevel() - 1); } } class EditorFontZoomReset extends EditorAction { constructor() { super({ id: 'editor.action.fontZoomReset', label: nls.localize('EditorFontZoomReset.label', "Editor Font Zoom Reset"), alias: 'Editor Font Zoom Reset', precondition: undefined }); } public run(accessor: ServicesAccessor, editor: ICodeEditor): void { EditorZoom.setZoomLevel(0); } } registerEditorAction(EditorFontZoomIn); registerEditorAction(EditorFontZoomOut); registerEditorAction(EditorFontZoomReset);
src/vs/editor/contrib/fontZoom/fontZoom.ts
0
https://github.com/microsoft/vscode/commit/574ee2032cc24ed250ef15962ce100838d4e5e4a
[ 0.00017498276429250836, 0.00017220116569660604, 0.00016627991863060743, 0.00017313341959379613, 0.000002648488589329645 ]
{ "id": 3, "code_window": [ "\t\tthis._terminalTabs.push(terminalTab);\n", "\n", "\t\tconst instance = terminalTab.terminalInstances[0];\n", "\t\tif (this._willFocusNewTerminal) {\n", "\t\t\tinstance.focusWhenReady();\n", "\t\t\tthis._willFocusNewTerminal = false;\n", "\t\t}\n", "\n", "\t\tterminalTab.addDisposable(terminalTab.onDisposed(this._onTabDisposed.fire, this._onTabDisposed));\n", "\t\tterminalTab.addDisposable(terminalTab.onInstancesChanged(this._onInstancesChanged.fire, this._onInstancesChanged));\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/contrib/terminal/browser/terminalService.ts", "type": "replace", "edit_start_line_idx": 686 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Action, IAction, Separator, SubmenuAction } from 'vs/base/common/actions'; import { SyncDescriptor0, createSyncDescriptor } from 'vs/platform/instantiation/common/descriptors'; import { IConstructorSignature2, createDecorator, BrandedService, ServicesAccessor } from 'vs/platform/instantiation/common/instantiation'; import { IKeybindings, KeybindingsRegistry, IKeybindingRule } from 'vs/platform/keybinding/common/keybindingsRegistry'; import { ContextKeyExpr, IContextKeyService, ContextKeyExpression } from 'vs/platform/contextkey/common/contextkey'; import { ICommandService, CommandsRegistry, ICommandHandlerDescription } from 'vs/platform/commands/common/commands'; import { IDisposable, DisposableStore, toDisposable } from 'vs/base/common/lifecycle'; import { Event, Emitter } from 'vs/base/common/event'; import { URI } from 'vs/base/common/uri'; import { ThemeIcon } from 'vs/platform/theme/common/themeService'; import { UriDto } from 'vs/base/common/types'; import { Iterable } from 'vs/base/common/iterator'; import { LinkedList } from 'vs/base/common/linkedList'; export interface ILocalizedString { value: string; original: string; } export type Icon = { dark?: URI; light?: URI; } | ThemeIcon; export interface ICommandAction { id: string; title: string | ILocalizedString; category?: string | ILocalizedString; tooltip?: string | ILocalizedString; icon?: Icon; precondition?: ContextKeyExpression; toggled?: ContextKeyExpression | { condition: ContextKeyExpression, icon?: Icon, tooltip?: string | ILocalizedString }; } export type ISerializableCommandAction = UriDto<ICommandAction>; export interface IMenuItem { command: ICommandAction; alt?: ICommandAction; when?: ContextKeyExpression; group?: 'navigation' | string; order?: number; } export interface ISubmenuItem { title: string | ILocalizedString; submenu: MenuId; icon?: Icon; when?: ContextKeyExpression; group?: 'navigation' | string; order?: number; } export function isIMenuItem(item: IMenuItem | ISubmenuItem): item is IMenuItem { return (item as IMenuItem).command !== undefined; } export function isISubmenuItem(item: IMenuItem | ISubmenuItem): item is ISubmenuItem { return (item as ISubmenuItem).submenu !== undefined; } export class MenuId { private static _idPool = 0; static readonly CommandPalette = new MenuId('CommandPalette'); static readonly DebugBreakpointsContext = new MenuId('DebugBreakpointsContext'); static readonly DebugCallStackContext = new MenuId('DebugCallStackContext'); static readonly DebugConsoleContext = new MenuId('DebugConsoleContext'); static readonly DebugVariablesContext = new MenuId('DebugVariablesContext'); static readonly DebugWatchContext = new MenuId('DebugWatchContext'); static readonly DebugToolBar = new MenuId('DebugToolBar'); static readonly EditorContext = new MenuId('EditorContext'); static readonly EditorContextPeek = new MenuId('EditorContextPeek'); static readonly EditorTitle = new MenuId('EditorTitle'); static readonly EditorTitleContext = new MenuId('EditorTitleContext'); static readonly EmptyEditorGroupContext = new MenuId('EmptyEditorGroupContext'); static readonly ExplorerContext = new MenuId('ExplorerContext'); static readonly ExtensionContext = new MenuId('ExtensionContext'); static readonly GlobalActivity = new MenuId('GlobalActivity'); static readonly MenubarAppearanceMenu = new MenuId('MenubarAppearanceMenu'); static readonly MenubarDebugMenu = new MenuId('MenubarDebugMenu'); static readonly MenubarEditMenu = new MenuId('MenubarEditMenu'); static readonly MenubarFileMenu = new MenuId('MenubarFileMenu'); static readonly MenubarGoMenu = new MenuId('MenubarGoMenu'); static readonly MenubarHelpMenu = new MenuId('MenubarHelpMenu'); static readonly MenubarLayoutMenu = new MenuId('MenubarLayoutMenu'); static readonly MenubarNewBreakpointMenu = new MenuId('MenubarNewBreakpointMenu'); static readonly MenubarPreferencesMenu = new MenuId('MenubarPreferencesMenu'); static readonly MenubarRecentMenu = new MenuId('MenubarRecentMenu'); static readonly MenubarSelectionMenu = new MenuId('MenubarSelectionMenu'); static readonly MenubarSwitchEditorMenu = new MenuId('MenubarSwitchEditorMenu'); static readonly MenubarSwitchGroupMenu = new MenuId('MenubarSwitchGroupMenu'); static readonly MenubarTerminalMenu = new MenuId('MenubarTerminalMenu'); static readonly MenubarViewMenu = new MenuId('MenubarViewMenu'); static readonly MenubarWebNavigationMenu = new MenuId('MenubarWebNavigationMenu'); static readonly OpenEditorsContext = new MenuId('OpenEditorsContext'); static readonly ProblemsPanelContext = new MenuId('ProblemsPanelContext'); static readonly SCMChangeContext = new MenuId('SCMChangeContext'); static readonly SCMResourceContext = new MenuId('SCMResourceContext'); static readonly SCMResourceFolderContext = new MenuId('SCMResourceFolderContext'); static readonly SCMResourceGroupContext = new MenuId('SCMResourceGroupContext'); static readonly SCMSourceControl = new MenuId('SCMSourceControl'); static readonly SCMTitle = new MenuId('SCMTitle'); static readonly SearchContext = new MenuId('SearchContext'); static readonly StatusBarWindowIndicatorMenu = new MenuId('StatusBarWindowIndicatorMenu'); static readonly TouchBarContext = new MenuId('TouchBarContext'); static readonly TitleBarContext = new MenuId('TitleBarContext'); static readonly TunnelContext = new MenuId('TunnelContext'); static readonly TunnelInline = new MenuId('TunnelInline'); static readonly TunnelTitle = new MenuId('TunnelTitle'); static readonly ViewItemContext = new MenuId('ViewItemContext'); static readonly ViewContainerTitleContext = new MenuId('ViewContainerTitleContext'); static readonly ViewTitle = new MenuId('ViewTitle'); static readonly ViewTitleContext = new MenuId('ViewTitleContext'); static readonly CommentThreadTitle = new MenuId('CommentThreadTitle'); static readonly CommentThreadActions = new MenuId('CommentThreadActions'); static readonly CommentTitle = new MenuId('CommentTitle'); static readonly CommentActions = new MenuId('CommentActions'); static readonly NotebookCellTitle = new MenuId('NotebookCellTitle'); static readonly NotebookCellInsert = new MenuId('NotebookCellInsert'); static readonly NotebookCellBetween = new MenuId('NotebookCellBetween'); static readonly NotebookCellListTop = new MenuId('NotebookCellTop'); static readonly NotebookDiffCellInputTitle = new MenuId('NotebookDiffCellInputTitle'); static readonly NotebookDiffCellMetadataTitle = new MenuId('NotebookDiffCellMetadataTitle'); static readonly NotebookDiffCellOutputsTitle = new MenuId('NotebookDiffCellOutputsTitle'); static readonly BulkEditTitle = new MenuId('BulkEditTitle'); static readonly BulkEditContext = new MenuId('BulkEditContext'); static readonly TimelineItemContext = new MenuId('TimelineItemContext'); static readonly TimelineTitle = new MenuId('TimelineTitle'); static readonly TimelineTitleContext = new MenuId('TimelineTitleContext'); static readonly AccountsContext = new MenuId('AccountsContext'); readonly id: number; readonly _debugName: string; constructor(debugName: string) { this.id = MenuId._idPool++; this._debugName = debugName; } } export interface IMenuActionOptions { arg?: any; shouldForwardArgs?: boolean; } export interface IMenu extends IDisposable { readonly onDidChange: Event<IMenu | undefined>; getActions(options?: IMenuActionOptions): [string, Array<MenuItemAction | SubmenuItemAction>][]; } export const IMenuService = createDecorator<IMenuService>('menuService'); export interface IMenuService { readonly _serviceBrand: undefined; createMenu(id: MenuId, scopedKeybindingService: IContextKeyService): IMenu; } export type ICommandsMap = Map<string, ICommandAction>; export interface IMenuRegistryChangeEvent { has(id: MenuId): boolean; } export interface IMenuRegistry { readonly onDidChangeMenu: Event<IMenuRegistryChangeEvent>; addCommands(newCommands: Iterable<ICommandAction>): IDisposable; addCommand(userCommand: ICommandAction): IDisposable; getCommand(id: string): ICommandAction | undefined; getCommands(): ICommandsMap; appendMenuItems(items: Iterable<{ id: MenuId, item: IMenuItem | ISubmenuItem }>): IDisposable; appendMenuItem(menu: MenuId, item: IMenuItem | ISubmenuItem): IDisposable; getMenuItems(loc: MenuId): Array<IMenuItem | ISubmenuItem>; } export const MenuRegistry: IMenuRegistry = new class implements IMenuRegistry { private readonly _commands = new Map<string, ICommandAction>(); private readonly _menuItems = new Map<MenuId, LinkedList<IMenuItem | ISubmenuItem>>(); private readonly _onDidChangeMenu = new Emitter<IMenuRegistryChangeEvent>(); readonly onDidChangeMenu: Event<IMenuRegistryChangeEvent> = this._onDidChangeMenu.event; addCommand(command: ICommandAction): IDisposable { return this.addCommands(Iterable.single(command)); } private readonly _commandPaletteChangeEvent: IMenuRegistryChangeEvent = { has: id => id === MenuId.CommandPalette }; addCommands(commands: Iterable<ICommandAction>): IDisposable { for (const command of commands) { this._commands.set(command.id, command); } this._onDidChangeMenu.fire(this._commandPaletteChangeEvent); return toDisposable(() => { let didChange = false; for (const command of commands) { didChange = this._commands.delete(command.id) || didChange; } if (didChange) { this._onDidChangeMenu.fire(this._commandPaletteChangeEvent); } }); } getCommand(id: string): ICommandAction | undefined { return this._commands.get(id); } getCommands(): ICommandsMap { const map = new Map<string, ICommandAction>(); this._commands.forEach((value, key) => map.set(key, value)); return map; } appendMenuItem(id: MenuId, item: IMenuItem | ISubmenuItem): IDisposable { return this.appendMenuItems(Iterable.single({ id, item })); } appendMenuItems(items: Iterable<{ id: MenuId, item: IMenuItem | ISubmenuItem }>): IDisposable { const changedIds = new Set<MenuId>(); const toRemove = new LinkedList<Function>(); for (const { id, item } of items) { let list = this._menuItems.get(id); if (!list) { list = new LinkedList(); this._menuItems.set(id, list); } toRemove.push(list.push(item)); changedIds.add(id); } this._onDidChangeMenu.fire(changedIds); return toDisposable(() => { if (toRemove.size > 0) { for (let fn of toRemove) { fn(); } this._onDidChangeMenu.fire(changedIds); toRemove.clear(); } }); } getMenuItems(id: MenuId): Array<IMenuItem | ISubmenuItem> { let result: Array<IMenuItem | ISubmenuItem>; if (this._menuItems.has(id)) { result = [...this._menuItems.get(id)!]; } else { result = []; } if (id === MenuId.CommandPalette) { // CommandPalette is special because it shows // all commands by default this._appendImplicitItems(result); } return result; } private _appendImplicitItems(result: Array<IMenuItem | ISubmenuItem>) { const set = new Set<string>(); for (const item of result) { if (isIMenuItem(item)) { set.add(item.command.id); if (item.alt) { set.add(item.alt.id); } } } this._commands.forEach((command, id) => { if (!set.has(id)) { result.push({ command }); } }); } }; export class ExecuteCommandAction extends Action { constructor( id: string, label: string, @ICommandService private readonly _commandService: ICommandService) { super(id, label); } run(...args: any[]): Promise<any> { return this._commandService.executeCommand(this.id, ...args); } } export class SubmenuItemAction extends SubmenuAction { readonly item: ISubmenuItem; constructor( item: ISubmenuItem, menuService: IMenuService, contextKeyService: IContextKeyService, options?: IMenuActionOptions ) { const result: IAction[] = []; const menu = menuService.createMenu(item.submenu, contextKeyService); const groups = menu.getActions(options); menu.dispose(); for (let group of groups) { const [, actions] = group; if (actions.length > 0) { result.push(...actions); result.push(new Separator()); } } if (result.length) { result.pop(); // remove last separator } super(`submenuitem.${item.submenu.id}`, typeof item.title === 'string' ? item.title : item.title.value, result, 'submenu'); this.item = item; } } export class MenuItemAction extends ExecuteCommandAction { readonly item: ICommandAction; readonly alt: MenuItemAction | undefined; private _options: IMenuActionOptions; constructor( item: ICommandAction, alt: ICommandAction | undefined, options: IMenuActionOptions, @IContextKeyService contextKeyService: IContextKeyService, @ICommandService commandService: ICommandService ) { typeof item.title === 'string' ? super(item.id, item.title, commandService) : super(item.id, item.title.value, commandService); this._cssClass = undefined; this._enabled = !item.precondition || contextKeyService.contextMatchesRules(item.precondition); this._tooltip = item.tooltip ? typeof item.tooltip === 'string' ? item.tooltip : item.tooltip.value : undefined; if (item.toggled) { const toggled = ((item.toggled as { condition: ContextKeyExpression }).condition ? item.toggled : { condition: item.toggled }) as { condition: ContextKeyExpression, icon?: Icon, tooltip?: string | ILocalizedString }; this._checked = contextKeyService.contextMatchesRules(toggled.condition); if (this._checked && toggled.tooltip) { this._tooltip = typeof toggled.tooltip === 'string' ? toggled.tooltip : toggled.tooltip.value; } } this._options = options || {}; this.item = item; this.alt = alt ? new MenuItemAction(alt, undefined, this._options, contextKeyService, commandService) : undefined; } dispose(): void { if (this.alt) { this.alt.dispose(); } super.dispose(); } run(...args: any[]): Promise<any> { let runArgs: any[] = []; if (this._options.arg) { runArgs = [...runArgs, this._options.arg]; } if (this._options.shouldForwardArgs) { runArgs = [...runArgs, ...args]; } return super.run(...runArgs); } } export class SyncActionDescriptor { private readonly _descriptor: SyncDescriptor0<Action>; private readonly _id: string; private readonly _label?: string; private readonly _keybindings: IKeybindings | undefined; private readonly _keybindingContext: ContextKeyExpression | undefined; private readonly _keybindingWeight: number | undefined; public static create<Services extends BrandedService[]>(ctor: { new(id: string, label: string, ...services: Services): Action }, id: string, label: string | undefined, keybindings?: IKeybindings, keybindingContext?: ContextKeyExpression, keybindingWeight?: number ): SyncActionDescriptor { return new SyncActionDescriptor(ctor as IConstructorSignature2<string, string | undefined, Action>, id, label, keybindings, keybindingContext, keybindingWeight); } public static from<Services extends BrandedService[]>( ctor: { new(id: string, label: string, ...services: Services): Action; readonly ID: string; readonly LABEL: string; }, keybindings?: IKeybindings, keybindingContext?: ContextKeyExpression, keybindingWeight?: number ): SyncActionDescriptor { return SyncActionDescriptor.create(ctor, ctor.ID, ctor.LABEL, keybindings, keybindingContext, keybindingWeight); } private constructor(ctor: IConstructorSignature2<string, string | undefined, Action>, id: string, label: string | undefined, keybindings?: IKeybindings, keybindingContext?: ContextKeyExpression, keybindingWeight?: number ) { this._id = id; this._label = label; this._keybindings = keybindings; this._keybindingContext = keybindingContext; this._keybindingWeight = keybindingWeight; this._descriptor = createSyncDescriptor(ctor, this._id, this._label); } public get syncDescriptor(): SyncDescriptor0<Action> { return this._descriptor; } public get id(): string { return this._id; } public get label(): string | undefined { return this._label; } public get keybindings(): IKeybindings | undefined { return this._keybindings; } public get keybindingContext(): ContextKeyExpression | undefined { return this._keybindingContext; } public get keybindingWeight(): number | undefined { return this._keybindingWeight; } } //#region --- IAction2 type OneOrN<T> = T | T[]; export interface IAction2Options extends ICommandAction { /** * Shorthand to add this command to the command palette */ f1?: boolean; /** * One or many menu items. */ menu?: OneOrN<{ id: MenuId } & Omit<IMenuItem, 'command'>>; /** * One keybinding. */ keybinding?: OneOrN<Omit<IKeybindingRule, 'id'>>; /** * Metadata about this command, used for API commands or when * showing keybindings that have no other UX. */ description?: ICommandHandlerDescription; } export abstract class Action2 { constructor(readonly desc: Readonly<IAction2Options>) { } abstract run(accessor: ServicesAccessor, ...args: any[]): any; } export function registerAction2(ctor: { new(): Action2 }): IDisposable { const disposables = new DisposableStore(); const action = new ctor(); const { f1, menu, keybinding, description, ...command } = action.desc; // command disposables.add(CommandsRegistry.registerCommand({ id: command.id, handler: (accessor, ...args) => action.run(accessor, ...args), description: description, })); // menu if (Array.isArray(menu)) { disposables.add(MenuRegistry.appendMenuItems(menu.map(item => ({ id: item.id, item: { command, ...item } })))); } else if (menu) { disposables.add(MenuRegistry.appendMenuItem(menu.id, { command, ...menu })); } if (f1) { disposables.add(MenuRegistry.appendMenuItem(MenuId.CommandPalette, { command, when: command.precondition })); disposables.add(MenuRegistry.addCommand(command)); } // keybinding if (Array.isArray(keybinding)) { for (let item of keybinding) { KeybindingsRegistry.registerKeybindingRule({ ...item, id: command.id, when: command.precondition ? ContextKeyExpr.and(command.precondition, item.when) : item.when }); } } else if (keybinding) { KeybindingsRegistry.registerKeybindingRule({ ...keybinding, id: command.id, when: command.precondition ? ContextKeyExpr.and(command.precondition, keybinding.when) : keybinding.when }); } return disposables; } //#endregion
src/vs/platform/actions/common/actions.ts
0
https://github.com/microsoft/vscode/commit/574ee2032cc24ed250ef15962ce100838d4e5e4a
[ 0.00017708689847495407, 0.00017133976507466286, 0.00016240576223935932, 0.00017266925715375692, 0.00000397672010876704 ]
{ "id": 4, "code_window": [ "import { URI } from 'vs/base/common/uri';\n", "import { TERMINAL_BACKGROUND_COLOR, TERMINAL_BORDER_COLOR } from 'vs/workbench/contrib/terminal/common/terminalColorRegistry';\n", "import { DataTransfers } from 'vs/base/browser/dnd';\n", "import { INotificationService, IPromptChoice, Severity } from 'vs/platform/notification/common/notification';\n", "import { ITerminalService } from 'vs/workbench/contrib/terminal/browser/terminal';\n", "import { BrowserFeatures } from 'vs/base/browser/canIUse';\n", "import { ViewPane, IViewPaneOptions } from 'vs/workbench/browser/parts/views/viewPaneContainer';\n", "import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';\n", "import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey';\n", "import { IViewDescriptorService } from 'vs/workbench/common/views';\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { ITerminalService, TerminalConnectionState } from 'vs/workbench/contrib/terminal/browser/terminal';\n" ], "file_path": "src/vs/workbench/contrib/terminal/browser/terminalView.ts", "type": "replace", "edit_start_line_idx": 21 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { timeout } from 'vs/base/common/async'; import { Emitter, Event } from 'vs/base/common/event'; import { IDisposable } from 'vs/base/common/lifecycle'; import { basename } from 'vs/base/common/path'; import { isMacintosh, isWeb, isWindows, OperatingSystem } from 'vs/base/common/platform'; import { URI } from 'vs/base/common/uri'; import { FindReplaceState } from 'vs/editor/contrib/find/findState'; import * as nls from 'vs/nls'; import { ConfigurationTarget, IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IContextKey, IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { IDialogService } from 'vs/platform/dialogs/common/dialogs'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IPickOptions, IQuickInputService, IQuickPickItem } from 'vs/platform/quickinput/common/quickInput'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IViewDescriptorService, IViewsService, ViewContainerLocation } from 'vs/workbench/common/views'; import { TerminalConnectionState, IRemoteTerminalService, ITerminalExternalLinkProvider, ITerminalInstance, ITerminalService, ITerminalTab, TerminalShellType, WindowsShellType } from 'vs/workbench/contrib/terminal/browser/terminal'; import { TerminalConfigHelper } from 'vs/workbench/contrib/terminal/browser/terminalConfigHelper'; import { TerminalInstance } from 'vs/workbench/contrib/terminal/browser/terminalInstance'; import { TerminalTab } from 'vs/workbench/contrib/terminal/browser/terminalTab'; import { TerminalViewPane } from 'vs/workbench/contrib/terminal/browser/terminalView'; import { IAvailableShellsRequest, IShellDefinition, IShellLaunchConfig, ISpawnExtHostProcessRequest, IStartExtensionTerminalRequest, ITerminalConfigHelper, ITerminalLaunchError, ITerminalNativeWindowsDelegate, ITerminalProcessExtHostProxy, KEYBINDING_CONTEXT_TERMINAL_FIND_VISIBLE, KEYBINDING_CONTEXT_TERMINAL_FOCUS, KEYBINDING_CONTEXT_TERMINAL_IS_OPEN, KEYBINDING_CONTEXT_TERMINAL_PROCESS_SUPPORTED, KEYBINDING_CONTEXT_TERMINAL_SHELL_TYPE, LinuxDistro, TERMINAL_VIEW_ID } from 'vs/workbench/contrib/terminal/common/terminal'; import { escapeNonWindowsPath } from 'vs/workbench/contrib/terminal/common/terminalEnvironment'; import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService'; import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions'; import { IWorkbenchLayoutService } from 'vs/workbench/services/layout/browser/layoutService'; import { ILifecycleService } from 'vs/workbench/services/lifecycle/common/lifecycle'; import { IRemoteAgentService } from 'vs/workbench/services/remote/common/remoteAgentService'; interface IExtHostReadyEntry { promise: Promise<void>; resolve: () => void; } export class TerminalService implements ITerminalService { public _serviceBrand: undefined; private _isShuttingDown: boolean; private _terminalFocusContextKey: IContextKey<boolean>; private _terminalShellTypeContextKey: IContextKey<string>; private _findWidgetVisible: IContextKey<boolean>; private _terminalTabs: ITerminalTab[] = []; private _backgroundedTerminalInstances: ITerminalInstance[] = []; private get _terminalInstances(): ITerminalInstance[] { return this._terminalTabs.reduce((p, c) => p.concat(c.terminalInstances), <ITerminalInstance[]>[]); } private _findState: FindReplaceState; private _extHostsReady: { [authority: string]: IExtHostReadyEntry | undefined } = {}; private _activeTabIndex: number; private _linkProviders: Set<ITerminalExternalLinkProvider> = new Set(); private _linkProviderDisposables: Map<ITerminalExternalLinkProvider, IDisposable[]> = new Map(); private _processSupportContextKey: IContextKey<boolean>; public get activeTabIndex(): number { return this._activeTabIndex; } public get terminalInstances(): ITerminalInstance[] { return this._terminalInstances; } public get terminalTabs(): ITerminalTab[] { return this._terminalTabs; } public get isProcessSupportRegistered(): boolean { return !!this._processSupportContextKey.get(); } private _configHelper: TerminalConfigHelper; private _terminalContainer: HTMLElement | undefined; private _nativeWindowsDelegate: ITerminalNativeWindowsDelegate | undefined; private _remoteTerminalsInitialized: Promise<void> | undefined; private _willFocusNewTerminal = false; private _connectionState: TerminalConnectionState; public get configHelper(): ITerminalConfigHelper { return this._configHelper; } private readonly _onActiveTabChanged = new Emitter<void>(); public get onActiveTabChanged(): Event<void> { return this._onActiveTabChanged.event; } private readonly _onInstanceCreated = new Emitter<ITerminalInstance>(); public get onInstanceCreated(): Event<ITerminalInstance> { return this._onInstanceCreated.event; } private readonly _onInstanceDisposed = new Emitter<ITerminalInstance>(); public get onInstanceDisposed(): Event<ITerminalInstance> { return this._onInstanceDisposed.event; } private readonly _onInstanceProcessIdReady = new Emitter<ITerminalInstance>(); public get onInstanceProcessIdReady(): Event<ITerminalInstance> { return this._onInstanceProcessIdReady.event; } private readonly _onInstanceLinksReady = new Emitter<ITerminalInstance>(); public get onInstanceLinksReady(): Event<ITerminalInstance> { return this._onInstanceLinksReady.event; } private readonly _onInstanceRequestSpawnExtHostProcess = new Emitter<ISpawnExtHostProcessRequest>(); public get onInstanceRequestSpawnExtHostProcess(): Event<ISpawnExtHostProcessRequest> { return this._onInstanceRequestSpawnExtHostProcess.event; } private readonly _onInstanceRequestStartExtensionTerminal = new Emitter<IStartExtensionTerminalRequest>(); public get onInstanceRequestStartExtensionTerminal(): Event<IStartExtensionTerminalRequest> { return this._onInstanceRequestStartExtensionTerminal.event; } private readonly _onInstanceDimensionsChanged = new Emitter<ITerminalInstance>(); public get onInstanceDimensionsChanged(): Event<ITerminalInstance> { return this._onInstanceDimensionsChanged.event; } private readonly _onInstanceMaximumDimensionsChanged = new Emitter<ITerminalInstance>(); public get onInstanceMaximumDimensionsChanged(): Event<ITerminalInstance> { return this._onInstanceMaximumDimensionsChanged.event; } private readonly _onInstancesChanged = new Emitter<void>(); public get onInstancesChanged(): Event<void> { return this._onInstancesChanged.event; } private readonly _onInstanceTitleChanged = new Emitter<ITerminalInstance | undefined>(); public get onInstanceTitleChanged(): Event<ITerminalInstance | undefined> { return this._onInstanceTitleChanged.event; } private readonly _onActiveInstanceChanged = new Emitter<ITerminalInstance | undefined>(); public get onActiveInstanceChanged(): Event<ITerminalInstance | undefined> { return this._onActiveInstanceChanged.event; } private readonly _onTabDisposed = new Emitter<ITerminalTab>(); public get onTabDisposed(): Event<ITerminalTab> { return this._onTabDisposed.event; } private readonly _onRequestAvailableShells = new Emitter<IAvailableShellsRequest>(); public get onRequestAvailableShells(): Event<IAvailableShellsRequest> { return this._onRequestAvailableShells.event; } private readonly _onDidRegisterProcessSupport = new Emitter<void>(); public get onDidRegisterProcessSupport(): Event<void> { return this._onDidRegisterProcessSupport.event; } private readonly _onDidChangeConnectionState = new Emitter<void>(); public get onDidChangeConnectionState(): Event<void> { return this._onDidChangeConnectionState.event; } public get connectionState(): TerminalConnectionState { return this._connectionState; } public set willFocusNewTerminal(v: boolean) { this._willFocusNewTerminal = v; } constructor( @IContextKeyService private _contextKeyService: IContextKeyService, @IWorkbenchLayoutService private _layoutService: IWorkbenchLayoutService, @ILifecycleService lifecycleService: ILifecycleService, @IDialogService private _dialogService: IDialogService, @IInstantiationService private _instantiationService: IInstantiationService, @IExtensionService private _extensionService: IExtensionService, @IRemoteAgentService private _remoteAgentService: IRemoteAgentService, @IQuickInputService private _quickInputService: IQuickInputService, @IConfigurationService private _configurationService: IConfigurationService, @IViewsService private _viewsService: IViewsService, @IViewDescriptorService private readonly _viewDescriptorService: IViewDescriptorService, @IWorkbenchEnvironmentService private readonly _environmentService: IWorkbenchEnvironmentService, @IRemoteTerminalService private readonly _remoteTerminalService: IRemoteTerminalService, @ITelemetryService private readonly _telemetryService: ITelemetryService ) { this._activeTabIndex = 0; this._isShuttingDown = false; this._findState = new FindReplaceState(); lifecycleService.onBeforeShutdown(async event => event.veto(this._onBeforeShutdown())); lifecycleService.onShutdown(() => this._onShutdown()); this._terminalFocusContextKey = KEYBINDING_CONTEXT_TERMINAL_FOCUS.bindTo(this._contextKeyService); this._terminalShellTypeContextKey = KEYBINDING_CONTEXT_TERMINAL_SHELL_TYPE.bindTo(this._contextKeyService); this._findWidgetVisible = KEYBINDING_CONTEXT_TERMINAL_FIND_VISIBLE.bindTo(this._contextKeyService); this._configHelper = this._instantiationService.createInstance(TerminalConfigHelper); this.onTabDisposed(tab => this._removeTab(tab)); this.onActiveTabChanged(() => { const instance = this.getActiveInstance(); this._onActiveInstanceChanged.fire(instance ? instance : undefined); }); this.onInstanceLinksReady(instance => this._setInstanceLinkProviders(instance)); this._handleInstanceContextKeys(); this._processSupportContextKey = KEYBINDING_CONTEXT_TERMINAL_PROCESS_SUPPORTED.bindTo(this._contextKeyService); this._processSupportContextKey.set(!isWeb || this._remoteAgentService.getConnection() !== null); const enableTerminalReconnection = this.configHelper.config.enablePersistentSessions; const serverSpawn = this.configHelper.config.serverSpawn; if (!!this._environmentService.remoteAuthority && enableTerminalReconnection && serverSpawn) { this._remoteTerminalsInitialized = this._reconnectToRemoteTerminals(); this._connectionState = TerminalConnectionState.Connecting; } else { this._connectionState = TerminalConnectionState.Connected; } } private async _reconnectToRemoteTerminals(): Promise<void> { const remoteTerms = await this._remoteTerminalService.listTerminals(); this._connectionState = TerminalConnectionState.Connected; this._onDidChangeConnectionState.fire(); const unattachedRemoteTerms = remoteTerms.filter(term => !this.isAttachedToTerminalWithPid(term.pid)); /* __GDPR__ "terminalReconnection" : { "count" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true } } */ const data = { count: unattachedRemoteTerms.length }; this._telemetryService.publicLog('terminalReconnection', data); if (unattachedRemoteTerms.length > 0) { // Reattach to all remote terminals for (let term of unattachedRemoteTerms) { this.createTerminal({ remoteAttach: term }); } } } public setNativeWindowsDelegate(delegate: ITerminalNativeWindowsDelegate): void { this._nativeWindowsDelegate = delegate; } public setLinuxDistro(linuxDistro: LinuxDistro): void { this._configHelper.setLinuxDistro(linuxDistro); } private _handleInstanceContextKeys(): void { const terminalIsOpenContext = KEYBINDING_CONTEXT_TERMINAL_IS_OPEN.bindTo(this._contextKeyService); const updateTerminalContextKeys = () => { terminalIsOpenContext.set(this.terminalInstances.length > 0); }; this.onInstancesChanged(() => updateTerminalContextKeys()); } public getActiveOrCreateInstance(): ITerminalInstance { const activeInstance = this.getActiveInstance(); return activeInstance ? activeInstance : this.createTerminal(undefined); } public async requestSpawnExtHostProcess(proxy: ITerminalProcessExtHostProxy, shellLaunchConfig: IShellLaunchConfig, activeWorkspaceRootUri: URI | undefined, cols: number, rows: number, isWorkspaceShellAllowed: boolean): Promise<ITerminalLaunchError | undefined> { await this._extensionService.whenInstalledExtensionsRegistered(); // Wait for the remoteAuthority to be ready (and listening for events) before firing // the event to spawn the ext host process const conn = this._remoteAgentService.getConnection(); const remoteAuthority = conn ? conn.remoteAuthority : 'null'; await this._whenExtHostReady(remoteAuthority); return new Promise<ITerminalLaunchError | undefined>(callback => { this._onInstanceRequestSpawnExtHostProcess.fire({ proxy, shellLaunchConfig, activeWorkspaceRootUri, cols, rows, isWorkspaceShellAllowed, callback }); }); } public requestStartExtensionTerminal(proxy: ITerminalProcessExtHostProxy, cols: number, rows: number): Promise<ITerminalLaunchError | undefined> { // The initial request came from the extension host, no need to wait for it return new Promise<ITerminalLaunchError | undefined>(callback => { this._onInstanceRequestStartExtensionTerminal.fire({ proxy, cols, rows, callback }); }); } public async extHostReady(remoteAuthority: string): Promise<void> { this._createExtHostReadyEntry(remoteAuthority); this._extHostsReady[remoteAuthority]!.resolve(); } private async _whenExtHostReady(remoteAuthority: string): Promise<void> { this._createExtHostReadyEntry(remoteAuthority); return this._extHostsReady[remoteAuthority]!.promise; } private _createExtHostReadyEntry(remoteAuthority: string): void { if (this._extHostsReady[remoteAuthority]) { return; } let resolve!: () => void; const promise = new Promise<void>(r => resolve = r); this._extHostsReady[remoteAuthority] = { promise, resolve }; } private _onBeforeShutdown(): boolean | Promise<boolean> { if (this.terminalInstances.length === 0) { // No terminal instances, don't veto return false; } if (this.configHelper.config.confirmOnExit) { return this._onBeforeShutdownAsync(); } this._isShuttingDown = true; return false; } private async _onBeforeShutdownAsync(): Promise<boolean> { // veto if configured to show confirmation and the user choosed not to exit const veto = await this._showTerminalCloseConfirmation(); if (!veto) { this._isShuttingDown = true; } return veto; } private _onShutdown(): void { // Dispose of all instances this.terminalInstances.forEach(instance => instance.dispose(true)); } public getTabLabels(): string[] { return this._terminalTabs.filter(tab => tab.terminalInstances.length > 0).map((tab, index) => `${index + 1}: ${tab.title ? tab.title : ''}`); } public getFindState(): FindReplaceState { return this._findState; } private _removeTab(tab: ITerminalTab): void { // Get the index of the tab and remove it from the list const index = this._terminalTabs.indexOf(tab); const activeTab = this.getActiveTab(); const activeTabIndex = activeTab ? this._terminalTabs.indexOf(activeTab) : -1; const wasActiveTab = tab === activeTab; if (index !== -1) { this._terminalTabs.splice(index, 1); } // Adjust focus if the tab was active if (wasActiveTab && this._terminalTabs.length > 0) { // TODO: Only focus the new tab if the removed tab had focus? // const hasFocusOnExit = tab.activeInstance.hadFocusOnExit; const newIndex = index < this._terminalTabs.length ? index : this._terminalTabs.length - 1; this.setActiveTabByIndex(newIndex); const activeInstance = this.getActiveInstance(); if (activeInstance) { activeInstance.focus(true); } } else if (activeTabIndex >= this._terminalTabs.length) { const newIndex = this._terminalTabs.length - 1; this.setActiveTabByIndex(newIndex); } // Hide the panel if there are no more instances, provided that VS Code is not shutting // down. When shutting down the panel is locked in place so that it is restored upon next // launch. if (this._terminalTabs.length === 0 && !this._isShuttingDown) { this.hidePanel(); this._onActiveInstanceChanged.fire(undefined); } // Fire events this._onInstancesChanged.fire(); if (wasActiveTab) { this._onActiveTabChanged.fire(); } } public refreshActiveTab(): void { // Fire active instances changed this._onActiveTabChanged.fire(); } public getActiveTab(): ITerminalTab | null { if (this._activeTabIndex < 0 || this._activeTabIndex >= this._terminalTabs.length) { return null; } return this._terminalTabs[this._activeTabIndex]; } public getActiveInstance(): ITerminalInstance | null { const tab = this.getActiveTab(); if (!tab) { return null; } return tab.activeInstance; } public doWithActiveInstance<T>(callback: (terminal: ITerminalInstance) => T): T | void { const instance = this.getActiveInstance(); if (instance) { return callback(instance); } } public getInstanceFromId(terminalId: number): ITerminalInstance | undefined { let bgIndex = -1; this._backgroundedTerminalInstances.forEach((terminalInstance, i) => { if (terminalInstance.id === terminalId) { bgIndex = i; } }); if (bgIndex !== -1) { return this._backgroundedTerminalInstances[bgIndex]; } try { return this.terminalInstances[this._getIndexFromId(terminalId)]; } catch { return undefined; } } public getInstanceFromIndex(terminalIndex: number): ITerminalInstance { return this.terminalInstances[terminalIndex]; } public setActiveInstance(terminalInstance: ITerminalInstance): void { // If this was a hideFromUser terminal created by the API this was triggered by show, // in which case we need to create the terminal tab if (terminalInstance.shellLaunchConfig.hideFromUser) { this._showBackgroundTerminal(terminalInstance); } this.setActiveInstanceByIndex(this._getIndexFromId(terminalInstance.id)); } public setActiveTabByIndex(tabIndex: number): void { if (tabIndex >= this._terminalTabs.length) { return; } const didTabChange = this._activeTabIndex !== tabIndex; this._activeTabIndex = tabIndex; this._terminalTabs.forEach((t, i) => t.setVisible(i === this._activeTabIndex)); if (didTabChange) { this._onActiveTabChanged.fire(); } } private isAttachedToTerminalWithPid(pid: number): boolean { return this.terminalInstances.some(term => term.processId === pid); } public async initializeTerminals(): Promise<void> { if (this._remoteTerminalsInitialized) { await this._remoteTerminalsInitialized; if (!this.terminalTabs.length) { this.createTerminal(undefined); } } else if (!this._environmentService.remoteAuthority && this.terminalTabs.length === 0) { // Local, just create a terminal this.createTerminal(); } } private _getInstanceFromGlobalInstanceIndex(index: number): { tab: ITerminalTab, tabIndex: number, instance: ITerminalInstance, localInstanceIndex: number } | null { let currentTabIndex = 0; while (index >= 0 && currentTabIndex < this._terminalTabs.length) { const tab = this._terminalTabs[currentTabIndex]; const count = tab.terminalInstances.length; if (index < count) { return { tab, tabIndex: currentTabIndex, instance: tab.terminalInstances[index], localInstanceIndex: index }; } index -= count; currentTabIndex++; } return null; } public setActiveInstanceByIndex(terminalIndex: number): void { const query = this._getInstanceFromGlobalInstanceIndex(terminalIndex); if (!query) { return; } query.tab.setActiveInstanceByIndex(query.localInstanceIndex); const didTabChange = this._activeTabIndex !== query.tabIndex; this._activeTabIndex = query.tabIndex; this._terminalTabs.forEach((t, i) => t.setVisible(i === query.tabIndex)); // Only fire the event if there was a change if (didTabChange) { this._onActiveTabChanged.fire(); } } public setActiveTabToNext(): void { if (this._terminalTabs.length <= 1) { return; } let newIndex = this._activeTabIndex + 1; if (newIndex >= this._terminalTabs.length) { newIndex = 0; } this.setActiveTabByIndex(newIndex); } public setActiveTabToPrevious(): void { if (this._terminalTabs.length <= 1) { return; } let newIndex = this._activeTabIndex - 1; if (newIndex < 0) { newIndex = this._terminalTabs.length - 1; } this.setActiveTabByIndex(newIndex); } public splitInstance(instanceToSplit: ITerminalInstance, shellLaunchConfig: IShellLaunchConfig = {}): ITerminalInstance | null { const tab = this._getTabForInstance(instanceToSplit); if (!tab) { return null; } const instance = tab.split(shellLaunchConfig); this._initInstanceListeners(instance); this._onInstancesChanged.fire(); this._terminalTabs.forEach((t, i) => t.setVisible(i === this._activeTabIndex)); return instance; } protected _initInstanceListeners(instance: ITerminalInstance): void { instance.addDisposable(instance.onDisposed(this._onInstanceDisposed.fire, this._onInstanceDisposed)); instance.addDisposable(instance.onTitleChanged(this._onInstanceTitleChanged.fire, this._onInstanceTitleChanged)); instance.addDisposable(instance.onProcessIdReady(this._onInstanceProcessIdReady.fire, this._onInstanceProcessIdReady)); instance.addDisposable(instance.onLinksReady(this._onInstanceLinksReady.fire, this._onInstanceLinksReady)); instance.addDisposable(instance.onDimensionsChanged(() => this._onInstanceDimensionsChanged.fire(instance))); instance.addDisposable(instance.onMaximumDimensionsChanged(() => this._onInstanceMaximumDimensionsChanged.fire(instance))); instance.addDisposable(instance.onFocus(this._onActiveInstanceChanged.fire, this._onActiveInstanceChanged)); } public registerProcessSupport(isSupported: boolean): void { if (!isSupported) { return; } this._processSupportContextKey.set(isSupported); this._onDidRegisterProcessSupport.fire(); } public registerLinkProvider(linkProvider: ITerminalExternalLinkProvider): IDisposable { const disposables: IDisposable[] = []; this._linkProviders.add(linkProvider); for (const instance of this.terminalInstances) { if (instance.areLinksReady) { disposables.push(instance.registerLinkProvider(linkProvider)); } } this._linkProviderDisposables.set(linkProvider, disposables); return { dispose: () => { const disposables = this._linkProviderDisposables.get(linkProvider) || []; for (const disposable of disposables) { disposable.dispose(); } this._linkProviders.delete(linkProvider); } }; } private _setInstanceLinkProviders(instance: ITerminalInstance): void { for (const linkProvider of this._linkProviders) { const disposables = this._linkProviderDisposables.get(linkProvider); const provider = instance.registerLinkProvider(linkProvider); disposables?.push(provider); } } private _getTabForInstance(instance: ITerminalInstance): ITerminalTab | undefined { return this._terminalTabs.find(tab => tab.terminalInstances.indexOf(instance) !== -1); } public async showPanel(focus?: boolean): Promise<void> { const pane = this._viewsService.getActiveViewWithId(TERMINAL_VIEW_ID) as TerminalViewPane; if (!pane) { await this._viewsService.openView(TERMINAL_VIEW_ID, focus); } if (focus) { // Do the focus call asynchronously as going through the // command palette will force editor focus await timeout(0); const instance = this.getActiveInstance(); if (instance) { await instance.focusWhenReady(true); } } } private _getIndexFromId(terminalId: number): number { let terminalIndex = -1; this.terminalInstances.forEach((terminalInstance, i) => { if (terminalInstance.id === terminalId) { terminalIndex = i; } }); if (terminalIndex === -1) { throw new Error(`Terminal with ID ${terminalId} does not exist (has it already been disposed?)`); } return terminalIndex; } public async manageWorkspaceShellPermissions(): Promise<void> { const allowItem: IQuickPickItem = { label: nls.localize('workbench.action.terminal.allowWorkspaceShell', "Allow Workspace Shell Configuration") }; const disallowItem: IQuickPickItem = { label: nls.localize('workbench.action.terminal.disallowWorkspaceShell', "Disallow Workspace Shell Configuration") }; const value = await this._quickInputService.pick([allowItem, disallowItem], { canPickMany: false }); if (!value) { return; } this.configHelper.setWorkspaceShellAllowed(value === allowItem); } protected async _showTerminalCloseConfirmation(): Promise<boolean> { let message: string; if (this.terminalInstances.length === 1) { message = nls.localize('terminalService.terminalCloseConfirmationSingular', "There is an active terminal session, do you want to kill it?"); } else { message = nls.localize('terminalService.terminalCloseConfirmationPlural', "There are {0} active terminal sessions, do you want to kill them?", this.terminalInstances.length); } const res = await this._dialogService.confirm({ message, type: 'warning', }); return !res.confirmed; } public preparePathForTerminalAsync(originalPath: string, executable: string, title: string, shellType: TerminalShellType): Promise<string> { return new Promise<string>(c => { if (!executable) { c(originalPath); return; } const hasSpace = originalPath.indexOf(' ') !== -1; const pathBasename = basename(executable, '.exe'); const isPowerShell = pathBasename === 'pwsh' || title === 'pwsh' || pathBasename === 'powershell' || title === 'powershell'; if (isPowerShell && (hasSpace || originalPath.indexOf('\'') !== -1)) { c(`& '${originalPath.replace(/'/g, '\'\'')}'`); return; } if (isWindows) { // 17063 is the build number where wsl path was introduced. // Update Windows uriPath to be executed in WSL. if (shellType !== undefined) { if (shellType === WindowsShellType.GitBash) { c(originalPath.replace(/\\/g, '/')); return; } else if (shellType === WindowsShellType.Wsl) { if (this._nativeWindowsDelegate && this._nativeWindowsDelegate.getWindowsBuildNumber() >= 17063) { c(this._nativeWindowsDelegate.getWslPath(originalPath)); } else { c(originalPath.replace(/\\/g, '/')); } return; } if (hasSpace) { c('"' + originalPath + '"'); } else { c(originalPath); } } else { const lowerExecutable = executable.toLowerCase(); if (this._nativeWindowsDelegate && this._nativeWindowsDelegate.getWindowsBuildNumber() >= 17063 && (lowerExecutable.indexOf('wsl') !== -1 || (lowerExecutable.indexOf('bash.exe') !== -1 && lowerExecutable.toLowerCase().indexOf('git') === -1))) { c(this._nativeWindowsDelegate.getWslPath(originalPath)); return; } else if (hasSpace) { c('"' + originalPath + '"'); } else { c(originalPath); } } return; } c(escapeNonWindowsPath(originalPath)); }); } public async selectDefaultShell(): Promise<void> { const shells = await this._detectShells(); const options: IPickOptions<IQuickPickItem> = { placeHolder: nls.localize('terminal.integrated.chooseWindowsShell', "Select your preferred terminal shell, you can change this later in your settings") }; const quickPickItems = shells.map((s): IQuickPickItem => { return { label: s.label, description: s.path }; }); const value = await this._quickInputService.pick(quickPickItems, options); if (!value) { return undefined; } const shell = value.description; const env = await this._remoteAgentService.getEnvironment(); let platformKey: string; if (env) { platformKey = env.os === OperatingSystem.Windows ? 'windows' : (env.os === OperatingSystem.Macintosh ? 'osx' : 'linux'); } else { platformKey = isWindows ? 'windows' : (isMacintosh ? 'osx' : 'linux'); } await this._configurationService.updateValue(`terminal.integrated.shell.${platformKey}`, shell, ConfigurationTarget.USER); } private _detectShells(): Promise<IShellDefinition[]> { return new Promise(r => this._onRequestAvailableShells.fire({ callback: r })); } public createInstance(container: HTMLElement | undefined, shellLaunchConfig: IShellLaunchConfig): ITerminalInstance { const instance = this._instantiationService.createInstance(TerminalInstance, this._terminalFocusContextKey, this._terminalShellTypeContextKey, this._configHelper, container, shellLaunchConfig); this._onInstanceCreated.fire(instance); return instance; } public createTerminal(shell: IShellLaunchConfig = {}): ITerminalInstance { if (!this.isProcessSupportRegistered) { throw new Error('Could not create terminal when process support is not registered'); } if (shell.hideFromUser) { const instance = this.createInstance(undefined, shell); this._backgroundedTerminalInstances.push(instance); this._initInstanceListeners(instance); return instance; } const terminalTab = this._instantiationService.createInstance(TerminalTab, this._terminalContainer, shell); this._terminalTabs.push(terminalTab); const instance = terminalTab.terminalInstances[0]; if (this._willFocusNewTerminal) { instance.focusWhenReady(); this._willFocusNewTerminal = false; } terminalTab.addDisposable(terminalTab.onDisposed(this._onTabDisposed.fire, this._onTabDisposed)); terminalTab.addDisposable(terminalTab.onInstancesChanged(this._onInstancesChanged.fire, this._onInstancesChanged)); this._initInstanceListeners(instance); if (this.terminalInstances.length === 1) { // It's the first instance so it should be made active automatically this.setActiveInstanceByIndex(0); } this._onInstancesChanged.fire(); return instance; } protected _showBackgroundTerminal(instance: ITerminalInstance): void { this._backgroundedTerminalInstances.splice(this._backgroundedTerminalInstances.indexOf(instance), 1); instance.shellLaunchConfig.hideFromUser = false; const terminalTab = this._instantiationService.createInstance(TerminalTab, this._terminalContainer, instance); this._terminalTabs.push(terminalTab); terminalTab.addDisposable(terminalTab.onDisposed(this._onTabDisposed.fire, this._onTabDisposed)); terminalTab.addDisposable(terminalTab.onInstancesChanged(this._onInstancesChanged.fire, this._onInstancesChanged)); if (this.terminalInstances.length === 1) { // It's the first instance so it should be made active automatically this.setActiveInstanceByIndex(0); } this._onInstancesChanged.fire(); } public async focusFindWidget(): Promise<void> { await this.showPanel(false); const pane = this._viewsService.getActiveViewWithId(TERMINAL_VIEW_ID) as TerminalViewPane; pane.focusFindWidget(); this._findWidgetVisible.set(true); } public hideFindWidget(): void { const pane = this._viewsService.getActiveViewWithId(TERMINAL_VIEW_ID) as TerminalViewPane; if (pane) { pane.hideFindWidget(); this._findWidgetVisible.reset(); pane.focus(); } } public findNext(): void { const pane = this._viewsService.getActiveViewWithId(TERMINAL_VIEW_ID) as TerminalViewPane; if (pane) { pane.showFindWidget(); pane.getFindWidget().find(false); } } public findPrevious(): void { const pane = this._viewsService.getActiveViewWithId(TERMINAL_VIEW_ID) as TerminalViewPane; if (pane) { pane.showFindWidget(); pane.getFindWidget().find(true); } } public setContainers(panelContainer: HTMLElement, terminalContainer: HTMLElement): void { this._configHelper.panelContainer = panelContainer; this._terminalContainer = terminalContainer; this._terminalTabs.forEach(tab => tab.attachToElement(terminalContainer)); } public hidePanel(): void { // Hide the panel if the terminal is in the panel and it has no sibling views const location = this._viewDescriptorService.getViewLocationById(TERMINAL_VIEW_ID); if (location === ViewContainerLocation.Panel) { const panel = this._viewDescriptorService.getViewContainerByViewId(TERMINAL_VIEW_ID); if (panel && this._viewDescriptorService.getViewContainerModel(panel).activeViewDescriptors.length === 1) { this._layoutService.setPanelHidden(true); } } } }
src/vs/workbench/contrib/terminal/browser/terminalService.ts
1
https://github.com/microsoft/vscode/commit/574ee2032cc24ed250ef15962ce100838d4e5e4a
[ 0.02412853017449379, 0.0014928276650607586, 0.00016528436390217394, 0.00017272582044824958, 0.004404318984597921 ]
{ "id": 4, "code_window": [ "import { URI } from 'vs/base/common/uri';\n", "import { TERMINAL_BACKGROUND_COLOR, TERMINAL_BORDER_COLOR } from 'vs/workbench/contrib/terminal/common/terminalColorRegistry';\n", "import { DataTransfers } from 'vs/base/browser/dnd';\n", "import { INotificationService, IPromptChoice, Severity } from 'vs/platform/notification/common/notification';\n", "import { ITerminalService } from 'vs/workbench/contrib/terminal/browser/terminal';\n", "import { BrowserFeatures } from 'vs/base/browser/canIUse';\n", "import { ViewPane, IViewPaneOptions } from 'vs/workbench/browser/parts/views/viewPaneContainer';\n", "import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';\n", "import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey';\n", "import { IViewDescriptorService } from 'vs/workbench/common/views';\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { ITerminalService, TerminalConnectionState } from 'vs/workbench/contrib/terminal/browser/terminal';\n" ], "file_path": "src/vs/workbench/contrib/terminal/browser/terminalView.ts", "type": "replace", "edit_start_line_idx": 21 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as dom from 'vs/base/browser/dom'; import { GlobalMouseMoveMonitor } from 'vs/base/browser/globalMouseMoveMonitor'; import { StandardMouseEvent } from 'vs/base/browser/mouseEvent'; import { Disposable, IDisposable } from 'vs/base/common/lifecycle'; /** * Coordinates relative to the whole document (e.g. mouse event's pageX and pageY) */ export class PageCoordinates { _pageCoordinatesBrand: void; constructor( public readonly x: number, public readonly y: number ) { } public toClientCoordinates(): ClientCoordinates { return new ClientCoordinates(this.x - dom.StandardWindow.scrollX, this.y - dom.StandardWindow.scrollY); } } /** * Coordinates within the application's client area (i.e. origin is document's scroll position). * * For example, clicking in the top-left corner of the client area will * always result in a mouse event with a client.x value of 0, regardless * of whether the page is scrolled horizontally. */ export class ClientCoordinates { _clientCoordinatesBrand: void; constructor( public readonly clientX: number, public readonly clientY: number ) { } public toPageCoordinates(): PageCoordinates { return new PageCoordinates(this.clientX + dom.StandardWindow.scrollX, this.clientY + dom.StandardWindow.scrollY); } } /** * The position of the editor in the page. */ export class EditorPagePosition { _editorPagePositionBrand: void; constructor( public readonly x: number, public readonly y: number, public readonly width: number, public readonly height: number ) { } } export function createEditorPagePosition(editorViewDomNode: HTMLElement): EditorPagePosition { const editorPos = dom.getDomNodePagePosition(editorViewDomNode); return new EditorPagePosition(editorPos.left, editorPos.top, editorPos.width, editorPos.height); } export class EditorMouseEvent extends StandardMouseEvent { _editorMouseEventBrand: void; /** * Coordinates relative to the whole document. */ public readonly pos: PageCoordinates; /** * Editor's coordinates relative to the whole document. */ public readonly editorPos: EditorPagePosition; constructor(e: MouseEvent, editorViewDomNode: HTMLElement) { super(e); this.pos = new PageCoordinates(this.posx, this.posy); this.editorPos = createEditorPagePosition(editorViewDomNode); } } export interface EditorMouseEventMerger { (lastEvent: EditorMouseEvent | null, currentEvent: EditorMouseEvent): EditorMouseEvent; } export class EditorMouseEventFactory { private readonly _editorViewDomNode: HTMLElement; constructor(editorViewDomNode: HTMLElement) { this._editorViewDomNode = editorViewDomNode; } private _create(e: MouseEvent): EditorMouseEvent { return new EditorMouseEvent(e, this._editorViewDomNode); } public onContextMenu(target: HTMLElement, callback: (e: EditorMouseEvent) => void): IDisposable { return dom.addDisposableListener(target, 'contextmenu', (e: MouseEvent) => { callback(this._create(e)); }); } public onMouseUp(target: HTMLElement, callback: (e: EditorMouseEvent) => void): IDisposable { return dom.addDisposableListener(target, 'mouseup', (e: MouseEvent) => { callback(this._create(e)); }); } public onMouseDown(target: HTMLElement, callback: (e: EditorMouseEvent) => void): IDisposable { return dom.addDisposableListener(target, 'mousedown', (e: MouseEvent) => { callback(this._create(e)); }); } public onMouseLeave(target: HTMLElement, callback: (e: EditorMouseEvent) => void): IDisposable { return dom.addDisposableNonBubblingMouseOutListener(target, (e: MouseEvent) => { callback(this._create(e)); }); } public onMouseMoveThrottled(target: HTMLElement, callback: (e: EditorMouseEvent) => void, merger: EditorMouseEventMerger, minimumTimeMs: number): IDisposable { const myMerger: dom.IEventMerger<EditorMouseEvent, MouseEvent> = (lastEvent: EditorMouseEvent | null, currentEvent: MouseEvent): EditorMouseEvent => { return merger(lastEvent, this._create(currentEvent)); }; return dom.addDisposableThrottledListener<EditorMouseEvent, MouseEvent>(target, 'mousemove', callback, myMerger, minimumTimeMs); } } export class EditorPointerEventFactory { private readonly _editorViewDomNode: HTMLElement; constructor(editorViewDomNode: HTMLElement) { this._editorViewDomNode = editorViewDomNode; } private _create(e: MouseEvent): EditorMouseEvent { return new EditorMouseEvent(e, this._editorViewDomNode); } public onPointerUp(target: HTMLElement, callback: (e: EditorMouseEvent) => void): IDisposable { return dom.addDisposableListener(target, 'pointerup', (e: MouseEvent) => { callback(this._create(e)); }); } public onPointerDown(target: HTMLElement, callback: (e: EditorMouseEvent) => void): IDisposable { return dom.addDisposableListener(target, 'pointerdown', (e: MouseEvent) => { callback(this._create(e)); }); } public onPointerLeave(target: HTMLElement, callback: (e: EditorMouseEvent) => void): IDisposable { return dom.addDisposableNonBubblingPointerOutListener(target, (e: MouseEvent) => { callback(this._create(e)); }); } public onPointerMoveThrottled(target: HTMLElement, callback: (e: EditorMouseEvent) => void, merger: EditorMouseEventMerger, minimumTimeMs: number): IDisposable { const myMerger: dom.IEventMerger<EditorMouseEvent, MouseEvent> = (lastEvent: EditorMouseEvent | null, currentEvent: MouseEvent): EditorMouseEvent => { return merger(lastEvent, this._create(currentEvent)); }; return dom.addDisposableThrottledListener<EditorMouseEvent, MouseEvent>(target, 'pointermove', callback, myMerger, minimumTimeMs); } } export class GlobalEditorMouseMoveMonitor extends Disposable { private readonly _editorViewDomNode: HTMLElement; private readonly _globalMouseMoveMonitor: GlobalMouseMoveMonitor<EditorMouseEvent>; private _keydownListener: IDisposable | null; constructor(editorViewDomNode: HTMLElement) { super(); this._editorViewDomNode = editorViewDomNode; this._globalMouseMoveMonitor = this._register(new GlobalMouseMoveMonitor<EditorMouseEvent>()); this._keydownListener = null; } public startMonitoring( initialElement: HTMLElement, initialButtons: number, merger: EditorMouseEventMerger, mouseMoveCallback: (e: EditorMouseEvent) => void, onStopCallback: () => void ): void { // Add a <<capture>> keydown event listener that will cancel the monitoring // if something other than a modifier key is pressed this._keydownListener = dom.addStandardDisposableListener(<any>document, 'keydown', (e) => { const kb = e.toKeybinding(); if (kb.isModifierKey()) { // Allow modifier keys return; } this._globalMouseMoveMonitor.stopMonitoring(true); }, true); const myMerger: dom.IEventMerger<EditorMouseEvent, MouseEvent> = (lastEvent: EditorMouseEvent | null, currentEvent: MouseEvent): EditorMouseEvent => { return merger(lastEvent, new EditorMouseEvent(currentEvent, this._editorViewDomNode)); }; this._globalMouseMoveMonitor.startMonitoring(initialElement, initialButtons, myMerger, mouseMoveCallback, () => { this._keydownListener!.dispose(); onStopCallback(); }); } }
src/vs/editor/browser/editorDom.ts
0
https://github.com/microsoft/vscode/commit/574ee2032cc24ed250ef15962ce100838d4e5e4a
[ 0.00017512546037323773, 0.00017232725804205984, 0.00016606284771114588, 0.00017284008208662271, 0.000002307744580321014 ]
{ "id": 4, "code_window": [ "import { URI } from 'vs/base/common/uri';\n", "import { TERMINAL_BACKGROUND_COLOR, TERMINAL_BORDER_COLOR } from 'vs/workbench/contrib/terminal/common/terminalColorRegistry';\n", "import { DataTransfers } from 'vs/base/browser/dnd';\n", "import { INotificationService, IPromptChoice, Severity } from 'vs/platform/notification/common/notification';\n", "import { ITerminalService } from 'vs/workbench/contrib/terminal/browser/terminal';\n", "import { BrowserFeatures } from 'vs/base/browser/canIUse';\n", "import { ViewPane, IViewPaneOptions } from 'vs/workbench/browser/parts/views/viewPaneContainer';\n", "import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';\n", "import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey';\n", "import { IViewDescriptorService } from 'vs/workbench/common/views';\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { ITerminalService, TerminalConnectionState } from 'vs/workbench/contrib/terminal/browser/terminal';\n" ], "file_path": "src/vs/workbench/contrib/terminal/browser/terminalView.ts", "type": "replace", "edit_start_line_idx": 21 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // @ts-check /** * @typedef {{ * postMessage: (channel: string, data?: any) => void, * onMessage: (channel: string, handler: any) => void, * focusIframeOnCreate?: boolean, * ready?: Promise<void>, * onIframeLoaded?: (iframe: HTMLIFrameElement) => void, * fakeLoad?: boolean, * rewriteCSP: (existingCSP: string, endpoint?: string) => string, * onElectron?: boolean * }} WebviewHost */ (function () { 'use strict'; const isSafari = navigator.vendor && navigator.vendor.indexOf('Apple') > -1 && navigator.userAgent && navigator.userAgent.indexOf('CriOS') === -1 && navigator.userAgent.indexOf('FxiOS') === -1; /** * Use polling to track focus of main webview and iframes within the webview * * @param {Object} handlers * @param {() => void} handlers.onFocus * @param {() => void} handlers.onBlur */ const trackFocus = ({ onFocus, onBlur }) => { const interval = 50; let isFocused = document.hasFocus(); setInterval(() => { const isCurrentlyFocused = document.hasFocus(); if (isCurrentlyFocused === isFocused) { return; } isFocused = isCurrentlyFocused; if (isCurrentlyFocused) { onFocus(); } else { onBlur(); } }, interval); }; const getActiveFrame = () => { return /** @type {HTMLIFrameElement} */ (document.getElementById('active-frame')); }; const getPendingFrame = () => { return /** @type {HTMLIFrameElement} */ (document.getElementById('pending-frame')); }; const defaultCssRules = ` body { background-color: transparent; color: var(--vscode-editor-foreground); font-family: var(--vscode-font-family); font-weight: var(--vscode-font-weight); font-size: var(--vscode-font-size); margin: 0; padding: 0 20px; } img { max-width: 100%; max-height: 100%; } a { color: var(--vscode-textLink-foreground); } a:hover { color: var(--vscode-textLink-activeForeground); } a:focus, input:focus, select:focus, textarea:focus { outline: 1px solid -webkit-focus-ring-color; outline-offset: -1px; } code { color: var(--vscode-textPreformat-foreground); } blockquote { background: var(--vscode-textBlockQuote-background); border-color: var(--vscode-textBlockQuote-border); } kbd { color: var(--vscode-editor-foreground); border-radius: 3px; vertical-align: middle; padding: 1px 3px; background-color: hsla(0,0%,50%,.17); border: 1px solid rgba(71,71,71,.4); border-bottom-color: rgba(88,88,88,.4); box-shadow: inset 0 -1px 0 rgba(88,88,88,.4); } .vscode-light kbd { background-color: hsla(0,0%,87%,.5); border: 1px solid hsla(0,0%,80%,.7); border-bottom-color: hsla(0,0%,73%,.7); box-shadow: inset 0 -1px 0 hsla(0,0%,73%,.7); } ::-webkit-scrollbar { width: 10px; height: 10px; } ::-webkit-scrollbar-corner { background-color: var(--vscode-editor-background); } ::-webkit-scrollbar-thumb { background-color: var(--vscode-scrollbarSlider-background); } ::-webkit-scrollbar-thumb:hover { background-color: var(--vscode-scrollbarSlider-hoverBackground); } ::-webkit-scrollbar-thumb:active { background-color: var(--vscode-scrollbarSlider-activeBackground); }`; /** * @param {boolean} allowMultipleAPIAcquire * @param {*} [state] * @return {string} */ function getVsCodeApiScript(allowMultipleAPIAcquire, state) { const encodedState = state ? encodeURIComponent(state) : undefined; return ` globalThis.acquireVsCodeApi = (function() { const originalPostMessage = window.parent.postMessage.bind(window.parent); const targetOrigin = '*'; let acquired = false; let state = ${state ? `JSON.parse(decodeURIComponent("${encodedState}"))` : undefined}; return () => { if (acquired && !${allowMultipleAPIAcquire}) { throw new Error('An instance of the VS Code API has already been acquired'); } acquired = true; return Object.freeze({ postMessage: function(msg) { return originalPostMessage({ command: 'onmessage', data: msg }, targetOrigin); }, setState: function(newState) { state = newState; originalPostMessage({ command: 'do-update-state', data: JSON.stringify(newState) }, targetOrigin); return newState; }, getState: function() { return state; } }); }; })(); delete window.parent; delete window.top; delete window.frameElement; `; } /** * @param {WebviewHost} host */ function createWebviewManager(host) { // state let firstLoad = true; let loadTimeout; let pendingMessages = []; const initData = { initialScrollProgress: undefined, }; /** * @param {HTMLDocument?} document * @param {HTMLElement?} body */ const applyStyles = (document, body) => { if (!document) { return; } if (body) { body.classList.remove('vscode-light', 'vscode-dark', 'vscode-high-contrast'); body.classList.add(initData.activeTheme); body.dataset.vscodeThemeKind = initData.activeTheme; body.dataset.vscodeThemeName = initData.themeName || ''; } if (initData.styles) { const documentStyle = document.documentElement.style; // Remove stale properties for (let i = documentStyle.length - 1; i >= 0; i--) { const property = documentStyle[i]; // Don't remove properties that the webview might have added separately if (property && property.startsWith('--vscode-')) { documentStyle.removeProperty(property); } } // Re-add new properties for (const variable of Object.keys(initData.styles)) { documentStyle.setProperty(`--${variable}`, initData.styles[variable]); } } }; /** * @param {MouseEvent} event */ const handleInnerClick = (event) => { if (!event || !event.view || !event.view.document) { return; } let baseElement = event.view.document.getElementsByTagName('base')[0]; /** @type {any} */ let node = event.target; while (node) { if (node.tagName && node.tagName.toLowerCase() === 'a' && node.href) { if (node.getAttribute('href') === '#') { event.view.scrollTo(0, 0); } else if (node.hash && (node.getAttribute('href') === node.hash || (baseElement && node.href.indexOf(baseElement.href) >= 0))) { let scrollTarget = event.view.document.getElementById(node.hash.substr(1, node.hash.length - 1)); if (scrollTarget) { scrollTarget.scrollIntoView(); } } else { host.postMessage('did-click-link', node.href.baseVal || node.href); } event.preventDefault(); break; } node = node.parentNode; } }; /** * @param {MouseEvent} event */ const handleAuxClick = (event) => { // Prevent middle clicks opening a broken link in the browser if (!event.view || !event.view.document) { return; } if (event.button === 1) { let node = /** @type {any} */ (event.target); while (node) { if (node.tagName && node.tagName.toLowerCase() === 'a' && node.href) { event.preventDefault(); break; } node = node.parentNode; } } }; /** * @param {KeyboardEvent} e */ const handleInnerKeydown = (e) => { // If the keypress would trigger a browser event, such as copy or paste, // make sure we block the browser from dispatching it. Instead VS Code // handles these events and will dispatch a copy/paste back to the webview // if needed if (isUndoRedo(e)) { e.preventDefault(); } else if (isCopyPasteOrCut(e)) { if (host.onElectron) { e.preventDefault(); } else { return; // let the browser handle this } } host.postMessage('did-keydown', { key: e.key, keyCode: e.keyCode, code: e.code, shiftKey: e.shiftKey, altKey: e.altKey, ctrlKey: e.ctrlKey, metaKey: e.metaKey, repeat: e.repeat }); }; /** * @param {KeyboardEvent} e * @return {boolean} */ function isCopyPasteOrCut(e) { const hasMeta = e.ctrlKey || e.metaKey; return hasMeta && ['c', 'v', 'x'].includes(e.key); } /** * @param {KeyboardEvent} e * @return {boolean} */ function isUndoRedo(e) { const hasMeta = e.ctrlKey || e.metaKey; return hasMeta && ['z', 'y'].includes(e.key); } let isHandlingScroll = false; const handleWheel = (event) => { if (isHandlingScroll) { return; } host.postMessage('did-scroll-wheel', { deltaMode: event.deltaMode, deltaX: event.deltaX, deltaY: event.deltaY, deltaZ: event.deltaZ, detail: event.detail, type: event.type }); }; const handleInnerScroll = (event) => { if (!event.target || !event.target.body) { return; } if (isHandlingScroll) { return; } const progress = event.currentTarget.scrollY / event.target.body.clientHeight; if (isNaN(progress)) { return; } isHandlingScroll = true; window.requestAnimationFrame(() => { try { host.postMessage('did-scroll', progress); } catch (e) { // noop } isHandlingScroll = false; }); }; /** * @return {string} */ function toContentHtml(data) { const options = data.options; const text = data.contents; const newDocument = new DOMParser().parseFromString(text, 'text/html'); newDocument.querySelectorAll('a').forEach(a => { if (!a.title) { a.title = a.getAttribute('href'); } }); // apply default script if (options.allowScripts) { const defaultScript = newDocument.createElement('script'); defaultScript.id = '_vscodeApiScript'; defaultScript.textContent = getVsCodeApiScript(options.allowMultipleAPIAcquire, data.state); newDocument.head.prepend(defaultScript); } // apply default styles const defaultStyles = newDocument.createElement('style'); defaultStyles.id = '_defaultStyles'; defaultStyles.textContent = defaultCssRules; newDocument.head.prepend(defaultStyles); applyStyles(newDocument, newDocument.body); // Check for CSP const csp = newDocument.querySelector('meta[http-equiv="Content-Security-Policy"]'); if (!csp) { host.postMessage('no-csp-found'); } else { try { csp.setAttribute('content', host.rewriteCSP(csp.getAttribute('content'), data.endpoint)); } catch (e) { console.error(`Could not rewrite csp: ${e}`); } } // set DOCTYPE for newDocument explicitly as DOMParser.parseFromString strips it off // and DOCTYPE is needed in the iframe to ensure that the user agent stylesheet is correctly overridden return '<!DOCTYPE html>\n' + newDocument.documentElement.outerHTML; } document.addEventListener('DOMContentLoaded', () => { const idMatch = document.location.search.match(/\bid=([\w-]+)/); const ID = idMatch ? idMatch[1] : undefined; if (!document.body) { return; } host.onMessage('styles', (_event, data) => { initData.styles = data.styles; initData.activeTheme = data.activeTheme; initData.themeName = data.themeName; const target = getActiveFrame(); if (!target) { return; } if (target.contentDocument) { applyStyles(target.contentDocument, target.contentDocument.body); } }); // propagate focus host.onMessage('focus', () => { const target = getActiveFrame(); if (target) { target.contentWindow.focus(); } }); // update iframe-contents let updateId = 0; host.onMessage('content', async (_event, data) => { const currentUpdateId = ++updateId; await host.ready; if (currentUpdateId !== updateId) { return; } const options = data.options; const newDocument = toContentHtml(data); const frame = getActiveFrame(); const wasFirstLoad = firstLoad; // keep current scrollY around and use later let setInitialScrollPosition; if (firstLoad) { firstLoad = false; setInitialScrollPosition = (body, window) => { if (!isNaN(initData.initialScrollProgress)) { if (window.scrollY === 0) { window.scroll(0, body.clientHeight * initData.initialScrollProgress); } } }; } else { const scrollY = frame && frame.contentDocument && frame.contentDocument.body ? frame.contentWindow.scrollY : 0; setInitialScrollPosition = (body, window) => { if (window.scrollY === 0) { window.scroll(0, scrollY); } }; } // Clean up old pending frames and set current one as new one const previousPendingFrame = getPendingFrame(); if (previousPendingFrame) { previousPendingFrame.setAttribute('id', ''); document.body.removeChild(previousPendingFrame); } if (!wasFirstLoad) { pendingMessages = []; } const newFrame = document.createElement('iframe'); newFrame.setAttribute('id', 'pending-frame'); newFrame.setAttribute('frameborder', '0'); newFrame.setAttribute('sandbox', options.allowScripts ? 'allow-scripts allow-forms allow-same-origin allow-pointer-lock allow-downloads' : 'allow-same-origin allow-pointer-lock'); if (host.fakeLoad) { // We should just be able to use srcdoc, but I wasn't // seeing the service worker applying properly. // Fake load an empty on the correct origin and then write real html // into it to get around this. newFrame.src = `./fake.html?id=${ID}`; } newFrame.style.cssText = 'display: block; margin: 0; overflow: hidden; position: absolute; width: 100%; height: 100%; visibility: hidden'; document.body.appendChild(newFrame); if (!host.fakeLoad) { // write new content onto iframe newFrame.contentDocument.open(); } /** * @param {Document} contentDocument */ function onFrameLoaded(contentDocument) { // Workaround for https://bugs.chromium.org/p/chromium/issues/detail?id=978325 setTimeout(() => { if (host.fakeLoad) { contentDocument.open(); contentDocument.write(newDocument); contentDocument.close(); hookupOnLoadHandlers(newFrame); } if (contentDocument) { applyStyles(contentDocument, contentDocument.body); } }, 0); } if (host.fakeLoad && !options.allowScripts && isSafari) { // On Safari for iframes with scripts disabled, the `DOMContentLoaded` never seems to be fired. // Use polling instead. const interval = setInterval(() => { // If the frame is no longer mounted, loading has stopped if (!newFrame.parentElement) { clearInterval(interval); return; } if (newFrame.contentDocument.readyState !== 'loading') { clearInterval(interval); onFrameLoaded(newFrame.contentDocument); } }, 10); } else { newFrame.contentWindow.addEventListener('DOMContentLoaded', e => { const contentDocument = e.target ? (/** @type {HTMLDocument} */ (e.target)) : undefined; onFrameLoaded(contentDocument); }); } /** * @param {Document} contentDocument * @param {Window} contentWindow */ const onLoad = (contentDocument, contentWindow) => { if (contentDocument && contentDocument.body) { // Workaround for https://github.com/microsoft/vscode/issues/12865 // check new scrollY and reset if necessary setInitialScrollPosition(contentDocument.body, contentWindow); } const newFrame = getPendingFrame(); if (newFrame && newFrame.contentDocument && newFrame.contentDocument === contentDocument) { const oldActiveFrame = getActiveFrame(); if (oldActiveFrame) { document.body.removeChild(oldActiveFrame); } // Styles may have changed since we created the element. Make sure we re-style applyStyles(newFrame.contentDocument, newFrame.contentDocument.body); newFrame.setAttribute('id', 'active-frame'); newFrame.style.visibility = 'visible'; if (host.focusIframeOnCreate) { newFrame.contentWindow.focus(); } contentWindow.addEventListener('scroll', handleInnerScroll); contentWindow.addEventListener('wheel', handleWheel); pendingMessages.forEach((data) => { contentWindow.postMessage(data, '*'); }); pendingMessages = []; } host.postMessage('did-load'); }; /** * @param {HTMLIFrameElement} newFrame */ function hookupOnLoadHandlers(newFrame) { clearTimeout(loadTimeout); loadTimeout = undefined; loadTimeout = setTimeout(() => { clearTimeout(loadTimeout); loadTimeout = undefined; onLoad(newFrame.contentDocument, newFrame.contentWindow); }, 200); newFrame.contentWindow.addEventListener('load', function (e) { const contentDocument = /** @type {Document} */ (e.target); if (loadTimeout) { clearTimeout(loadTimeout); loadTimeout = undefined; onLoad(contentDocument, this); } }); // Bubble out various events newFrame.contentWindow.addEventListener('click', handleInnerClick); newFrame.contentWindow.addEventListener('auxclick', handleAuxClick); newFrame.contentWindow.addEventListener('keydown', handleInnerKeydown); newFrame.contentWindow.addEventListener('contextmenu', e => e.preventDefault()); if (host.onIframeLoaded) { host.onIframeLoaded(newFrame); } } if (!host.fakeLoad) { hookupOnLoadHandlers(newFrame); } if (!host.fakeLoad) { newFrame.contentDocument.write(newDocument); newFrame.contentDocument.close(); } host.postMessage('did-set-content', undefined); }); // Forward message to the embedded iframe host.onMessage('message', (_event, data) => { const pending = getPendingFrame(); if (!pending) { const target = getActiveFrame(); if (target) { target.contentWindow.postMessage(data, '*'); return; } } pendingMessages.push(data); }); host.onMessage('initial-scroll-position', (_event, progress) => { initData.initialScrollProgress = progress; }); host.onMessage('execCommand', (_event, data) => { const target = getActiveFrame(); if (!target) { return; } target.contentDocument.execCommand(data); }); trackFocus({ onFocus: () => host.postMessage('did-focus'), onBlur: () => host.postMessage('did-blur') }); // signal ready host.postMessage('webview-ready', {}); }); } if (typeof module !== 'undefined') { module.exports = createWebviewManager; } else { (/** @type {any} */ (window)).createWebviewManager = createWebviewManager; } }());
src/vs/workbench/contrib/webview/browser/pre/main.js
0
https://github.com/microsoft/vscode/commit/574ee2032cc24ed250ef15962ce100838d4e5e4a
[ 0.00017870510055217892, 0.00017204154573846608, 0.00016304751625284553, 0.00017215550178661942, 0.0000025463914425927214 ]
{ "id": 4, "code_window": [ "import { URI } from 'vs/base/common/uri';\n", "import { TERMINAL_BACKGROUND_COLOR, TERMINAL_BORDER_COLOR } from 'vs/workbench/contrib/terminal/common/terminalColorRegistry';\n", "import { DataTransfers } from 'vs/base/browser/dnd';\n", "import { INotificationService, IPromptChoice, Severity } from 'vs/platform/notification/common/notification';\n", "import { ITerminalService } from 'vs/workbench/contrib/terminal/browser/terminal';\n", "import { BrowserFeatures } from 'vs/base/browser/canIUse';\n", "import { ViewPane, IViewPaneOptions } from 'vs/workbench/browser/parts/views/viewPaneContainer';\n", "import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';\n", "import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey';\n", "import { IViewDescriptorService } from 'vs/workbench/common/views';\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { ITerminalService, TerminalConnectionState } from 'vs/workbench/contrib/terminal/browser/terminal';\n" ], "file_path": "src/vs/workbench/contrib/terminal/browser/terminalView.ts", "type": "replace", "edit_start_line_idx": 21 }
{ "name": "Ignore", "scopeName": "source.ignore", "patterns": [ { "match": "^#.*", "name": "comment.line.number-sign.ignore" } ] }
extensions/git/syntaxes/ignore.tmLanguage.json
0
https://github.com/microsoft/vscode/commit/574ee2032cc24ed250ef15962ce100838d4e5e4a
[ 0.0001730406511342153, 0.00017045706044882536, 0.00016787348431535065, 0.00017045706044882536, 0.0000025835834094323218 ]
{ "id": 5, "code_window": [ "\t\t\t}\n", "\t\t\tthis._onDidChangeViewWelcomeState.fire();\n", "\t\t});\n", "\n", "\t\tthis._register(this.onDidBlur(() => {\n", "\t\t\tthis._terminalService.willFocusNewTerminal = false;\n", "\t\t}));\n", "\t}\n", "\n", "\tprotected renderBody(container: HTMLElement): void {\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/contrib/terminal/browser/terminalView.ts", "type": "replace", "edit_start_line_idx": 69 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as dom from 'vs/base/browser/dom'; import * as nls from 'vs/nls'; import * as platform from 'vs/base/common/platform'; import { Action, IAction, Separator, IActionViewItem } from 'vs/base/common/actions'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IContextMenuService } from 'vs/platform/contextview/browser/contextView'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IThemeService, IColorTheme, registerThemingParticipant, ICssStyleCollector } from 'vs/platform/theme/common/themeService'; import { TerminalFindWidget } from 'vs/workbench/contrib/terminal/browser/terminalFindWidget'; import { KillTerminalAction, SwitchTerminalAction, SwitchTerminalActionViewItem, CopyTerminalSelectionAction, TerminalPasteAction, ClearTerminalAction, SelectAllTerminalAction, CreateNewTerminalAction, SplitTerminalAction } from 'vs/workbench/contrib/terminal/browser/terminalActions'; import { StandardMouseEvent } from 'vs/base/browser/mouseEvent'; import { URI } from 'vs/base/common/uri'; import { TERMINAL_BACKGROUND_COLOR, TERMINAL_BORDER_COLOR } from 'vs/workbench/contrib/terminal/common/terminalColorRegistry'; import { DataTransfers } from 'vs/base/browser/dnd'; import { INotificationService, IPromptChoice, Severity } from 'vs/platform/notification/common/notification'; import { ITerminalService } from 'vs/workbench/contrib/terminal/browser/terminal'; import { BrowserFeatures } from 'vs/base/browser/canIUse'; import { ViewPane, IViewPaneOptions } from 'vs/workbench/browser/parts/views/viewPaneContainer'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { IViewDescriptorService } from 'vs/workbench/common/views'; import { IOpenerService } from 'vs/platform/opener/common/opener'; import { PANEL_BACKGROUND, SIDE_BAR_BACKGROUND } from 'vs/workbench/common/theme'; import { Orientation } from 'vs/base/browser/ui/sash/sash'; const FIND_FOCUS_CLASS = 'find-focused'; export class TerminalViewPane extends ViewPane { private _actions: IAction[] | undefined; private _copyContextMenuAction: IAction | undefined; private _contextMenuActions: IAction[] | undefined; private _cancelContextMenu: boolean = false; private _fontStyleElement: HTMLElement | undefined; private _parentDomElement: HTMLElement | undefined; private _terminalContainer: HTMLElement | undefined; private _findWidget: TerminalFindWidget | undefined; private _splitTerminalAction: IAction | undefined; private _terminalsInitialized = false; private _bodyDimensions: { width: number, height: number } = { width: 0, height: 0 }; constructor( options: IViewPaneOptions, @IKeybindingService keybindingService: IKeybindingService, @IContextKeyService contextKeyService: IContextKeyService, @IViewDescriptorService viewDescriptorService: IViewDescriptorService, @IConfigurationService configurationService: IConfigurationService, @IContextMenuService private readonly _contextMenuService: IContextMenuService, @IInstantiationService private readonly _instantiationService: IInstantiationService, @ITerminalService private readonly _terminalService: ITerminalService, @IThemeService protected readonly themeService: IThemeService, @ITelemetryService telemetryService: ITelemetryService, @INotificationService private readonly _notificationService: INotificationService, @IOpenerService openerService: IOpenerService, ) { super(options, keybindingService, _contextMenuService, configurationService, contextKeyService, viewDescriptorService, _instantiationService, openerService, themeService, telemetryService); this._terminalService.onDidRegisterProcessSupport(() => { if (this._actions) { for (const action of this._actions) { action.enabled = true; } } this._onDidChangeViewWelcomeState.fire(); }); this._register(this.onDidBlur(() => { this._terminalService.willFocusNewTerminal = false; })); } protected renderBody(container: HTMLElement): void { super.renderBody(container); if (this.shouldShowWelcome()) { return; } this._parentDomElement = container; this._parentDomElement.classList.add('integrated-terminal'); this._fontStyleElement = document.createElement('style'); this._terminalContainer = document.createElement('div'); this._terminalContainer.classList.add('terminal-outer-container'); this._findWidget = this._instantiationService.createInstance(TerminalFindWidget, this._terminalService.getFindState()); this._findWidget.focusTracker.onDidFocus(() => this._terminalContainer!.classList.add(FIND_FOCUS_CLASS)); this._parentDomElement.appendChild(this._fontStyleElement); this._parentDomElement.appendChild(this._terminalContainer); this._parentDomElement.appendChild(this._findWidget.getDomNode()); this._attachEventListeners(this._parentDomElement, this._terminalContainer); this._terminalService.setContainers(container, this._terminalContainer); this._register(this.themeService.onDidColorThemeChange(theme => this._updateTheme(theme))); this._register(this.configurationService.onDidChangeConfiguration(e => { if (e.affectsConfiguration('terminal.integrated.fontFamily') || e.affectsConfiguration('editor.fontFamily')) { const configHelper = this._terminalService.configHelper; if (!configHelper.configFontIsMonospace()) { const choices: IPromptChoice[] = [{ label: nls.localize('terminal.useMonospace', "Use 'monospace'"), run: () => this.configurationService.updateValue('terminal.integrated.fontFamily', 'monospace'), }]; this._notificationService.prompt(Severity.Warning, nls.localize('terminal.monospaceOnly', "The terminal only supports monospace fonts. Be sure to restart VS Code if this is a newly installed font."), choices); } } })); this._updateTheme(); this._register(this.onDidChangeBodyVisibility(visible => { if (visible) { const hadTerminals = !!this._terminalService.terminalTabs.length; if (this._terminalsInitialized) { if (!hadTerminals) { this._terminalService.createTerminal(); } } else { this._terminalsInitialized = true; this._terminalService.initializeTerminals(); } this._updateTheme(); if (hadTerminals) { this._terminalService.getActiveTab()?.setVisible(visible); } else { // TODO@Tyriar - this call seems unnecessary this.layoutBody(this._bodyDimensions.height, this._bodyDimensions.width); } } else { this._terminalService.getActiveTab()?.setVisible(false); } })); // Force another layout (first is setContainers) since config has changed this.layoutBody(this._terminalContainer.offsetHeight, this._terminalContainer.offsetWidth); } protected layoutBody(height: number, width: number): void { super.layoutBody(height, width); if (this.shouldShowWelcome()) { return; } this._bodyDimensions.width = width; this._bodyDimensions.height = height; this._terminalService.terminalTabs.forEach(t => t.layout(width, height)); // Update orientation of split button icon if (this._splitTerminalAction) { this._splitTerminalAction.class = this.orientation === Orientation.HORIZONTAL ? SplitTerminalAction.HORIZONTAL_CLASS : SplitTerminalAction.VERTICAL_CLASS; } } public getActions(): IAction[] { if (!this._actions) { this._splitTerminalAction = this._instantiationService.createInstance(SplitTerminalAction, SplitTerminalAction.ID, SplitTerminalAction.LABEL); this._actions = [ this._instantiationService.createInstance(SwitchTerminalAction, SwitchTerminalAction.ID, SwitchTerminalAction.LABEL), this._instantiationService.createInstance(CreateNewTerminalAction, CreateNewTerminalAction.ID, CreateNewTerminalAction.SHORT_LABEL), this._splitTerminalAction, this._instantiationService.createInstance(KillTerminalAction, KillTerminalAction.ID, KillTerminalAction.PANEL_LABEL) ]; for (const action of this._actions) { if (!this._terminalService.isProcessSupportRegistered) { action.enabled = false; } this._register(action); } } return this._actions; } private _getContextMenuActions(): IAction[] { if (!this._contextMenuActions || !this._copyContextMenuAction) { this._copyContextMenuAction = this._instantiationService.createInstance(CopyTerminalSelectionAction, CopyTerminalSelectionAction.ID, CopyTerminalSelectionAction.SHORT_LABEL); const clipboardActions = []; if (BrowserFeatures.clipboard.writeText) { clipboardActions.push(this._copyContextMenuAction); } if (BrowserFeatures.clipboard.readText) { clipboardActions.push(this._instantiationService.createInstance(TerminalPasteAction, TerminalPasteAction.ID, TerminalPasteAction.SHORT_LABEL)); } clipboardActions.push(this._instantiationService.createInstance(SelectAllTerminalAction, SelectAllTerminalAction.ID, SelectAllTerminalAction.LABEL)); this._contextMenuActions = [ this._instantiationService.createInstance(CreateNewTerminalAction, CreateNewTerminalAction.ID, CreateNewTerminalAction.SHORT_LABEL), this._instantiationService.createInstance(SplitTerminalAction, SplitTerminalAction.ID, SplitTerminalAction.SHORT_LABEL), new Separator(), ...clipboardActions, new Separator(), this._instantiationService.createInstance(ClearTerminalAction, ClearTerminalAction.ID, ClearTerminalAction.LABEL), new Separator(), this._instantiationService.createInstance(KillTerminalAction, KillTerminalAction.ID, KillTerminalAction.PANEL_LABEL) ]; this._contextMenuActions.forEach(a => { this._register(a); }); } const activeInstance = this._terminalService.getActiveInstance(); this._copyContextMenuAction.enabled = !!activeInstance && activeInstance.hasSelection(); return this._contextMenuActions; } public getActionViewItem(action: Action): IActionViewItem | undefined { if (action.id === SwitchTerminalAction.ID) { return this._instantiationService.createInstance(SwitchTerminalActionViewItem, action); } return super.getActionViewItem(action); } public focus() { if (this._terminalService.getActiveInstance()) { this._terminalService.getActiveInstance()?.focusWhenReady(); } else { this._terminalService.willFocusNewTerminal = true; } } public focusFindWidget() { const activeInstance = this._terminalService.getActiveInstance(); if (activeInstance && activeInstance.hasSelection() && activeInstance.selection!.indexOf('\n') === -1) { this._findWidget!.reveal(activeInstance.selection); } else { this._findWidget!.reveal(); } } public hideFindWidget() { this._findWidget!.hide(); } public showFindWidget() { const activeInstance = this._terminalService.getActiveInstance(); if (activeInstance && activeInstance.hasSelection() && activeInstance.selection!.indexOf('\n') === -1) { this._findWidget!.show(activeInstance.selection); } else { this._findWidget!.show(); } } public getFindWidget(): TerminalFindWidget { return this._findWidget!; } private _attachEventListeners(parentDomElement: HTMLElement, terminalContainer: HTMLElement): void { this._register(dom.addDisposableListener(parentDomElement, 'mousedown', async (event: MouseEvent) => { if (this._terminalService.terminalInstances.length === 0) { return; } if (event.which === 2 && platform.isLinux) { // Drop selection and focus terminal on Linux to enable middle button paste when click // occurs on the selection itself. const terminal = this._terminalService.getActiveInstance(); if (terminal) { terminal.focus(); } } else if (event.which === 3) { const rightClickBehavior = this._terminalService.configHelper.config.rightClickBehavior; if (rightClickBehavior === 'copyPaste' || rightClickBehavior === 'paste') { const terminal = this._terminalService.getActiveInstance(); if (!terminal) { return; } // copyPaste: Shift+right click should open context menu if (rightClickBehavior === 'copyPaste' && event.shiftKey) { this._openContextMenu(event); return; } if (rightClickBehavior === 'copyPaste' && terminal.hasSelection()) { await terminal.copySelection(); terminal.clearSelection(); } else { terminal.paste(); } // Clear selection after all click event bubbling is finished on Mac to prevent // right-click selecting a word which is seemed cannot be disabled. There is a // flicker when pasting but this appears to give the best experience if the // setting is enabled. if (platform.isMacintosh) { setTimeout(() => { terminal.clearSelection(); }, 0); } this._cancelContextMenu = true; } } })); this._register(dom.addDisposableListener(parentDomElement, 'contextmenu', (event: MouseEvent) => { if (!this._cancelContextMenu) { this._openContextMenu(event); } event.preventDefault(); event.stopImmediatePropagation(); this._cancelContextMenu = false; })); this._register(dom.addDisposableListener(document, 'keydown', (event: KeyboardEvent) => { terminalContainer.classList.toggle('alt-active', !!event.altKey); })); this._register(dom.addDisposableListener(document, 'keyup', (event: KeyboardEvent) => { terminalContainer.classList.toggle('alt-active', !!event.altKey); })); this._register(dom.addDisposableListener(parentDomElement, 'keyup', (event: KeyboardEvent) => { if (event.keyCode === 27) { // Keep terminal open on escape event.stopPropagation(); } })); this._register(dom.addDisposableListener(parentDomElement, dom.EventType.DROP, async (e: DragEvent) => { if (e.target === this._parentDomElement || dom.isAncestor(e.target as HTMLElement, parentDomElement)) { if (!e.dataTransfer) { return; } // Check if files were dragged from the tree explorer let path: string | undefined; const resources = e.dataTransfer.getData(DataTransfers.RESOURCES); if (resources) { path = URI.parse(JSON.parse(resources)[0]).fsPath; } else if (e.dataTransfer.files.length > 0 && e.dataTransfer.files[0].path /* Electron only */) { // Check if the file was dragged from the filesystem path = URI.file(e.dataTransfer.files[0].path).fsPath; } if (!path) { return; } const terminal = this._terminalService.getActiveInstance(); if (terminal) { const preparedPath = await this._terminalService.preparePathForTerminalAsync(path, terminal.shellLaunchConfig.executable, terminal.title, terminal.shellType); terminal.sendText(preparedPath, false); terminal.focus(); } } })); } private _openContextMenu(event: MouseEvent): void { const standardEvent = new StandardMouseEvent(event); const anchor: { x: number, y: number } = { x: standardEvent.posx, y: standardEvent.posy }; this._contextMenuService.showContextMenu({ getAnchor: () => anchor, getActions: () => this._getContextMenuActions(), getActionsContext: () => this._parentDomElement }); } private _updateTheme(theme?: IColorTheme): void { if (!theme) { theme = this.themeService.getColorTheme(); } this._findWidget?.updateTheme(theme); } shouldShowWelcome(): boolean { return !this._terminalService.isProcessSupportRegistered; } } registerThemingParticipant((theme: IColorTheme, collector: ICssStyleCollector) => { const panelBackgroundColor = theme.getColor(TERMINAL_BACKGROUND_COLOR) || theme.getColor(PANEL_BACKGROUND); collector.addRule(`.monaco-workbench .part.panel .pane-body.integrated-terminal .terminal-outer-container { background-color: ${panelBackgroundColor ? panelBackgroundColor.toString() : ''}; }`); const sidebarBackgroundColor = theme.getColor(TERMINAL_BACKGROUND_COLOR) || theme.getColor(SIDE_BAR_BACKGROUND); collector.addRule(`.monaco-workbench .part.sidebar .pane-body.integrated-terminal .terminal-outer-container { background-color: ${sidebarBackgroundColor ? sidebarBackgroundColor.toString() : ''}; }`); const borderColor = theme.getColor(TERMINAL_BORDER_COLOR); if (borderColor) { collector.addRule(`.monaco-workbench .pane-body.integrated-terminal .split-view-view:not(:first-child) { border-color: ${borderColor.toString()}; }`); } });
src/vs/workbench/contrib/terminal/browser/terminalView.ts
1
https://github.com/microsoft/vscode/commit/574ee2032cc24ed250ef15962ce100838d4e5e4a
[ 0.9986922144889832, 0.08130718022584915, 0.00016212662740144879, 0.0004007191746495664, 0.26355352997779846 ]
{ "id": 5, "code_window": [ "\t\t\t}\n", "\t\t\tthis._onDidChangeViewWelcomeState.fire();\n", "\t\t});\n", "\n", "\t\tthis._register(this.onDidBlur(() => {\n", "\t\t\tthis._terminalService.willFocusNewTerminal = false;\n", "\t\t}));\n", "\t}\n", "\n", "\tprotected renderBody(container: HTMLElement): void {\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/contrib/terminal/browser/terminalView.ts", "type": "replace", "edit_start_line_idx": 69 }
{ "allowTrailingCommas": true, "title": "JSON schema for the TypeScript compiler's configuration file", "type": "object", "default": { "compilerOptions": { "module": "commonjs" }, "exclude": [ "node_modules" ] } }
extensions/typescript-language-features/schemas/tsconfig.schema.json
0
https://github.com/microsoft/vscode/commit/574ee2032cc24ed250ef15962ce100838d4e5e4a
[ 0.00017900680541060865, 0.0001757922291290015, 0.00017257765284739435, 0.0001757922291290015, 0.000003214576281607151 ]
{ "id": 5, "code_window": [ "\t\t\t}\n", "\t\t\tthis._onDidChangeViewWelcomeState.fire();\n", "\t\t});\n", "\n", "\t\tthis._register(this.onDidBlur(() => {\n", "\t\t\tthis._terminalService.willFocusNewTerminal = false;\n", "\t\t}));\n", "\t}\n", "\n", "\tprotected renderBody(container: HTMLElement): void {\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/contrib/terminal/browser/terminalView.ts", "type": "replace", "edit_start_line_idx": 69 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { RawContextKey, IContextKeyService, IContextKey } from 'vs/platform/contextkey/common/contextkey'; import { IDisposable, Disposable } from 'vs/base/common/lifecycle'; import { ICodeEditor } from 'vs/editor/browser/editorBrowser'; import { EditorOption } from 'vs/editor/common/config/editorOptions'; export class WordContextKey extends Disposable { static readonly AtEnd = new RawContextKey<boolean>('atEndOfWord', false); private readonly _ckAtEnd: IContextKey<boolean>; private _enabled: boolean = false; private _selectionListener?: IDisposable; constructor( private readonly _editor: ICodeEditor, @IContextKeyService contextKeyService: IContextKeyService, ) { super(); this._ckAtEnd = WordContextKey.AtEnd.bindTo(contextKeyService); this._register(this._editor.onDidChangeConfiguration(e => e.hasChanged(EditorOption.tabCompletion) && this._update())); this._update(); } dispose(): void { super.dispose(); this._selectionListener?.dispose(); this._ckAtEnd.reset(); } private _update(): void { // only update this when tab completions are enabled const enabled = this._editor.getOption(EditorOption.tabCompletion) === 'on'; if (this._enabled === enabled) { return; } this._enabled = enabled; if (this._enabled) { const checkForWordEnd = () => { if (!this._editor.hasModel()) { this._ckAtEnd.set(false); return; } const model = this._editor.getModel(); const selection = this._editor.getSelection(); const word = model.getWordAtPosition(selection.getStartPosition()); if (!word) { this._ckAtEnd.set(false); return; } this._ckAtEnd.set(word.endColumn === selection.getStartPosition().column); }; this._selectionListener = this._editor.onDidChangeCursorSelection(checkForWordEnd); checkForWordEnd(); } else if (this._selectionListener) { this._ckAtEnd.reset(); this._selectionListener.dispose(); this._selectionListener = undefined; } } }
src/vs/editor/contrib/suggest/wordContextKey.ts
0
https://github.com/microsoft/vscode/commit/574ee2032cc24ed250ef15962ce100838d4e5e4a
[ 0.00020064513955730945, 0.00017578985716681927, 0.0001665218878770247, 0.000170726198120974, 0.000010859367648663465 ]
{ "id": 5, "code_window": [ "\t\t\t}\n", "\t\t\tthis._onDidChangeViewWelcomeState.fire();\n", "\t\t});\n", "\n", "\t\tthis._register(this.onDidBlur(() => {\n", "\t\t\tthis._terminalService.willFocusNewTerminal = false;\n", "\t\t}));\n", "\t}\n", "\n", "\tprotected renderBody(container: HTMLElement): void {\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/contrib/terminal/browser/terminalView.ts", "type": "replace", "edit_start_line_idx": 69 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as vscode from 'vscode'; import { smokeTestActivate } from './notebookSmokeTestMain'; export function activate(context: vscode.ExtensionContext): any { smokeTestActivate(context); const _onDidChangeNotebook = new vscode.EventEmitter<vscode.NotebookDocumentEditEvent | vscode.NotebookDocumentContentChangeEvent>(); context.subscriptions.push(_onDidChangeNotebook); context.subscriptions.push(vscode.notebook.registerNotebookContentProvider('notebookCoreTest', { onDidChangeNotebook: _onDidChangeNotebook.event, openNotebook: async (_resource: vscode.Uri) => { if (/.*empty\-.*\.vsctestnb$/.test(_resource.path)) { return { languages: ['typescript'], metadata: {}, cells: [] }; } const dto: vscode.NotebookData = { languages: ['typescript'], metadata: { custom: { testMetadata: false } }, cells: [ { source: 'test', language: 'typescript', cellKind: vscode.CellKind.Code, outputs: [], metadata: { custom: { testCellMetadata: 123 } } } ] }; return dto; }, resolveNotebook: async (_document: vscode.NotebookDocument) => { return; }, saveNotebook: async (_document: vscode.NotebookDocument, _cancellation: vscode.CancellationToken) => { return; }, saveNotebookAs: async (_targetResource: vscode.Uri, _document: vscode.NotebookDocument, _cancellation: vscode.CancellationToken) => { return; }, backupNotebook: async (_document: vscode.NotebookDocument, _context: vscode.NotebookDocumentBackupContext, _cancellation: vscode.CancellationToken) => { return { id: '1', delete: () => { } }; } })); const kernel: vscode.NotebookKernel = { label: 'Notebook Test Kernel', isPreferred: true, executeAllCells: async (_document: vscode.NotebookDocument) => { const cell = _document.cells[0]; cell.outputs = [{ outputKind: vscode.CellOutputKind.Rich, data: { 'text/plain': ['my output'] } }]; return; }, cancelAllCellsExecution: async (_document: vscode.NotebookDocument) => { }, executeCell: async (document: vscode.NotebookDocument, cell: vscode.NotebookCell | undefined) => { if (!cell) { cell = document.cells[0]; } if (document.uri.path.endsWith('customRenderer.vsctestnb')) { cell.outputs = [{ outputKind: vscode.CellOutputKind.Rich, data: { 'text/custom': 'test' } }]; return; } const previousOutputs = cell.outputs; const newOutputs: vscode.CellOutput[] = [{ outputKind: vscode.CellOutputKind.Rich, data: { 'text/plain': ['my output'] } }]; cell.outputs = newOutputs; _onDidChangeNotebook.fire({ document: document, undo: () => { if (cell) { cell.outputs = previousOutputs; } }, redo: () => { if (cell) { cell.outputs = newOutputs; } } }); return; }, cancelCellExecution: async (_document: vscode.NotebookDocument, _cell: vscode.NotebookCell) => { } }; context.subscriptions.push(vscode.notebook.registerNotebookKernelProvider({ filenamePattern: '*.vsctestnb' }, { provideKernels: async () => { return [kernel]; } })); }
extensions/vscode-notebook-tests/src/notebookTestMain.ts
0
https://github.com/microsoft/vscode/commit/574ee2032cc24ed250ef15962ce100838d4e5e4a
[ 0.00018701564113143831, 0.00017526233568787575, 0.00016784259059932083, 0.00017452835163567215, 0.000004235725555190584 ]
{ "id": 6, "code_window": [ "\n", "\t\treturn super.getActionViewItem(action);\n", "\t}\n", "\n", "\tpublic focus() {\n", "\t\tif (this._terminalService.getActiveInstance()) {\n", "\t\t\tthis._terminalService.getActiveInstance()?.focusWhenReady();\n", "\t\t} else {\n", "\t\t\tthis._terminalService.willFocusNewTerminal = true;\n", "\t\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep" ], "after_edit": [ "\t\tif (this._terminalService.connectionState === TerminalConnectionState.Connecting) {\n", "\t\t\tconst activeElement = document.activeElement;\n", "\t\t\t// Note that focus may be shifted unexpected here if this is called, then editor is focused manually, then connection happens\n", "\t\t\t// Could verify document.activeElement is the same to avoid that?\n", "\t\t\tthis._register(this._terminalService.onDidChangeConnectionState(() => {\n", "\t\t\t\tif (document.activeElement === activeElement) {\n", "\t\t\t\t\t// Only focus the terminal if the activeElement has not changed since focus() was called\n", "\t\t\t\t\tthis._focus();\n", "\t\t\t\t}\n", "\t\t\t}));\n", "\n", "\t\t\treturn;\n" ], "file_path": "src/vs/workbench/contrib/terminal/browser/terminalView.ts", "type": "replace", "edit_start_line_idx": 219 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import type { Terminal as XTermTerminal } from 'xterm'; import type { SearchAddon as XTermSearchAddon } from 'xterm-addon-search'; import type { Unicode11Addon as XTermUnicode11Addon } from 'xterm-addon-unicode11'; import type { WebglAddon as XTermWebglAddon } from 'xterm-addon-webgl'; import { IWindowsShellHelper, ITerminalConfigHelper, ITerminalChildProcess, IShellLaunchConfig, IDefaultShellAndArgsRequest, ISpawnExtHostProcessRequest, IStartExtensionTerminalRequest, IAvailableShellsRequest, ITerminalProcessExtHostProxy, ICommandTracker, INavigationMode, TitleEventSource, ITerminalDimensions, ITerminalLaunchError, ITerminalNativeWindowsDelegate, LinuxDistro, IRemoteTerminalAttachTarget } from 'vs/workbench/contrib/terminal/common/terminal'; import { createDecorator } from 'vs/platform/instantiation/common/instantiation'; import { IProcessEnvironment, Platform } from 'vs/base/common/platform'; import { Event } from 'vs/base/common/event'; import { IDisposable } from 'vs/base/common/lifecycle'; import { FindReplaceState } from 'vs/editor/contrib/find/findState'; import { URI } from 'vs/base/common/uri'; export const ITerminalService = createDecorator<ITerminalService>('terminalService'); export const ITerminalInstanceService = createDecorator<ITerminalInstanceService>('terminalInstanceService'); export const IRemoteTerminalService = createDecorator<IRemoteTerminalService>('remoteTerminalService'); /** * A service used by TerminalInstance (and components owned by it) that allows it to break its * dependency on electron-browser and node layers, while at the same time avoiding a cyclic * dependency on ITerminalService. */ export interface ITerminalInstanceService { readonly _serviceBrand: undefined; // These events are optional as the requests they make are only needed on the browser side onRequestDefaultShellAndArgs?: Event<IDefaultShellAndArgsRequest>; getXtermConstructor(): Promise<typeof XTermTerminal>; getXtermSearchConstructor(): Promise<typeof XTermSearchAddon>; getXtermUnicode11Constructor(): Promise<typeof XTermUnicode11Addon>; getXtermWebglConstructor(): Promise<typeof XTermWebglAddon>; createWindowsShellHelper(shellProcessId: number, xterm: XTermTerminal): IWindowsShellHelper; createTerminalProcess(shellLaunchConfig: IShellLaunchConfig, cwd: string, cols: number, rows: number, env: IProcessEnvironment, windowsEnableConpty: boolean): ITerminalChildProcess; getDefaultShellAndArgs(useAutomationShell: boolean, platformOverride?: Platform): Promise<{ shell: string, args: string[] | string | undefined }>; getMainProcessParentEnv(): Promise<IProcessEnvironment>; } export interface IBrowserTerminalConfigHelper extends ITerminalConfigHelper { panelContainer: HTMLElement | undefined; } export const enum Direction { Left = 0, Right = 1, Up = 2, Down = 3 } export interface ITerminalTab { activeInstance: ITerminalInstance | null; terminalInstances: ITerminalInstance[]; title: string; onDisposed: Event<ITerminalTab>; onInstancesChanged: Event<void>; focusPreviousPane(): void; focusNextPane(): void; resizePane(direction: Direction): void; setActiveInstanceByIndex(index: number): void; attachToElement(element: HTMLElement): void; setVisible(visible: boolean): void; layout(width: number, height: number): void; addDisposable(disposable: IDisposable): void; split(shellLaunchConfig: IShellLaunchConfig): ITerminalInstance; } export const enum TerminalConnectionState { Connecting, Connected } export interface ITerminalService { readonly _serviceBrand: undefined; activeTabIndex: number; configHelper: ITerminalConfigHelper; terminalInstances: ITerminalInstance[]; terminalTabs: ITerminalTab[]; isProcessSupportRegistered: boolean; willFocusNewTerminal: boolean; readonly connectionState: TerminalConnectionState; initializeTerminals(): Promise<void>; onActiveTabChanged: Event<void>; onTabDisposed: Event<ITerminalTab>; onInstanceCreated: Event<ITerminalInstance>; onInstanceDisposed: Event<ITerminalInstance>; onInstanceProcessIdReady: Event<ITerminalInstance>; onInstanceDimensionsChanged: Event<ITerminalInstance>; onInstanceMaximumDimensionsChanged: Event<ITerminalInstance>; onInstanceRequestSpawnExtHostProcess: Event<ISpawnExtHostProcessRequest>; onInstanceRequestStartExtensionTerminal: Event<IStartExtensionTerminalRequest>; onInstancesChanged: Event<void>; onInstanceTitleChanged: Event<ITerminalInstance | undefined>; onActiveInstanceChanged: Event<ITerminalInstance | undefined>; onRequestAvailableShells: Event<IAvailableShellsRequest>; onDidRegisterProcessSupport: Event<void>; onDidChangeConnectionState: Event<void>; /** * Creates a terminal. * @param shell The shell launch configuration to use. */ createTerminal(shell?: IShellLaunchConfig): ITerminalInstance; /** * Creates a raw terminal instance, this should not be used outside of the terminal part. */ createInstance(container: HTMLElement | undefined, shellLaunchConfig: IShellLaunchConfig): ITerminalInstance; getInstanceFromId(terminalId: number): ITerminalInstance | undefined; getInstanceFromIndex(terminalIndex: number): ITerminalInstance; getTabLabels(): string[]; getActiveInstance(): ITerminalInstance | null; setActiveInstance(terminalInstance: ITerminalInstance): void; setActiveInstanceByIndex(terminalIndex: number): void; getActiveOrCreateInstance(): ITerminalInstance; splitInstance(instance: ITerminalInstance, shell?: IShellLaunchConfig): ITerminalInstance | null; /** * Perform an action with the active terminal instance, if the terminal does * not exist the callback will not be called. * @param callback The callback that fires with the active terminal */ doWithActiveInstance<T>(callback: (terminal: ITerminalInstance) => T): T | void; getActiveTab(): ITerminalTab | null; setActiveTabToNext(): void; setActiveTabToPrevious(): void; setActiveTabByIndex(tabIndex: number): void; /** * Fire the onActiveTabChanged event, this will trigger the terminal dropdown to be updated, * among other things. */ refreshActiveTab(): void; showPanel(focus?: boolean): Promise<void>; hidePanel(): void; focusFindWidget(): Promise<void>; hideFindWidget(): void; getFindState(): FindReplaceState; findNext(): void; findPrevious(): void; registerProcessSupport(isSupported: boolean): void; /** * Registers a link provider that enables integrators to add links to the terminal. * @param linkProvider When registered, the link provider is asked whenever a cell is hovered * for links at that position. This lets the terminal know all links at a given area and also * labels for what these links are going to do. */ registerLinkProvider(linkProvider: ITerminalExternalLinkProvider): IDisposable; selectDefaultShell(): Promise<void>; setContainers(panelContainer: HTMLElement, terminalContainer: HTMLElement): void; manageWorkspaceShellPermissions(): void; /** * Injects native Windows functionality into the service. */ setNativeWindowsDelegate(delegate: ITerminalNativeWindowsDelegate): void; setLinuxDistro(linuxDistro: LinuxDistro): void; /** * Takes a path and returns the properly escaped path to send to the terminal. * On Windows, this included trying to prepare the path for WSL if needed. * * @param executable The executable off the shellLaunchConfig * @param title The terminal's title * @param path The path to be escaped and formatted. * @returns An escaped version of the path to be execuded in the terminal. */ preparePathForTerminalAsync(path: string, executable: string | undefined, title: string, shellType: TerminalShellType): Promise<string>; extHostReady(remoteAuthority: string): void; requestSpawnExtHostProcess(proxy: ITerminalProcessExtHostProxy, shellLaunchConfig: IShellLaunchConfig, activeWorkspaceRootUri: URI | undefined, cols: number, rows: number, isWorkspaceShellAllowed: boolean): Promise<ITerminalLaunchError | undefined>; requestStartExtensionTerminal(proxy: ITerminalProcessExtHostProxy, cols: number, rows: number): Promise<ITerminalLaunchError | undefined>; } export interface IRemoteTerminalService { readonly _serviceBrand: undefined; dispose(): void; listTerminals(): Promise<IRemoteTerminalAttachTarget[]>; createRemoteTerminalProcess(terminalId: number, shellLaunchConfig: IShellLaunchConfig, activeWorkspaceRootUri: URI | undefined, cols: number, rows: number, configHelper: ITerminalConfigHelper,): Promise<ITerminalChildProcess>; } /** * Similar to xterm.js' ILinkProvider but using promises and hides xterm.js internals (like buffer * positions, decorations, etc.) from the rest of vscode. This is the interface to use for * workbench integrations. */ export interface ITerminalExternalLinkProvider { provideLinks(instance: ITerminalInstance, line: string): Promise<ITerminalLink[] | undefined>; } export interface ITerminalLink { /** 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; /** * Activates the link. * @param text The text of the link. */ activate(text: string): void; } export interface ISearchOptions { /** Whether the find should be done as a regex. */ regex?: boolean; /** Whether only whole words should match. */ wholeWord?: boolean; /** Whether find should pay attention to case. */ caseSensitive?: boolean; /** Whether the search should start at the current search position (not the next row). */ incremental?: boolean; } export enum WindowsShellType { CommandPrompt = 'cmd', PowerShell = 'pwsh', Wsl = 'wsl', GitBash = 'gitbash' } export type TerminalShellType = WindowsShellType | undefined; export interface ITerminalBeforeHandleLinkEvent { terminal?: ITerminalInstance; /** The text of the link */ link: string; /** Call with whether the link was handled by the interceptor */ resolve(wasHandled: boolean): void; } export interface ITerminalInstance { /** * The ID of the terminal instance, this is an arbitrary number only used to identify the * terminal instance. */ readonly id: number; readonly cols: number; readonly rows: number; readonly maxCols: number; readonly maxRows: number; /** * The process ID of the shell process, this is undefined when there is no process associated * with this terminal. */ processId: number | undefined; /** * An event that fires when the terminal instance's title changes. */ onTitleChanged: Event<ITerminalInstance>; /** * An event that fires when the terminal instance is disposed. */ onDisposed: Event<ITerminalInstance>; onFocused: Event<ITerminalInstance>; onProcessIdReady: Event<ITerminalInstance>; onLinksReady: Event<ITerminalInstance>; onRequestExtHostProcess: Event<ITerminalInstance>; onDimensionsChanged: Event<void>; onMaximumDimensionsChanged: Event<void>; onFocus: Event<ITerminalInstance>; /** * Attach a listener to the raw data stream coming from the pty, including ANSI escape * sequences. */ onData: Event<string>; /** * Attach a listener to listen for new lines added to this terminal instance. * * @param listener The listener function which takes new line strings added to the terminal, * excluding ANSI escape sequences. The line event will fire when an LF character is added to * the terminal (ie. the line is not wrapped). Note that this means that the line data will * not fire for the last line, until either the line is ended with a LF character of the process * is exited. The lineData string will contain the fully wrapped line, not containing any LF/CR * characters. */ onLineData: Event<string>; /** * Attach a listener that fires when the terminal's pty process exits. The number in the event * is the processes' exit code, an exit code of null means the process was killed as a result of * the ITerminalInstance being disposed. */ onExit: Event<number | undefined>; readonly exitCode: number | undefined; readonly areLinksReady: boolean; /** * Returns an array of data events that have fired within the first 10 seconds. If this is * called 10 seconds after the terminal has existed the result will be undefined. This is useful * when objects that depend on the data events have delayed initialization, like extension * hosts. */ readonly initialDataEvents: string[] | undefined; /** A promise that resolves when the terminal's pty/process have been created. */ processReady: Promise<void>; /** * The title of the terminal. This is either title or the process currently running or an * explicit name given to the terminal instance through the extension API. */ readonly title: string; /** * The shell type of the terminal. */ readonly shellType: TerminalShellType; /** * The focus state of the terminal before exiting. */ readonly hadFocusOnExit: boolean; /** * False when the title is set by an API or the user. We check this to make sure we * do not override the title when the process title changes in the terminal. */ isTitleSetByProcess: boolean; /** * The shell launch config used to launch the shell. */ readonly shellLaunchConfig: IShellLaunchConfig; /** * Whether to disable layout for the terminal. This is useful when the size of the terminal is * being manipulating (e.g. adding a split pane) and we want the terminal to ignore particular * resize events. */ disableLayout: boolean; /** * An object that tracks when commands are run and enables navigating and selecting between * them. */ readonly commandTracker: ICommandTracker | undefined; readonly navigationMode: INavigationMode | undefined; /** * Shows the environment information hover if the widget exists. */ showEnvironmentInfoHover(): void; /** * Dispose the terminal instance, removing it from the panel/service and freeing up resources. * * @param immediate Whether the kill should be immediate or not. Immediate should only be used * when VS Code is shutting down or in cases where the terminal dispose was user initiated. * The immediate===false exists to cover an edge case where the final output of the terminal can * get cut off. If immediate kill any terminal processes immediately. */ dispose(immediate?: boolean): void; /** * Forces the terminal to redraw its viewport. */ forceRedraw(): void; /** * Check if anything is selected in terminal. */ hasSelection(): boolean; /** * Copies the terminal selection to the clipboard. */ copySelection(): Promise<void>; /** * Current selection in the terminal. */ readonly selection: string | undefined; /** * Clear current selection. */ clearSelection(): void; /** * Select all text in the terminal. */ selectAll(): void; /** * Find the next instance of the term */ findNext(term: string, searchOptions: ISearchOptions): boolean; /** * Find the previous instance of the term */ findPrevious(term: string, searchOptions: ISearchOptions): boolean; /** * Notifies the terminal that the find widget's focus state has been changed. */ notifyFindWidgetFocusChanged(isFocused: boolean): void; /** * Focuses the terminal instance if it's able to (xterm.js instance exists). * * @param focus Force focus even if there is a selection. */ focus(force?: boolean): void; /** * Focuses the terminal instance when it's ready (the xterm.js instance is created). Use this * when the terminal is being shown. * * @param focus Force focus even if there is a selection. */ focusWhenReady(force?: boolean): Promise<void>; /** * Focuses and pastes the contents of the clipboard into the terminal instance. */ paste(): Promise<void>; /** * Send text to the terminal instance. The text is written to the stdin of the underlying pty * process (shell) of the terminal instance. * * @param text The text to send. * @param addNewLine Whether to add a new line to the text being sent, this is normally * required to run a command in the terminal. The character(s) added are \n or \r\n * depending on the platform. This defaults to `true`. */ sendText(text: string, addNewLine: boolean): void; /** Scroll the terminal buffer down 1 line. */ scrollDownLine(): void; /** Scroll the terminal buffer down 1 page. */ scrollDownPage(): void; /** Scroll the terminal buffer to the bottom. */ scrollToBottom(): void; /** Scroll the terminal buffer up 1 line. */ scrollUpLine(): void; /** Scroll the terminal buffer up 1 page. */ scrollUpPage(): void; /** Scroll the terminal buffer to the top. */ scrollToTop(): void; /** * Clears the terminal buffer, leaving only the prompt line. */ clear(): void; /** * Attaches the terminal instance to an element on the DOM, before this is called the terminal * instance process may run in the background but cannot be displayed on the UI. * * @param container The element to attach the terminal instance to. */ attachToElement(container: HTMLElement): void; /** * Configure the dimensions of the terminal instance. * * @param dimension The dimensions of the container. */ layout(dimension: { width: number, height: number }): void; /** * Sets whether the terminal instance's element is visible in the DOM. * * @param visible Whether the element is visible. */ setVisible(visible: boolean): void; /** * Immediately kills the terminal's current pty process and launches a new one to replace it. * * @param shell The new launch configuration. */ reuseTerminal(shell: IShellLaunchConfig): void; /** * Relaunches the terminal, killing it and reusing the launch config used initially. Any * environment variable changes will be recalculated when this happens. */ relaunch(): void; /** * Sets the title of the terminal instance. */ setTitle(title: string, eventSource: TitleEventSource): void; /** * Sets the shell type of the terminal instance. */ setShellType(shellType: TerminalShellType): void; waitForTitle(): Promise<string>; setDimensions(dimensions: ITerminalDimensions): void; addDisposable(disposable: IDisposable): void; toggleEscapeSequenceLogging(): void; getInitialCwd(): Promise<string>; getCwd(): Promise<string>; /** * @throws when called before xterm.js is ready. */ registerLinkProvider(provider: ITerminalExternalLinkProvider): IDisposable; }
src/vs/workbench/contrib/terminal/browser/terminal.ts
1
https://github.com/microsoft/vscode/commit/574ee2032cc24ed250ef15962ce100838d4e5e4a
[ 0.9049948453903198, 0.017402449622750282, 0.00016268115723505616, 0.0001758749276632443, 0.12192748486995697 ]
{ "id": 6, "code_window": [ "\n", "\t\treturn super.getActionViewItem(action);\n", "\t}\n", "\n", "\tpublic focus() {\n", "\t\tif (this._terminalService.getActiveInstance()) {\n", "\t\t\tthis._terminalService.getActiveInstance()?.focusWhenReady();\n", "\t\t} else {\n", "\t\t\tthis._terminalService.willFocusNewTerminal = true;\n", "\t\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep" ], "after_edit": [ "\t\tif (this._terminalService.connectionState === TerminalConnectionState.Connecting) {\n", "\t\t\tconst activeElement = document.activeElement;\n", "\t\t\t// Note that focus may be shifted unexpected here if this is called, then editor is focused manually, then connection happens\n", "\t\t\t// Could verify document.activeElement is the same to avoid that?\n", "\t\t\tthis._register(this._terminalService.onDidChangeConnectionState(() => {\n", "\t\t\t\tif (document.activeElement === activeElement) {\n", "\t\t\t\t\t// Only focus the terminal if the activeElement has not changed since focus() was called\n", "\t\t\t\t\tthis._focus();\n", "\t\t\t\t}\n", "\t\t\t}));\n", "\n", "\t\t\treturn;\n" ], "file_path": "src/vs/workbench/contrib/terminal/browser/terminalView.ts", "type": "replace", "edit_start_line_idx": 219 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as vscode from 'vscode'; export function isWeb(): boolean { // @ts-expect-error return typeof navigator !== 'undefined' && vscode.env.uiKind === vscode.UIKind.Web; }
extensions/typescript-language-features/src/utils/platform.ts
0
https://github.com/microsoft/vscode/commit/574ee2032cc24ed250ef15962ce100838d4e5e4a
[ 0.00017732262494973838, 0.0001770836825016886, 0.00017684475460555404, 0.0001770836825016886, 2.389351720921695e-7 ]
{ "id": 6, "code_window": [ "\n", "\t\treturn super.getActionViewItem(action);\n", "\t}\n", "\n", "\tpublic focus() {\n", "\t\tif (this._terminalService.getActiveInstance()) {\n", "\t\t\tthis._terminalService.getActiveInstance()?.focusWhenReady();\n", "\t\t} else {\n", "\t\t\tthis._terminalService.willFocusNewTerminal = true;\n", "\t\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep" ], "after_edit": [ "\t\tif (this._terminalService.connectionState === TerminalConnectionState.Connecting) {\n", "\t\t\tconst activeElement = document.activeElement;\n", "\t\t\t// Note that focus may be shifted unexpected here if this is called, then editor is focused manually, then connection happens\n", "\t\t\t// Could verify document.activeElement is the same to avoid that?\n", "\t\t\tthis._register(this._terminalService.onDidChangeConnectionState(() => {\n", "\t\t\t\tif (document.activeElement === activeElement) {\n", "\t\t\t\t\t// Only focus the terminal if the activeElement has not changed since focus() was called\n", "\t\t\t\t\tthis._focus();\n", "\t\t\t\t}\n", "\t\t\t}));\n", "\n", "\t\t\treturn;\n" ], "file_path": "src/vs/workbench/contrib/terminal/browser/terminalView.ts", "type": "replace", "edit_start_line_idx": 219 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { flatten, tail, coalesce } from 'vs/base/common/arrays'; import { IStringDictionary } from 'vs/base/common/collections'; import { Emitter, Event } from 'vs/base/common/event'; import { JSONVisitor, visit } from 'vs/base/common/json'; import { Disposable, IReference } from 'vs/base/common/lifecycle'; import { URI } from 'vs/base/common/uri'; import { IRange, Range } from 'vs/editor/common/core/range'; import { Selection } from 'vs/editor/common/core/selection'; import { IIdentifiedSingleEditOperation, ITextModel } from 'vs/editor/common/model'; import { ITextEditorModel } from 'vs/editor/common/services/resolverService'; import * as nls from 'vs/nls'; import { ConfigurationTarget, IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { ConfigurationScope, Extensions, IConfigurationNode, IConfigurationPropertySchema, IConfigurationRegistry, OVERRIDE_PROPERTY_PATTERN, IConfigurationExtensionInfo } from 'vs/platform/configuration/common/configurationRegistry'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; import { Registry } from 'vs/platform/registry/common/platform'; import { EditorModel } from 'vs/workbench/common/editor'; import { IFilterMetadata, IFilterResult, IGroupFilter, IKeybindingsEditorModel, ISearchResultGroup, ISetting, ISettingMatch, ISettingMatcher, ISettingsEditorModel, ISettingsGroup } from 'vs/workbench/services/preferences/common/preferences'; import { withNullAsUndefined, isArray } from 'vs/base/common/types'; import { FOLDER_SCOPES, WORKSPACE_SCOPES } from 'vs/workbench/services/configuration/common/configuration'; import { createValidator } from 'vs/workbench/services/preferences/common/preferencesValidation'; export const nullRange: IRange = { startLineNumber: -1, startColumn: -1, endLineNumber: -1, endColumn: -1 }; export function isNullRange(range: IRange): boolean { return range.startLineNumber === -1 && range.startColumn === -1 && range.endLineNumber === -1 && range.endColumn === -1; } export abstract class AbstractSettingsModel extends EditorModel { protected _currentResultGroups = new Map<string, ISearchResultGroup>(); updateResultGroup(id: string, resultGroup: ISearchResultGroup | undefined): IFilterResult | undefined { if (resultGroup) { this._currentResultGroups.set(id, resultGroup); } else { this._currentResultGroups.delete(id); } this.removeDuplicateResults(); return this.update(); } /** * Remove duplicates between result groups, preferring results in earlier groups */ private removeDuplicateResults(): void { const settingKeys = new Set<string>(); [...this._currentResultGroups.keys()] .sort((a, b) => this._currentResultGroups.get(a)!.order - this._currentResultGroups.get(b)!.order) .forEach(groupId => { const group = this._currentResultGroups.get(groupId)!; group.result.filterMatches = group.result.filterMatches.filter(s => !settingKeys.has(s.setting.key)); group.result.filterMatches.forEach(s => settingKeys.add(s.setting.key)); }); } filterSettings(filter: string, groupFilter: IGroupFilter, settingMatcher: ISettingMatcher): ISettingMatch[] { const allGroups = this.filterGroups; const filterMatches: ISettingMatch[] = []; for (const group of allGroups) { const groupMatched = groupFilter(group); for (const section of group.sections) { for (const setting of section.settings) { const settingMatchResult = settingMatcher(setting, group); if (groupMatched || settingMatchResult) { filterMatches.push({ setting, matches: settingMatchResult && settingMatchResult.matches, score: settingMatchResult ? settingMatchResult.score : 0 }); } } } } return filterMatches.sort((a, b) => b.score - a.score); } getPreference(key: string): ISetting | undefined { for (const group of this.settingsGroups) { for (const section of group.sections) { for (const setting of section.settings) { if (key === setting.key) { return setting; } } } } return undefined; } protected collectMetadata(groups: ISearchResultGroup[]): IStringDictionary<IFilterMetadata> { const metadata = Object.create(null); let hasMetadata = false; groups.forEach(g => { if (g.result.metadata) { metadata[g.id] = g.result.metadata; hasMetadata = true; } }); return hasMetadata ? metadata : null; } protected get filterGroups(): ISettingsGroup[] { return this.settingsGroups; } abstract settingsGroups: ISettingsGroup[]; abstract findValueMatches(filter: string, setting: ISetting): IRange[]; protected abstract update(): IFilterResult | undefined; } export class SettingsEditorModel extends AbstractSettingsModel implements ISettingsEditorModel { private _settingsGroups: ISettingsGroup[] | undefined; protected settingsModel: ITextModel; private readonly _onDidChangeGroups: Emitter<void> = this._register(new Emitter<void>()); readonly onDidChangeGroups: Event<void> = this._onDidChangeGroups.event; constructor(reference: IReference<ITextEditorModel>, private _configurationTarget: ConfigurationTarget) { super(); this.settingsModel = reference.object.textEditorModel!; this._register(this.onDispose(() => reference.dispose())); this._register(this.settingsModel.onDidChangeContent(() => { this._settingsGroups = undefined; this._onDidChangeGroups.fire(); })); } get uri(): URI { return this.settingsModel.uri; } get configurationTarget(): ConfigurationTarget { return this._configurationTarget; } get settingsGroups(): ISettingsGroup[] { if (!this._settingsGroups) { this.parse(); } return this._settingsGroups!; } get content(): string { return this.settingsModel.getValue(); } findValueMatches(filter: string, setting: ISetting): IRange[] { return this.settingsModel.findMatches(filter, setting.valueRange, false, false, null, false).map(match => match.range); } protected isSettingsProperty(property: string, previousParents: string[]): boolean { return previousParents.length === 0; // Settings is root } protected parse(): void { this._settingsGroups = parse(this.settingsModel, (property: string, previousParents: string[]): boolean => this.isSettingsProperty(property, previousParents)); } protected update(): IFilterResult | undefined { const resultGroups = [...this._currentResultGroups.values()]; if (!resultGroups.length) { return undefined; } // Transform resultGroups into IFilterResult - ISetting ranges are already correct here const filteredSettings: ISetting[] = []; const matches: IRange[] = []; resultGroups.forEach(group => { group.result.filterMatches.forEach(filterMatch => { filteredSettings.push(filterMatch.setting); if (filterMatch.matches) { matches.push(...filterMatch.matches); } }); }); let filteredGroup: ISettingsGroup | undefined; const modelGroup = this.settingsGroups[0]; // Editable model has one or zero groups if (modelGroup) { filteredGroup = { id: modelGroup.id, range: modelGroup.range, sections: [{ settings: filteredSettings }], title: modelGroup.title, titleRange: modelGroup.titleRange, extensionInfo: modelGroup.extensionInfo }; } const metadata = this.collectMetadata(resultGroups); return { allGroups: this.settingsGroups, filteredGroups: filteredGroup ? [filteredGroup] : [], matches, metadata }; } } export class Settings2EditorModel extends AbstractSettingsModel implements ISettingsEditorModel { private readonly _onDidChangeGroups: Emitter<void> = this._register(new Emitter<void>()); readonly onDidChangeGroups: Event<void> = this._onDidChangeGroups.event; private dirty = false; constructor( private _defaultSettings: DefaultSettings, @IConfigurationService configurationService: IConfigurationService, ) { super(); this._register(configurationService.onDidChangeConfiguration(e => { if (e.source === ConfigurationTarget.DEFAULT) { this.dirty = true; this._onDidChangeGroups.fire(); } })); this._register(Registry.as<IConfigurationRegistry>(Extensions.Configuration).onDidSchemaChange(e => { this.dirty = true; this._onDidChangeGroups.fire(); })); } protected get filterGroups(): ISettingsGroup[] { // Don't filter "commonly used" return this.settingsGroups.slice(1); } get settingsGroups(): ISettingsGroup[] { const groups = this._defaultSettings.getSettingsGroups(this.dirty); this.dirty = false; return groups; } findValueMatches(filter: string, setting: ISetting): IRange[] { // TODO @roblou return []; } protected update(): IFilterResult { throw new Error('Not supported'); } } function parse(model: ITextModel, isSettingsProperty: (currentProperty: string, previousParents: string[]) => boolean): ISettingsGroup[] { const settings: ISetting[] = []; let overrideSetting: ISetting | null = null; let currentProperty: string | null = null; let currentParent: any = []; const previousParents: any[] = []; let settingsPropertyIndex: number = -1; const range = { startLineNumber: 0, startColumn: 0, endLineNumber: 0, endColumn: 0 }; function onValue(value: any, offset: number, length: number) { if (Array.isArray(currentParent)) { (<any[]>currentParent).push(value); } else if (currentProperty) { currentParent[currentProperty] = value; } if (previousParents.length === settingsPropertyIndex + 1 || (previousParents.length === settingsPropertyIndex + 2 && overrideSetting !== null)) { // settings value started const setting = previousParents.length === settingsPropertyIndex + 1 ? settings[settings.length - 1] : overrideSetting!.overrides![overrideSetting!.overrides!.length - 1]; if (setting) { const valueStartPosition = model.getPositionAt(offset); const valueEndPosition = model.getPositionAt(offset + length); setting.value = value; setting.valueRange = { startLineNumber: valueStartPosition.lineNumber, startColumn: valueStartPosition.column, endLineNumber: valueEndPosition.lineNumber, endColumn: valueEndPosition.column }; setting.range = Object.assign(setting.range, { endLineNumber: valueEndPosition.lineNumber, endColumn: valueEndPosition.column }); } } } const visitor: JSONVisitor = { onObjectBegin: (offset: number, length: number) => { if (isSettingsProperty(currentProperty!, previousParents)) { // Settings started settingsPropertyIndex = previousParents.length; const position = model.getPositionAt(offset); range.startLineNumber = position.lineNumber; range.startColumn = position.column; } const object = {}; onValue(object, offset, length); currentParent = object; currentProperty = null; previousParents.push(currentParent); }, onObjectProperty: (name: string, offset: number, length: number) => { currentProperty = name; if (previousParents.length === settingsPropertyIndex + 1 || (previousParents.length === settingsPropertyIndex + 2 && overrideSetting !== null)) { // setting started const settingStartPosition = model.getPositionAt(offset); const setting: ISetting = { description: [], descriptionIsMarkdown: false, key: name, keyRange: { startLineNumber: settingStartPosition.lineNumber, startColumn: settingStartPosition.column + 1, endLineNumber: settingStartPosition.lineNumber, endColumn: settingStartPosition.column + length }, range: { startLineNumber: settingStartPosition.lineNumber, startColumn: settingStartPosition.column, endLineNumber: 0, endColumn: 0 }, value: null, valueRange: nullRange, descriptionRanges: [], overrides: [], overrideOf: withNullAsUndefined(overrideSetting) }; if (previousParents.length === settingsPropertyIndex + 1) { settings.push(setting); if (OVERRIDE_PROPERTY_PATTERN.test(name)) { overrideSetting = setting; } } else { overrideSetting!.overrides!.push(setting); } } }, onObjectEnd: (offset: number, length: number) => { currentParent = previousParents.pop(); if (previousParents.length === settingsPropertyIndex + 1 || (previousParents.length === settingsPropertyIndex + 2 && overrideSetting !== null)) { // setting ended const setting = previousParents.length === settingsPropertyIndex + 1 ? settings[settings.length - 1] : overrideSetting!.overrides![overrideSetting!.overrides!.length - 1]; if (setting) { const valueEndPosition = model.getPositionAt(offset + length); setting.valueRange = Object.assign(setting.valueRange, { endLineNumber: valueEndPosition.lineNumber, endColumn: valueEndPosition.column }); setting.range = Object.assign(setting.range, { endLineNumber: valueEndPosition.lineNumber, endColumn: valueEndPosition.column }); } if (previousParents.length === settingsPropertyIndex + 1) { overrideSetting = null; } } if (previousParents.length === settingsPropertyIndex) { // settings ended const position = model.getPositionAt(offset); range.endLineNumber = position.lineNumber; range.endColumn = position.column; settingsPropertyIndex = -1; } }, onArrayBegin: (offset: number, length: number) => { const array: any[] = []; onValue(array, offset, length); previousParents.push(currentParent); currentParent = array; currentProperty = null; }, onArrayEnd: (offset: number, length: number) => { currentParent = previousParents.pop(); if (previousParents.length === settingsPropertyIndex + 1 || (previousParents.length === settingsPropertyIndex + 2 && overrideSetting !== null)) { // setting value ended const setting = previousParents.length === settingsPropertyIndex + 1 ? settings[settings.length - 1] : overrideSetting!.overrides![overrideSetting!.overrides!.length - 1]; if (setting) { const valueEndPosition = model.getPositionAt(offset + length); setting.valueRange = Object.assign(setting.valueRange, { endLineNumber: valueEndPosition.lineNumber, endColumn: valueEndPosition.column }); setting.range = Object.assign(setting.range, { endLineNumber: valueEndPosition.lineNumber, endColumn: valueEndPosition.column }); } } }, onLiteralValue: onValue, onError: (error) => { const setting = settings[settings.length - 1]; if (setting && (isNullRange(setting.range) || isNullRange(setting.keyRange) || isNullRange(setting.valueRange))) { settings.pop(); } } }; if (!model.isDisposed()) { visit(model.getValue(), visitor); } return settings.length > 0 ? [<ISettingsGroup>{ sections: [ { settings } ], title: '', titleRange: nullRange, range }] : []; } export class WorkspaceConfigurationEditorModel extends SettingsEditorModel { private _configurationGroups: ISettingsGroup[] = []; get configurationGroups(): ISettingsGroup[] { return this._configurationGroups; } protected parse(): void { super.parse(); this._configurationGroups = parse(this.settingsModel, (property: string, previousParents: string[]): boolean => previousParents.length === 0); } protected isSettingsProperty(property: string, previousParents: string[]): boolean { return property === 'settings' && previousParents.length === 1; } } export class DefaultSettings extends Disposable { private _allSettingsGroups: ISettingsGroup[] | undefined; private _content: string | undefined; private _settingsByName = new Map<string, ISetting>(); readonly _onDidChange: Emitter<void> = this._register(new Emitter<void>()); readonly onDidChange: Event<void> = this._onDidChange.event; constructor( private _mostCommonlyUsedSettingsKeys: string[], readonly target: ConfigurationTarget, ) { super(); } getContent(forceUpdate = false): string { if (!this._content || forceUpdate) { this.initialize(); } return this._content!; } getSettingsGroups(forceUpdate = false): ISettingsGroup[] { if (!this._allSettingsGroups || forceUpdate) { this.initialize(); } return this._allSettingsGroups!; } private initialize(): void { this._allSettingsGroups = this.parse(); this._content = this.toContent(this._allSettingsGroups); } private parse(): ISettingsGroup[] { const settingsGroups = this.getRegisteredGroups(); this.initAllSettingsMap(settingsGroups); const mostCommonlyUsed = this.getMostCommonlyUsedSettings(settingsGroups); return [mostCommonlyUsed, ...settingsGroups]; } getRegisteredGroups(): ISettingsGroup[] { const configurations = Registry.as<IConfigurationRegistry>(Extensions.Configuration).getConfigurations().slice(); const groups = this.removeEmptySettingsGroups(configurations.sort(this.compareConfigurationNodes) .reduce<ISettingsGroup[]>((result, config, index, array) => this.parseConfig(config, result, array), [])); return this.sortGroups(groups); } private sortGroups(groups: ISettingsGroup[]): ISettingsGroup[] { groups.forEach(group => { group.sections.forEach(section => { section.settings.sort((a, b) => a.key.localeCompare(b.key)); }); }); return groups; } private initAllSettingsMap(allSettingsGroups: ISettingsGroup[]): void { this._settingsByName = new Map<string, ISetting>(); for (const group of allSettingsGroups) { for (const section of group.sections) { for (const setting of section.settings) { this._settingsByName.set(setting.key, setting); } } } } private getMostCommonlyUsedSettings(allSettingsGroups: ISettingsGroup[]): ISettingsGroup { const settings = coalesce(this._mostCommonlyUsedSettingsKeys.map(key => { const setting = this._settingsByName.get(key); if (setting) { return <ISetting>{ description: setting.description, key: setting.key, value: setting.value, keyRange: nullRange, range: nullRange, valueRange: nullRange, overrides: [], scope: ConfigurationScope.RESOURCE, type: setting.type, enum: setting.enum, enumDescriptions: setting.enumDescriptions, descriptionRanges: [] }; } return null; })); return <ISettingsGroup>{ id: 'mostCommonlyUsed', range: nullRange, title: nls.localize('commonlyUsed', "Commonly Used"), titleRange: nullRange, sections: [ { settings } ] }; } private parseConfig(config: IConfigurationNode, result: ISettingsGroup[], configurations: IConfigurationNode[], settingsGroup?: ISettingsGroup, seenSettings?: { [key: string]: boolean }): ISettingsGroup[] { seenSettings = seenSettings ? seenSettings : {}; let title = config.title; if (!title) { const configWithTitleAndSameId = configurations.find(c => (c.id === config.id) && c.title); if (configWithTitleAndSameId) { title = configWithTitleAndSameId.title; } } if (title) { if (!settingsGroup) { settingsGroup = result.find(g => g.title === title && g.extensionInfo?.id === config.extensionInfo?.id); if (!settingsGroup) { settingsGroup = { sections: [{ settings: [] }], id: config.id || '', title: title || '', titleRange: nullRange, range: nullRange, extensionInfo: config.extensionInfo }; result.push(settingsGroup); } } else { settingsGroup.sections[settingsGroup.sections.length - 1].title = title; } } if (config.properties) { if (!settingsGroup) { settingsGroup = { sections: [{ settings: [] }], id: config.id || '', title: config.id || '', titleRange: nullRange, range: nullRange, extensionInfo: config.extensionInfo }; result.push(settingsGroup); } const configurationSettings: ISetting[] = []; for (const setting of [...settingsGroup.sections[settingsGroup.sections.length - 1].settings, ...this.parseSettings(config.properties, config.extensionInfo)]) { if (!seenSettings[setting.key]) { configurationSettings.push(setting); seenSettings[setting.key] = true; } } if (configurationSettings.length) { settingsGroup.sections[settingsGroup.sections.length - 1].settings = configurationSettings; } } if (config.allOf) { config.allOf.forEach(c => this.parseConfig(c, result, configurations, settingsGroup, seenSettings)); } return result; } private removeEmptySettingsGroups(settingsGroups: ISettingsGroup[]): ISettingsGroup[] { const result: ISettingsGroup[] = []; for (const settingsGroup of settingsGroups) { settingsGroup.sections = settingsGroup.sections.filter(section => section.settings.length > 0); if (settingsGroup.sections.length) { result.push(settingsGroup); } } return result; } private parseSettings(settingsObject: { [path: string]: IConfigurationPropertySchema; }, extensionInfo?: IConfigurationExtensionInfo): ISetting[] { const result: ISetting[] = []; for (const key in settingsObject) { const prop = settingsObject[key]; if (this.matchesScope(prop)) { const value = prop.default; const description = (prop.description || prop.markdownDescription || '').split('\n'); const overrides = OVERRIDE_PROPERTY_PATTERN.test(key) ? this.parseOverrideSettings(prop.default) : []; const listItemType = prop.type === 'array' && prop.items && !isArray(prop.items) && prop.items.type && !isArray(prop.items.type) ? prop.items.type : undefined; const objectProperties = prop.type === 'object' ? prop.properties : undefined; const objectPatternProperties = prop.type === 'object' ? prop.patternProperties : undefined; const objectAdditionalProperties = prop.type === 'object' ? prop.additionalProperties : undefined; result.push({ key, value, description, descriptionIsMarkdown: !prop.description, range: nullRange, keyRange: nullRange, valueRange: nullRange, descriptionRanges: [], overrides, scope: prop.scope, type: prop.type, arrayItemType: listItemType, objectProperties, objectPatternProperties, objectAdditionalProperties, enum: prop.enum, enumDescriptions: prop.enumDescriptions || prop.markdownEnumDescriptions, enumDescriptionsAreMarkdown: !prop.enumDescriptions, tags: prop.tags, disallowSyncIgnore: prop.disallowSyncIgnore, extensionInfo: extensionInfo, deprecationMessage: prop.markdownDeprecationMessage || prop.deprecationMessage, deprecationMessageIsMarkdown: !!prop.markdownDeprecationMessage, validator: createValidator(prop), enumItemLabels: prop.enumItemLabels }); } } return result; } private parseOverrideSettings(overrideSettings: any): ISetting[] { return Object.keys(overrideSettings).map((key) => ({ key, value: overrideSettings[key], description: [], descriptionIsMarkdown: false, range: nullRange, keyRange: nullRange, valueRange: nullRange, descriptionRanges: [], overrides: [] })); } private matchesScope(property: IConfigurationNode): boolean { if (!property.scope) { return true; } if (this.target === ConfigurationTarget.WORKSPACE_FOLDER) { return FOLDER_SCOPES.indexOf(property.scope) !== -1; } if (this.target === ConfigurationTarget.WORKSPACE) { return WORKSPACE_SCOPES.indexOf(property.scope) !== -1; } return true; } private compareConfigurationNodes(c1: IConfigurationNode, c2: IConfigurationNode): number { if (typeof c1.order !== 'number') { return 1; } if (typeof c2.order !== 'number') { return -1; } if (c1.order === c2.order) { const title1 = c1.title || ''; const title2 = c2.title || ''; return title1.localeCompare(title2); } return c1.order - c2.order; } private toContent(settingsGroups: ISettingsGroup[]): string { const builder = new SettingsContentBuilder(); builder.pushLine('['); settingsGroups.forEach((settingsGroup, i) => { builder.pushGroup(settingsGroup); builder.pushLine(','); }); builder.pushLine(']'); return builder.getContent(); } } export class DefaultSettingsEditorModel extends AbstractSettingsModel implements ISettingsEditorModel { private _model: ITextModel; private readonly _onDidChangeGroups: Emitter<void> = this._register(new Emitter<void>()); readonly onDidChangeGroups: Event<void> = this._onDidChangeGroups.event; constructor( private _uri: URI, reference: IReference<ITextEditorModel>, private readonly defaultSettings: DefaultSettings ) { super(); this._register(defaultSettings.onDidChange(() => this._onDidChangeGroups.fire())); this._model = reference.object.textEditorModel!; this._register(this.onDispose(() => reference.dispose())); } get uri(): URI { return this._uri; } get target(): ConfigurationTarget { return this.defaultSettings.target; } get settingsGroups(): ISettingsGroup[] { return this.defaultSettings.getSettingsGroups(); } protected get filterGroups(): ISettingsGroup[] { // Don't look at "commonly used" for filter return this.settingsGroups.slice(1); } protected update(): IFilterResult | undefined { if (this._model.isDisposed()) { return undefined; } // Grab current result groups, only render non-empty groups const resultGroups = [...this._currentResultGroups.values()] .sort((a, b) => a.order - b.order); const nonEmptyResultGroups = resultGroups.filter(group => group.result.filterMatches.length); const startLine = tail(this.settingsGroups).range.endLineNumber + 2; const { settingsGroups: filteredGroups, matches } = this.writeResultGroups(nonEmptyResultGroups, startLine); const metadata = this.collectMetadata(resultGroups); return resultGroups.length ? <IFilterResult>{ allGroups: this.settingsGroups, filteredGroups, matches, metadata } : undefined; } /** * Translate the ISearchResultGroups to text, and write it to the editor model */ private writeResultGroups(groups: ISearchResultGroup[], startLine: number): { matches: IRange[], settingsGroups: ISettingsGroup[] } { const contentBuilderOffset = startLine - 1; const builder = new SettingsContentBuilder(contentBuilderOffset); const settingsGroups: ISettingsGroup[] = []; const matches: IRange[] = []; builder.pushLine(','); groups.forEach(resultGroup => { const settingsGroup = this.getGroup(resultGroup); settingsGroups.push(settingsGroup); matches.push(...this.writeSettingsGroupToBuilder(builder, settingsGroup, resultGroup.result.filterMatches)); }); // note: 1-indexed line numbers here const groupContent = builder.getContent() + '\n'; const groupEndLine = this._model.getLineCount(); const cursorPosition = new Selection(startLine, 1, startLine, 1); const edit: IIdentifiedSingleEditOperation = { text: groupContent, forceMoveMarkers: true, range: new Range(startLine, 1, groupEndLine, 1), identifier: { major: 1, minor: 0 } }; this._model.pushEditOperations([cursorPosition], [edit], () => [cursorPosition]); // Force tokenization now - otherwise it may be slightly delayed, causing a flash of white text const tokenizeTo = Math.min(startLine + 60, this._model.getLineCount()); this._model.forceTokenization(tokenizeTo); return { matches, settingsGroups }; } private writeSettingsGroupToBuilder(builder: SettingsContentBuilder, settingsGroup: ISettingsGroup, filterMatches: ISettingMatch[]): IRange[] { filterMatches = filterMatches .map(filteredMatch => { // Fix match ranges to offset from setting start line return <ISettingMatch>{ setting: filteredMatch.setting, score: filteredMatch.score, matches: filteredMatch.matches && filteredMatch.matches.map(match => { return new Range( match.startLineNumber - filteredMatch.setting.range.startLineNumber, match.startColumn, match.endLineNumber - filteredMatch.setting.range.startLineNumber, match.endColumn); }) }; }); builder.pushGroup(settingsGroup); builder.pushLine(','); // builder has rewritten settings ranges, fix match ranges const fixedMatches = flatten( filterMatches .map(m => m.matches || []) .map((settingMatches, i) => { const setting = settingsGroup.sections[0].settings[i]; return settingMatches.map(range => { return new Range( range.startLineNumber + setting.range.startLineNumber, range.startColumn, range.endLineNumber + setting.range.startLineNumber, range.endColumn); }); })); return fixedMatches; } private copySetting(setting: ISetting): ISetting { return { description: setting.description, scope: setting.scope, type: setting.type, enum: setting.enum, enumDescriptions: setting.enumDescriptions, key: setting.key, value: setting.value, range: setting.range, overrides: [], overrideOf: setting.overrideOf, tags: setting.tags, deprecationMessage: setting.deprecationMessage, keyRange: nullRange, valueRange: nullRange, descriptionIsMarkdown: undefined, descriptionRanges: [] }; } findValueMatches(filter: string, setting: ISetting): IRange[] { return []; } getPreference(key: string): ISetting | undefined { for (const group of this.settingsGroups) { for (const section of group.sections) { for (const setting of section.settings) { if (setting.key === key) { return setting; } } } } return undefined; } private getGroup(resultGroup: ISearchResultGroup): ISettingsGroup { return <ISettingsGroup>{ id: resultGroup.id, range: nullRange, title: resultGroup.label, titleRange: nullRange, sections: [ { settings: resultGroup.result.filterMatches.map(m => this.copySetting(m.setting)) } ] }; } } class SettingsContentBuilder { private _contentByLines: string[]; private get lineCountWithOffset(): number { return this._contentByLines.length + this._rangeOffset; } private get lastLine(): string { return this._contentByLines[this._contentByLines.length - 1] || ''; } constructor(private _rangeOffset = 0) { this._contentByLines = []; } pushLine(...lineText: string[]): void { this._contentByLines.push(...lineText); } pushGroup(settingsGroups: ISettingsGroup): void { this._contentByLines.push('{'); this._contentByLines.push(''); this._contentByLines.push(''); const lastSetting = this._pushGroup(settingsGroups, ' '); if (lastSetting) { // Strip the comma from the last setting const lineIdx = lastSetting.range.endLineNumber - this._rangeOffset; const content = this._contentByLines[lineIdx - 2]; this._contentByLines[lineIdx - 2] = content.substring(0, content.length - 1); } this._contentByLines.push('}'); } protected _pushGroup(group: ISettingsGroup, indent: string): ISetting | null { let lastSetting: ISetting | null = null; const groupStart = this.lineCountWithOffset + 1; for (const section of group.sections) { if (section.title) { const sectionTitleStart = this.lineCountWithOffset + 1; this.addDescription([section.title], indent, this._contentByLines); section.titleRange = { startLineNumber: sectionTitleStart, startColumn: 1, endLineNumber: this.lineCountWithOffset, endColumn: this.lastLine.length }; } if (section.settings.length) { for (const setting of section.settings) { this.pushSetting(setting, indent); lastSetting = setting; } } } group.range = { startLineNumber: groupStart, startColumn: 1, endLineNumber: this.lineCountWithOffset, endColumn: this.lastLine.length }; return lastSetting; } getContent(): string { return this._contentByLines.join('\n'); } private pushSetting(setting: ISetting, indent: string): void { const settingStart = this.lineCountWithOffset + 1; this.pushSettingDescription(setting, indent); let preValueContent = indent; const keyString = JSON.stringify(setting.key); preValueContent += keyString; setting.keyRange = { startLineNumber: this.lineCountWithOffset + 1, startColumn: preValueContent.indexOf(setting.key) + 1, endLineNumber: this.lineCountWithOffset + 1, endColumn: setting.key.length }; preValueContent += ': '; const valueStart = this.lineCountWithOffset + 1; this.pushValue(setting, preValueContent, indent); setting.valueRange = { startLineNumber: valueStart, startColumn: preValueContent.length + 1, endLineNumber: this.lineCountWithOffset, endColumn: this.lastLine.length + 1 }; this._contentByLines[this._contentByLines.length - 1] += ','; this._contentByLines.push(''); setting.range = { startLineNumber: settingStart, startColumn: 1, endLineNumber: this.lineCountWithOffset, endColumn: this.lastLine.length }; } private pushSettingDescription(setting: ISetting, indent: string): void { const fixSettingLink = (line: string) => line.replace(/`#(.*)#`/g, (match, settingName) => `\`${settingName}\``); setting.descriptionRanges = []; const descriptionPreValue = indent + '// '; for (let line of (setting.deprecationMessage ? [setting.deprecationMessage, ...setting.description] : setting.description)) { line = fixSettingLink(line); this._contentByLines.push(descriptionPreValue + line); setting.descriptionRanges.push({ startLineNumber: this.lineCountWithOffset, startColumn: this.lastLine.indexOf(line) + 1, endLineNumber: this.lineCountWithOffset, endColumn: this.lastLine.length }); } if (setting.enumDescriptions && setting.enumDescriptions.some(desc => !!desc)) { setting.enumDescriptions.forEach((desc, i) => { const displayEnum = escapeInvisibleChars(String(setting.enum![i])); const line = desc ? `${displayEnum}: ${fixSettingLink(desc)}` : displayEnum; this._contentByLines.push(`${indent}// - ${line}`); setting.descriptionRanges.push({ startLineNumber: this.lineCountWithOffset, startColumn: this.lastLine.indexOf(line) + 1, endLineNumber: this.lineCountWithOffset, endColumn: this.lastLine.length }); }); } } private pushValue(setting: ISetting, preValueConent: string, indent: string): void { const valueString = JSON.stringify(setting.value, null, indent); if (valueString && (typeof setting.value === 'object')) { if (setting.overrides && setting.overrides.length) { this._contentByLines.push(preValueConent + ' {'); for (const subSetting of setting.overrides) { this.pushSetting(subSetting, indent + indent); this._contentByLines.pop(); } const lastSetting = setting.overrides[setting.overrides.length - 1]; const content = this._contentByLines[lastSetting.range.endLineNumber - 2]; this._contentByLines[lastSetting.range.endLineNumber - 2] = content.substring(0, content.length - 1); this._contentByLines.push(indent + '}'); } else { const mulitLineValue = valueString.split('\n'); this._contentByLines.push(preValueConent + mulitLineValue[0]); for (let i = 1; i < mulitLineValue.length; i++) { this._contentByLines.push(indent + mulitLineValue[i]); } } } else { this._contentByLines.push(preValueConent + valueString); } } private addDescription(description: string[], indent: string, result: string[]) { for (const line of description) { result.push(indent + '// ' + line); } } } class RawSettingsContentBuilder extends SettingsContentBuilder { constructor(private indent: string = '\t') { super(0); } pushGroup(settingsGroups: ISettingsGroup): void { this._pushGroup(settingsGroups, this.indent); } } export class DefaultRawSettingsEditorModel extends Disposable { private _content: string | null = null; constructor(private defaultSettings: DefaultSettings) { super(); this._register(defaultSettings.onDidChange(() => this._content = null)); } get content(): string { if (this._content === null) { const builder = new RawSettingsContentBuilder(); builder.pushLine('{'); for (const settingsGroup of this.defaultSettings.getRegisteredGroups()) { builder.pushGroup(settingsGroup); } builder.pushLine('}'); this._content = builder.getContent(); } return this._content; } } function escapeInvisibleChars(enumValue: string): string { return enumValue && enumValue .replace(/\n/g, '\\n') .replace(/\r/g, '\\r'); } export function defaultKeybindingsContents(keybindingService: IKeybindingService): string { const defaultsHeader = '// ' + nls.localize('defaultKeybindingsHeader', "Override key bindings by placing them into your key bindings file."); return defaultsHeader + '\n' + keybindingService.getDefaultKeybindingsContent(); } export class DefaultKeybindingsEditorModel implements IKeybindingsEditorModel<any> { private _content: string | undefined; constructor(private _uri: URI, @IKeybindingService private readonly keybindingService: IKeybindingService) { } get uri(): URI { return this._uri; } get content(): string { if (!this._content) { this._content = defaultKeybindingsContents(this.keybindingService); } return this._content; } getPreference(): any { return null; } dispose(): void { // Not disposable } }
src/vs/workbench/services/preferences/common/preferencesModels.ts
0
https://github.com/microsoft/vscode/commit/574ee2032cc24ed250ef15962ce100838d4e5e4a
[ 0.0001782045146683231, 0.0001719599385978654, 0.00016272833454422653, 0.00017223958275280893, 0.00000267213749793882 ]
{ "id": 6, "code_window": [ "\n", "\t\treturn super.getActionViewItem(action);\n", "\t}\n", "\n", "\tpublic focus() {\n", "\t\tif (this._terminalService.getActiveInstance()) {\n", "\t\t\tthis._terminalService.getActiveInstance()?.focusWhenReady();\n", "\t\t} else {\n", "\t\t\tthis._terminalService.willFocusNewTerminal = true;\n", "\t\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep" ], "after_edit": [ "\t\tif (this._terminalService.connectionState === TerminalConnectionState.Connecting) {\n", "\t\t\tconst activeElement = document.activeElement;\n", "\t\t\t// Note that focus may be shifted unexpected here if this is called, then editor is focused manually, then connection happens\n", "\t\t\t// Could verify document.activeElement is the same to avoid that?\n", "\t\t\tthis._register(this._terminalService.onDidChangeConnectionState(() => {\n", "\t\t\t\tif (document.activeElement === activeElement) {\n", "\t\t\t\t\t// Only focus the terminal if the activeElement has not changed since focus() was called\n", "\t\t\t\t\tthis._focus();\n", "\t\t\t\t}\n", "\t\t\t}));\n", "\n", "\t\t\treturn;\n" ], "file_path": "src/vs/workbench/contrib/terminal/browser/terminalView.ts", "type": "replace", "edit_start_line_idx": 219 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { CancellationToken, ResponseError, ErrorCodes } from 'vscode-languageserver'; export function formatError(message: string, err: any): string { if (err instanceof Error) { let error = <Error>err; return `${message}: ${error.message}\n${error.stack}`; } else if (typeof err === 'string') { return `${message}: ${err}`; } else if (err) { return `${message}: ${err.toString()}`; } return message; } export function runSafeAsync<T>(func: () => Thenable<T>, errorVal: T, errorMessage: string, token: CancellationToken): Thenable<T | ResponseError<any>> { return new Promise<T | ResponseError<any>>((resolve) => { setImmediate(() => { if (token.isCancellationRequested) { resolve(cancelValue()); } return func().then(result => { if (token.isCancellationRequested) { resolve(cancelValue()); return; } else { resolve(result); } }, e => { console.error(formatError(errorMessage, e)); resolve(errorVal); }); }); }); } export function runSafe<T, E>(func: () => T, errorVal: T, errorMessage: string, token: CancellationToken): Thenable<T | ResponseError<E>> { return new Promise<T | ResponseError<E>>((resolve) => { setImmediate(() => { if (token.isCancellationRequested) { resolve(cancelValue()); } else { try { let result = func(); if (token.isCancellationRequested) { resolve(cancelValue()); return; } else { resolve(result); } } catch (e) { console.error(formatError(errorMessage, e)); resolve(errorVal); } } }); }); } function cancelValue<E>() { console.log('cancelled'); return new ResponseError<E>(ErrorCodes.RequestCancelled, 'Request cancelled'); }
extensions/json-language-features/server/src/utils/runner.ts
0
https://github.com/microsoft/vscode/commit/574ee2032cc24ed250ef15962ce100838d4e5e4a
[ 0.00017667874635662884, 0.0001711429940769449, 0.0001675119565334171, 0.00017093209316954017, 0.000002579828333182377 ]
{ "id": 7, "code_window": [ "\t\t}\n", "\t}\n", "\n", "\tpublic focusFindWidget() {\n", "\t\tconst activeInstance = this._terminalService.getActiveInstance();\n", "\t\tif (activeInstance && activeInstance.hasSelection() && activeInstance.selection!.indexOf('\\n') === -1) {\n" ], "labels": [ "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis._focus();\n", "\t}\n", "\n", "\tprivate _focus() {\n", "\t\tthis._terminalService.getActiveInstance()?.focusWhenReady();\n" ], "file_path": "src/vs/workbench/contrib/terminal/browser/terminalView.ts", "type": "add", "edit_start_line_idx": 224 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as dom from 'vs/base/browser/dom'; import * as nls from 'vs/nls'; import * as platform from 'vs/base/common/platform'; import { Action, IAction, Separator, IActionViewItem } from 'vs/base/common/actions'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IContextMenuService } from 'vs/platform/contextview/browser/contextView'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IThemeService, IColorTheme, registerThemingParticipant, ICssStyleCollector } from 'vs/platform/theme/common/themeService'; import { TerminalFindWidget } from 'vs/workbench/contrib/terminal/browser/terminalFindWidget'; import { KillTerminalAction, SwitchTerminalAction, SwitchTerminalActionViewItem, CopyTerminalSelectionAction, TerminalPasteAction, ClearTerminalAction, SelectAllTerminalAction, CreateNewTerminalAction, SplitTerminalAction } from 'vs/workbench/contrib/terminal/browser/terminalActions'; import { StandardMouseEvent } from 'vs/base/browser/mouseEvent'; import { URI } from 'vs/base/common/uri'; import { TERMINAL_BACKGROUND_COLOR, TERMINAL_BORDER_COLOR } from 'vs/workbench/contrib/terminal/common/terminalColorRegistry'; import { DataTransfers } from 'vs/base/browser/dnd'; import { INotificationService, IPromptChoice, Severity } from 'vs/platform/notification/common/notification'; import { ITerminalService } from 'vs/workbench/contrib/terminal/browser/terminal'; import { BrowserFeatures } from 'vs/base/browser/canIUse'; import { ViewPane, IViewPaneOptions } from 'vs/workbench/browser/parts/views/viewPaneContainer'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { IViewDescriptorService } from 'vs/workbench/common/views'; import { IOpenerService } from 'vs/platform/opener/common/opener'; import { PANEL_BACKGROUND, SIDE_BAR_BACKGROUND } from 'vs/workbench/common/theme'; import { Orientation } from 'vs/base/browser/ui/sash/sash'; const FIND_FOCUS_CLASS = 'find-focused'; export class TerminalViewPane extends ViewPane { private _actions: IAction[] | undefined; private _copyContextMenuAction: IAction | undefined; private _contextMenuActions: IAction[] | undefined; private _cancelContextMenu: boolean = false; private _fontStyleElement: HTMLElement | undefined; private _parentDomElement: HTMLElement | undefined; private _terminalContainer: HTMLElement | undefined; private _findWidget: TerminalFindWidget | undefined; private _splitTerminalAction: IAction | undefined; private _terminalsInitialized = false; private _bodyDimensions: { width: number, height: number } = { width: 0, height: 0 }; constructor( options: IViewPaneOptions, @IKeybindingService keybindingService: IKeybindingService, @IContextKeyService contextKeyService: IContextKeyService, @IViewDescriptorService viewDescriptorService: IViewDescriptorService, @IConfigurationService configurationService: IConfigurationService, @IContextMenuService private readonly _contextMenuService: IContextMenuService, @IInstantiationService private readonly _instantiationService: IInstantiationService, @ITerminalService private readonly _terminalService: ITerminalService, @IThemeService protected readonly themeService: IThemeService, @ITelemetryService telemetryService: ITelemetryService, @INotificationService private readonly _notificationService: INotificationService, @IOpenerService openerService: IOpenerService, ) { super(options, keybindingService, _contextMenuService, configurationService, contextKeyService, viewDescriptorService, _instantiationService, openerService, themeService, telemetryService); this._terminalService.onDidRegisterProcessSupport(() => { if (this._actions) { for (const action of this._actions) { action.enabled = true; } } this._onDidChangeViewWelcomeState.fire(); }); this._register(this.onDidBlur(() => { this._terminalService.willFocusNewTerminal = false; })); } protected renderBody(container: HTMLElement): void { super.renderBody(container); if (this.shouldShowWelcome()) { return; } this._parentDomElement = container; this._parentDomElement.classList.add('integrated-terminal'); this._fontStyleElement = document.createElement('style'); this._terminalContainer = document.createElement('div'); this._terminalContainer.classList.add('terminal-outer-container'); this._findWidget = this._instantiationService.createInstance(TerminalFindWidget, this._terminalService.getFindState()); this._findWidget.focusTracker.onDidFocus(() => this._terminalContainer!.classList.add(FIND_FOCUS_CLASS)); this._parentDomElement.appendChild(this._fontStyleElement); this._parentDomElement.appendChild(this._terminalContainer); this._parentDomElement.appendChild(this._findWidget.getDomNode()); this._attachEventListeners(this._parentDomElement, this._terminalContainer); this._terminalService.setContainers(container, this._terminalContainer); this._register(this.themeService.onDidColorThemeChange(theme => this._updateTheme(theme))); this._register(this.configurationService.onDidChangeConfiguration(e => { if (e.affectsConfiguration('terminal.integrated.fontFamily') || e.affectsConfiguration('editor.fontFamily')) { const configHelper = this._terminalService.configHelper; if (!configHelper.configFontIsMonospace()) { const choices: IPromptChoice[] = [{ label: nls.localize('terminal.useMonospace', "Use 'monospace'"), run: () => this.configurationService.updateValue('terminal.integrated.fontFamily', 'monospace'), }]; this._notificationService.prompt(Severity.Warning, nls.localize('terminal.monospaceOnly', "The terminal only supports monospace fonts. Be sure to restart VS Code if this is a newly installed font."), choices); } } })); this._updateTheme(); this._register(this.onDidChangeBodyVisibility(visible => { if (visible) { const hadTerminals = !!this._terminalService.terminalTabs.length; if (this._terminalsInitialized) { if (!hadTerminals) { this._terminalService.createTerminal(); } } else { this._terminalsInitialized = true; this._terminalService.initializeTerminals(); } this._updateTheme(); if (hadTerminals) { this._terminalService.getActiveTab()?.setVisible(visible); } else { // TODO@Tyriar - this call seems unnecessary this.layoutBody(this._bodyDimensions.height, this._bodyDimensions.width); } } else { this._terminalService.getActiveTab()?.setVisible(false); } })); // Force another layout (first is setContainers) since config has changed this.layoutBody(this._terminalContainer.offsetHeight, this._terminalContainer.offsetWidth); } protected layoutBody(height: number, width: number): void { super.layoutBody(height, width); if (this.shouldShowWelcome()) { return; } this._bodyDimensions.width = width; this._bodyDimensions.height = height; this._terminalService.terminalTabs.forEach(t => t.layout(width, height)); // Update orientation of split button icon if (this._splitTerminalAction) { this._splitTerminalAction.class = this.orientation === Orientation.HORIZONTAL ? SplitTerminalAction.HORIZONTAL_CLASS : SplitTerminalAction.VERTICAL_CLASS; } } public getActions(): IAction[] { if (!this._actions) { this._splitTerminalAction = this._instantiationService.createInstance(SplitTerminalAction, SplitTerminalAction.ID, SplitTerminalAction.LABEL); this._actions = [ this._instantiationService.createInstance(SwitchTerminalAction, SwitchTerminalAction.ID, SwitchTerminalAction.LABEL), this._instantiationService.createInstance(CreateNewTerminalAction, CreateNewTerminalAction.ID, CreateNewTerminalAction.SHORT_LABEL), this._splitTerminalAction, this._instantiationService.createInstance(KillTerminalAction, KillTerminalAction.ID, KillTerminalAction.PANEL_LABEL) ]; for (const action of this._actions) { if (!this._terminalService.isProcessSupportRegistered) { action.enabled = false; } this._register(action); } } return this._actions; } private _getContextMenuActions(): IAction[] { if (!this._contextMenuActions || !this._copyContextMenuAction) { this._copyContextMenuAction = this._instantiationService.createInstance(CopyTerminalSelectionAction, CopyTerminalSelectionAction.ID, CopyTerminalSelectionAction.SHORT_LABEL); const clipboardActions = []; if (BrowserFeatures.clipboard.writeText) { clipboardActions.push(this._copyContextMenuAction); } if (BrowserFeatures.clipboard.readText) { clipboardActions.push(this._instantiationService.createInstance(TerminalPasteAction, TerminalPasteAction.ID, TerminalPasteAction.SHORT_LABEL)); } clipboardActions.push(this._instantiationService.createInstance(SelectAllTerminalAction, SelectAllTerminalAction.ID, SelectAllTerminalAction.LABEL)); this._contextMenuActions = [ this._instantiationService.createInstance(CreateNewTerminalAction, CreateNewTerminalAction.ID, CreateNewTerminalAction.SHORT_LABEL), this._instantiationService.createInstance(SplitTerminalAction, SplitTerminalAction.ID, SplitTerminalAction.SHORT_LABEL), new Separator(), ...clipboardActions, new Separator(), this._instantiationService.createInstance(ClearTerminalAction, ClearTerminalAction.ID, ClearTerminalAction.LABEL), new Separator(), this._instantiationService.createInstance(KillTerminalAction, KillTerminalAction.ID, KillTerminalAction.PANEL_LABEL) ]; this._contextMenuActions.forEach(a => { this._register(a); }); } const activeInstance = this._terminalService.getActiveInstance(); this._copyContextMenuAction.enabled = !!activeInstance && activeInstance.hasSelection(); return this._contextMenuActions; } public getActionViewItem(action: Action): IActionViewItem | undefined { if (action.id === SwitchTerminalAction.ID) { return this._instantiationService.createInstance(SwitchTerminalActionViewItem, action); } return super.getActionViewItem(action); } public focus() { if (this._terminalService.getActiveInstance()) { this._terminalService.getActiveInstance()?.focusWhenReady(); } else { this._terminalService.willFocusNewTerminal = true; } } public focusFindWidget() { const activeInstance = this._terminalService.getActiveInstance(); if (activeInstance && activeInstance.hasSelection() && activeInstance.selection!.indexOf('\n') === -1) { this._findWidget!.reveal(activeInstance.selection); } else { this._findWidget!.reveal(); } } public hideFindWidget() { this._findWidget!.hide(); } public showFindWidget() { const activeInstance = this._terminalService.getActiveInstance(); if (activeInstance && activeInstance.hasSelection() && activeInstance.selection!.indexOf('\n') === -1) { this._findWidget!.show(activeInstance.selection); } else { this._findWidget!.show(); } } public getFindWidget(): TerminalFindWidget { return this._findWidget!; } private _attachEventListeners(parentDomElement: HTMLElement, terminalContainer: HTMLElement): void { this._register(dom.addDisposableListener(parentDomElement, 'mousedown', async (event: MouseEvent) => { if (this._terminalService.terminalInstances.length === 0) { return; } if (event.which === 2 && platform.isLinux) { // Drop selection and focus terminal on Linux to enable middle button paste when click // occurs on the selection itself. const terminal = this._terminalService.getActiveInstance(); if (terminal) { terminal.focus(); } } else if (event.which === 3) { const rightClickBehavior = this._terminalService.configHelper.config.rightClickBehavior; if (rightClickBehavior === 'copyPaste' || rightClickBehavior === 'paste') { const terminal = this._terminalService.getActiveInstance(); if (!terminal) { return; } // copyPaste: Shift+right click should open context menu if (rightClickBehavior === 'copyPaste' && event.shiftKey) { this._openContextMenu(event); return; } if (rightClickBehavior === 'copyPaste' && terminal.hasSelection()) { await terminal.copySelection(); terminal.clearSelection(); } else { terminal.paste(); } // Clear selection after all click event bubbling is finished on Mac to prevent // right-click selecting a word which is seemed cannot be disabled. There is a // flicker when pasting but this appears to give the best experience if the // setting is enabled. if (platform.isMacintosh) { setTimeout(() => { terminal.clearSelection(); }, 0); } this._cancelContextMenu = true; } } })); this._register(dom.addDisposableListener(parentDomElement, 'contextmenu', (event: MouseEvent) => { if (!this._cancelContextMenu) { this._openContextMenu(event); } event.preventDefault(); event.stopImmediatePropagation(); this._cancelContextMenu = false; })); this._register(dom.addDisposableListener(document, 'keydown', (event: KeyboardEvent) => { terminalContainer.classList.toggle('alt-active', !!event.altKey); })); this._register(dom.addDisposableListener(document, 'keyup', (event: KeyboardEvent) => { terminalContainer.classList.toggle('alt-active', !!event.altKey); })); this._register(dom.addDisposableListener(parentDomElement, 'keyup', (event: KeyboardEvent) => { if (event.keyCode === 27) { // Keep terminal open on escape event.stopPropagation(); } })); this._register(dom.addDisposableListener(parentDomElement, dom.EventType.DROP, async (e: DragEvent) => { if (e.target === this._parentDomElement || dom.isAncestor(e.target as HTMLElement, parentDomElement)) { if (!e.dataTransfer) { return; } // Check if files were dragged from the tree explorer let path: string | undefined; const resources = e.dataTransfer.getData(DataTransfers.RESOURCES); if (resources) { path = URI.parse(JSON.parse(resources)[0]).fsPath; } else if (e.dataTransfer.files.length > 0 && e.dataTransfer.files[0].path /* Electron only */) { // Check if the file was dragged from the filesystem path = URI.file(e.dataTransfer.files[0].path).fsPath; } if (!path) { return; } const terminal = this._terminalService.getActiveInstance(); if (terminal) { const preparedPath = await this._terminalService.preparePathForTerminalAsync(path, terminal.shellLaunchConfig.executable, terminal.title, terminal.shellType); terminal.sendText(preparedPath, false); terminal.focus(); } } })); } private _openContextMenu(event: MouseEvent): void { const standardEvent = new StandardMouseEvent(event); const anchor: { x: number, y: number } = { x: standardEvent.posx, y: standardEvent.posy }; this._contextMenuService.showContextMenu({ getAnchor: () => anchor, getActions: () => this._getContextMenuActions(), getActionsContext: () => this._parentDomElement }); } private _updateTheme(theme?: IColorTheme): void { if (!theme) { theme = this.themeService.getColorTheme(); } this._findWidget?.updateTheme(theme); } shouldShowWelcome(): boolean { return !this._terminalService.isProcessSupportRegistered; } } registerThemingParticipant((theme: IColorTheme, collector: ICssStyleCollector) => { const panelBackgroundColor = theme.getColor(TERMINAL_BACKGROUND_COLOR) || theme.getColor(PANEL_BACKGROUND); collector.addRule(`.monaco-workbench .part.panel .pane-body.integrated-terminal .terminal-outer-container { background-color: ${panelBackgroundColor ? panelBackgroundColor.toString() : ''}; }`); const sidebarBackgroundColor = theme.getColor(TERMINAL_BACKGROUND_COLOR) || theme.getColor(SIDE_BAR_BACKGROUND); collector.addRule(`.monaco-workbench .part.sidebar .pane-body.integrated-terminal .terminal-outer-container { background-color: ${sidebarBackgroundColor ? sidebarBackgroundColor.toString() : ''}; }`); const borderColor = theme.getColor(TERMINAL_BORDER_COLOR); if (borderColor) { collector.addRule(`.monaco-workbench .pane-body.integrated-terminal .split-view-view:not(:first-child) { border-color: ${borderColor.toString()}; }`); } });
src/vs/workbench/contrib/terminal/browser/terminalView.ts
1
https://github.com/microsoft/vscode/commit/574ee2032cc24ed250ef15962ce100838d4e5e4a
[ 0.9980292916297913, 0.18149910867214203, 0.00016235590737778693, 0.0007900330820120871, 0.3740392029285431 ]
{ "id": 7, "code_window": [ "\t\t}\n", "\t}\n", "\n", "\tpublic focusFindWidget() {\n", "\t\tconst activeInstance = this._terminalService.getActiveInstance();\n", "\t\tif (activeInstance && activeInstance.hasSelection() && activeInstance.selection!.indexOf('\\n') === -1) {\n" ], "labels": [ "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis._focus();\n", "\t}\n", "\n", "\tprivate _focus() {\n", "\t\tthis._terminalService.getActiveInstance()?.focusWhenReady();\n" ], "file_path": "src/vs/workbench/contrib/terminal/browser/terminalView.ts", "type": "add", "edit_start_line_idx": 224 }
/*--------------------------------------------------------------------------------------------- * 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 { Registry } from 'vs/platform/registry/common/platform'; import { Action2, registerAction2 } from 'vs/platform/actions/common/actions'; import { ServicesAccessor } from 'vs/platform/instantiation/common/instantiation'; import { IQuickInputService, IQuickPickItem, QuickPickInput } from 'vs/platform/quickinput/common/quickInput'; import { INotebookActionContext, NOTEBOOK_ACTIONS_CATEGORY, getActiveNotebookEditor } from 'vs/workbench/contrib/notebook/browser/contrib/coreActions'; import { INotebookEditor, NOTEBOOK_IS_ACTIVE_EDITOR } from 'vs/workbench/contrib/notebook/browser/notebookBrowser'; import { INotebookService } from 'vs/workbench/contrib/notebook/common/notebookService'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; import { CancellationTokenSource } from 'vs/base/common/cancellation'; import { INotebookKernelInfo2 } from 'vs/workbench/contrib/notebook/common/notebookCommon'; import { Extensions as WorkbenchExtensions, IWorkbenchContributionsRegistry, IWorkbenchContribution } from 'vs/workbench/common/contributions'; import { LifecyclePhase } from 'vs/workbench/services/lifecycle/common/lifecycle'; import { Disposable, DisposableStore, MutableDisposable } from 'vs/base/common/lifecycle'; import { IStatusbarEntryAccessor, IStatusbarService, StatusbarAlignment } from 'vs/workbench/services/statusbar/common/statusbar'; import { NotebookKernelProviderAssociation, NotebookKernelProviderAssociations, notebookKernelProviderAssociationsSettingId } from 'vs/workbench/contrib/notebook/browser/notebookKernelAssociation'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; registerAction2(class extends Action2 { constructor() { super({ id: 'notebook.selectKernel', category: NOTEBOOK_ACTIONS_CATEGORY, title: { value: nls.localize('notebookActions.selectKernel', "Select Notebook Kernel"), original: 'Select Notebook Kernel' }, precondition: NOTEBOOK_IS_ACTIVE_EDITOR, icon: { id: 'codicon/server-environment' }, f1: true }); } async run(accessor: ServicesAccessor, context?: INotebookActionContext): Promise<void> { const editorService = accessor.get<IEditorService>(IEditorService); const notebookService = accessor.get<INotebookService>(INotebookService); const quickInputService = accessor.get<IQuickInputService>(IQuickInputService); const configurationService = accessor.get<IConfigurationService>(IConfigurationService); const activeEditorPane = editorService.activeEditorPane as unknown as { isNotebookEditor?: boolean } | undefined; if (!activeEditorPane?.isNotebookEditor) { return; } const editor = editorService.activeEditorPane?.getControl() as INotebookEditor; const activeKernel = editor.activeKernel; const tokenSource = new CancellationTokenSource(); const availableKernels2 = await notebookService.getContributedNotebookKernels2(editor.viewModel!.viewType, editor.viewModel!.uri, tokenSource.token); const picks: QuickPickInput<IQuickPickItem & { run(): void; kernelProviderId?: string; }>[] = [...availableKernels2].map((a) => { return { id: a.id, label: a.label, picked: a.id === activeKernel?.id, description: a.description ? a.description : a.extension.value + (a.id === activeKernel?.id ? nls.localize('currentActiveKernel', " (Currently Active)") : ''), detail: a.detail, kernelProviderId: a.extension.value, run: async () => { editor.activeKernel = a; a.resolve(editor.uri!, editor.getId(), tokenSource.token); }, buttons: [{ iconClass: 'codicon-settings-gear', tooltip: nls.localize('notebook.promptKernel.setDefaultTooltip', "Set as default kernel provider for '{0}'", editor.viewModel!.viewType) }] }; }); const picker = quickInputService.createQuickPick<(IQuickPickItem & { run(): void; kernelProviderId?: string })>(); picker.items = picks; picker.activeItems = picks.filter(pick => (pick as IQuickPickItem).picked) as (IQuickPickItem & { run(): void; kernelProviderId?: string; })[]; picker.placeholder = nls.localize('pickAction', "Select Action"); picker.matchOnDetail = true; const pickedItem = await new Promise<(IQuickPickItem & { run(): void; kernelProviderId?: string; }) | undefined>(resolve => { picker.onDidAccept(() => { resolve(picker.selectedItems.length === 1 ? picker.selectedItems[0] : undefined); picker.dispose(); }); picker.onDidTriggerItemButton(e => { const pick = e.item; const id = pick.id; resolve(pick); // open the view picker.dispose(); // And persist the setting if (pick && id && pick.kernelProviderId) { const newAssociation: NotebookKernelProviderAssociation = { viewType: editor.viewModel!.viewType, kernelProvider: pick.kernelProviderId }; const currentAssociations = [...configurationService.getValue<NotebookKernelProviderAssociations>(notebookKernelProviderAssociationsSettingId)]; // First try updating existing association for (let i = 0; i < currentAssociations.length; ++i) { const existing = currentAssociations[i]; if (existing.viewType === newAssociation.viewType) { currentAssociations.splice(i, 1, newAssociation); configurationService.updateValue(notebookKernelProviderAssociationsSettingId, currentAssociations); return; } } // Otherwise, create a new one currentAssociations.unshift(newAssociation); configurationService.updateValue(notebookKernelProviderAssociationsSettingId, currentAssociations); } }); picker.show(); }); tokenSource.dispose(); return pickedItem?.run(); } }); export class KernelStatus extends Disposable implements IWorkbenchContribution { private _editorDisposable = new DisposableStore(); private readonly kernelInfoElement = this._register(new MutableDisposable<IStatusbarEntryAccessor>()); constructor( @IEditorService private readonly _editorService: IEditorService, @INotebookService private readonly _notebookService: INotebookService, @IStatusbarService private readonly _statusbarService: IStatusbarService, ) { super(); this.registerListeners(); } registerListeners() { this._register(this._editorService.onDidActiveEditorChange(() => this.updateStatusbar())); this._register(this._notebookService.onDidChangeActiveEditor(() => this.updateStatusbar())); this._register(this._notebookService.onDidChangeKernels(() => this.updateStatusbar())); } updateStatusbar() { this._editorDisposable.clear(); const activeEditor = getActiveNotebookEditor(this._editorService); if (activeEditor) { this._editorDisposable.add(activeEditor.onDidChangeKernel(() => { if (activeEditor.multipleKernelsAvailable) { this.showKernelStatus(activeEditor.activeKernel); } else { this.kernelInfoElement.clear(); } })); this._editorDisposable.add(activeEditor.onDidChangeAvailableKernels(() => { if (activeEditor.multipleKernelsAvailable) { this.showKernelStatus(activeEditor.activeKernel); } else { this.kernelInfoElement.clear(); } })); } if (activeEditor && activeEditor.multipleKernelsAvailable) { this.showKernelStatus(activeEditor.activeKernel); } else { this.kernelInfoElement.clear(); } } showKernelStatus(kernel: INotebookKernelInfo2 | undefined) { this.kernelInfoElement.value = this._statusbarService.addEntry({ text: kernel ? kernel.label : 'Choose Kernel', ariaLabel: kernel ? kernel.label : 'Choose Kernel', tooltip: nls.localize('chooseActiveKernel', "Choose kernel for current notebook"), command: 'notebook.selectKernel', }, 'notebook.selectKernel', nls.localize('notebook.selectKernel', "Choose kernel for current notebook"), StatusbarAlignment.RIGHT, 100); } } Registry.as<IWorkbenchContributionsRegistry>(WorkbenchExtensions.Workbench).registerWorkbenchContribution(KernelStatus, LifecyclePhase.Ready);
src/vs/workbench/contrib/notebook/browser/contrib/status/editorStatus.ts
0
https://github.com/microsoft/vscode/commit/574ee2032cc24ed250ef15962ce100838d4e5e4a
[ 0.00017608558118809015, 0.00017249712254852057, 0.00016518321353942156, 0.00017367374675814062, 0.000002744583980529569 ]
{ "id": 7, "code_window": [ "\t\t}\n", "\t}\n", "\n", "\tpublic focusFindWidget() {\n", "\t\tconst activeInstance = this._terminalService.getActiveInstance();\n", "\t\tif (activeInstance && activeInstance.hasSelection() && activeInstance.selection!.indexOf('\\n') === -1) {\n" ], "labels": [ "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis._focus();\n", "\t}\n", "\n", "\tprivate _focus() {\n", "\t\tthis._terminalService.getActiveInstance()?.focusWhenReady();\n" ], "file_path": "src/vs/workbench/contrib/terminal/browser/terminalView.ts", "type": "add", "edit_start_line_idx": 224 }
/*--------------------------------------------------------------------------------------------- * 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 { Event } from 'vs/base/common/event'; import { MenuBarVisibility } from 'vs/platform/windows/common/windows'; import { ILayoutService } from 'vs/platform/layout/browser/layoutService'; import { Part } from 'vs/workbench/browser/part'; import { Dimension } from 'vs/base/browser/dom'; import { Direction } from 'vs/base/browser/ui/grid/grid'; export const IWorkbenchLayoutService = createDecorator<IWorkbenchLayoutService>('layoutService'); export const enum Parts { TITLEBAR_PART = 'workbench.parts.titlebar', ACTIVITYBAR_PART = 'workbench.parts.activitybar', SIDEBAR_PART = 'workbench.parts.sidebar', PANEL_PART = 'workbench.parts.panel', EDITOR_PART = 'workbench.parts.editor', STATUSBAR_PART = 'workbench.parts.statusbar' } export const enum Position { LEFT, RIGHT, BOTTOM } export const enum PanelOpensMaximizedOptions { ALWAYS, NEVER, REMEMBER_LAST } export function positionToString(position: Position): string { switch (position) { case Position.LEFT: return 'left'; case Position.RIGHT: return 'right'; case Position.BOTTOM: return 'bottom'; default: return 'bottom'; } } const positionsByString: { [key: string]: Position } = { [positionToString(Position.LEFT)]: Position.LEFT, [positionToString(Position.RIGHT)]: Position.RIGHT, [positionToString(Position.BOTTOM)]: Position.BOTTOM }; export function positionFromString(str: string): Position { return positionsByString[str]; } export function panelOpensMaximizedSettingToString(setting: PanelOpensMaximizedOptions): string { switch (setting) { case PanelOpensMaximizedOptions.ALWAYS: return 'always'; case PanelOpensMaximizedOptions.NEVER: return 'never'; case PanelOpensMaximizedOptions.REMEMBER_LAST: return 'preserve'; default: return 'preserve'; } } const panelOpensMaximizedByString: { [key: string]: PanelOpensMaximizedOptions } = { [panelOpensMaximizedSettingToString(PanelOpensMaximizedOptions.ALWAYS)]: PanelOpensMaximizedOptions.ALWAYS, [panelOpensMaximizedSettingToString(PanelOpensMaximizedOptions.NEVER)]: PanelOpensMaximizedOptions.NEVER, [panelOpensMaximizedSettingToString(PanelOpensMaximizedOptions.REMEMBER_LAST)]: PanelOpensMaximizedOptions.REMEMBER_LAST }; export function panelOpensMaximizedFromString(str: string): PanelOpensMaximizedOptions { return panelOpensMaximizedByString[str]; } export interface IWorkbenchLayoutService extends ILayoutService { readonly _serviceBrand: undefined; /** * Emits when the zen mode is enabled or disabled. */ readonly onZenModeChange: Event<boolean>; /** * Emits when fullscreen is enabled or disabled. */ readonly onFullscreenChange: Event<boolean>; /** * Emits when the window is maximized or unmaximized. */ readonly onMaximizeChange: Event<boolean>; /** * Emits when centered layout is enabled or disabled. */ readonly onCenteredLayoutChange: Event<boolean>; /** * Emit when panel position changes. */ readonly onPanelPositionChange: Event<string>; /** * Emit when part visibility changes */ readonly onPartVisibilityChange: Event<void>; /** * Asks the part service if all parts have been fully restored. For editor part * this means that the contents of editors have loaded. */ isRestored(): boolean; /** * Returns whether the given part has the keyboard focus or not. */ hasFocus(part: Parts): boolean; /** * Focuses the part. If the part is not visible this is a noop. */ focusPart(part: Parts): void; /** * Returns the parts HTML element, if there is one. */ getContainer(part: Parts): HTMLElement | undefined; /** * Returns if the part is visible. */ isVisible(part: Parts): boolean; /** * Returns if the part is visible. */ getDimension(part: Parts): Dimension | undefined; /** * Set activity bar hidden or not */ setActivityBarHidden(hidden: boolean): void; /** * * Set editor area hidden or not */ setEditorHidden(hidden: boolean): void; /** * Set sidebar hidden or not */ setSideBarHidden(hidden: boolean): void; /** * Set panel part hidden or not */ setPanelHidden(hidden: boolean): void; /** * Maximizes the panel height if the panel is not already maximized. * Shrinks the panel to the default starting size if the panel is maximized. */ toggleMaximizedPanel(): void; /** * Returns true if the window has a border. */ hasWindowBorder(): boolean; /** * Returns the window border width. */ getWindowBorderWidth(): number; /** * Returns the window border radius if any. */ getWindowBorderRadius(): string | undefined; /** * Returns true if the panel is maximized. */ isPanelMaximized(): boolean; /** * Gets the current side bar position. Note that the sidebar can be hidden too. */ getSideBarPosition(): Position; /** * Gets the current menubar visibility. */ getMenubarVisibility(): MenuBarVisibility; /** * Gets the current panel position. Note that the panel can be hidden too. */ getPanelPosition(): Position; /** * Sets the panel position. */ setPanelPosition(position: Position): void; /** * Gets the maximum possible size for editor. */ getMaximumEditorDimensions(): Dimension; /** * Returns the element that is parent of the workbench element. */ getWorkbenchContainer(): HTMLElement; /** * Toggles the workbench in and out of zen mode - parts get hidden and window goes fullscreen. */ toggleZenMode(): void; /** * Returns whether the centered editor layout is active. */ isEditorLayoutCentered(): boolean; /** * Sets the workbench in and out of centered editor layout. */ centerEditorLayout(active: boolean): void; /** * Resizes currently focused part on main access */ resizePart(part: Parts, sizeChangeWidth: number, sizeChangeHeight: number): void; /** * Register a part to participate in the layout. */ registerPart(part: Part): void; /** * Returns whether the window is maximized. */ isWindowMaximized(): boolean; /** * Updates the maximized state of the window. */ updateWindowMaximizedState(maximized: boolean): void; /** * Returns the next visible view part in a given direction */ getVisibleNeighborPart(part: Parts, direction: Direction): Parts | undefined; /** * True if a default layout with default editors was applied at startup */ readonly openedDefaultEditors: boolean; }
src/vs/workbench/services/layout/browser/layoutService.ts
0
https://github.com/microsoft/vscode/commit/574ee2032cc24ed250ef15962ce100838d4e5e4a
[ 0.0005929808830842376, 0.00020621891599148512, 0.00016525677347090095, 0.0001748436625348404, 0.00008637283463031054 ]
{ "id": 7, "code_window": [ "\t\t}\n", "\t}\n", "\n", "\tpublic focusFindWidget() {\n", "\t\tconst activeInstance = this._terminalService.getActiveInstance();\n", "\t\tif (activeInstance && activeInstance.hasSelection() && activeInstance.selection!.indexOf('\\n') === -1) {\n" ], "labels": [ "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis._focus();\n", "\t}\n", "\n", "\tprivate _focus() {\n", "\t\tthis._terminalService.getActiveInstance()?.focusWhenReady();\n" ], "file_path": "src/vs/workbench/contrib/terminal/browser/terminalView.ts", "type": "add", "edit_start_line_idx": 224 }
# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. # yarn lockfile v1 "@types/[email protected]": version "4.1.5" resolved "https://registry.yarnpkg.com/@types/debug/-/debug-4.1.5.tgz#b14efa8852b7768d898906613c23f688713e02cd" integrity sha512-Q1y515GcOdTHgagaVFhHnIFQ38ygs/kmxdNpvpou+raI9UO3YZcHDngBSYKQklcKlvA7iuQlmIKbzvmxcOE9CQ== "@types/[email protected]": version "0.5.1" resolved "https://registry.yarnpkg.com/@types/mkdirp/-/mkdirp-0.5.1.tgz#ea887cd024f691c1ca67cce20b7606b053e43b0f" integrity sha512-XA4vNO6GCBz8Smq0hqSRo4yRWMqr4FPQrWjhJt6nKskzly4/p87SfuJMFYGRyYb6jo2WNIQU2FDBsY5r1BibUA== dependencies: "@types/node" "*" "@types/[email protected]": version "2.0.1" resolved "https://registry.yarnpkg.com/@types/ncp/-/ncp-2.0.1.tgz#749432511f6ad747d04e98837b18cca9045567fb" integrity sha512-TeiJ7uvv/92ugSqZ0v9l0eNXzutlki0aK+R1K5bfA5SYUil46ITlxLW4iNTCf55P4L5weCmaOdtxGeGWvudwPg== dependencies: "@types/node" "*" "@types/node@*": version "12.7.1" resolved "https://registry.yarnpkg.com/@types/node/-/node-12.7.1.tgz#3b5c3a26393c19b400844ac422bd0f631a94d69d" integrity sha512-aK9jxMypeSrhiYofWWBf/T7O+KwaiAHzM4sveCdWPn71lzUSMimRnKzhXDKfKwV1kWoBo2P1aGgaIYGLf9/ljw== "@types/node@^12.11.7": version "12.12.26" resolved "https://registry.yarnpkg.com/@types/node/-/node-12.12.26.tgz#213e153babac0ed169d44a6d919501e68f59dea9" integrity sha512-UmUm94/QZvU5xLcUlNR8hA7Ac+fGpO1EG/a8bcWVz0P0LqtxFmun9Y2bbtuckwGboWJIT70DoWq1r3hb56n3DA== "@types/[email protected]": version "0.1.0" resolved "https://registry.yarnpkg.com/@types/tmp/-/tmp-0.1.0.tgz#19cf73a7bcf641965485119726397a096f0049bd" integrity sha512-6IwZ9HzWbCq6XoQWhxLpDjuADodH/MKXRUIDFudvgjcVdjFknvmR+DNsoUeer4XPrEnrZs04Jj+kfV9pFsrhmA== abbrev@1: version "1.1.1" resolved "https://registry.yarnpkg.com/abbrev/-/abbrev-1.1.1.tgz#f8f2c887ad10bf67f634f005b6987fed3179aac8" integrity sha512-nne9/IiQ/hzIhY6pdDnbBtz7DjPTKrY00P/zvPSm5pOFkl6xuGrGnXn/VtTNNfNtAfZ9/1RtehkszU9qcTii0Q== ansi-regex@^2.0.0: version "2.1.1" resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-2.1.1.tgz#c3b33ab5ee360d86e0e628f0468ae7ef27d654df" integrity sha1-w7M6te42DYbg5ijwRorn7yfWVN8= ansi-regex@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-3.0.0.tgz#ed0317c322064f79466c02966bddb605ab37d998" integrity sha1-7QMXwyIGT3lGbAKWa922Bas32Zg= ansi-styles@^3.2.1: version "3.2.1" resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-3.2.1.tgz#41fbb20243e50b12be0f04b8dedbf07520ce841d" integrity sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA== dependencies: color-convert "^1.9.0" anymatch@^1.3.0: version "1.3.2" resolved "https://registry.yarnpkg.com/anymatch/-/anymatch-1.3.2.tgz#553dcb8f91e3c889845dfdba34c77721b90b9d7a" integrity sha512-0XNayC8lTHQ2OI8aljNCN3sSx6hsr/1+rlcDAotXJR7C1oZZHCNsfpbKwMjRA3Uqb5tF1Rae2oloTr4xpq+WjA== dependencies: micromatch "^2.1.5" normalize-path "^2.0.0" aproba@^1.0.3: version "1.2.0" resolved "https://registry.yarnpkg.com/aproba/-/aproba-1.2.0.tgz#6802e6264efd18c790a1b0d517f0f2627bf2c94a" integrity sha512-Y9J6ZjXtoYh8RnXVCMOU/ttDmk1aBjunq9vO0ta5x85WDQiQfUF9sIPBITdbiiIVcBo03Hi3jMxigBtsddlXRw== are-we-there-yet@~1.1.2: version "1.1.5" resolved "https://registry.yarnpkg.com/are-we-there-yet/-/are-we-there-yet-1.1.5.tgz#4b35c2944f062a8bfcda66410760350fe9ddfc21" integrity sha512-5hYdAkZlcG8tOLujVDTgCT+uPX0VnpAH28gWsLfzpXYm7wP6mp5Q/gYyR7YQ0cKVJcXJnl3j2kpBan13PtQf6w== dependencies: delegates "^1.0.0" readable-stream "^2.0.6" arr-diff@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/arr-diff/-/arr-diff-2.0.0.tgz#8f3b827f955a8bd669697e4a4256ac3ceae356cf" integrity sha1-jzuCf5Vai9ZpaX5KQlasPOrjVs8= dependencies: arr-flatten "^1.0.1" arr-diff@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/arr-diff/-/arr-diff-4.0.0.tgz#d6461074febfec71e7e15235761a329a5dc7c520" integrity sha1-1kYQdP6/7HHn4VI1dhoyml3HxSA= arr-flatten@^1.0.1, arr-flatten@^1.1.0: version "1.1.0" resolved "https://registry.yarnpkg.com/arr-flatten/-/arr-flatten-1.1.0.tgz#36048bbff4e7b47e136644316c99669ea5ae91f1" integrity sha512-L3hKV5R/p5o81R7O02IGnwpDmkp6E982XhtbuwSe3O4qOtMMMtodicASA1Cny2U+aCXcNpml+m4dPsvsJ3jatg== arr-union@^3.1.0: version "3.1.0" resolved "https://registry.yarnpkg.com/arr-union/-/arr-union-3.1.0.tgz#e39b09aea9def866a8f206e288af63919bae39c4" integrity sha1-45sJrqne+Gao8gbiiK9jkZuuOcQ= array-unique@^0.2.1: version "0.2.1" resolved "https://registry.yarnpkg.com/array-unique/-/array-unique-0.2.1.tgz#a1d97ccafcbc2625cc70fadceb36a50c58b01a53" integrity sha1-odl8yvy8JiXMcPrc6zalDFiwGlM= array-unique@^0.3.2: version "0.3.2" resolved "https://registry.yarnpkg.com/array-unique/-/array-unique-0.3.2.tgz#a894b75d4bc4f6cd679ef3244a9fd8f46ae2d428" integrity sha1-qJS3XUvE9s1nnvMkSp/Y9Gri1Cg= assign-symbols@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/assign-symbols/-/assign-symbols-1.0.0.tgz#59667f41fadd4f20ccbc2bb96b8d4f7f78ec0367" integrity sha1-WWZ/QfrdTyDMvCu5a41Pf3jsA2c= async-each@^1.0.0: version "1.0.3" resolved "https://registry.yarnpkg.com/async-each/-/async-each-1.0.3.tgz#b727dbf87d7651602f06f4d4ac387f47d91b0cbf" integrity sha512-z/WhQ5FPySLdvREByI2vZiTWwCnF0moMJ1hK9YQwDTHKh6I7/uSckMetoRGb5UBZPC1z0jlw+n/XCgjeH7y1AQ== atob@^2.1.1: version "2.1.2" resolved "https://registry.yarnpkg.com/atob/-/atob-2.1.2.tgz#6d9517eb9e030d2436666651e86bd9f6f13533c9" integrity sha512-Wm6ukoaOGJi/73p/cl2GvLjTI5JM1k/O14isD73YML8StrH/7/lRFgmg8nICZgD3bZZvjwCGxtMOD3wWNAu8cg== babel-runtime@^6.9.2: version "6.26.0" resolved "https://registry.yarnpkg.com/babel-runtime/-/babel-runtime-6.26.0.tgz#965c7058668e82b55d7bfe04ff2337bc8b5647fe" integrity sha1-llxwWGaOgrVde/4E/yM3vItWR/4= dependencies: core-js "^2.4.0" regenerator-runtime "^0.11.0" balanced-match@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/balanced-match/-/balanced-match-1.0.0.tgz#89b4d199ab2bee49de164ea02b89ce462d71b767" integrity sha1-ibTRmasr7kneFk6gK4nORi1xt2c= base@^0.11.1: version "0.11.2" resolved "https://registry.yarnpkg.com/base/-/base-0.11.2.tgz#7bde5ced145b6d551a90db87f83c558b4eb48a8f" integrity sha512-5T6P4xPgpp0YDFvSWwEZ4NoE3aM4QBQXDzmVbraCkFj8zHM+mba8SyqB5DbZWyR7mYHo6Y7BdQo3MoA4m0TeQg== dependencies: cache-base "^1.0.1" class-utils "^0.3.5" component-emitter "^1.2.1" define-property "^1.0.0" isobject "^3.0.1" mixin-deep "^1.2.0" pascalcase "^0.1.1" binary-extensions@^1.0.0: version "1.13.1" resolved "https://registry.yarnpkg.com/binary-extensions/-/binary-extensions-1.13.1.tgz#598afe54755b2868a5330d2aff9d4ebb53209b65" integrity sha512-Un7MIEDdUC5gNpcGDV97op1Ywk748MpHcFTHoYs6qnj1Z3j7I53VG3nwZhKzoBZmbdRNnb6WRdFlwl7tSDuZGw== brace-expansion@^1.1.7: version "1.1.11" resolved "https://registry.yarnpkg.com/brace-expansion/-/brace-expansion-1.1.11.tgz#3c7fcbf529d87226f3d2f52b966ff5271eb441dd" integrity sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA== dependencies: balanced-match "^1.0.0" concat-map "0.0.1" braces@^1.8.2: version "1.8.5" resolved "https://registry.yarnpkg.com/braces/-/braces-1.8.5.tgz#ba77962e12dff969d6b76711e914b737857bf6a7" integrity sha1-uneWLhLf+WnWt2cR6RS3N4V79qc= dependencies: expand-range "^1.8.1" preserve "^0.2.0" repeat-element "^1.1.2" braces@^2.3.1: version "2.3.2" resolved "https://registry.yarnpkg.com/braces/-/braces-2.3.2.tgz#5979fd3f14cd531565e5fa2df1abfff1dfaee729" integrity sha512-aNdbnj9P8PjdXU4ybaWLK2IF3jc/EoDYbC7AazW6to3TRsfXxscC9UXOB5iDiEQrkyIbWp2SLQda4+QAa7nc3w== dependencies: arr-flatten "^1.1.0" array-unique "^0.3.2" extend-shallow "^2.0.1" fill-range "^4.0.0" isobject "^3.0.1" repeat-element "^1.1.2" snapdragon "^0.8.1" snapdragon-node "^2.0.1" split-string "^3.0.2" to-regex "^3.0.1" cache-base@^1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/cache-base/-/cache-base-1.0.1.tgz#0a7f46416831c8b662ee36fe4e7c59d76f666ab2" integrity sha512-AKcdTnFSWATd5/GCPRxr2ChwIJ85CeyrEyjRHlKxQ56d4XJMGym0uAiKn0xbLOGOl3+yRpOTi484dVCEc5AUzQ== dependencies: collection-visit "^1.0.0" component-emitter "^1.2.1" get-value "^2.0.6" has-value "^1.0.0" isobject "^3.0.1" set-value "^2.0.0" to-object-path "^0.3.0" union-value "^1.0.0" unset-value "^1.0.0" chalk@^2.4.1: version "2.4.2" resolved "https://registry.yarnpkg.com/chalk/-/chalk-2.4.2.tgz#cd42541677a54333cf541a49108c1432b44c9424" integrity sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ== dependencies: ansi-styles "^3.2.1" escape-string-regexp "^1.0.5" supports-color "^5.3.0" chokidar@^1.6.0: version "1.7.0" resolved "https://registry.yarnpkg.com/chokidar/-/chokidar-1.7.0.tgz#798e689778151c8076b4b360e5edd28cda2bb468" integrity sha1-eY5ol3gVHIB2tLNg5e3SjNortGg= dependencies: anymatch "^1.3.0" async-each "^1.0.0" glob-parent "^2.0.0" inherits "^2.0.1" is-binary-path "^1.0.0" is-glob "^2.0.0" path-is-absolute "^1.0.0" readdirp "^2.0.0" optionalDependencies: fsevents "^1.0.0" chownr@^1.1.1: version "1.1.2" resolved "https://registry.yarnpkg.com/chownr/-/chownr-1.1.2.tgz#a18f1e0b269c8a6a5d3c86eb298beb14c3dd7bf6" integrity sha512-GkfeAQh+QNy3wquu9oIZr6SS5x7wGdSgNQvD10X3r+AZr1Oys22HW8kAmDMvNg2+Dm0TeGaEuO8gFwdBXxwO8A== class-utils@^0.3.5: version "0.3.6" resolved "https://registry.yarnpkg.com/class-utils/-/class-utils-0.3.6.tgz#f93369ae8b9a7ce02fd41faad0ca83033190c463" integrity sha512-qOhPa/Fj7s6TY8H8esGu5QNpMMQxz79h+urzrNYN6mn+9BnxlDGf5QZ+XeCDsxSjPqsSR56XOZOJmpeurnLMeg== dependencies: arr-union "^3.1.0" define-property "^0.2.5" isobject "^3.0.0" static-extend "^0.1.1" code-point-at@^1.0.0: version "1.1.0" resolved "https://registry.yarnpkg.com/code-point-at/-/code-point-at-1.1.0.tgz#0d070b4d043a5bea33a2f1a40e2edb3d9a4ccf77" integrity sha1-DQcLTQQ6W+ozovGkDi7bPZpMz3c= collection-visit@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/collection-visit/-/collection-visit-1.0.0.tgz#4bc0373c164bc3291b4d368c829cf1a80a59dca0" integrity sha1-S8A3PBZLwykbTTaMgpzxqApZ3KA= dependencies: map-visit "^1.0.0" object-visit "^1.0.0" color-convert@^1.9.0: version "1.9.3" resolved "https://registry.yarnpkg.com/color-convert/-/color-convert-1.9.3.tgz#bb71850690e1f136567de629d2d5471deda4c1e8" integrity sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg== dependencies: color-name "1.1.3" [email protected]: version "1.1.3" resolved "https://registry.yarnpkg.com/color-name/-/color-name-1.1.3.tgz#a7d0558bd89c42f795dd42328f740831ca53bc25" integrity sha1-p9BVi9icQveV3UIyj3QIMcpTvCU= [email protected]: version "2.6.0" resolved "https://registry.yarnpkg.com/commander/-/commander-2.6.0.tgz#9df7e52fb2a0cb0fb89058ee80c3104225f37e1d" integrity sha1-nfflL7Kgyw+4kFjugMMQQiXzfh0= component-emitter@^1.2.1: version "1.3.0" resolved "https://registry.yarnpkg.com/component-emitter/-/component-emitter-1.3.0.tgz#16e4070fba8ae29b679f2215853ee181ab2eabc0" integrity sha512-Rd3se6QB+sO1TwqZjscQrurpEPIfO0/yYnSin6Q/rD3mOutHvUrCAhJub3r90uNb+SESBuE0QYoB90YdfatsRg== [email protected]: version "0.0.1" resolved "https://registry.yarnpkg.com/concat-map/-/concat-map-0.0.1.tgz#d8a96bd77fd68df7793a73036a3ba0d5405d477b" integrity sha1-2Klr13/Wjfd5OnMDajug1UBdR3s= concurrently@^3.5.1: version "3.6.1" resolved "https://registry.yarnpkg.com/concurrently/-/concurrently-3.6.1.tgz#2f95baec5c4051294dfbb55b57a3b98a3e2b45ec" integrity sha512-/+ugz+gwFSEfTGUxn0KHkY+19XPRTXR8+7oUK/HxgiN1n7FjeJmkrbSiXAJfyQ0zORgJYPaenmymwon51YXH9Q== dependencies: chalk "^2.4.1" commander "2.6.0" date-fns "^1.23.0" lodash "^4.5.1" read-pkg "^3.0.0" rx "2.3.24" spawn-command "^0.0.2-1" supports-color "^3.2.3" tree-kill "^1.1.0" console-control-strings@^1.0.0, console-control-strings@~1.1.0: version "1.1.0" resolved "https://registry.yarnpkg.com/console-control-strings/-/console-control-strings-1.1.0.tgz#3d7cf4464db6446ea644bf4b39507f9851008e8e" integrity sha1-PXz0Rk22RG6mRL9LOVB/mFEAjo4= copy-descriptor@^0.1.0: version "0.1.1" resolved "https://registry.yarnpkg.com/copy-descriptor/-/copy-descriptor-0.1.1.tgz#676f6eb3c39997c2ee1ac3a924fd6124748f578d" integrity sha1-Z29us8OZl8LuGsOpJP1hJHSPV40= core-js@^2.4.0: version "2.6.9" resolved "https://registry.yarnpkg.com/core-js/-/core-js-2.6.9.tgz#6b4b214620c834152e179323727fc19741b084f2" integrity sha512-HOpZf6eXmnl7la+cUdMnLvUxKNqLUzJvgIziQ0DiF3JwSImNphIqdGqzj6hIKyX04MmV0poclQ7+wjWvxQyR2A== core-util-is@~1.0.0: version "1.0.2" resolved "https://registry.yarnpkg.com/core-util-is/-/core-util-is-1.0.2.tgz#b5fd54220aa2bc5ab57aab7140c940754503c1a7" integrity sha1-tf1UIgqivFq1eqtxQMlAdUUDwac= cpx@^1.5.0: version "1.5.0" resolved "https://registry.yarnpkg.com/cpx/-/cpx-1.5.0.tgz#185be018511d87270dedccc293171e37655ab88f" integrity sha1-GFvgGFEdhycN7czCkxceN2VauI8= dependencies: babel-runtime "^6.9.2" chokidar "^1.6.0" duplexer "^0.1.1" glob "^7.0.5" glob2base "^0.0.12" minimatch "^3.0.2" mkdirp "^0.5.1" resolve "^1.1.7" safe-buffer "^5.0.1" shell-quote "^1.6.1" subarg "^1.0.0" date-fns@^1.23.0: version "1.30.1" resolved "https://registry.yarnpkg.com/date-fns/-/date-fns-1.30.1.tgz#2e71bf0b119153dbb4cc4e88d9ea5acfb50dc05c" integrity sha512-hBSVCvSmWC+QypYObzwGOd9wqdDpOt+0wl0KbU+R+uuZBS1jN8VsD1ss3irQDknRj5NvxiTF6oj/nDRnN/UQNw== debug@^2.2.0, debug@^2.3.3: version "2.6.9" resolved "https://registry.yarnpkg.com/debug/-/debug-2.6.9.tgz#5d128515df134ff327e90a4c93f4e077a536341f" integrity sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA== dependencies: ms "2.0.0" debug@^3.2.6: version "3.2.6" resolved "https://registry.yarnpkg.com/debug/-/debug-3.2.6.tgz#e83d17de16d8a7efb7717edbe5fb10135eee629b" integrity sha512-mel+jf7nrtEl5Pn1Qx46zARXKDpBbvzezse7p7LqINmdoIk8PYP5SySaxEmYv6TZ0JyEKA1hsCId6DIhgITtWQ== dependencies: ms "^2.1.1" decode-uri-component@^0.2.0: version "0.2.0" resolved "https://registry.yarnpkg.com/decode-uri-component/-/decode-uri-component-0.2.0.tgz#eb3913333458775cb84cd1a1fae062106bb87545" integrity sha1-6zkTMzRYd1y4TNGh+uBiEGu4dUU= deep-extend@^0.6.0: version "0.6.0" resolved "https://registry.yarnpkg.com/deep-extend/-/deep-extend-0.6.0.tgz#c4fa7c95404a17a9c3e8ca7e1537312b736330ac" integrity sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA== define-property@^0.2.5: version "0.2.5" resolved "https://registry.yarnpkg.com/define-property/-/define-property-0.2.5.tgz#c35b1ef918ec3c990f9a5bc57be04aacec5c8116" integrity sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY= dependencies: is-descriptor "^0.1.0" define-property@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/define-property/-/define-property-1.0.0.tgz#769ebaaf3f4a63aad3af9e8d304c9bbe79bfb0e6" integrity sha1-dp66rz9KY6rTr56NMEybvnm/sOY= dependencies: is-descriptor "^1.0.0" define-property@^2.0.2: version "2.0.2" resolved "https://registry.yarnpkg.com/define-property/-/define-property-2.0.2.tgz#d459689e8d654ba77e02a817f8710d702cb16e9d" integrity sha512-jwK2UV4cnPpbcG7+VRARKTZPUWowwXA8bzH5NP6ud0oeAxyYPuGZUAC7hMugpCdz4BeSZl2Dl9k66CHJ/46ZYQ== dependencies: is-descriptor "^1.0.2" isobject "^3.0.1" delegates@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/delegates/-/delegates-1.0.0.tgz#84c6e159b81904fdca59a0ef44cd870d31250f9a" integrity sha1-hMbhWbgZBP3KWaDvRM2HDTElD5o= detect-libc@^1.0.2: version "1.0.3" resolved "https://registry.yarnpkg.com/detect-libc/-/detect-libc-1.0.3.tgz#fa137c4bd698edf55cd5cd02ac559f91a4c4ba9b" integrity sha1-+hN8S9aY7fVc1c0CrFWfkaTEups= duplexer@^0.1.1: version "0.1.1" resolved "https://registry.yarnpkg.com/duplexer/-/duplexer-0.1.1.tgz#ace6ff808c1ce66b57d1ebf97977acb02334cfc1" integrity sha1-rOb/gIwc5mtX0ev5eXessCM0z8E= error-ex@^1.3.1: version "1.3.2" resolved "https://registry.yarnpkg.com/error-ex/-/error-ex-1.3.2.tgz#b4ac40648107fdcdcfae242f428bea8a14d4f1bf" integrity sha512-7dFHNmqeFSEt2ZBsCriorKnn3Z2pj+fd9kmI6QoWw4//DL+icEBfc0U7qJCisqrTsKTjw4fNFy2pW9OqStD84g== dependencies: is-arrayish "^0.2.1" escape-string-regexp@^1.0.5: version "1.0.5" resolved "https://registry.yarnpkg.com/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz#1b61c0562190a8dff6ae3bb2cf0200ca130b86d4" integrity sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ= exec-sh@^0.2.0: version "0.2.2" resolved "https://registry.yarnpkg.com/exec-sh/-/exec-sh-0.2.2.tgz#2a5e7ffcbd7d0ba2755bdecb16e5a427dfbdec36" integrity sha512-FIUCJz1RbuS0FKTdaAafAByGS0CPvU3R0MeHxgtl+djzCc//F8HakL8GzmVNZanasTbTAY/3DRFA0KpVqj/eAw== dependencies: merge "^1.2.0" expand-brackets@^0.1.4: version "0.1.5" resolved "https://registry.yarnpkg.com/expand-brackets/-/expand-brackets-0.1.5.tgz#df07284e342a807cd733ac5af72411e581d1177b" integrity sha1-3wcoTjQqgHzXM6xa9yQR5YHRF3s= dependencies: is-posix-bracket "^0.1.0" expand-brackets@^2.1.4: version "2.1.4" resolved "https://registry.yarnpkg.com/expand-brackets/-/expand-brackets-2.1.4.tgz#b77735e315ce30f6b6eff0f83b04151a22449622" integrity sha1-t3c14xXOMPa27/D4OwQVGiJEliI= dependencies: debug "^2.3.3" define-property "^0.2.5" extend-shallow "^2.0.1" posix-character-classes "^0.1.0" regex-not "^1.0.0" snapdragon "^0.8.1" to-regex "^3.0.1" expand-range@^1.8.1: version "1.8.2" resolved "https://registry.yarnpkg.com/expand-range/-/expand-range-1.8.2.tgz#a299effd335fe2721ebae8e257ec79644fc85337" integrity sha1-opnv/TNf4nIeuujiV+x5ZE/IUzc= dependencies: fill-range "^2.1.0" extend-shallow@^2.0.1: version "2.0.1" resolved "https://registry.yarnpkg.com/extend-shallow/-/extend-shallow-2.0.1.tgz#51af7d614ad9a9f610ea1bafbb989d6b1c56890f" integrity sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8= dependencies: is-extendable "^0.1.0" extend-shallow@^3.0.0, extend-shallow@^3.0.2: version "3.0.2" resolved "https://registry.yarnpkg.com/extend-shallow/-/extend-shallow-3.0.2.tgz#26a71aaf073b39fb2127172746131c2704028db8" integrity sha1-Jqcarwc7OfshJxcnRhMcJwQCjbg= dependencies: assign-symbols "^1.0.0" is-extendable "^1.0.1" extglob@^0.3.1: version "0.3.2" resolved "https://registry.yarnpkg.com/extglob/-/extglob-0.3.2.tgz#2e18ff3d2f49ab2765cec9023f011daa8d8349a1" integrity sha1-Lhj/PS9JqydlzskCPwEdqo2DSaE= dependencies: is-extglob "^1.0.0" extglob@^2.0.4: version "2.0.4" resolved "https://registry.yarnpkg.com/extglob/-/extglob-2.0.4.tgz#ad00fe4dc612a9232e8718711dc5cb5ab0285543" integrity sha512-Nmb6QXkELsuBr24CJSkilo6UHHgbekK5UiZgfE6UHD3Eb27YC6oD+bhcT+tJ6cl8dmsgdQxnWlcry8ksBIBLpw== dependencies: array-unique "^0.3.2" define-property "^1.0.0" expand-brackets "^2.1.4" extend-shallow "^2.0.1" fragment-cache "^0.2.1" regex-not "^1.0.0" snapdragon "^0.8.1" to-regex "^3.0.1" filename-regex@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/filename-regex/-/filename-regex-2.0.1.tgz#c1c4b9bee3e09725ddb106b75c1e301fe2f18b26" integrity sha1-wcS5vuPglyXdsQa3XB4wH+LxiyY= fill-range@^2.1.0: version "2.2.4" resolved "https://registry.yarnpkg.com/fill-range/-/fill-range-2.2.4.tgz#eb1e773abb056dcd8df2bfdf6af59b8b3a936565" integrity sha512-cnrcCbj01+j2gTG921VZPnHbjmdAf8oQV/iGeV2kZxGSyfYjjTyY79ErsK1WJWMpw6DaApEX72binqJE+/d+5Q== dependencies: is-number "^2.1.0" isobject "^2.0.0" randomatic "^3.0.0" repeat-element "^1.1.2" repeat-string "^1.5.2" fill-range@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/fill-range/-/fill-range-4.0.0.tgz#d544811d428f98eb06a63dc402d2403c328c38f7" integrity sha1-1USBHUKPmOsGpj3EAtJAPDKMOPc= dependencies: extend-shallow "^2.0.1" is-number "^3.0.0" repeat-string "^1.6.1" to-regex-range "^2.1.0" find-index@^0.1.1: version "0.1.1" resolved "https://registry.yarnpkg.com/find-index/-/find-index-0.1.1.tgz#675d358b2ca3892d795a1ab47232f8b6e2e0dde4" integrity sha1-Z101iyyjiS15Whq0cjL4tuLg3eQ= for-in@^1.0.1, for-in@^1.0.2: version "1.0.2" resolved "https://registry.yarnpkg.com/for-in/-/for-in-1.0.2.tgz#81068d295a8142ec0ac726c6e2200c30fb6d5e80" integrity sha1-gQaNKVqBQuwKxybG4iAMMPttXoA= for-own@^0.1.4: version "0.1.5" resolved "https://registry.yarnpkg.com/for-own/-/for-own-0.1.5.tgz#5265c681a4f294dabbf17c9509b6763aa84510ce" integrity sha1-UmXGgaTylNq78XyVCbZ2OqhFEM4= dependencies: for-in "^1.0.1" fragment-cache@^0.2.1: version "0.2.1" resolved "https://registry.yarnpkg.com/fragment-cache/-/fragment-cache-0.2.1.tgz#4290fad27f13e89be7f33799c6bc5a0abfff0d19" integrity sha1-QpD60n8T6Jvn8zeZxrxaCr//DRk= dependencies: map-cache "^0.2.2" fs-minipass@^1.2.5: version "1.2.6" resolved "https://registry.yarnpkg.com/fs-minipass/-/fs-minipass-1.2.6.tgz#2c5cc30ded81282bfe8a0d7c7c1853ddeb102c07" integrity sha512-crhvyXcMejjv3Z5d2Fa9sf5xLYVCF5O1c71QxbVnbLsmYMBEvDAftewesN/HhY03YRoA7zOMxjNGrF5svGaaeQ== dependencies: minipass "^2.2.1" fs.realpath@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/fs.realpath/-/fs.realpath-1.0.0.tgz#1504ad2523158caa40db4a2787cb01411994ea4f" integrity sha1-FQStJSMVjKpA20onh8sBQRmU6k8= fsevents@^1.0.0: version "1.2.9" resolved "https://registry.yarnpkg.com/fsevents/-/fsevents-1.2.9.tgz#3f5ed66583ccd6f400b5a00db6f7e861363e388f" integrity sha512-oeyj2H3EjjonWcFjD5NvZNE9Rqe4UW+nQBU2HNeKw0koVLEFIhtyETyAakeAM3de7Z/SW5kcA+fZUait9EApnw== dependencies: nan "^2.12.1" node-pre-gyp "^0.12.0" gauge@~2.7.3: version "2.7.4" resolved "https://registry.yarnpkg.com/gauge/-/gauge-2.7.4.tgz#2c03405c7538c39d7eb37b317022e325fb018bf7" integrity sha1-LANAXHU4w51+s3sxcCLjJfsBi/c= dependencies: aproba "^1.0.3" console-control-strings "^1.0.0" has-unicode "^2.0.0" object-assign "^4.1.0" signal-exit "^3.0.0" string-width "^1.0.1" strip-ansi "^3.0.1" wide-align "^1.1.0" get-value@^2.0.3, get-value@^2.0.6: version "2.0.6" resolved "https://registry.yarnpkg.com/get-value/-/get-value-2.0.6.tgz#dc15ca1c672387ca76bd37ac0a395ba2042a2c28" integrity sha1-3BXKHGcjh8p2vTesCjlbogQqLCg= glob-base@^0.3.0: version "0.3.0" resolved "https://registry.yarnpkg.com/glob-base/-/glob-base-0.3.0.tgz#dbb164f6221b1c0b1ccf82aea328b497df0ea3c4" integrity sha1-27Fk9iIbHAscz4Kuoyi0l98Oo8Q= dependencies: glob-parent "^2.0.0" is-glob "^2.0.0" glob-parent@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/glob-parent/-/glob-parent-2.0.0.tgz#81383d72db054fcccf5336daa902f182f6edbb28" integrity sha1-gTg9ctsFT8zPUzbaqQLxgvbtuyg= dependencies: is-glob "^2.0.0" glob2base@^0.0.12: version "0.0.12" resolved "https://registry.yarnpkg.com/glob2base/-/glob2base-0.0.12.tgz#9d419b3e28f12e83a362164a277055922c9c0d56" integrity sha1-nUGbPijxLoOjYhZKJ3BVkiycDVY= dependencies: find-index "^0.1.1" glob@^7.0.5, glob@^7.1.3: version "7.1.4" resolved "https://registry.yarnpkg.com/glob/-/glob-7.1.4.tgz#aa608a2f6c577ad357e1ae5a5c26d9a8d1969255" integrity sha512-hkLPepehmnKk41pUGm3sYxoFs/umurYfYJCerbXEyFIWcAzvpipAgVkBqqT9RBKMGjnq6kMuyYwha6csxbiM1A== dependencies: fs.realpath "^1.0.0" inflight "^1.0.4" inherits "2" minimatch "^3.0.4" once "^1.3.0" path-is-absolute "^1.0.0" graceful-fs@^4.1.11, graceful-fs@^4.1.2: version "4.2.2" resolved "https://registry.yarnpkg.com/graceful-fs/-/graceful-fs-4.2.2.tgz#6f0952605d0140c1cfdb138ed005775b92d67b02" integrity sha512-IItsdsea19BoLC7ELy13q1iJFNmd7ofZH5+X/pJr90/nRoPEX0DJo1dHDbgtYWOhJhcCgMDTOw84RZ72q6lB+Q== has-flag@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/has-flag/-/has-flag-1.0.0.tgz#9d9e793165ce017a00f00418c43f942a7b1d11fa" integrity sha1-nZ55MWXOAXoA8AQYxD+UKnsdEfo= has-flag@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/has-flag/-/has-flag-3.0.0.tgz#b5d454dc2199ae225699f3467e5a07f3b955bafd" integrity sha1-tdRU3CGZriJWmfNGfloH87lVuv0= has-unicode@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/has-unicode/-/has-unicode-2.0.1.tgz#e0e6fe6a28cf51138855e086d1691e771de2a8b9" integrity sha1-4Ob+aijPUROIVeCG0Wkedx3iqLk= has-value@^0.3.1: version "0.3.1" resolved "https://registry.yarnpkg.com/has-value/-/has-value-0.3.1.tgz#7b1f58bada62ca827ec0a2078025654845995e1f" integrity sha1-ex9YutpiyoJ+wKIHgCVlSEWZXh8= dependencies: get-value "^2.0.3" has-values "^0.1.4" isobject "^2.0.0" has-value@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/has-value/-/has-value-1.0.0.tgz#18b281da585b1c5c51def24c930ed29a0be6b177" integrity sha1-GLKB2lhbHFxR3vJMkw7SmgvmsXc= dependencies: get-value "^2.0.6" has-values "^1.0.0" isobject "^3.0.0" has-values@^0.1.4: version "0.1.4" resolved "https://registry.yarnpkg.com/has-values/-/has-values-0.1.4.tgz#6d61de95d91dfca9b9a02089ad384bff8f62b771" integrity sha1-bWHeldkd/Km5oCCJrThL/49it3E= has-values@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/has-values/-/has-values-1.0.0.tgz#95b0b63fec2146619a6fe57fe75628d5a39efe4f" integrity sha1-lbC2P+whRmGab+V/51Yo1aOe/k8= dependencies: is-number "^3.0.0" kind-of "^4.0.0" hosted-git-info@^2.1.4: version "2.8.4" resolved "https://registry.yarnpkg.com/hosted-git-info/-/hosted-git-info-2.8.4.tgz#44119abaf4bc64692a16ace34700fed9c03e2546" integrity sha512-pzXIvANXEFrc5oFFXRMkbLPQ2rXRoDERwDLyrcUxGhaZhgP54BBSl9Oheh7Vv0T090cszWBxPjkQQ5Sq1PbBRQ== iconv-lite@^0.4.4: version "0.4.24" resolved "https://registry.yarnpkg.com/iconv-lite/-/iconv-lite-0.4.24.tgz#2022b4b25fbddc21d2f524974a474aafe733908b" integrity sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA== dependencies: safer-buffer ">= 2.1.2 < 3" ignore-walk@^3.0.1: version "3.0.1" resolved "https://registry.yarnpkg.com/ignore-walk/-/ignore-walk-3.0.1.tgz#a83e62e7d272ac0e3b551aaa82831a19b69f82f8" integrity sha512-DTVlMx3IYPe0/JJcYP7Gxg7ttZZu3IInhuEhbchuqneY9wWe5Ojy2mXLBaQFUQmo0AW2r3qG7m1mg86js+gnlQ== dependencies: minimatch "^3.0.4" inflight@^1.0.4: version "1.0.6" resolved "https://registry.yarnpkg.com/inflight/-/inflight-1.0.6.tgz#49bd6331d7d02d0c09bc910a1075ba8165b56df9" integrity sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk= dependencies: once "^1.3.0" wrappy "1" inherits@2, inherits@^2.0.1, inherits@~2.0.3: version "2.0.4" resolved "https://registry.yarnpkg.com/inherits/-/inherits-2.0.4.tgz#0fa2c64f932917c3433a0ded55363aae37416b7c" integrity sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ== ini@~1.3.0: version "1.3.5" resolved "https://registry.yarnpkg.com/ini/-/ini-1.3.5.tgz#eee25f56db1c9ec6085e0c22778083f596abf927" integrity sha512-RZY5huIKCMRWDUqZlEi72f/lmXKMvuszcMBduliQ3nnWbx9X/ZBQO7DijMEYS9EhHBb2qacRUMtC7svLwe0lcw== is-accessor-descriptor@^0.1.6: version "0.1.6" resolved "https://registry.yarnpkg.com/is-accessor-descriptor/-/is-accessor-descriptor-0.1.6.tgz#a9e12cb3ae8d876727eeef3843f8a0897b5c98d6" integrity sha1-qeEss66Nh2cn7u84Q/igiXtcmNY= dependencies: kind-of "^3.0.2" is-accessor-descriptor@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/is-accessor-descriptor/-/is-accessor-descriptor-1.0.0.tgz#169c2f6d3df1f992618072365c9b0ea1f6878656" integrity sha512-m5hnHTkcVsPfqx3AKlyttIPb7J+XykHvJP2B9bZDjlhLIoEq4XoK64Vg7boZlVWYK6LUY94dYPEE7Lh0ZkZKcQ== dependencies: kind-of "^6.0.0" is-arrayish@^0.2.1: version "0.2.1" resolved "https://registry.yarnpkg.com/is-arrayish/-/is-arrayish-0.2.1.tgz#77c99840527aa8ecb1a8ba697b80645a7a926a9d" integrity sha1-d8mYQFJ6qOyxqLppe4BkWnqSap0= is-binary-path@^1.0.0: version "1.0.1" resolved "https://registry.yarnpkg.com/is-binary-path/-/is-binary-path-1.0.1.tgz#75f16642b480f187a711c814161fd3a4a7655898" integrity sha1-dfFmQrSA8YenEcgUFh/TpKdlWJg= dependencies: binary-extensions "^1.0.0" is-buffer@^1.1.5: version "1.1.6" resolved "https://registry.yarnpkg.com/is-buffer/-/is-buffer-1.1.6.tgz#efaa2ea9daa0d7ab2ea13a97b2b8ad51fefbe8be" integrity sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w== is-data-descriptor@^0.1.4: version "0.1.4" resolved "https://registry.yarnpkg.com/is-data-descriptor/-/is-data-descriptor-0.1.4.tgz#0b5ee648388e2c860282e793f1856fec3f301b56" integrity sha1-C17mSDiOLIYCgueT8YVv7D8wG1Y= dependencies: kind-of "^3.0.2" is-data-descriptor@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/is-data-descriptor/-/is-data-descriptor-1.0.0.tgz#d84876321d0e7add03990406abbbbd36ba9268c7" integrity sha512-jbRXy1FmtAoCjQkVmIVYwuuqDFUbaOeDjmed1tOGPrsMhtJA4rD9tkgA0F1qJ3gRFRXcHYVkdeaP50Q5rE/jLQ== dependencies: kind-of "^6.0.0" is-descriptor@^0.1.0: version "0.1.6" resolved "https://registry.yarnpkg.com/is-descriptor/-/is-descriptor-0.1.6.tgz#366d8240dde487ca51823b1ab9f07a10a78251ca" integrity sha512-avDYr0SB3DwO9zsMov0gKCESFYqCnE4hq/4z3TdUlukEy5t9C0YRq7HLrsN52NAcqXKaepeCD0n+B0arnVG3Hg== dependencies: is-accessor-descriptor "^0.1.6" is-data-descriptor "^0.1.4" kind-of "^5.0.0" is-descriptor@^1.0.0, is-descriptor@^1.0.2: version "1.0.2" resolved "https://registry.yarnpkg.com/is-descriptor/-/is-descriptor-1.0.2.tgz#3b159746a66604b04f8c81524ba365c5f14d86ec" integrity sha512-2eis5WqQGV7peooDyLmNEPUrps9+SXX5c9pL3xEB+4e9HnGuDa7mB7kHxHw4CbqS9k1T2hOH3miL8n8WtiYVtg== dependencies: is-accessor-descriptor "^1.0.0" is-data-descriptor "^1.0.0" kind-of "^6.0.2" is-dotfile@^1.0.0: version "1.0.3" resolved "https://registry.yarnpkg.com/is-dotfile/-/is-dotfile-1.0.3.tgz#a6a2f32ffd2dfb04f5ca25ecd0f6b83cf798a1e1" integrity sha1-pqLzL/0t+wT1yiXs0Pa4PPeYoeE= is-equal-shallow@^0.1.3: version "0.1.3" resolved "https://registry.yarnpkg.com/is-equal-shallow/-/is-equal-shallow-0.1.3.tgz#2238098fc221de0bcfa5d9eac4c45d638aa1c534" integrity sha1-IjgJj8Ih3gvPpdnqxMRdY4qhxTQ= dependencies: is-primitive "^2.0.0" is-extendable@^0.1.0, is-extendable@^0.1.1: version "0.1.1" resolved "https://registry.yarnpkg.com/is-extendable/-/is-extendable-0.1.1.tgz#62b110e289a471418e3ec36a617d472e301dfc89" integrity sha1-YrEQ4omkcUGOPsNqYX1HLjAd/Ik= is-extendable@^1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/is-extendable/-/is-extendable-1.0.1.tgz#a7470f9e426733d81bd81e1155264e3a3507cab4" integrity sha512-arnXMxT1hhoKo9k1LZdmlNyJdDDfy2v0fXjFlmok4+i8ul/6WlbVge9bhM74OpNPQPMGUToDtz+KXa1PneJxOA== dependencies: is-plain-object "^2.0.4" is-extglob@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/is-extglob/-/is-extglob-1.0.0.tgz#ac468177c4943405a092fc8f29760c6ffc6206c0" integrity sha1-rEaBd8SUNAWgkvyPKXYMb/xiBsA= is-fullwidth-code-point@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/is-fullwidth-code-point/-/is-fullwidth-code-point-1.0.0.tgz#ef9e31386f031a7f0d643af82fde50c457ef00cb" integrity sha1-754xOG8DGn8NZDr4L95QxFfvAMs= dependencies: number-is-nan "^1.0.0" is-fullwidth-code-point@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/is-fullwidth-code-point/-/is-fullwidth-code-point-2.0.0.tgz#a3b30a5c4f199183167aaab93beefae3ddfb654f" integrity sha1-o7MKXE8ZkYMWeqq5O+764937ZU8= is-glob@^2.0.0, is-glob@^2.0.1: version "2.0.1" resolved "https://registry.yarnpkg.com/is-glob/-/is-glob-2.0.1.tgz#d096f926a3ded5600f3fdfd91198cb0888c2d863" integrity sha1-0Jb5JqPe1WAPP9/ZEZjLCIjC2GM= dependencies: is-extglob "^1.0.0" is-number@^2.1.0: version "2.1.0" resolved "https://registry.yarnpkg.com/is-number/-/is-number-2.1.0.tgz#01fcbbb393463a548f2f466cce16dece49db908f" integrity sha1-Afy7s5NGOlSPL0ZszhbezknbkI8= dependencies: kind-of "^3.0.2" is-number@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/is-number/-/is-number-3.0.0.tgz#24fd6201a4782cf50561c810276afc7d12d71195" integrity sha1-JP1iAaR4LPUFYcgQJ2r8fRLXEZU= dependencies: kind-of "^3.0.2" is-number@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/is-number/-/is-number-4.0.0.tgz#0026e37f5454d73e356dfe6564699867c6a7f0ff" integrity sha512-rSklcAIlf1OmFdyAqbnWTLVelsQ58uvZ66S/ZyawjWqIviTWCjg2PzVGw8WUA+nNuPTqb4wgA+NszrJ+08LlgQ== is-plain-object@^2.0.3, is-plain-object@^2.0.4: version "2.0.4" resolved "https://registry.yarnpkg.com/is-plain-object/-/is-plain-object-2.0.4.tgz#2c163b3fafb1b606d9d17928f05c2a1c38e07677" integrity sha512-h5PpgXkWitc38BBMYawTYMWJHFZJVnBquFE57xFpjB8pJFiF6gZ+bU+WyI/yqXiFR5mdLsgYNaPe8uao6Uv9Og== dependencies: isobject "^3.0.1" is-posix-bracket@^0.1.0: version "0.1.1" resolved "https://registry.yarnpkg.com/is-posix-bracket/-/is-posix-bracket-0.1.1.tgz#3334dc79774368e92f016e6fbc0a88f5cd6e6bc4" integrity sha1-MzTceXdDaOkvAW5vvAqI9c1ua8Q= is-primitive@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/is-primitive/-/is-primitive-2.0.0.tgz#207bab91638499c07b2adf240a41a87210034575" integrity sha1-IHurkWOEmcB7Kt8kCkGochADRXU= is-windows@^1.0.2: version "1.0.2" resolved "https://registry.yarnpkg.com/is-windows/-/is-windows-1.0.2.tgz#d1850eb9791ecd18e6182ce12a30f396634bb19d" integrity sha512-eXK1UInq2bPmjyX6e3VHIzMLobc4J94i4AWn+Hpq3OU5KkrRC96OAcR3PRJ/pGu6m8TRnBHP9dkXQVsT/COVIA== [email protected], isarray@~1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/isarray/-/isarray-1.0.0.tgz#bb935d48582cba168c06834957a54a3e07124f11" integrity sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE= isobject@^2.0.0: version "2.1.0" resolved "https://registry.yarnpkg.com/isobject/-/isobject-2.1.0.tgz#f065561096a3f1da2ef46272f815c840d87e0c89" integrity sha1-8GVWEJaj8dou9GJy+BXIQNh+DIk= dependencies: isarray "1.0.0" isobject@^3.0.0, isobject@^3.0.1: version "3.0.1" resolved "https://registry.yarnpkg.com/isobject/-/isobject-3.0.1.tgz#4e431e92b11a9731636aa1f9c8d1ccbcfdab78df" integrity sha1-TkMekrEalzFjaqH5yNHMvP2reN8= json-parse-better-errors@^1.0.1: version "1.0.2" resolved "https://registry.yarnpkg.com/json-parse-better-errors/-/json-parse-better-errors-1.0.2.tgz#bb867cfb3450e69107c131d1c514bab3dc8bcaa9" integrity sha512-mrqyZKfX5EhL7hvqcV6WG1yYjnjeuYDzDhhcAAUrq8Po85NBQBJP+ZDUT75qZQ98IkUoBqdkExkukOU7Ts2wrw== kind-of@^3.0.2, kind-of@^3.0.3, kind-of@^3.2.0: version "3.2.2" resolved "https://registry.yarnpkg.com/kind-of/-/kind-of-3.2.2.tgz#31ea21a734bab9bbb0f32466d893aea51e4a3c64" integrity sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ= dependencies: is-buffer "^1.1.5" kind-of@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/kind-of/-/kind-of-4.0.0.tgz#20813df3d712928b207378691a45066fae72dd57" integrity sha1-IIE989cSkosgc3hpGkUGb65y3Vc= dependencies: is-buffer "^1.1.5" kind-of@^5.0.0: version "5.1.0" resolved "https://registry.yarnpkg.com/kind-of/-/kind-of-5.1.0.tgz#729c91e2d857b7a419a1f9aa65685c4c33f5845d" integrity sha512-NGEErnH6F2vUuXDh+OlbcKW7/wOcfdRHaZ7VWtqCztfHri/++YKmP51OdWeGPuqCOba6kk2OTe5d02VmTB80Pw== kind-of@^6.0.0, kind-of@^6.0.2: version "6.0.2" resolved "https://registry.yarnpkg.com/kind-of/-/kind-of-6.0.2.tgz#01146b36a6218e64e58f3a8d66de5d7fc6f6d051" integrity sha512-s5kLOcnH0XqDO+FvuaLX8DDjZ18CGFk7VygH40QoKPUQhW4e2rvM0rwUq0t8IQDOwYSeLK01U90OjzBTme2QqA== load-json-file@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/load-json-file/-/load-json-file-4.0.0.tgz#2f5f45ab91e33216234fd53adab668eb4ec0993b" integrity sha1-L19Fq5HjMhYjT9U62rZo607AmTs= dependencies: graceful-fs "^4.1.2" parse-json "^4.0.0" pify "^3.0.0" strip-bom "^3.0.0" lodash@^4.5.1: version "4.17.15" resolved "https://registry.yarnpkg.com/lodash/-/lodash-4.17.15.tgz#b447f6670a0455bbfeedd11392eff330ea097548" integrity sha512-8xOcRHvCjnocdS5cpwXQXVzmmh5e5+saE2QGoeQmbKmRS6J3VQppPOIt0MnmE+4xlZoumy0GPG0D0MVIQbNA1A== map-cache@^0.2.2: version "0.2.2" resolved "https://registry.yarnpkg.com/map-cache/-/map-cache-0.2.2.tgz#c32abd0bd6525d9b051645bb4f26ac5dc98a0dbf" integrity sha1-wyq9C9ZSXZsFFkW7TyasXcmKDb8= map-visit@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/map-visit/-/map-visit-1.0.0.tgz#ecdca8f13144e660f1b5bd41f12f3479d98dfb8f" integrity sha1-7Nyo8TFE5mDxtb1B8S80edmN+48= dependencies: object-visit "^1.0.0" math-random@^1.0.1: version "1.0.4" resolved "https://registry.yarnpkg.com/math-random/-/math-random-1.0.4.tgz#5dd6943c938548267016d4e34f057583080c514c" integrity sha512-rUxjysqif/BZQH2yhd5Aaq7vXMSx9NdEsQcyA07uEzIvxgI7zIr33gGsh+RU0/XjmQpCW7RsVof1vlkvQVCK5A== merge@^1.2.0: version "1.2.1" resolved "https://registry.yarnpkg.com/merge/-/merge-1.2.1.tgz#38bebf80c3220a8a487b6fcfb3941bb11720c145" integrity sha512-VjFo4P5Whtj4vsLzsYBu5ayHhoHJ0UqNm7ibvShmbmoz7tGi0vXaoJbGdB+GmDMLUdg8DpQXEIeVDAe8MaABvQ== micromatch@^2.1.5: version "2.3.11" resolved "https://registry.yarnpkg.com/micromatch/-/micromatch-2.3.11.tgz#86677c97d1720b363431d04d0d15293bd38c1565" integrity sha1-hmd8l9FyCzY0MdBNDRUpO9OMFWU= dependencies: arr-diff "^2.0.0" array-unique "^0.2.1" braces "^1.8.2" expand-brackets "^0.1.4" extglob "^0.3.1" filename-regex "^2.0.0" is-extglob "^1.0.0" is-glob "^2.0.1" kind-of "^3.0.2" normalize-path "^2.0.1" object.omit "^2.0.0" parse-glob "^3.0.4" regex-cache "^0.4.2" micromatch@^3.1.10: version "3.1.10" resolved "https://registry.yarnpkg.com/micromatch/-/micromatch-3.1.10.tgz#70859bc95c9840952f359a068a3fc49f9ecfac23" integrity sha512-MWikgl9n9M3w+bpsY3He8L+w9eF9338xRl8IAO5viDizwSzziFEyUzo2xrrloB64ADbTf8uA8vRqqttDTOmccg== dependencies: arr-diff "^4.0.0" array-unique "^0.3.2" braces "^2.3.1" define-property "^2.0.2" extend-shallow "^3.0.2" extglob "^2.0.4" fragment-cache "^0.2.1" kind-of "^6.0.2" nanomatch "^1.2.9" object.pick "^1.3.0" regex-not "^1.0.0" snapdragon "^0.8.1" to-regex "^3.0.2" minimatch@^3.0.2, minimatch@^3.0.4: version "3.0.4" resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-3.0.4.tgz#5166e286457f03306064be5497e8dbb0c3d32083" integrity sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA== dependencies: brace-expansion "^1.1.7" [email protected]: version "0.0.8" resolved "https://registry.yarnpkg.com/minimist/-/minimist-0.0.8.tgz#857fcabfc3397d2625b8228262e86aa7a011b05d" integrity sha1-hX/Kv8M5fSYluCKCYuhqp6ARsF0= minimist@^1.1.0, minimist@^1.2.0: version "1.2.0" resolved "https://registry.yarnpkg.com/minimist/-/minimist-1.2.0.tgz#a35008b20f41383eec1fb914f4cd5df79a264284" integrity sha1-o1AIsg9BOD7sH7kU9M1d95omQoQ= minipass@^2.2.1, minipass@^2.3.5: version "2.3.5" resolved "https://registry.yarnpkg.com/minipass/-/minipass-2.3.5.tgz#cacebe492022497f656b0f0f51e2682a9ed2d848" integrity sha512-Gi1W4k059gyRbyVUZQ4mEqLm0YIUiGYfvxhF6SIlk3ui1WVxMTGfGdQ2SInh3PDrRTVvPKgULkpJtT4RH10+VA== dependencies: safe-buffer "^5.1.2" yallist "^3.0.0" minizlib@^1.2.1: version "1.2.1" resolved "https://registry.yarnpkg.com/minizlib/-/minizlib-1.2.1.tgz#dd27ea6136243c7c880684e8672bb3a45fd9b614" integrity sha512-7+4oTUOWKg7AuL3vloEWekXY2/D20cevzsrNT2kGWm+39J9hGTCBv8VI5Pm5lXZ/o3/mdR4f8rflAPhnQb8mPA== dependencies: minipass "^2.2.1" mixin-deep@^1.2.0: version "1.3.2" resolved "https://registry.yarnpkg.com/mixin-deep/-/mixin-deep-1.3.2.tgz#1120b43dc359a785dce65b55b82e257ccf479566" integrity sha512-WRoDn//mXBiJ1H40rqa3vH0toePwSsGb45iInWlTySa+Uu4k3tYUSxa2v1KqAiLtvlrSzaExqS1gtk96A9zvEA== dependencies: for-in "^1.0.2" is-extendable "^1.0.1" mkdirp@^0.5.0, mkdirp@^0.5.1: version "0.5.1" resolved "https://registry.yarnpkg.com/mkdirp/-/mkdirp-0.5.1.tgz#30057438eac6cf7f8c4767f38648d6697d75c903" integrity sha1-MAV0OOrGz3+MR2fzhkjWaX11yQM= dependencies: minimist "0.0.8" [email protected]: version "2.0.0" resolved "https://registry.yarnpkg.com/ms/-/ms-2.0.0.tgz#5608aeadfc00be6c2901df5f9861788de0d597c8" integrity sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g= ms@^2.1.1: version "2.1.2" resolved "https://registry.yarnpkg.com/ms/-/ms-2.1.2.tgz#d09d1f357b443f493382a8eb3ccd183872ae6009" integrity sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w== nan@^2.12.1: version "2.14.0" resolved "https://registry.yarnpkg.com/nan/-/nan-2.14.0.tgz#7818f722027b2459a86f0295d434d1fc2336c52c" integrity sha512-INOFj37C7k3AfaNTtX8RhsTw7qRy7eLET14cROi9+5HAVbbHuIWUHEauBv5qT4Av2tWasiTY1Jw6puUNqRJXQg== nanomatch@^1.2.9: version "1.2.13" resolved "https://registry.yarnpkg.com/nanomatch/-/nanomatch-1.2.13.tgz#b87a8aa4fc0de8fe6be88895b38983ff265bd119" integrity sha512-fpoe2T0RbHwBTBUOftAfBPaDEi06ufaUai0mE6Yn1kacc3SnTErfb/h+X94VXzI64rKFHYImXSvdwGGCmwOqCA== dependencies: arr-diff "^4.0.0" array-unique "^0.3.2" define-property "^2.0.2" extend-shallow "^3.0.2" fragment-cache "^0.2.1" is-windows "^1.0.2" kind-of "^6.0.2" object.pick "^1.3.0" regex-not "^1.0.0" snapdragon "^0.8.1" to-regex "^3.0.1" ncp@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/ncp/-/ncp-2.0.0.tgz#195a21d6c46e361d2fb1281ba38b91e9df7bdbb3" integrity sha1-GVoh1sRuNh0vsSgbo4uR6d9727M= needle@^2.2.1: version "2.4.0" resolved "https://registry.yarnpkg.com/needle/-/needle-2.4.0.tgz#6833e74975c444642590e15a750288c5f939b57c" integrity sha512-4Hnwzr3mi5L97hMYeNl8wRW/Onhy4nUKR/lVemJ8gJedxxUyBLm9kkrDColJvoSfwi0jCNhD+xCdOtiGDQiRZg== dependencies: debug "^3.2.6" iconv-lite "^0.4.4" sax "^1.2.4" node-pre-gyp@^0.12.0: version "0.12.0" resolved "https://registry.yarnpkg.com/node-pre-gyp/-/node-pre-gyp-0.12.0.tgz#39ba4bb1439da030295f899e3b520b7785766149" integrity sha512-4KghwV8vH5k+g2ylT+sLTjy5wmUOb9vPhnM8NHvRf9dHmnW/CndrFXy2aRPaPST6dugXSdHXfeaHQm77PIz/1A== dependencies: detect-libc "^1.0.2" mkdirp "^0.5.1" needle "^2.2.1" nopt "^4.0.1" npm-packlist "^1.1.6" npmlog "^4.0.2" rc "^1.2.7" rimraf "^2.6.1" semver "^5.3.0" tar "^4" nopt@^4.0.1: version "4.0.1" resolved "https://registry.yarnpkg.com/nopt/-/nopt-4.0.1.tgz#d0d4685afd5415193c8c7505602d0d17cd64474d" integrity sha1-0NRoWv1UFRk8jHUFYC0NF81kR00= dependencies: abbrev "1" osenv "^0.1.4" normalize-package-data@^2.3.2: version "2.5.0" resolved "https://registry.yarnpkg.com/normalize-package-data/-/normalize-package-data-2.5.0.tgz#e66db1838b200c1dfc233225d12cb36520e234a8" integrity sha512-/5CMN3T0R4XTj4DcGaexo+roZSdSFW/0AOOTROrjxzCG1wrWXEsGbRKevjlIL+ZDE4sZlJr5ED4YW0yqmkK+eA== dependencies: hosted-git-info "^2.1.4" resolve "^1.10.0" semver "2 || 3 || 4 || 5" validate-npm-package-license "^3.0.1" normalize-path@^2.0.0, normalize-path@^2.0.1: version "2.1.1" resolved "https://registry.yarnpkg.com/normalize-path/-/normalize-path-2.1.1.tgz#1ab28b556e198363a8c1a6f7e6fa20137fe6aed9" integrity sha1-GrKLVW4Zg2Oowab35vogE3/mrtk= dependencies: remove-trailing-separator "^1.0.1" npm-bundled@^1.0.1: version "1.0.6" resolved "https://registry.yarnpkg.com/npm-bundled/-/npm-bundled-1.0.6.tgz#e7ba9aadcef962bb61248f91721cd932b3fe6bdd" integrity sha512-8/JCaftHwbd//k6y2rEWp6k1wxVfpFzB6t1p825+cUb7Ym2XQfhwIC5KwhrvzZRJu+LtDE585zVaS32+CGtf0g== npm-packlist@^1.1.6: version "1.4.4" resolved "https://registry.yarnpkg.com/npm-packlist/-/npm-packlist-1.4.4.tgz#866224233850ac534b63d1a6e76050092b5d2f44" integrity sha512-zTLo8UcVYtDU3gdeaFu2Xu0n0EvelfHDGuqtNIn5RO7yQj4H1TqNdBc/yZjxnWA0PVB8D3Woyp0i5B43JwQ6Vw== dependencies: ignore-walk "^3.0.1" npm-bundled "^1.0.1" npmlog@^4.0.2: version "4.1.2" resolved "https://registry.yarnpkg.com/npmlog/-/npmlog-4.1.2.tgz#08a7f2a8bf734604779a9efa4ad5cc717abb954b" integrity sha512-2uUqazuKlTaSI/dC8AzicUck7+IrEaOnN/e0jd3Xtt1KcGpwx30v50mL7oPyr/h9bL3E4aZccVwpwP+5W9Vjkg== dependencies: are-we-there-yet "~1.1.2" console-control-strings "~1.1.0" gauge "~2.7.3" set-blocking "~2.0.0" number-is-nan@^1.0.0: version "1.0.1" resolved "https://registry.yarnpkg.com/number-is-nan/-/number-is-nan-1.0.1.tgz#097b602b53422a522c1afb8790318336941a011d" integrity sha1-CXtgK1NCKlIsGvuHkDGDNpQaAR0= object-assign@^4.1.0: version "4.1.1" resolved "https://registry.yarnpkg.com/object-assign/-/object-assign-4.1.1.tgz#2109adc7965887cfc05cbbd442cac8bfbb360863" integrity sha1-IQmtx5ZYh8/AXLvUQsrIv7s2CGM= object-copy@^0.1.0: version "0.1.0" resolved "https://registry.yarnpkg.com/object-copy/-/object-copy-0.1.0.tgz#7e7d858b781bd7c991a41ba975ed3812754e998c" integrity sha1-fn2Fi3gb18mRpBupde04EnVOmYw= dependencies: copy-descriptor "^0.1.0" define-property "^0.2.5" kind-of "^3.0.3" object-visit@^1.0.0: version "1.0.1" resolved "https://registry.yarnpkg.com/object-visit/-/object-visit-1.0.1.tgz#f79c4493af0c5377b59fe39d395e41042dd045bb" integrity sha1-95xEk68MU3e1n+OdOV5BBC3QRbs= dependencies: isobject "^3.0.0" object.omit@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/object.omit/-/object.omit-2.0.1.tgz#1a9c744829f39dbb858c76ca3579ae2a54ebd1fa" integrity sha1-Gpx0SCnznbuFjHbKNXmuKlTr0fo= dependencies: for-own "^0.1.4" is-extendable "^0.1.1" object.pick@^1.3.0: version "1.3.0" resolved "https://registry.yarnpkg.com/object.pick/-/object.pick-1.3.0.tgz#87a10ac4c1694bd2e1cbf53591a66141fb5dd747" integrity sha1-h6EKxMFpS9Lhy/U1kaZhQftd10c= dependencies: isobject "^3.0.1" once@^1.3.0: version "1.4.0" resolved "https://registry.yarnpkg.com/once/-/once-1.4.0.tgz#583b1aa775961d4b113ac17d9c50baef9dd76bd1" integrity sha1-WDsap3WWHUsROsF9nFC6753Xa9E= dependencies: wrappy "1" os-homedir@^1.0.0: version "1.0.2" resolved "https://registry.yarnpkg.com/os-homedir/-/os-homedir-1.0.2.tgz#ffbc4988336e0e833de0c168c7ef152121aa7fb3" integrity sha1-/7xJiDNuDoM94MFox+8VISGqf7M= os-tmpdir@^1.0.0: version "1.0.2" resolved "https://registry.yarnpkg.com/os-tmpdir/-/os-tmpdir-1.0.2.tgz#bbe67406c79aa85c5cfec766fe5734555dfa1274" integrity sha1-u+Z0BseaqFxc/sdm/lc0VV36EnQ= osenv@^0.1.4: version "0.1.5" resolved "https://registry.yarnpkg.com/osenv/-/osenv-0.1.5.tgz#85cdfafaeb28e8677f416e287592b5f3f49ea410" integrity sha512-0CWcCECdMVc2Rw3U5w9ZjqX6ga6ubk1xDVKxtBQPK7wis/0F2r9T6k4ydGYhecl7YUBxBVxhL5oisPsNxAPe2g== dependencies: os-homedir "^1.0.0" os-tmpdir "^1.0.0" parse-glob@^3.0.4: version "3.0.4" resolved "https://registry.yarnpkg.com/parse-glob/-/parse-glob-3.0.4.tgz#b2c376cfb11f35513badd173ef0bb6e3a388391c" integrity sha1-ssN2z7EfNVE7rdFz7wu246OIORw= dependencies: glob-base "^0.3.0" is-dotfile "^1.0.0" is-extglob "^1.0.0" is-glob "^2.0.0" parse-json@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/parse-json/-/parse-json-4.0.0.tgz#be35f5425be1f7f6c747184f98a788cb99477ee0" integrity sha1-vjX1Qlvh9/bHRxhPmKeIy5lHfuA= dependencies: error-ex "^1.3.1" json-parse-better-errors "^1.0.1" pascalcase@^0.1.1: version "0.1.1" resolved "https://registry.yarnpkg.com/pascalcase/-/pascalcase-0.1.1.tgz#b363e55e8006ca6fe21784d2db22bd15d7917f14" integrity sha1-s2PlXoAGym/iF4TS2yK9FdeRfxQ= path-is-absolute@^1.0.0: version "1.0.1" resolved "https://registry.yarnpkg.com/path-is-absolute/-/path-is-absolute-1.0.1.tgz#174b9268735534ffbc7ace6bf53a5a9e1b5c5f5f" integrity sha1-F0uSaHNVNP+8es5r9TpanhtcX18= path-parse@^1.0.6: version "1.0.6" resolved "https://registry.yarnpkg.com/path-parse/-/path-parse-1.0.6.tgz#d62dbb5679405d72c4737ec58600e9ddcf06d24c" integrity sha512-GSmOT2EbHrINBf9SR7CDELwlJ8AENk3Qn7OikK4nFYAu3Ote2+JYNVvkpAEQm3/TLNEJFD/xZJjzyxg3KBWOzw== path-type@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/path-type/-/path-type-3.0.0.tgz#cef31dc8e0a1a3bb0d105c0cd97cf3bf47f4e36f" integrity sha512-T2ZUsdZFHgA3u4e5PfPbjd7HDDpxPnQb5jN0SrDsjNSuVXHJqtwTnWqG0B1jZrgmJ/7lj1EmVIByWt1gxGkWvg== dependencies: pify "^3.0.0" pify@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/pify/-/pify-3.0.0.tgz#e5a4acd2c101fdf3d9a4d07f0dbc4db49dd28176" integrity sha1-5aSs0sEB/fPZpNB/DbxNtJ3SgXY= posix-character-classes@^0.1.0: version "0.1.1" resolved "https://registry.yarnpkg.com/posix-character-classes/-/posix-character-classes-0.1.1.tgz#01eac0fe3b5af71a2a6c02feabb8c1fef7e00eab" integrity sha1-AerA/jta9xoqbAL+q7jB/vfgDqs= preserve@^0.2.0: version "0.2.0" resolved "https://registry.yarnpkg.com/preserve/-/preserve-0.2.0.tgz#815ed1f6ebc65926f865b310c0713bcb3315ce4b" integrity sha1-gV7R9uvGWSb4ZbMQwHE7yzMVzks= process-nextick-args@~2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/process-nextick-args/-/process-nextick-args-2.0.1.tgz#7820d9b16120cc55ca9ae7792680ae7dba6d7fe2" integrity sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag== randomatic@^3.0.0: version "3.1.1" resolved "https://registry.yarnpkg.com/randomatic/-/randomatic-3.1.1.tgz#b776efc59375984e36c537b2f51a1f0aff0da1ed" integrity sha512-TuDE5KxZ0J461RVjrJZCJc+J+zCkTb1MbH9AQUq68sMhOMcy9jLcb3BrZKgp9q9Ncltdg4QVqWrH02W2EFFVYw== dependencies: is-number "^4.0.0" kind-of "^6.0.0" math-random "^1.0.1" rc@^1.2.7: version "1.2.8" resolved "https://registry.yarnpkg.com/rc/-/rc-1.2.8.tgz#cd924bf5200a075b83c188cd6b9e211b7fc0d3ed" integrity sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw== dependencies: deep-extend "^0.6.0" ini "~1.3.0" minimist "^1.2.0" strip-json-comments "~2.0.1" read-pkg@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/read-pkg/-/read-pkg-3.0.0.tgz#9cbc686978fee65d16c00e2b19c237fcf6e38389" integrity sha1-nLxoaXj+5l0WwA4rGcI3/Pbjg4k= dependencies: load-json-file "^4.0.0" normalize-package-data "^2.3.2" path-type "^3.0.0" readable-stream@^2.0.2, readable-stream@^2.0.6: version "2.3.6" resolved "https://registry.yarnpkg.com/readable-stream/-/readable-stream-2.3.6.tgz#b11c27d88b8ff1fbe070643cf94b0c79ae1b0aaf" integrity sha512-tQtKA9WIAhBF3+VLAseyMqZeBjW0AHJoxOtYqSUZNJxauErmLbVm2FW1y+J/YA9dUrAC39ITejlZWhVIwawkKw== dependencies: core-util-is "~1.0.0" inherits "~2.0.3" isarray "~1.0.0" process-nextick-args "~2.0.0" safe-buffer "~5.1.1" string_decoder "~1.1.1" util-deprecate "~1.0.1" readdirp@^2.0.0: version "2.2.1" resolved "https://registry.yarnpkg.com/readdirp/-/readdirp-2.2.1.tgz#0e87622a3325aa33e892285caf8b4e846529a525" integrity sha512-1JU/8q+VgFZyxwrJ+SVIOsh+KywWGpds3NTqikiKpDMZWScmAYyKIgqkO+ARvNWJfXeXR1zxz7aHF4u4CyH6vQ== dependencies: graceful-fs "^4.1.11" micromatch "^3.1.10" readable-stream "^2.0.2" regenerator-runtime@^0.11.0: version "0.11.1" resolved "https://registry.yarnpkg.com/regenerator-runtime/-/regenerator-runtime-0.11.1.tgz#be05ad7f9bf7d22e056f9726cee5017fbf19e2e9" integrity sha512-MguG95oij0fC3QV3URf4V2SDYGJhJnJGqvIIgdECeODCT98wSWDAJ94SSuVpYQUoTcGUIL6L4yNB7j1DFFHSBg== regex-cache@^0.4.2: version "0.4.4" resolved "https://registry.yarnpkg.com/regex-cache/-/regex-cache-0.4.4.tgz#75bdc58a2a1496cec48a12835bc54c8d562336dd" integrity sha512-nVIZwtCjkC9YgvWkpM55B5rBhBYRZhAaJbgcFYXXsHnbZ9UZI9nnVWYZpBlCqv9ho2eZryPnWrZGsOdPwVWXWQ== dependencies: is-equal-shallow "^0.1.3" regex-not@^1.0.0, regex-not@^1.0.2: version "1.0.2" resolved "https://registry.yarnpkg.com/regex-not/-/regex-not-1.0.2.tgz#1f4ece27e00b0b65e0247a6810e6a85d83a5752c" integrity sha512-J6SDjUgDxQj5NusnOtdFxDwN/+HWykR8GELwctJ7mdqhcyy1xEc4SRFHUXvxTp661YaVKAjfRLZ9cCqS6tn32A== dependencies: extend-shallow "^3.0.2" safe-regex "^1.1.0" remove-trailing-separator@^1.0.1: version "1.1.0" resolved "https://registry.yarnpkg.com/remove-trailing-separator/-/remove-trailing-separator-1.1.0.tgz#c24bce2a283adad5bc3f58e0d48249b92379d8ef" integrity sha1-wkvOKig62tW8P1jg1IJJuSN52O8= repeat-element@^1.1.2: version "1.1.3" resolved "https://registry.yarnpkg.com/repeat-element/-/repeat-element-1.1.3.tgz#782e0d825c0c5a3bb39731f84efee6b742e6b1ce" integrity sha512-ahGq0ZnV5m5XtZLMb+vP76kcAM5nkLqk0lpqAuojSKGgQtn4eRi4ZZGm2olo2zKFH+sMsWaqOCW1dqAnOru72g== repeat-string@^1.5.2, repeat-string@^1.6.1: version "1.6.1" resolved "https://registry.yarnpkg.com/repeat-string/-/repeat-string-1.6.1.tgz#8dcae470e1c88abc2d600fff4a776286da75e637" integrity sha1-jcrkcOHIirwtYA//Sndihtp15jc= resolve-url@^0.2.1: version "0.2.1" resolved "https://registry.yarnpkg.com/resolve-url/-/resolve-url-0.2.1.tgz#2c637fe77c893afd2a663fe21aa9080068e2052a" integrity sha1-LGN/53yJOv0qZj/iGqkIAGjiBSo= resolve@^1.1.7, resolve@^1.10.0: version "1.12.0" resolved "https://registry.yarnpkg.com/resolve/-/resolve-1.12.0.tgz#3fc644a35c84a48554609ff26ec52b66fa577df6" integrity sha512-B/dOmuoAik5bKcD6s6nXDCjzUKnaDvdkRyAk6rsmsKLipWj4797iothd7jmmUhWTfinVMU+wc56rYKsit2Qy4w== dependencies: path-parse "^1.0.6" ret@~0.1.10: version "0.1.15" resolved "https://registry.yarnpkg.com/ret/-/ret-0.1.15.tgz#b8a4825d5bdb1fc3f6f53c2bc33f81388681c7bc" integrity sha512-TTlYpa+OL+vMMNG24xSlQGEJ3B/RzEfUlLct7b5G/ytav+wPrplCpVMFuwzXbkecJrb6IYo1iFb0S9v37754mg== rimraf@^2.6.1, rimraf@^2.6.3: version "2.7.0" resolved "https://registry.yarnpkg.com/rimraf/-/rimraf-2.7.0.tgz#eb43198c5e2fb83b9323abee63bd87836f9a7c85" integrity sha512-4Liqw7ccABzsWV5BzeZeGRSq7KWIgQYzOcmRDEwSX4WAawlQpcAFXZ1Kid72XYrjSnK5yxOS6Gez/iGusYE/Pw== dependencies: glob "^7.1.3" [email protected]: version "2.3.24" resolved "https://registry.yarnpkg.com/rx/-/rx-2.3.24.tgz#14f950a4217d7e35daa71bbcbe58eff68ea4b2b7" integrity sha1-FPlQpCF9fjXapxu8vljv9o6ksrc= safe-buffer@^5.0.1, safe-buffer@^5.1.2: version "5.2.0" resolved "https://registry.yarnpkg.com/safe-buffer/-/safe-buffer-5.2.0.tgz#b74daec49b1148f88c64b68d49b1e815c1f2f519" integrity sha512-fZEwUGbVl7kouZs1jCdMLdt95hdIv0ZeHg6L7qPeciMZhZ+/gdesW4wgTARkrFWEpspjEATAzUGPG8N2jJiwbg== safe-buffer@~5.1.0, safe-buffer@~5.1.1: version "5.1.2" resolved "https://registry.yarnpkg.com/safe-buffer/-/safe-buffer-5.1.2.tgz#991ec69d296e0313747d59bdfd2b745c35f8828d" integrity sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g== safe-regex@^1.1.0: version "1.1.0" resolved "https://registry.yarnpkg.com/safe-regex/-/safe-regex-1.1.0.tgz#40a3669f3b077d1e943d44629e157dd48023bf2e" integrity sha1-QKNmnzsHfR6UPURinhV91IAjvy4= dependencies: ret "~0.1.10" "safer-buffer@>= 2.1.2 < 3": version "2.1.2" resolved "https://registry.yarnpkg.com/safer-buffer/-/safer-buffer-2.1.2.tgz#44fa161b0187b9549dd84bb91802f9bd8385cd6a" integrity sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg== sax@^1.2.4: version "1.2.4" resolved "https://registry.yarnpkg.com/sax/-/sax-1.2.4.tgz#2816234e2378bddc4e5354fab5caa895df7100d9" integrity sha512-NqVDv9TpANUjFm0N8uM5GxL36UgKi9/atZw+x7YFnQ8ckwFGKrl4xX4yWtrey3UJm5nP1kUbnYgLopqWNSRhWw== "semver@2 || 3 || 4 || 5", semver@^5.3.0: version "5.7.1" resolved "https://registry.yarnpkg.com/semver/-/semver-5.7.1.tgz#a954f931aeba508d307bbf069eff0c01c96116f7" integrity sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ== set-blocking@~2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/set-blocking/-/set-blocking-2.0.0.tgz#045f9782d011ae9a6803ddd382b24392b3d890f7" integrity sha1-BF+XgtARrppoA93TgrJDkrPYkPc= set-value@^2.0.0, set-value@^2.0.1: version "2.0.1" resolved "https://registry.yarnpkg.com/set-value/-/set-value-2.0.1.tgz#a18d40530e6f07de4228c7defe4227af8cad005b" integrity sha512-JxHc1weCN68wRY0fhCoXpyK55m/XPHafOmK4UWD7m2CI14GMcFypt4w/0+NV5f/ZMby2F6S2wwA7fgynh9gWSw== dependencies: extend-shallow "^2.0.1" is-extendable "^0.1.1" is-plain-object "^2.0.3" split-string "^3.0.1" shell-quote@^1.6.1: version "1.7.1" resolved "https://registry.yarnpkg.com/shell-quote/-/shell-quote-1.7.1.tgz#3161d969886fb14f9140c65245a5dd19b6f0b06b" integrity sha512-2kUqeAGnMAu6YrTPX4E3LfxacH9gKljzVjlkUeSqY0soGwK4KLl7TURXCem712tkhBCeeaFP9QK4dKn88s3Icg== signal-exit@^3.0.0: version "3.0.2" resolved "https://registry.yarnpkg.com/signal-exit/-/signal-exit-3.0.2.tgz#b5fdc08f1287ea1178628e415e25132b73646c6d" integrity sha1-tf3AjxKH6hF4Yo5BXiUTK3NkbG0= snapdragon-node@^2.0.1: version "2.1.1" resolved "https://registry.yarnpkg.com/snapdragon-node/-/snapdragon-node-2.1.1.tgz#6c175f86ff14bdb0724563e8f3c1b021a286853b" integrity sha512-O27l4xaMYt/RSQ5TR3vpWCAB5Kb/czIcqUFOM/C4fYcLnbZUc1PkjTAMjof2pBWaSTwOUd6qUHcFGVGj7aIwnw== dependencies: define-property "^1.0.0" isobject "^3.0.0" snapdragon-util "^3.0.1" snapdragon-util@^3.0.1: version "3.0.1" resolved "https://registry.yarnpkg.com/snapdragon-util/-/snapdragon-util-3.0.1.tgz#f956479486f2acd79700693f6f7b805e45ab56e2" integrity sha512-mbKkMdQKsjX4BAL4bRYTj21edOf8cN7XHdYUJEe+Zn99hVEYcMvKPct1IqNe7+AZPirn8BCDOQBHQZknqmKlZQ== dependencies: kind-of "^3.2.0" snapdragon@^0.8.1: version "0.8.2" resolved "https://registry.yarnpkg.com/snapdragon/-/snapdragon-0.8.2.tgz#64922e7c565b0e14204ba1aa7d6964278d25182d" integrity sha512-FtyOnWN/wCHTVXOMwvSv26d+ko5vWlIDD6zoUJ7LW8vh+ZBC8QdljveRP+crNrtBwioEUWy/4dMtbBjA4ioNlg== dependencies: base "^0.11.1" debug "^2.2.0" define-property "^0.2.5" extend-shallow "^2.0.1" map-cache "^0.2.2" source-map "^0.5.6" source-map-resolve "^0.5.0" use "^3.1.0" source-map-resolve@^0.5.0: version "0.5.2" resolved "https://registry.yarnpkg.com/source-map-resolve/-/source-map-resolve-0.5.2.tgz#72e2cc34095543e43b2c62b2c4c10d4a9054f259" integrity sha512-MjqsvNwyz1s0k81Goz/9vRBe9SZdB09Bdw+/zYyO+3CuPk6fouTaxscHkgtE8jKvf01kVfl8riHzERQ/kefaSA== dependencies: atob "^2.1.1" decode-uri-component "^0.2.0" resolve-url "^0.2.1" source-map-url "^0.4.0" urix "^0.1.0" source-map-url@^0.4.0: version "0.4.0" resolved "https://registry.yarnpkg.com/source-map-url/-/source-map-url-0.4.0.tgz#3e935d7ddd73631b97659956d55128e87b5084a3" integrity sha1-PpNdfd1zYxuXZZlW1VEo6HtQhKM= source-map@^0.5.6: version "0.5.7" resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.5.7.tgz#8a039d2d1021d22d1ea14c80d8ea468ba2ef3fcc" integrity sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w= spawn-command@^0.0.2-1: version "0.0.2-1" resolved "https://registry.yarnpkg.com/spawn-command/-/spawn-command-0.0.2-1.tgz#62f5e9466981c1b796dc5929937e11c9c6921bd0" integrity sha1-YvXpRmmBwbeW3Fkpk34RycaSG9A= spdx-correct@^3.0.0: version "3.1.0" resolved "https://registry.yarnpkg.com/spdx-correct/-/spdx-correct-3.1.0.tgz#fb83e504445268f154b074e218c87c003cd31df4" integrity sha512-lr2EZCctC2BNR7j7WzJ2FpDznxky1sjfxvvYEyzxNyb6lZXHODmEoJeFu4JupYlkfha1KZpJyoqiJ7pgA1qq8Q== dependencies: spdx-expression-parse "^3.0.0" spdx-license-ids "^3.0.0" spdx-exceptions@^2.1.0: version "2.2.0" resolved "https://registry.yarnpkg.com/spdx-exceptions/-/spdx-exceptions-2.2.0.tgz#2ea450aee74f2a89bfb94519c07fcd6f41322977" integrity sha512-2XQACfElKi9SlVb1CYadKDXvoajPgBVPn/gOQLrTvHdElaVhr7ZEbqJaRnJLVNeaI4cMEAgVCeBMKF6MWRDCRA== spdx-expression-parse@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/spdx-expression-parse/-/spdx-expression-parse-3.0.0.tgz#99e119b7a5da00e05491c9fa338b7904823b41d0" integrity sha512-Yg6D3XpRD4kkOmTpdgbUiEJFKghJH03fiC1OPll5h/0sO6neh2jqRDVHOQ4o/LMea0tgCkbMgea5ip/e+MkWyg== dependencies: spdx-exceptions "^2.1.0" spdx-license-ids "^3.0.0" spdx-license-ids@^3.0.0: version "3.0.5" resolved "https://registry.yarnpkg.com/spdx-license-ids/-/spdx-license-ids-3.0.5.tgz#3694b5804567a458d3c8045842a6358632f62654" integrity sha512-J+FWzZoynJEXGphVIS+XEh3kFSjZX/1i9gFBaWQcB+/tmpe2qUsSBABpcxqxnAxFdiUFEgAX1bjYGQvIZmoz9Q== split-string@^3.0.1, split-string@^3.0.2: version "3.1.0" resolved "https://registry.yarnpkg.com/split-string/-/split-string-3.1.0.tgz#7cb09dda3a86585705c64b39a6466038682e8fe2" integrity sha512-NzNVhJDYpwceVVii8/Hu6DKfD2G+NrQHlS/V/qgv763EYudVwEcMQNxd2lh+0VrUByXN/oJkl5grOhYWvQUYiw== dependencies: extend-shallow "^3.0.0" static-extend@^0.1.1: version "0.1.2" resolved "https://registry.yarnpkg.com/static-extend/-/static-extend-0.1.2.tgz#60809c39cbff55337226fd5e0b520f341f1fb5c6" integrity sha1-YICcOcv/VTNyJv1eC1IPNB8ftcY= dependencies: define-property "^0.2.5" object-copy "^0.1.0" string-width@^1.0.1: version "1.0.2" resolved "https://registry.yarnpkg.com/string-width/-/string-width-1.0.2.tgz#118bdf5b8cdc51a2a7e70d211e07e2b0b9b107d3" integrity sha1-EYvfW4zcUaKn5w0hHgfisLmxB9M= dependencies: code-point-at "^1.0.0" is-fullwidth-code-point "^1.0.0" strip-ansi "^3.0.0" "string-width@^1.0.2 || 2": version "2.1.1" resolved "https://registry.yarnpkg.com/string-width/-/string-width-2.1.1.tgz#ab93f27a8dc13d28cac815c462143a6d9012ae9e" integrity sha512-nOqH59deCq9SRHlxq1Aw85Jnt4w6KvLKqWVik6oA9ZklXLNIOlqg4F2yrT1MVaTjAqvVwdfeZ7w7aCvJD7ugkw== dependencies: is-fullwidth-code-point "^2.0.0" strip-ansi "^4.0.0" string_decoder@~1.1.1: version "1.1.1" resolved "https://registry.yarnpkg.com/string_decoder/-/string_decoder-1.1.1.tgz#9cf1611ba62685d7030ae9e4ba34149c3af03fc8" integrity sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg== dependencies: safe-buffer "~5.1.0" strip-ansi@^3.0.0, strip-ansi@^3.0.1: version "3.0.1" resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-3.0.1.tgz#6a385fb8853d952d5ff05d0e8aaf94278dc63dcf" integrity sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8= dependencies: ansi-regex "^2.0.0" strip-ansi@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-4.0.0.tgz#a8479022eb1ac368a871389b635262c505ee368f" integrity sha1-qEeQIusaw2iocTibY1JixQXuNo8= dependencies: ansi-regex "^3.0.0" strip-bom@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/strip-bom/-/strip-bom-3.0.0.tgz#2334c18e9c759f7bdd56fdef7e9ae3d588e68ed3" integrity sha1-IzTBjpx1n3vdVv3vfprj1YjmjtM= strip-json-comments@~2.0.1: version "2.0.1" resolved "https://registry.yarnpkg.com/strip-json-comments/-/strip-json-comments-2.0.1.tgz#3c531942e908c2697c0ec344858c286c7ca0a60a" integrity sha1-PFMZQukIwml8DsNEhYwobHygpgo= subarg@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/subarg/-/subarg-1.0.0.tgz#f62cf17581e996b48fc965699f54c06ae268b8d2" integrity sha1-9izxdYHplrSPyWVpn1TAauJouNI= dependencies: minimist "^1.1.0" supports-color@^3.2.3: version "3.2.3" resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-3.2.3.tgz#65ac0504b3954171d8a64946b2ae3cbb8a5f54f6" integrity sha1-ZawFBLOVQXHYpklGsq48u4pfVPY= dependencies: has-flag "^1.0.0" supports-color@^5.3.0: version "5.5.0" resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-5.5.0.tgz#e2e69a44ac8772f78a1ec0b35b689df6530efc8f" integrity sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow== dependencies: has-flag "^3.0.0" tar@^4: version "4.4.10" resolved "https://registry.yarnpkg.com/tar/-/tar-4.4.10.tgz#946b2810b9a5e0b26140cf78bea6b0b0d689eba1" integrity sha512-g2SVs5QIxvo6OLp0GudTqEf05maawKUxXru104iaayWA09551tFCTI8f1Asb4lPfkBr91k07iL4c11XO3/b0tA== dependencies: chownr "^1.1.1" fs-minipass "^1.2.5" minipass "^2.3.5" minizlib "^1.2.1" mkdirp "^0.5.0" safe-buffer "^5.1.2" yallist "^3.0.3" [email protected]: version "0.1.0" resolved "https://registry.yarnpkg.com/tmp/-/tmp-0.1.0.tgz#ee434a4e22543082e294ba6201dcc6eafefa2877" integrity sha512-J7Z2K08jbGcdA1kkQpJSqLF6T0tdQqpR2pnSUXsIchbPdTI9v3e85cLW0d6WDhwuAleOV71j2xWs8qMPfK7nKw== dependencies: rimraf "^2.6.3" to-object-path@^0.3.0: version "0.3.0" resolved "https://registry.yarnpkg.com/to-object-path/-/to-object-path-0.3.0.tgz#297588b7b0e7e0ac08e04e672f85c1f4999e17af" integrity sha1-KXWIt7Dn4KwI4E5nL4XB9JmeF68= dependencies: kind-of "^3.0.2" to-regex-range@^2.1.0: version "2.1.1" resolved "https://registry.yarnpkg.com/to-regex-range/-/to-regex-range-2.1.1.tgz#7c80c17b9dfebe599e27367e0d4dd5590141db38" integrity sha1-fIDBe53+vlmeJzZ+DU3VWQFB2zg= dependencies: is-number "^3.0.0" repeat-string "^1.6.1" to-regex@^3.0.1, to-regex@^3.0.2: version "3.0.2" resolved "https://registry.yarnpkg.com/to-regex/-/to-regex-3.0.2.tgz#13cfdd9b336552f30b51f33a8ae1b42a7a7599ce" integrity sha512-FWtleNAtZ/Ki2qtqej2CXTOayOH9bHDQF+Q48VpWyDXjbYxA4Yz8iDB31zXOBUlOHHKidDbqGVrTUvQMPmBGBw== dependencies: define-property "^2.0.2" extend-shallow "^3.0.2" regex-not "^1.0.2" safe-regex "^1.1.0" [email protected]: version "1.2.2" resolved "https://registry.yarnpkg.com/tree-kill/-/tree-kill-1.2.2.tgz#4ca09a9092c88b73a7cdc5e8a01b507b0790a0cc" integrity sha512-L0Orpi8qGpRG//Nd+H90vFB+3iHnue1zSSGmNOOCh1GLJ7rUKVwV2HvijphGQS2UmhUZewS9VgvxYIdgr+fG1A== tree-kill@^1.1.0: version "1.2.1" resolved "https://registry.yarnpkg.com/tree-kill/-/tree-kill-1.2.1.tgz#5398f374e2f292b9dcc7b2e71e30a5c3bb6c743a" integrity sha512-4hjqbObwlh2dLyW4tcz0Ymw0ggoaVDMveUB9w8kFSQScdRLo0gxO9J7WFcUBo+W3C1TLdFIEwNOWebgZZ0RH9Q== [email protected]: version "3.7.5" resolved "https://registry.yarnpkg.com/typescript/-/typescript-3.7.5.tgz#0692e21f65fd4108b9330238aac11dd2e177a1ae" integrity sha512-/P5lkRXkWHNAbcJIiHPfRoKqyd7bsyCma1hZNUGfn20qm64T6ZBlrzprymeu918H+mB/0rIg2gGK/BXkhhYgBw== union-value@^1.0.0: version "1.0.1" resolved "https://registry.yarnpkg.com/union-value/-/union-value-1.0.1.tgz#0b6fe7b835aecda61c6ea4d4f02c14221e109847" integrity sha512-tJfXmxMeWYnczCVs7XAEvIV7ieppALdyepWMkHkwciRpZraG/xwT+s2JN8+pr1+8jCRf80FFzvr+MpQeeoF4Xg== dependencies: arr-union "^3.1.0" get-value "^2.0.6" is-extendable "^0.1.1" set-value "^2.0.1" unset-value@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/unset-value/-/unset-value-1.0.0.tgz#8376873f7d2335179ffb1e6fc3a8ed0dfc8ab559" integrity sha1-g3aHP30jNRef+x5vw6jtDfyKtVk= dependencies: has-value "^0.3.1" isobject "^3.0.0" urix@^0.1.0: version "0.1.0" resolved "https://registry.yarnpkg.com/urix/-/urix-0.1.0.tgz#da937f7a62e21fec1fd18d49b35c2935067a6c72" integrity sha1-2pN/emLiH+wf0Y1Js1wpNQZ6bHI= use@^3.1.0: version "3.1.1" resolved "https://registry.yarnpkg.com/use/-/use-3.1.1.tgz#d50c8cac79a19fbc20f2911f56eb973f4e10070f" integrity sha512-cwESVXlO3url9YWlFW/TA9cshCEhtu7IKJ/p5soJ/gGpj7vbvFrAY/eIioQ6Dw23KjZhYgiIo8HOs1nQ2vr/oQ== util-deprecate@~1.0.1: version "1.0.2" resolved "https://registry.yarnpkg.com/util-deprecate/-/util-deprecate-1.0.2.tgz#450d4dc9fa70de732762fbd2d4a28981419a0ccf" integrity sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8= validate-npm-package-license@^3.0.1: version "3.0.4" resolved "https://registry.yarnpkg.com/validate-npm-package-license/-/validate-npm-package-license-3.0.4.tgz#fc91f6b9c7ba15c857f4cb2c5defeec39d4f410a" integrity sha512-DpKm2Ui/xN7/HQKCtpZxoRWBhZ9Z0kqtygG8XCgNQ8ZlDnxuQmWhj566j8fN4Cu3/JmbhsDo7fcAJq4s9h27Ew== dependencies: spdx-correct "^3.0.0" spdx-expression-parse "^3.0.0" vscode-uri@^2.0.3: version "2.0.3" resolved "https://registry.yarnpkg.com/vscode-uri/-/vscode-uri-2.0.3.tgz#25e5f37f552fbee3cec7e5f80cef8469cefc6543" integrity sha512-4D3DI3F4uRy09WNtDGD93H9q034OHImxiIcSq664Hq1Y1AScehlP3qqZyTkX/RWxeu0MRMHGkrxYqm2qlDF/aw== watch@^1.0.2: version "1.0.2" resolved "https://registry.yarnpkg.com/watch/-/watch-1.0.2.tgz#340a717bde765726fa0aa07d721e0147a551df0c" integrity sha1-NApxe952Vyb6CqB9ch4BR6VR3ww= dependencies: exec-sh "^0.2.0" minimist "^1.2.0" wide-align@^1.1.0: version "1.1.3" resolved "https://registry.yarnpkg.com/wide-align/-/wide-align-1.1.3.tgz#ae074e6bdc0c14a431e804e624549c633b000457" integrity sha512-QGkOQc8XL6Bt5PwnsExKBPuMKBxnGxWWW3fU55Xt4feHozMUhdUMaBCk290qpm/wG5u/RSKzwdAC4i51YigihA== dependencies: string-width "^1.0.2 || 2" wrappy@1: version "1.0.2" resolved "https://registry.yarnpkg.com/wrappy/-/wrappy-1.0.2.tgz#b5243d8f3ec1aa35f1364605bc0d1036e30ab69f" integrity sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8= yallist@^3.0.0, yallist@^3.0.3: version "3.0.3" resolved "https://registry.yarnpkg.com/yallist/-/yallist-3.0.3.tgz#b4b049e314be545e3ce802236d6cd22cd91c3de9" integrity sha512-S+Zk8DEWE6oKpV+vI3qWkaK+jSbIK86pCwe2IF/xwIpQ8jEuxpw9NyaGjmp9+BoJv5FV2piqCDcoCtStppiq2A==
test/automation/yarn.lock
0
https://github.com/microsoft/vscode/commit/574ee2032cc24ed250ef15962ce100838d4e5e4a
[ 0.00017331608978565782, 0.00016758733545430005, 0.00016315544780809432, 0.00016733826487325132, 0.0000023511590825364692 ]
{ "id": 0, "code_window": [ "\t\tdispose(this._onChange);\n", "\t}\n", "}\n", "\n", "class SelectionTrait<T> extends Trait<T> {\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "class FocusTrait<T> extends Trait<T> {\n" ], "file_path": "src/vs/base/browser/ui/list/listWidget.ts", "type": "replace", "edit_start_line_idx": 182 }
/*--------------------------------------------------------------------------------------------- * 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!./list'; import { localize } from 'vs/nls'; import { IDisposable, dispose, DisposableStore } from 'vs/base/common/lifecycle'; import { isNumber } from 'vs/base/common/types'; import { range, firstIndex, binarySearch } from 'vs/base/common/arrays'; import { memoize } from 'vs/base/common/decorators'; import * as DOM from 'vs/base/browser/dom'; import * as platform from 'vs/base/common/platform'; import { Gesture } from 'vs/base/browser/touch'; import { KeyCode } from 'vs/base/common/keyCodes'; import { StandardKeyboardEvent, IKeyboardEvent } from 'vs/base/browser/keyboardEvent'; import { Event, Emitter, EventBufferer } from 'vs/base/common/event'; import { domEvent } from 'vs/base/browser/event'; import { IListVirtualDelegate, IListRenderer, IListEvent, IListContextMenuEvent, IListMouseEvent, IListTouchEvent, IListGestureEvent, IIdentityProvider, IKeyboardNavigationLabelProvider, IListDragAndDrop, IListDragOverReaction, ListAriaRootRole, ListError, IKeyboardNavigationDelegate } from './list'; import { ListView, IListViewOptions, IListViewDragAndDrop, IAriaProvider } from './listView'; import { Color } from 'vs/base/common/color'; import { mixin } from 'vs/base/common/objects'; import { ScrollbarVisibility, ScrollEvent } from 'vs/base/common/scrollable'; import { ISpliceable } from 'vs/base/common/sequence'; import { CombinedSpliceable } from 'vs/base/browser/ui/list/splice'; import { clamp } from 'vs/base/common/numbers'; import { matchesPrefix } from 'vs/base/common/filters'; import { IDragAndDropData } from 'vs/base/browser/dnd'; interface ITraitChangeEvent { indexes: number[]; browserEvent?: UIEvent; } type ITraitTemplateData = HTMLElement; interface IRenderedContainer { templateData: ITraitTemplateData; index: number; } class TraitRenderer<T> implements IListRenderer<T, ITraitTemplateData> { private renderedElements: IRenderedContainer[] = []; constructor(private trait: Trait<T>) { } get templateId(): string { return `template:${this.trait.trait}`; } renderTemplate(container: HTMLElement): ITraitTemplateData { return container; } renderElement(element: T, index: number, templateData: ITraitTemplateData): void { const renderedElementIndex = firstIndex(this.renderedElements, el => el.templateData === templateData); if (renderedElementIndex >= 0) { const rendered = this.renderedElements[renderedElementIndex]; this.trait.unrender(templateData); rendered.index = index; } else { const rendered = { index, templateData }; this.renderedElements.push(rendered); } this.trait.renderIndex(index, templateData); } splice(start: number, deleteCount: number, insertCount: number): void { const rendered: IRenderedContainer[] = []; for (const renderedElement of this.renderedElements) { if (renderedElement.index < start) { rendered.push(renderedElement); } else if (renderedElement.index >= start + deleteCount) { rendered.push({ index: renderedElement.index + insertCount - deleteCount, templateData: renderedElement.templateData }); } } this.renderedElements = rendered; } renderIndexes(indexes: number[]): void { for (const { index, templateData } of this.renderedElements) { if (indexes.indexOf(index) > -1) { this.trait.renderIndex(index, templateData); } } } disposeTemplate(templateData: ITraitTemplateData): void { const index = firstIndex(this.renderedElements, el => el.templateData === templateData); if (index < 0) { return; } this.renderedElements.splice(index, 1); } } class Trait<T> implements ISpliceable<boolean>, IDisposable { private indexes: number[] = []; private sortedIndexes: number[] = []; private readonly _onChange = new Emitter<ITraitChangeEvent>(); readonly onChange: Event<ITraitChangeEvent> = this._onChange.event; get trait(): string { return this._trait; } @memoize get renderer(): TraitRenderer<T> { return new TraitRenderer<T>(this); } constructor(private _trait: string) { } splice(start: number, deleteCount: number, elements: boolean[]): void { const diff = elements.length - deleteCount; const end = start + deleteCount; const indexes = [ ...this.sortedIndexes.filter(i => i < start), ...elements.map((hasTrait, i) => hasTrait ? i + start : -1).filter(i => i !== -1), ...this.sortedIndexes.filter(i => i >= end).map(i => i + diff) ]; this.renderer.splice(start, deleteCount, elements.length); this._set(indexes, indexes); } renderIndex(index: number, container: HTMLElement): void { DOM.toggleClass(container, this._trait, this.contains(index)); } unrender(container: HTMLElement): void { DOM.removeClass(container, this._trait); } /** * Sets the indexes which should have this trait. * * @param indexes Indexes which should have this trait. * @return The old indexes which had this trait. */ set(indexes: number[], browserEvent?: UIEvent): number[] { return this._set(indexes, [...indexes].sort(numericSort), browserEvent); } private _set(indexes: number[], sortedIndexes: number[], browserEvent?: UIEvent): number[] { const result = this.indexes; const sortedResult = this.sortedIndexes; this.indexes = indexes; this.sortedIndexes = sortedIndexes; const toRender = disjunction(sortedResult, indexes); this.renderer.renderIndexes(toRender); this._onChange.fire({ indexes, browserEvent }); return result; } get(): number[] { return this.indexes; } contains(index: number): boolean { return binarySearch(this.sortedIndexes, index, numericSort) >= 0; } dispose() { dispose(this._onChange); } } class SelectionTrait<T> extends Trait<T> { constructor() { super('selected'); } renderIndex(index: number, container: HTMLElement): void { super.renderIndex(index, container); if (this.contains(index)) { container.setAttribute('aria-selected', 'true'); } else { container.removeAttribute('aria-selected'); } } } /** * The TraitSpliceable is used as a util class to be able * to preserve traits across splice calls, given an identity * provider. */ class TraitSpliceable<T> implements ISpliceable<T> { constructor( private trait: Trait<T>, private view: ListView<T>, private identityProvider?: IIdentityProvider<T> ) { } splice(start: number, deleteCount: number, elements: T[]): void { if (!this.identityProvider) { return this.trait.splice(start, deleteCount, elements.map(() => false)); } const pastElementsWithTrait = this.trait.get().map(i => this.identityProvider!.getId(this.view.element(i)).toString()); const elementsWithTrait = elements.map(e => pastElementsWithTrait.indexOf(this.identityProvider!.getId(e).toString()) > -1); this.trait.splice(start, deleteCount, elementsWithTrait); } } function isInputElement(e: HTMLElement): boolean { return e.tagName === 'INPUT' || e.tagName === 'TEXTAREA'; } class KeyboardController<T> implements IDisposable { private readonly disposables = new DisposableStore(); private openController: IOpenController; constructor( private list: List<T>, private view: ListView<T>, options: IListOptions<T> ) { const multipleSelectionSupport = options.multipleSelectionSupport !== false; this.openController = options.openController || DefaultOpenController; const onKeyDown = Event.chain(domEvent(view.domNode, 'keydown')) .filter(e => !isInputElement(e.target as HTMLElement)) .map(e => new StandardKeyboardEvent(e)); onKeyDown.filter(e => e.keyCode === KeyCode.Enter).on(this.onEnter, this, this.disposables); onKeyDown.filter(e => e.keyCode === KeyCode.UpArrow).on(this.onUpArrow, this, this.disposables); onKeyDown.filter(e => e.keyCode === KeyCode.DownArrow).on(this.onDownArrow, this, this.disposables); onKeyDown.filter(e => e.keyCode === KeyCode.PageUp).on(this.onPageUpArrow, this, this.disposables); onKeyDown.filter(e => e.keyCode === KeyCode.PageDown).on(this.onPageDownArrow, this, this.disposables); onKeyDown.filter(e => e.keyCode === KeyCode.Escape).on(this.onEscape, this, this.disposables); if (multipleSelectionSupport) { onKeyDown.filter(e => (platform.isMacintosh ? e.metaKey : e.ctrlKey) && e.keyCode === KeyCode.KEY_A).on(this.onCtrlA, this, this.disposables); } } private onEnter(e: StandardKeyboardEvent): void { e.preventDefault(); e.stopPropagation(); this.list.setSelection(this.list.getFocus(), e.browserEvent); if (this.openController.shouldOpen(e.browserEvent)) { this.list.open(this.list.getFocus(), e.browserEvent); } } private onUpArrow(e: StandardKeyboardEvent): void { e.preventDefault(); e.stopPropagation(); this.list.focusPrevious(1, false, e.browserEvent); this.list.reveal(this.list.getFocus()[0]); this.view.domNode.focus(); } private onDownArrow(e: StandardKeyboardEvent): void { e.preventDefault(); e.stopPropagation(); this.list.focusNext(1, false, e.browserEvent); this.list.reveal(this.list.getFocus()[0]); this.view.domNode.focus(); } private onPageUpArrow(e: StandardKeyboardEvent): void { e.preventDefault(); e.stopPropagation(); this.list.focusPreviousPage(e.browserEvent); this.list.reveal(this.list.getFocus()[0]); this.view.domNode.focus(); } private onPageDownArrow(e: StandardKeyboardEvent): void { e.preventDefault(); e.stopPropagation(); this.list.focusNextPage(e.browserEvent); this.list.reveal(this.list.getFocus()[0]); this.view.domNode.focus(); } private onCtrlA(e: StandardKeyboardEvent): void { e.preventDefault(); e.stopPropagation(); this.list.setSelection(range(this.list.length), e.browserEvent); this.view.domNode.focus(); } private onEscape(e: StandardKeyboardEvent): void { e.preventDefault(); e.stopPropagation(); this.list.setSelection([], e.browserEvent); this.view.domNode.focus(); } dispose() { this.disposables.dispose(); } } enum TypeLabelControllerState { Idle, Typing } export const DefaultKeyboardNavigationDelegate = new class implements IKeyboardNavigationDelegate { mightProducePrintableCharacter(event: IKeyboardEvent): boolean { if (event.ctrlKey || event.metaKey || event.altKey) { return false; } return (event.keyCode >= KeyCode.KEY_A && event.keyCode <= KeyCode.KEY_Z) || (event.keyCode >= KeyCode.KEY_0 && event.keyCode <= KeyCode.KEY_9) || (event.keyCode >= KeyCode.NUMPAD_0 && event.keyCode <= KeyCode.NUMPAD_9) || (event.keyCode >= KeyCode.US_SEMICOLON && event.keyCode <= KeyCode.US_QUOTE); } }; class TypeLabelController<T> implements IDisposable { private enabled = false; private state: TypeLabelControllerState = TypeLabelControllerState.Idle; private automaticKeyboardNavigation = true; private triggered = false; private readonly enabledDisposables = new DisposableStore(); private readonly disposables = new DisposableStore(); constructor( private list: List<T>, private view: ListView<T>, private keyboardNavigationLabelProvider: IKeyboardNavigationLabelProvider<T>, private delegate: IKeyboardNavigationDelegate ) { this.updateOptions(list.options); } updateOptions(options: IListOptions<T>): void { const enableKeyboardNavigation = typeof options.enableKeyboardNavigation === 'undefined' ? true : !!options.enableKeyboardNavigation; if (enableKeyboardNavigation) { this.enable(); } else { this.disable(); } if (typeof options.automaticKeyboardNavigation !== 'undefined') { this.automaticKeyboardNavigation = options.automaticKeyboardNavigation; } } toggle(): void { this.triggered = !this.triggered; } private enable(): void { if (this.enabled) { return; } const onChar = Event.chain(domEvent(this.view.domNode, 'keydown')) .filter(e => !isInputElement(e.target as HTMLElement)) .filter(() => this.automaticKeyboardNavigation || this.triggered) .map(event => new StandardKeyboardEvent(event)) .filter(e => this.delegate.mightProducePrintableCharacter(e)) .forEach(e => { e.stopPropagation(); e.preventDefault(); }) .map(event => event.browserEvent.key) .event; const onClear = Event.debounce<string, null>(onChar, () => null, 800); const onInput = Event.reduce<string | null, string | null>(Event.any(onChar, onClear), (r, i) => i === null ? null : ((r || '') + i)); onInput(this.onInput, this, this.enabledDisposables); this.enabled = true; this.triggered = false; } private disable(): void { if (!this.enabled) { return; } this.enabledDisposables.clear(); this.enabled = false; this.triggered = false; } private onInput(word: string | null): void { if (!word) { this.state = TypeLabelControllerState.Idle; this.triggered = false; return; } const focus = this.list.getFocus(); const start = focus.length > 0 ? focus[0] : 0; const delta = this.state === TypeLabelControllerState.Idle ? 1 : 0; this.state = TypeLabelControllerState.Typing; for (let i = 0; i < this.list.length; i++) { const index = (start + i + delta) % this.list.length; const label = this.keyboardNavigationLabelProvider.getKeyboardNavigationLabel(this.view.element(index)); const labelStr = label && label.toString(); if (typeof labelStr === 'undefined' || matchesPrefix(word, labelStr)) { this.list.setFocus([index]); this.list.reveal(index); return; } } } dispose() { this.disable(); this.enabledDisposables.dispose(); this.disposables.dispose(); } } class DOMFocusController<T> implements IDisposable { private readonly disposables = new DisposableStore(); constructor( private list: List<T>, private view: ListView<T> ) { const onKeyDown = Event.chain(domEvent(view.domNode, 'keydown')) .filter(e => !isInputElement(e.target as HTMLElement)) .map(e => new StandardKeyboardEvent(e)); onKeyDown.filter(e => e.keyCode === KeyCode.Tab && !e.ctrlKey && !e.metaKey && !e.shiftKey && !e.altKey) .on(this.onTab, this, this.disposables); } private onTab(e: StandardKeyboardEvent): void { if (e.target !== this.view.domNode) { return; } const focus = this.list.getFocus(); if (focus.length === 0) { return; } const focusedDomElement = this.view.domElement(focus[0]); if (!focusedDomElement) { return; } const tabIndexElement = focusedDomElement.querySelector('[tabIndex]'); if (!tabIndexElement || !(tabIndexElement instanceof HTMLElement) || tabIndexElement.tabIndex === -1) { return; } const style = window.getComputedStyle(tabIndexElement); if (style.visibility === 'hidden' || style.display === 'none') { return; } e.preventDefault(); e.stopPropagation(); tabIndexElement.focus(); } dispose() { this.disposables.dispose(); } } export function isSelectionSingleChangeEvent(event: IListMouseEvent<any> | IListTouchEvent<any>): boolean { return platform.isMacintosh ? event.browserEvent.metaKey : event.browserEvent.ctrlKey; } export function isSelectionRangeChangeEvent(event: IListMouseEvent<any> | IListTouchEvent<any>): boolean { return event.browserEvent.shiftKey; } function isMouseRightClick(event: UIEvent): boolean { return event instanceof MouseEvent && event.button === 2; } const DefaultMultipleSelectionController = { isSelectionSingleChangeEvent, isSelectionRangeChangeEvent }; const DefaultOpenController: IOpenController = { shouldOpen: (event: UIEvent) => { if (event instanceof MouseEvent) { return !isMouseRightClick(event); } return true; } }; export class MouseController<T> implements IDisposable { private multipleSelectionSupport: boolean; readonly multipleSelectionController: IMultipleSelectionController<T> | undefined; private openController: IOpenController; private mouseSupport: boolean; private readonly disposables = new DisposableStore(); constructor(protected list: List<T>) { this.multipleSelectionSupport = !(list.options.multipleSelectionSupport === false); if (this.multipleSelectionSupport) { this.multipleSelectionController = list.options.multipleSelectionController || DefaultMultipleSelectionController; } this.openController = list.options.openController || DefaultOpenController; this.mouseSupport = typeof list.options.mouseSupport === 'undefined' || !!list.options.mouseSupport; if (this.mouseSupport) { list.onMouseDown(this.onMouseDown, this, this.disposables); list.onContextMenu(this.onContextMenu, this, this.disposables); list.onMouseDblClick(this.onDoubleClick, this, this.disposables); list.onTouchStart(this.onMouseDown, this, this.disposables); this.disposables.add(Gesture.addTarget(list.getHTMLElement())); } list.onMouseClick(this.onPointer, this, this.disposables); list.onMouseMiddleClick(this.onPointer, this, this.disposables); list.onTap(this.onPointer, this, this.disposables); } protected isSelectionSingleChangeEvent(event: IListMouseEvent<any> | IListTouchEvent<any>): boolean { if (this.multipleSelectionController) { return this.multipleSelectionController.isSelectionSingleChangeEvent(event); } return platform.isMacintosh ? event.browserEvent.metaKey : event.browserEvent.ctrlKey; } protected isSelectionRangeChangeEvent(event: IListMouseEvent<any> | IListTouchEvent<any>): boolean { if (this.multipleSelectionController) { return this.multipleSelectionController.isSelectionRangeChangeEvent(event); } return event.browserEvent.shiftKey; } private isSelectionChangeEvent(event: IListMouseEvent<any> | IListTouchEvent<any>): boolean { return this.isSelectionSingleChangeEvent(event) || this.isSelectionRangeChangeEvent(event); } private onMouseDown(e: IListMouseEvent<T> | IListTouchEvent<T>): void { if (document.activeElement !== e.browserEvent.target) { this.list.domFocus(); } } private onContextMenu(e: IListContextMenuEvent<T>): void { const focus = typeof e.index === 'undefined' ? [] : [e.index]; this.list.setFocus(focus, e.browserEvent); } protected onPointer(e: IListMouseEvent<T>): void { if (!this.mouseSupport) { return; } if (isInputElement(e.browserEvent.target as HTMLElement)) { return; } let reference = this.list.getFocus()[0]; const selection = this.list.getSelection(); reference = reference === undefined ? selection[0] : reference; const focus = e.index; if (typeof focus === 'undefined') { this.list.setFocus([], e.browserEvent); this.list.setSelection([], e.browserEvent); return; } if (this.multipleSelectionSupport && this.isSelectionRangeChangeEvent(e)) { return this.changeSelection(e, reference); } if (this.multipleSelectionSupport && this.isSelectionChangeEvent(e)) { return this.changeSelection(e, reference); } this.list.setFocus([focus], e.browserEvent); if (!isMouseRightClick(e.browserEvent)) { this.list.setSelection([focus], e.browserEvent); if (this.openController.shouldOpen(e.browserEvent)) { this.list.open([focus], e.browserEvent); } } } protected onDoubleClick(e: IListMouseEvent<T>): void { if (isInputElement(e.browserEvent.target as HTMLElement)) { return; } if (this.multipleSelectionSupport && this.isSelectionChangeEvent(e)) { return; } const focus = this.list.getFocus(); this.list.setSelection(focus, e.browserEvent); this.list.pin(focus); } private changeSelection(e: IListMouseEvent<T> | IListTouchEvent<T>, reference: number | undefined): void { const focus = e.index!; if (this.isSelectionRangeChangeEvent(e) && reference !== undefined) { const min = Math.min(reference, focus); const max = Math.max(reference, focus); const rangeSelection = range(min, max + 1); const selection = this.list.getSelection(); const contiguousRange = getContiguousRangeContaining(disjunction(selection, [reference]), reference); if (contiguousRange.length === 0) { return; } const newSelection = disjunction(rangeSelection, relativeComplement(selection, contiguousRange)); this.list.setSelection(newSelection, e.browserEvent); } else if (this.isSelectionSingleChangeEvent(e)) { const selection = this.list.getSelection(); const newSelection = selection.filter(i => i !== focus); this.list.setFocus([focus]); if (selection.length === newSelection.length) { this.list.setSelection([...newSelection, focus], e.browserEvent); } else { this.list.setSelection(newSelection, e.browserEvent); } } } dispose() { this.disposables.dispose(); } } export interface IMultipleSelectionController<T> { isSelectionSingleChangeEvent(event: IListMouseEvent<T> | IListTouchEvent<T>): boolean; isSelectionRangeChangeEvent(event: IListMouseEvent<T> | IListTouchEvent<T>): boolean; } export interface IOpenController { shouldOpen(event: UIEvent): boolean; } export interface IStyleController { style(styles: IListStyles): void; } export interface IAccessibilityProvider<T> { /** * Given an element in the tree, return the ARIA label that should be associated with the * item. This helps screen readers to provide a meaningful label for the currently focused * tree element. * * Returning null will not disable ARIA for the element. Instead it is up to the screen reader * to compute a meaningful label based on the contents of the element in the DOM * * See also: https://www.w3.org/TR/wai-aria/#aria-label */ getAriaLabel(element: T): string | null; /** * https://www.w3.org/TR/wai-aria/#aria-level */ getAriaLevel?(element: T): number | undefined; onDidChangeActiveDescendant?: Event<void>; getActiveDescendantId?(element: T): string | undefined; } export class DefaultStyleController implements IStyleController { constructor(private styleElement: HTMLStyleElement, private selectorSuffix: string) { } style(styles: IListStyles): void { const suffix = this.selectorSuffix && `.${this.selectorSuffix}`; const content: string[] = []; if (styles.listBackground) { if (styles.listBackground.isOpaque()) { content.push(`.monaco-list${suffix} .monaco-list-rows { background: ${styles.listBackground}; }`); } else if (!platform.isMacintosh) { // subpixel AA doesn't exist in macOS console.warn(`List with id '${this.selectorSuffix}' was styled with a non-opaque background color. This will break sub-pixel antialiasing.`); } } if (styles.listFocusBackground) { content.push(`.monaco-list${suffix}:focus .monaco-list-row.focused { background-color: ${styles.listFocusBackground}; }`); content.push(`.monaco-list${suffix}:focus .monaco-list-row.focused:hover { background-color: ${styles.listFocusBackground}; }`); // overwrite :hover style in this case! } if (styles.listFocusForeground) { content.push(`.monaco-list${suffix}:focus .monaco-list-row.focused { color: ${styles.listFocusForeground}; }`); } if (styles.listActiveSelectionBackground) { content.push(`.monaco-list${suffix}:focus .monaco-list-row.selected { background-color: ${styles.listActiveSelectionBackground}; }`); content.push(`.monaco-list${suffix}:focus .monaco-list-row.selected:hover { background-color: ${styles.listActiveSelectionBackground}; }`); // overwrite :hover style in this case! } if (styles.listActiveSelectionForeground) { content.push(`.monaco-list${suffix}:focus .monaco-list-row.selected { color: ${styles.listActiveSelectionForeground}; }`); } if (styles.listFocusAndSelectionBackground) { content.push(` .monaco-drag-image, .monaco-list${suffix}:focus .monaco-list-row.selected.focused { background-color: ${styles.listFocusAndSelectionBackground}; } `); } if (styles.listFocusAndSelectionForeground) { content.push(` .monaco-drag-image, .monaco-list${suffix}:focus .monaco-list-row.selected.focused { color: ${styles.listFocusAndSelectionForeground}; } `); } if (styles.listInactiveFocusBackground) { content.push(`.monaco-list${suffix} .monaco-list-row.focused { background-color: ${styles.listInactiveFocusBackground}; }`); content.push(`.monaco-list${suffix} .monaco-list-row.focused:hover { background-color: ${styles.listInactiveFocusBackground}; }`); // overwrite :hover style in this case! } if (styles.listInactiveSelectionBackground) { content.push(`.monaco-list${suffix} .monaco-list-row.selected { background-color: ${styles.listInactiveSelectionBackground}; }`); content.push(`.monaco-list${suffix} .monaco-list-row.selected:hover { background-color: ${styles.listInactiveSelectionBackground}; }`); // overwrite :hover style in this case! } if (styles.listInactiveSelectionForeground) { content.push(`.monaco-list${suffix} .monaco-list-row.selected { color: ${styles.listInactiveSelectionForeground}; }`); } if (styles.listHoverBackground) { content.push(`.monaco-list${suffix}:not(.drop-target) .monaco-list-row:hover:not(.selected):not(.focused) { background-color: ${styles.listHoverBackground}; }`); } if (styles.listHoverForeground) { content.push(`.monaco-list${suffix} .monaco-list-row:hover:not(.selected):not(.focused) { color: ${styles.listHoverForeground}; }`); } if (styles.listSelectionOutline) { content.push(`.monaco-list${suffix} .monaco-list-row.selected { outline: 1px dotted ${styles.listSelectionOutline}; outline-offset: -1px; }`); } if (styles.listFocusOutline) { content.push(` .monaco-drag-image, .monaco-list${suffix}:focus .monaco-list-row.focused { outline: 1px solid ${styles.listFocusOutline}; outline-offset: -1px; } `); } if (styles.listInactiveFocusOutline) { content.push(`.monaco-list${suffix} .monaco-list-row.focused { outline: 1px dotted ${styles.listInactiveFocusOutline}; outline-offset: -1px; }`); } if (styles.listHoverOutline) { content.push(`.monaco-list${suffix} .monaco-list-row:hover { outline: 1px dashed ${styles.listHoverOutline}; outline-offset: -1px; }`); } if (styles.listDropBackground) { content.push(` .monaco-list${suffix}.drop-target, .monaco-list${suffix} .monaco-list-rows.drop-target, .monaco-list${suffix} .monaco-list-row.drop-target { background-color: ${styles.listDropBackground} !important; color: inherit !important; } `); } if (styles.listFilterWidgetBackground) { content.push(`.monaco-list-type-filter { background-color: ${styles.listFilterWidgetBackground} }`); } if (styles.listFilterWidgetOutline) { content.push(`.monaco-list-type-filter { border: 1px solid ${styles.listFilterWidgetOutline}; }`); } if (styles.listFilterWidgetNoMatchesOutline) { content.push(`.monaco-list-type-filter.no-matches { border: 1px solid ${styles.listFilterWidgetNoMatchesOutline}; }`); } if (styles.listMatchesShadow) { content.push(`.monaco-list-type-filter { box-shadow: 1px 1px 1px ${styles.listMatchesShadow}; }`); } const newStyles = content.join('\n'); if (newStyles !== this.styleElement.innerHTML) { this.styleElement.innerHTML = newStyles; } } } export interface IListOptions<T> { readonly identityProvider?: IIdentityProvider<T>; readonly dnd?: IListDragAndDrop<T>; readonly enableKeyboardNavigation?: boolean; readonly automaticKeyboardNavigation?: boolean; readonly keyboardNavigationLabelProvider?: IKeyboardNavigationLabelProvider<T>; readonly keyboardNavigationDelegate?: IKeyboardNavigationDelegate; readonly ariaRole?: ListAriaRootRole | string; readonly ariaLabel?: string; readonly keyboardSupport?: boolean; readonly multipleSelectionSupport?: boolean; readonly multipleSelectionController?: IMultipleSelectionController<T>; readonly openController?: IOpenController; readonly styleController?: (suffix: string) => IStyleController; readonly accessibilityProvider?: IAccessibilityProvider<T>; // list view options readonly useShadows?: boolean; readonly verticalScrollMode?: ScrollbarVisibility; readonly setRowLineHeight?: boolean; readonly setRowHeight?: boolean; readonly supportDynamicHeights?: boolean; readonly mouseSupport?: boolean; readonly horizontalScrolling?: boolean; readonly ariaProvider?: IAriaProvider<T>; } export interface IListStyles { listBackground?: Color; listFocusBackground?: Color; listFocusForeground?: Color; listActiveSelectionBackground?: Color; listActiveSelectionForeground?: Color; listFocusAndSelectionBackground?: Color; listFocusAndSelectionForeground?: Color; listInactiveSelectionBackground?: Color; listInactiveSelectionForeground?: Color; listInactiveFocusBackground?: Color; listHoverBackground?: Color; listHoverForeground?: Color; listDropBackground?: Color; listFocusOutline?: Color; listInactiveFocusOutline?: Color; listSelectionOutline?: Color; listHoverOutline?: Color; listFilterWidgetBackground?: Color; listFilterWidgetOutline?: Color; listFilterWidgetNoMatchesOutline?: Color; listMatchesShadow?: Color; treeIndentGuidesStroke?: Color; } const defaultStyles: IListStyles = { listFocusBackground: Color.fromHex('#7FB0D0'), listActiveSelectionBackground: Color.fromHex('#0E639C'), listActiveSelectionForeground: Color.fromHex('#FFFFFF'), listFocusAndSelectionBackground: Color.fromHex('#094771'), listFocusAndSelectionForeground: Color.fromHex('#FFFFFF'), listInactiveSelectionBackground: Color.fromHex('#3F3F46'), listHoverBackground: Color.fromHex('#2A2D2E'), listDropBackground: Color.fromHex('#383B3D'), treeIndentGuidesStroke: Color.fromHex('#a9a9a9') }; const DefaultOptions = { keyboardSupport: true, mouseSupport: true, multipleSelectionSupport: true, dnd: { getDragURI() { return null; }, onDragStart(): void { }, onDragOver() { return false; }, drop() { } }, ariaRootRole: ListAriaRootRole.TREE }; // TODO@Joao: move these utils into a SortedArray class function getContiguousRangeContaining(range: number[], value: number): number[] { const index = range.indexOf(value); if (index === -1) { return []; } const result: number[] = []; let i = index - 1; while (i >= 0 && range[i] === value - (index - i)) { result.push(range[i--]); } result.reverse(); i = index; while (i < range.length && range[i] === value + (i - index)) { result.push(range[i++]); } return result; } /** * Given two sorted collections of numbers, returns the intersection * between them (OR). */ function disjunction(one: number[], other: number[]): number[] { const result: number[] = []; let i = 0, j = 0; while (i < one.length || j < other.length) { if (i >= one.length) { result.push(other[j++]); } else if (j >= other.length) { result.push(one[i++]); } else if (one[i] === other[j]) { result.push(one[i]); i++; j++; continue; } else if (one[i] < other[j]) { result.push(one[i++]); } else { result.push(other[j++]); } } return result; } /** * Given two sorted collections of numbers, returns the relative * complement between them (XOR). */ function relativeComplement(one: number[], other: number[]): number[] { const result: number[] = []; let i = 0, j = 0; while (i < one.length || j < other.length) { if (i >= one.length) { result.push(other[j++]); } else if (j >= other.length) { result.push(one[i++]); } else if (one[i] === other[j]) { i++; j++; continue; } else if (one[i] < other[j]) { result.push(one[i++]); } else { j++; } } return result; } const numericSort = (a: number, b: number) => a - b; class PipelineRenderer<T> implements IListRenderer<T, any> { constructor( private _templateId: string, private renderers: IListRenderer<any /* TODO@joao */, any>[] ) { } get templateId(): string { return this._templateId; } renderTemplate(container: HTMLElement): any[] { return this.renderers.map(r => r.renderTemplate(container)); } renderElement(element: T, index: number, templateData: any[], height: number | undefined): void { let i = 0; for (const renderer of this.renderers) { renderer.renderElement(element, index, templateData[i++], height); } } disposeElement(element: T, index: number, templateData: any[], height: number | undefined): void { let i = 0; for (const renderer of this.renderers) { if (renderer.disposeElement) { renderer.disposeElement(element, index, templateData[i], height); } i += 1; } } disposeTemplate(templateData: any[]): void { let i = 0; for (const renderer of this.renderers) { renderer.disposeTemplate(templateData[i++]); } } } class AccessibiltyRenderer<T> implements IListRenderer<T, HTMLElement> { templateId: string = 'a18n'; constructor(private accessibilityProvider: IAccessibilityProvider<T>) { } renderTemplate(container: HTMLElement): HTMLElement { return container; } renderElement(element: T, index: number, container: HTMLElement): void { const ariaLabel = this.accessibilityProvider.getAriaLabel(element); if (ariaLabel) { container.setAttribute('aria-label', ariaLabel); } else { container.removeAttribute('aria-label'); } const ariaLevel = this.accessibilityProvider.getAriaLevel && this.accessibilityProvider.getAriaLevel(element); if (typeof ariaLevel === 'number') { container.setAttribute('aria-level', `${ariaLevel}`); } else { container.removeAttribute('aria-level'); } } disposeTemplate(templateData: any): void { // noop } } class ListViewDragAndDrop<T> implements IListViewDragAndDrop<T> { constructor(private list: List<T>, private dnd: IListDragAndDrop<T>) { } getDragElements(element: T): T[] { const selection = this.list.getSelectedElements(); const elements = selection.indexOf(element) > -1 ? selection : [element]; return elements; } getDragURI(element: T): string | null { return this.dnd.getDragURI(element); } getDragLabel?(elements: T[], originalEvent: DragEvent): string | undefined { if (this.dnd.getDragLabel) { return this.dnd.getDragLabel(elements, originalEvent); } return undefined; } onDragStart(data: IDragAndDropData, originalEvent: DragEvent): void { if (this.dnd.onDragStart) { this.dnd.onDragStart(data, originalEvent); } } onDragOver(data: IDragAndDropData, targetElement: T, targetIndex: number, originalEvent: DragEvent): boolean | IListDragOverReaction { return this.dnd.onDragOver(data, targetElement, targetIndex, originalEvent); } onDragEnd(originalEvent: DragEvent): void { if (this.dnd.onDragEnd) { this.dnd.onDragEnd(originalEvent); } } drop(data: IDragAndDropData, targetElement: T, targetIndex: number, originalEvent: DragEvent): void { this.dnd.drop(data, targetElement, targetIndex, originalEvent); } } export interface IListOptionsUpdate { readonly enableKeyboardNavigation?: boolean; readonly automaticKeyboardNavigation?: boolean; } export class List<T> implements ISpliceable<T>, IDisposable { private focus: Trait<T>; private selection: Trait<T>; private eventBufferer = new EventBufferer(); protected view: ListView<T>; private spliceable: ISpliceable<T>; private styleController: IStyleController; private typeLabelController?: TypeLabelController<T>; private accessibilityProvider?: IAccessibilityProvider<T>; protected readonly disposables = new DisposableStore(); @memoize get onDidChangeFocus(): Event<IListEvent<T>> { return Event.map(this.eventBufferer.wrapEvent(this.focus.onChange), e => this.toListEvent(e)); } @memoize get onDidChangeSelection(): Event<IListEvent<T>> { return Event.map(this.eventBufferer.wrapEvent(this.selection.onChange), e => this.toListEvent(e)); } private readonly _onDidOpen = new Emitter<IListEvent<T>>(); readonly onDidOpen: Event<IListEvent<T>> = this._onDidOpen.event; private readonly _onDidPin = new Emitter<IListEvent<T>>(); readonly onDidPin: Event<IListEvent<T>> = this._onDidPin.event; get domId(): string { return this.view.domId; } get onDidScroll(): Event<ScrollEvent> { return this.view.onDidScroll; } get onMouseClick(): Event<IListMouseEvent<T>> { return this.view.onMouseClick; } get onMouseDblClick(): Event<IListMouseEvent<T>> { return this.view.onMouseDblClick; } get onMouseMiddleClick(): Event<IListMouseEvent<T>> { return this.view.onMouseMiddleClick; } get onMouseUp(): Event<IListMouseEvent<T>> { return this.view.onMouseUp; } get onMouseDown(): Event<IListMouseEvent<T>> { return this.view.onMouseDown; } get onMouseOver(): Event<IListMouseEvent<T>> { return this.view.onMouseOver; } get onMouseMove(): Event<IListMouseEvent<T>> { return this.view.onMouseMove; } get onMouseOut(): Event<IListMouseEvent<T>> { return this.view.onMouseOut; } get onTouchStart(): Event<IListTouchEvent<T>> { return this.view.onTouchStart; } get onTap(): Event<IListGestureEvent<T>> { return this.view.onTap; } private didJustPressContextMenuKey: boolean = false; @memoize get onContextMenu(): Event<IListContextMenuEvent<T>> { const fromKeydown = Event.chain(domEvent(this.view.domNode, 'keydown')) .map(e => new StandardKeyboardEvent(e)) .filter(e => this.didJustPressContextMenuKey = e.keyCode === KeyCode.ContextMenu || (e.shiftKey && e.keyCode === KeyCode.F10)) .filter(e => { e.preventDefault(); e.stopPropagation(); return false; }) .event as Event<any>; const fromKeyup = Event.chain(domEvent(this.view.domNode, 'keyup')) .filter(() => { const didJustPressContextMenuKey = this.didJustPressContextMenuKey; this.didJustPressContextMenuKey = false; return didJustPressContextMenuKey; }) .filter(() => this.getFocus().length > 0 && !!this.view.domElement(this.getFocus()[0])) .map(browserEvent => { const index = this.getFocus()[0]; const element = this.view.element(index); const anchor = this.view.domElement(index) as HTMLElement; return { index, element, anchor, browserEvent }; }) .event; const fromMouse = Event.chain(this.view.onContextMenu) .filter(() => !this.didJustPressContextMenuKey) .map(({ element, index, browserEvent }) => ({ element, index, anchor: { x: browserEvent.clientX + 1, y: browserEvent.clientY }, browserEvent })) .event; return Event.any<IListContextMenuEvent<T>>(fromKeydown, fromKeyup, fromMouse); } get onKeyDown(): Event<KeyboardEvent> { return domEvent(this.view.domNode, 'keydown'); } get onKeyUp(): Event<KeyboardEvent> { return domEvent(this.view.domNode, 'keyup'); } get onKeyPress(): Event<KeyboardEvent> { return domEvent(this.view.domNode, 'keypress'); } readonly onDidFocus: Event<void>; readonly onDidBlur: Event<void>; private readonly _onDidDispose = new Emitter<void>(); readonly onDidDispose: Event<void> = this._onDidDispose.event; constructor( private user: string, container: HTMLElement, virtualDelegate: IListVirtualDelegate<T>, renderers: IListRenderer<any /* TODO@joao */, any>[], private _options: IListOptions<T> = DefaultOptions ) { this.focus = new Trait('focused'); this.selection = new SelectionTrait(); mixin(_options, defaultStyles, false); const baseRenderers: IListRenderer<T, ITraitTemplateData>[] = [this.focus.renderer, this.selection.renderer]; this.accessibilityProvider = _options.accessibilityProvider; if (this.accessibilityProvider) { baseRenderers.push(new AccessibiltyRenderer<T>(this.accessibilityProvider)); if (this.accessibilityProvider.onDidChangeActiveDescendant) { this.accessibilityProvider.onDidChangeActiveDescendant(this.onDidChangeActiveDescendant, this, this.disposables); } } renderers = renderers.map(r => new PipelineRenderer(r.templateId, [...baseRenderers, r])); const viewOptions: IListViewOptions<T> = { ..._options, dnd: _options.dnd && new ListViewDragAndDrop(this, _options.dnd) }; this.view = new ListView(container, virtualDelegate, renderers, viewOptions); if (typeof _options.ariaRole !== 'string') { this.view.domNode.setAttribute('role', ListAriaRootRole.TREE); } else { this.view.domNode.setAttribute('role', _options.ariaRole); } if (_options.styleController) { this.styleController = _options.styleController(this.view.domId); } else { const styleElement = DOM.createStyleSheet(this.view.domNode); this.styleController = new DefaultStyleController(styleElement, this.view.domId); } this.spliceable = new CombinedSpliceable([ new TraitSpliceable(this.focus, this.view, _options.identityProvider), new TraitSpliceable(this.selection, this.view, _options.identityProvider), this.view ]); this.disposables.add(this.focus); this.disposables.add(this.selection); this.disposables.add(this.view); this.disposables.add(this._onDidDispose); this.onDidFocus = Event.map(domEvent(this.view.domNode, 'focus', true), () => null!); this.onDidBlur = Event.map(domEvent(this.view.domNode, 'blur', true), () => null!); this.disposables.add(new DOMFocusController(this, this.view)); if (typeof _options.keyboardSupport !== 'boolean' || _options.keyboardSupport) { const controller = new KeyboardController(this, this.view, _options); this.disposables.add(controller); } if (_options.keyboardNavigationLabelProvider) { const delegate = _options.keyboardNavigationDelegate || DefaultKeyboardNavigationDelegate; this.typeLabelController = new TypeLabelController(this, this.view, _options.keyboardNavigationLabelProvider, delegate); this.disposables.add(this.typeLabelController); } this.disposables.add(this.createMouseController(_options)); this.onDidChangeFocus(this._onFocusChange, this, this.disposables); this.onDidChangeSelection(this._onSelectionChange, this, this.disposables); if (_options.ariaLabel) { this.view.domNode.setAttribute('aria-label', localize('aria list', "{0}. Use the navigation keys to navigate.", _options.ariaLabel)); } if (_options.multipleSelectionSupport) { this.view.domNode.setAttribute('aria-multiselectable', 'true'); } } protected createMouseController(options: IListOptions<T>): MouseController<T> { return new MouseController(this); } updateOptions(optionsUpdate: IListOptionsUpdate = {}): void { this._options = { ...this._options, ...optionsUpdate }; if (this.typeLabelController) { this.typeLabelController.updateOptions(this._options); } } get options(): IListOptions<T> { return this._options; } splice(start: number, deleteCount: number, elements: T[] = []): void { if (start < 0 || start > this.view.length) { throw new ListError(this.user, `Invalid start index: ${start}`); } if (deleteCount < 0) { throw new ListError(this.user, `Invalid delete count: ${deleteCount}`); } if (deleteCount === 0 && elements.length === 0) { return; } this.eventBufferer.bufferEvents(() => this.spliceable.splice(start, deleteCount, elements)); } updateWidth(index: number): void { this.view.updateWidth(index); } updateElementHeight(index: number, size: number): void { this.view.updateElementHeight(index, size); } rerender(): void { this.view.rerender(); } element(index: number): T { return this.view.element(index); } get length(): number { return this.view.length; } get contentHeight(): number { return this.view.contentHeight; } get onDidChangeContentHeight(): Event<number> { return this.view.onDidChangeContentHeight; } get scrollTop(): number { return this.view.getScrollTop(); } set scrollTop(scrollTop: number) { this.view.setScrollTop(scrollTop); } get scrollLeft(): number { return this.view.getScrollLeft(); } set scrollLeft(scrollLeft: number) { this.view.setScrollLeft(scrollLeft); } get scrollHeight(): number { return this.view.scrollHeight; } get renderHeight(): number { return this.view.renderHeight; } get firstVisibleIndex(): number { return this.view.firstVisibleIndex; } get lastVisibleIndex(): number { return this.view.lastVisibleIndex; } domFocus(): void { this.view.domNode.focus(); } layout(height?: number, width?: number): void { this.view.layout(height, width); } toggleKeyboardNavigation(): void { if (this.typeLabelController) { this.typeLabelController.toggle(); } } setSelection(indexes: number[], browserEvent?: UIEvent): void { for (const index of indexes) { if (index < 0 || index >= this.length) { throw new ListError(this.user, `Invalid index ${index}`); } } this.selection.set(indexes, browserEvent); } getSelection(): number[] { return this.selection.get(); } getSelectedElements(): T[] { return this.getSelection().map(i => this.view.element(i)); } setFocus(indexes: number[], browserEvent?: UIEvent): void { for (const index of indexes) { if (index < 0 || index >= this.length) { throw new ListError(this.user, `Invalid index ${index}`); } } this.focus.set(indexes, browserEvent); } focusNext(n = 1, loop = false, browserEvent?: UIEvent, filter?: (element: T) => boolean): void { if (this.length === 0) { return; } const focus = this.focus.get(); const index = this.findNextIndex(focus.length > 0 ? focus[0] + n : 0, loop, filter); if (index > -1) { this.setFocus([index], browserEvent); } } focusPrevious(n = 1, loop = false, browserEvent?: UIEvent, filter?: (element: T) => boolean): void { if (this.length === 0) { return; } const focus = this.focus.get(); const index = this.findPreviousIndex(focus.length > 0 ? focus[0] - n : 0, loop, filter); if (index > -1) { this.setFocus([index], browserEvent); } } focusNextPage(browserEvent?: UIEvent, filter?: (element: T) => boolean): void { let lastPageIndex = this.view.indexAt(this.view.getScrollTop() + this.view.renderHeight); lastPageIndex = lastPageIndex === 0 ? 0 : lastPageIndex - 1; const lastPageElement = this.view.element(lastPageIndex); const currentlyFocusedElement = this.getFocusedElements()[0]; if (currentlyFocusedElement !== lastPageElement) { const lastGoodPageIndex = this.findPreviousIndex(lastPageIndex, false, filter); if (lastGoodPageIndex > -1 && currentlyFocusedElement !== this.view.element(lastGoodPageIndex)) { this.setFocus([lastGoodPageIndex], browserEvent); } else { this.setFocus([lastPageIndex], browserEvent); } } else { const previousScrollTop = this.view.getScrollTop(); this.view.setScrollTop(previousScrollTop + this.view.renderHeight - this.view.elementHeight(lastPageIndex)); if (this.view.getScrollTop() !== previousScrollTop) { // Let the scroll event listener run setTimeout(() => this.focusNextPage(browserEvent, filter), 0); } } } focusPreviousPage(browserEvent?: UIEvent, filter?: (element: T) => boolean): void { let firstPageIndex: number; const scrollTop = this.view.getScrollTop(); if (scrollTop === 0) { firstPageIndex = this.view.indexAt(scrollTop); } else { firstPageIndex = this.view.indexAfter(scrollTop - 1); } const firstPageElement = this.view.element(firstPageIndex); const currentlyFocusedElement = this.getFocusedElements()[0]; if (currentlyFocusedElement !== firstPageElement) { const firstGoodPageIndex = this.findNextIndex(firstPageIndex, false, filter); if (firstGoodPageIndex > -1 && currentlyFocusedElement !== this.view.element(firstGoodPageIndex)) { this.setFocus([firstGoodPageIndex], browserEvent); } else { this.setFocus([firstPageIndex], browserEvent); } } else { const previousScrollTop = scrollTop; this.view.setScrollTop(scrollTop - this.view.renderHeight); if (this.view.getScrollTop() !== previousScrollTop) { // Let the scroll event listener run setTimeout(() => this.focusPreviousPage(browserEvent, filter), 0); } } } focusLast(browserEvent?: UIEvent, filter?: (element: T) => boolean): void { if (this.length === 0) { return; } const index = this.findPreviousIndex(this.length - 1, false, filter); if (index > -1) { this.setFocus([index], browserEvent); } } focusFirst(browserEvent?: UIEvent, filter?: (element: T) => boolean): void { if (this.length === 0) { return; } const index = this.findNextIndex(0, false, filter); if (index > -1) { this.setFocus([index], browserEvent); } } private findNextIndex(index: number, loop = false, filter?: (element: T) => boolean): number { for (let i = 0; i < this.length; i++) { if (index >= this.length && !loop) { return -1; } index = index % this.length; if (!filter || filter(this.element(index))) { return index; } index++; } return -1; } private findPreviousIndex(index: number, loop = false, filter?: (element: T) => boolean): number { for (let i = 0; i < this.length; i++) { if (index < 0 && !loop) { return -1; } index = (this.length + (index % this.length)) % this.length; if (!filter || filter(this.element(index))) { return index; } index--; } return -1; } getFocus(): number[] { return this.focus.get(); } getFocusedElements(): T[] { return this.getFocus().map(i => this.view.element(i)); } reveal(index: number, relativeTop?: number): void { if (index < 0 || index >= this.length) { throw new ListError(this.user, `Invalid index ${index}`); } const scrollTop = this.view.getScrollTop(); const elementTop = this.view.elementTop(index); const elementHeight = this.view.elementHeight(index); if (isNumber(relativeTop)) { // y = mx + b const m = elementHeight - this.view.renderHeight; this.view.setScrollTop(m * clamp(relativeTop, 0, 1) + elementTop); } else { const viewItemBottom = elementTop + elementHeight; const wrapperBottom = scrollTop + this.view.renderHeight; if (elementTop < scrollTop && viewItemBottom >= wrapperBottom) { // The element is already overflowing the viewport, no-op } else if (elementTop < scrollTop) { this.view.setScrollTop(elementTop); } else if (viewItemBottom >= wrapperBottom) { this.view.setScrollTop(viewItemBottom - this.view.renderHeight); } } } /** * Returns the relative position of an element rendered in the list. * Returns `null` if the element isn't *entirely* in the visible viewport. */ getRelativeTop(index: number): number | null { if (index < 0 || index >= this.length) { throw new ListError(this.user, `Invalid index ${index}`); } const scrollTop = this.view.getScrollTop(); const elementTop = this.view.elementTop(index); const elementHeight = this.view.elementHeight(index); if (elementTop < scrollTop || elementTop + elementHeight > scrollTop + this.view.renderHeight) { return null; } // y = mx + b const m = elementHeight - this.view.renderHeight; return Math.abs((scrollTop - elementTop) / m); } isDOMFocused(): boolean { return this.view.domNode === document.activeElement; } getHTMLElement(): HTMLElement { return this.view.domNode; } open(indexes: number[], browserEvent?: UIEvent): void { for (const index of indexes) { if (index < 0 || index >= this.length) { throw new ListError(this.user, `Invalid index ${index}`); } } this._onDidOpen.fire({ indexes, elements: indexes.map(i => this.view.element(i)), browserEvent }); } pin(indexes: number[], browserEvent?: UIEvent): void { for (const index of indexes) { if (index < 0 || index >= this.length) { throw new ListError(this.user, `Invalid index ${index}`); } } this._onDidPin.fire({ indexes, elements: indexes.map(i => this.view.element(i)), browserEvent }); } style(styles: IListStyles): void { this.styleController.style(styles); } private toListEvent({ indexes, browserEvent }: ITraitChangeEvent) { return { indexes, elements: indexes.map(i => this.view.element(i)), browserEvent }; } private _onFocusChange(): void { const focus = this.focus.get(); DOM.toggleClass(this.view.domNode, 'element-focused', focus.length > 0); this.onDidChangeActiveDescendant(); } private onDidChangeActiveDescendant(): void { const focus = this.focus.get(); if (focus.length > 0) { let id: string | undefined; if (this.accessibilityProvider?.getActiveDescendantId) { id = this.accessibilityProvider.getActiveDescendantId(this.view.element(focus[0])); } this.view.domNode.setAttribute('aria-activedescendant', id || this.view.getElementDomId(focus[0])); } else { this.view.domNode.removeAttribute('aria-activedescendant'); } } private _onSelectionChange(): void { const selection = this.selection.get(); DOM.toggleClass(this.view.domNode, 'selection-none', selection.length === 0); DOM.toggleClass(this.view.domNode, 'selection-single', selection.length === 1); DOM.toggleClass(this.view.domNode, 'selection-multiple', selection.length > 1); } dispose(): void { this._onDidDispose.fire(); this.disposables.dispose(); this._onDidOpen.dispose(); this._onDidPin.dispose(); this._onDidDispose.dispose(); } }
src/vs/base/browser/ui/list/listWidget.ts
1
https://github.com/microsoft/vscode/commit/7aca51e3d98c58ee8e418df6b525930d90375d9f
[ 0.999127209186554, 0.03693818673491478, 0.00016277255781460553, 0.00017655579722486436, 0.1686544269323349 ]
{ "id": 0, "code_window": [ "\t\tdispose(this._onChange);\n", "\t}\n", "}\n", "\n", "class SelectionTrait<T> extends Trait<T> {\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "class FocusTrait<T> extends Trait<T> {\n" ], "file_path": "src/vs/base/browser/ui/list/listWidget.ts", "type": "replace", "edit_start_line_idx": 182 }
/*--------------------------------------------------------------------------------------------- * 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 { IWindowOpenable, isWorkspaceToOpen, isFileToOpen } from 'vs/platform/windows/common/windows'; import { IPickAndOpenOptions, ISaveDialogOptions, IOpenDialogOptions, FileFilter, IFileDialogService, IDialogService, ConfirmResult, getFileNamesMessage } from 'vs/platform/dialogs/common/dialogs'; import { IWorkspaceContextService, WorkbenchState } from 'vs/platform/workspace/common/workspace'; import { IHistoryService } from 'vs/workbench/services/history/common/history'; import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService'; import { URI } from 'vs/base/common/uri'; import { Schemas } from 'vs/base/common/network'; import * as resources from 'vs/base/common/resources'; import { IInstantiationService, } from 'vs/platform/instantiation/common/instantiation'; import { SimpleFileDialog } from 'vs/workbench/services/dialogs/browser/simpleFileDialog'; import { WORKSPACE_EXTENSION, isUntitledWorkspace, IWorkspacesService } from 'vs/platform/workspaces/common/workspaces'; import { REMOTE_HOST_SCHEME } from 'vs/platform/remote/common/remoteHosts'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IFileService } from 'vs/platform/files/common/files'; import { IOpenerService } from 'vs/platform/opener/common/opener'; import { IHostService } from 'vs/workbench/services/host/browser/host'; import Severity from 'vs/base/common/severity'; import { coalesce } from 'vs/base/common/arrays'; import { trim } from 'vs/base/common/strings'; import { IModeService } from 'vs/editor/common/services/modeService'; import { ILabelService } from 'vs/platform/label/common/label'; export abstract class AbstractFileDialogService implements IFileDialogService { _serviceBrand: undefined; constructor( @IHostService protected readonly hostService: IHostService, @IWorkspaceContextService protected readonly contextService: IWorkspaceContextService, @IHistoryService protected readonly historyService: IHistoryService, @IWorkbenchEnvironmentService protected readonly environmentService: IWorkbenchEnvironmentService, @IInstantiationService protected readonly instantiationService: IInstantiationService, @IConfigurationService protected readonly configurationService: IConfigurationService, @IFileService protected readonly fileService: IFileService, @IOpenerService protected readonly openerService: IOpenerService, @IDialogService private readonly dialogService: IDialogService, @IModeService private readonly modeService: IModeService, @IWorkspacesService private readonly workspacesService: IWorkspacesService, @ILabelService private readonly labelService: ILabelService ) { } defaultFilePath(schemeFilter = this.getSchemeFilterForWindow()): URI | undefined { // Check for last active file first... let candidate = this.historyService.getLastActiveFile(schemeFilter); // ...then for last active file root if (!candidate) { candidate = this.historyService.getLastActiveWorkspaceRoot(schemeFilter); } else { candidate = candidate && resources.dirname(candidate); } return candidate || undefined; } defaultFolderPath(schemeFilter = this.getSchemeFilterForWindow()): URI | undefined { // Check for last active file root first... let candidate = this.historyService.getLastActiveWorkspaceRoot(schemeFilter); // ...then for last active file if (!candidate) { candidate = this.historyService.getLastActiveFile(schemeFilter); } return candidate && resources.dirname(candidate) || undefined; } defaultWorkspacePath(schemeFilter = this.getSchemeFilterForWindow()): URI | undefined { // Check for current workspace config file first... if (this.contextService.getWorkbenchState() === WorkbenchState.WORKSPACE) { const configuration = this.contextService.getWorkspace().configuration; if (configuration && !isUntitledWorkspace(configuration, this.environmentService)) { return resources.dirname(configuration) || undefined; } } // ...then fallback to default file path return this.defaultFilePath(schemeFilter); } async showSaveConfirm(fileNamesOrResources: (string | URI)[]): Promise<ConfirmResult> { if (this.environmentService.isExtensionDevelopment) { return ConfirmResult.DONT_SAVE; // no veto when we are in extension dev mode because we cannot assume we run interactive (e.g. tests) } return this.doShowSaveConfirm(fileNamesOrResources); } protected async doShowSaveConfirm(fileNamesOrResources: (string | URI)[]): Promise<ConfirmResult> { if (fileNamesOrResources.length === 0) { return ConfirmResult.DONT_SAVE; } let message: string; let detail = nls.localize('saveChangesDetail', "Your changes will be lost if you don't save them."); if (fileNamesOrResources.length === 1) { message = nls.localize('saveChangesMessage', "Do you want to save the changes you made to {0}?", typeof fileNamesOrResources[0] === 'string' ? fileNamesOrResources[0] : resources.basename(fileNamesOrResources[0])); } else { message = nls.localize('saveChangesMessages', "Do you want to save the changes to the following {0} files?", fileNamesOrResources.length); detail = getFileNamesMessage(fileNamesOrResources) + '\n' + detail; } const buttons: string[] = [ fileNamesOrResources.length > 1 ? nls.localize({ key: 'saveAll', comment: ['&& denotes a mnemonic'] }, "&&Save All") : nls.localize({ key: 'save', comment: ['&& denotes a mnemonic'] }, "&&Save"), nls.localize({ key: 'dontSave', comment: ['&& denotes a mnemonic'] }, "Do&&n't Save"), nls.localize('cancel', "Cancel") ]; const { choice } = await this.dialogService.show(Severity.Warning, message, buttons, { cancelId: 2, detail }); switch (choice) { case 0: return ConfirmResult.SAVE; case 1: return ConfirmResult.DONT_SAVE; default: return ConfirmResult.CANCEL; } } protected abstract addFileSchemaIfNeeded(schema: string): string[]; protected async pickFileFolderAndOpenSimplified(schema: string, options: IPickAndOpenOptions, preferNewWindow: boolean): Promise<any> { const title = nls.localize('openFileOrFolder.title', 'Open File Or Folder'); const availableFileSystems = this.addFileSchemaIfNeeded(schema); const uri = await this.pickResource({ canSelectFiles: true, canSelectFolders: true, canSelectMany: false, defaultUri: options.defaultUri, title, availableFileSystems }); if (uri) { const stat = await this.fileService.resolve(uri); const toOpen: IWindowOpenable = stat.isDirectory ? { folderUri: uri } : { fileUri: uri }; if (!isWorkspaceToOpen(toOpen) && isFileToOpen(toOpen)) { // add the picked file into the list of recently opened this.workspacesService.addRecentlyOpened([{ fileUri: toOpen.fileUri, label: this.labelService.getUriLabel(toOpen.fileUri) }]); } if (stat.isDirectory || options.forceNewWindow || preferNewWindow) { return this.hostService.openWindow([toOpen], { forceNewWindow: options.forceNewWindow }); } else { return this.openerService.open(uri, { fromUserGesture: true }); } } } protected async pickFileAndOpenSimplified(schema: string, options: IPickAndOpenOptions, preferNewWindow: boolean): Promise<any> { const title = nls.localize('openFile.title', 'Open File'); const availableFileSystems = this.addFileSchemaIfNeeded(schema); const uri = await this.pickResource({ canSelectFiles: true, canSelectFolders: false, canSelectMany: false, defaultUri: options.defaultUri, title, availableFileSystems }); if (uri) { // add the picked file into the list of recently opened this.workspacesService.addRecentlyOpened([{ fileUri: uri, label: this.labelService.getUriLabel(uri) }]); if (options.forceNewWindow || preferNewWindow) { return this.hostService.openWindow([{ fileUri: uri }], { forceNewWindow: options.forceNewWindow }); } else { return this.openerService.open(uri, { fromUserGesture: true }); } } } protected async pickFolderAndOpenSimplified(schema: string, options: IPickAndOpenOptions): Promise<any> { const title = nls.localize('openFolder.title', 'Open Folder'); const availableFileSystems = this.addFileSchemaIfNeeded(schema); const uri = await this.pickResource({ canSelectFiles: false, canSelectFolders: true, canSelectMany: false, defaultUri: options.defaultUri, title, availableFileSystems }); if (uri) { return this.hostService.openWindow([{ folderUri: uri }], { forceNewWindow: options.forceNewWindow }); } } protected async pickWorkspaceAndOpenSimplified(schema: string, options: IPickAndOpenOptions): Promise<any> { const title = nls.localize('openWorkspace.title', 'Open Workspace'); const filters: FileFilter[] = [{ name: nls.localize('filterName.workspace', 'Workspace'), extensions: [WORKSPACE_EXTENSION] }]; const availableFileSystems = this.addFileSchemaIfNeeded(schema); const uri = await this.pickResource({ canSelectFiles: true, canSelectFolders: false, canSelectMany: false, defaultUri: options.defaultUri, title, filters, availableFileSystems }); if (uri) { return this.hostService.openWindow([{ workspaceUri: uri }], { forceNewWindow: options.forceNewWindow }); } } protected async pickFileToSaveSimplified(schema: string, options: ISaveDialogOptions): Promise<URI | undefined> { if (!options.availableFileSystems) { options.availableFileSystems = this.addFileSchemaIfNeeded(schema); } options.title = nls.localize('saveFileAs.title', 'Save As'); return this.saveRemoteResource(options); } protected async showSaveDialogSimplified(schema: string, options: ISaveDialogOptions): Promise<URI | undefined> { if (!options.availableFileSystems) { options.availableFileSystems = this.addFileSchemaIfNeeded(schema); } return this.saveRemoteResource(options); } protected async showOpenDialogSimplified(schema: string, options: IOpenDialogOptions): Promise<URI[] | undefined> { if (!options.availableFileSystems) { options.availableFileSystems = this.addFileSchemaIfNeeded(schema); } const uri = await this.pickResource(options); return uri ? [uri] : undefined; } private pickResource(options: IOpenDialogOptions): Promise<URI | undefined> { const simpleFileDialog = this.instantiationService.createInstance(SimpleFileDialog); return simpleFileDialog.showOpenDialog(options); } private saveRemoteResource(options: ISaveDialogOptions): Promise<URI | undefined> { const remoteFileDialog = this.instantiationService.createInstance(SimpleFileDialog); return remoteFileDialog.showSaveDialog(options); } protected getSchemeFilterForWindow(): string { return !this.environmentService.configuration.remoteAuthority ? Schemas.file : REMOTE_HOST_SCHEME; } protected getFileSystemSchema(options: { availableFileSystems?: readonly string[], defaultUri?: URI }): string { return options.availableFileSystems && options.availableFileSystems[0] || this.getSchemeFilterForWindow(); } abstract pickFileFolderAndOpen(options: IPickAndOpenOptions): Promise<void>; abstract pickFileAndOpen(options: IPickAndOpenOptions): Promise<void>; abstract pickFolderAndOpen(options: IPickAndOpenOptions): Promise<void>; abstract pickWorkspaceAndOpen(options: IPickAndOpenOptions): Promise<void>; abstract showSaveDialog(options: ISaveDialogOptions): Promise<URI | undefined>; abstract showOpenDialog(options: IOpenDialogOptions): Promise<URI[] | undefined>; abstract pickFileToSave(defaultUri: URI, availableFileSystems?: string[]): Promise<URI | undefined>; protected getPickFileToSaveDialogOptions(defaultUri: URI, availableFileSystems?: string[]): ISaveDialogOptions { const options: ISaveDialogOptions = { defaultUri, title: nls.localize('saveAsTitle', "Save As"), availableFileSystems, }; interface IFilter { name: string; extensions: string[]; } // Build the file filter by using our known languages const ext: string | undefined = defaultUri ? resources.extname(defaultUri) : undefined; let matchingFilter: IFilter | undefined; const filters: IFilter[] = coalesce(this.modeService.getRegisteredLanguageNames().map(languageName => { const extensions = this.modeService.getExtensions(languageName); if (!extensions || !extensions.length) { return null; } const filter: IFilter = { name: languageName, extensions: extensions.slice(0, 10).map(e => trim(e, '.')) }; if (ext && extensions.indexOf(ext) >= 0) { matchingFilter = filter; return null; // matching filter will be added last to the top } return filter; })); // Filters are a bit weird on Windows, based on having a match or not: // Match: we put the matching filter first so that it shows up selected and the all files last // No match: we put the all files filter first const allFilesFilter = { name: nls.localize('allFiles', "All Files"), extensions: ['*'] }; if (matchingFilter) { filters.unshift(matchingFilter); filters.unshift(allFilesFilter); } else { filters.unshift(allFilesFilter); } // Allow to save file without extension filters.push({ name: nls.localize('noExt', "No Extension"), extensions: [''] }); options.filters = filters; return options; } }
src/vs/workbench/services/dialogs/browser/abstractFileDialogService.ts
0
https://github.com/microsoft/vscode/commit/7aca51e3d98c58ee8e418df6b525930d90375d9f
[ 0.00017522786220069975, 0.00017124530859291553, 0.00016615280765108764, 0.00017094676150009036, 0.0000022951426217332482 ]
{ "id": 0, "code_window": [ "\t\tdispose(this._onChange);\n", "\t}\n", "}\n", "\n", "class SelectionTrait<T> extends Trait<T> {\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "class FocusTrait<T> extends Trait<T> {\n" ], "file_path": "src/vs/base/browser/ui/list/listWidget.ts", "type": "replace", "edit_start_line_idx": 182 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { IRequestService } from 'vs/platform/request/common/request'; import { IRequestOptions, IRequestContext, IHeaders } from 'vs/base/parts/request/common/request'; import { CancellationToken } from 'vs/base/common/cancellation'; import { IUserData, ResourceKey, IUserDataManifest, ALL_RESOURCE_KEYS, IUserDataSyncLogService, IUserDataSyncStoreService, IUserDataSyncUtilService, IUserDataSyncEnablementService, ISettingsSyncService, IUserDataSyncService, getDefaultIgnoredSettings } from 'vs/platform/userDataSync/common/userDataSync'; import { bufferToStream, VSBuffer } from 'vs/base/common/buffer'; import { generateUuid } from 'vs/base/common/uuid'; import { UserDataSyncService } from 'vs/platform/userDataSync/common/userDataSyncService'; import { TestInstantiationService } from 'vs/platform/instantiation/test/common/instantiationServiceMock'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { NullLogService, ILogService } from 'vs/platform/log/common/log'; import { UserDataSyncStoreService } from 'vs/platform/userDataSync/common/userDataSyncStoreService'; import { NullTelemetryService } from 'vs/platform/telemetry/common/telemetryUtils'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IFileService } from 'vs/platform/files/common/files'; import { FileService } from 'vs/platform/files/common/fileService'; import { Schemas } from 'vs/base/common/network'; import { IEnvironmentService } from 'vs/platform/environment/common/environment'; import { IStorageService, InMemoryStorageService } from 'vs/platform/storage/common/storage'; import { URI } from 'vs/base/common/uri'; import { joinPath } from 'vs/base/common/resources'; import { IStringDictionary } from 'vs/base/common/collections'; import { FormattingOptions } from 'vs/base/common/jsonFormatter'; import { UserDataSyncEnablementService } from 'vs/platform/userDataSync/common/userDataSyncEnablementService'; import { IGlobalExtensionEnablementService, IExtensionManagementService, IExtensionGalleryService, DidInstallExtensionEvent, DidUninstallExtensionEvent } from 'vs/platform/extensionManagement/common/extensionManagement'; import { GlobalExtensionEnablementService } from 'vs/platform/extensionManagement/common/extensionEnablementService'; import { InMemoryFileSystemProvider } from 'vs/platform/files/common/inMemoryFilesystemProvider'; import { ConfigurationService } from 'vs/platform/configuration/common/configurationService'; import { Disposable } from 'vs/base/common/lifecycle'; import { SettingsSynchroniser } from 'vs/platform/userDataSync/common/settingsSync'; import { Emitter } from 'vs/base/common/event'; import { IAuthenticationTokenService } from 'vs/platform/authentication/common/authentication'; import product from 'vs/platform/product/common/product'; import { IProductService } from 'vs/platform/product/common/productService'; export class UserDataSyncClient extends Disposable { readonly instantiationService: TestInstantiationService; constructor(readonly testServer: UserDataSyncTestServer = new UserDataSyncTestServer()) { super(); this.instantiationService = new TestInstantiationService(); } async setUp(empty: boolean = false): Promise<void> { const userDataDirectory = URI.file('userdata').with({ scheme: Schemas.inMemory }); const userDataSyncHome = joinPath(userDataDirectory, '.sync'); const environmentService = this.instantiationService.stub(IEnvironmentService, <Partial<IEnvironmentService>>{ userDataSyncHome, settingsResource: joinPath(userDataDirectory, 'settings.json'), settingsSyncPreviewResource: joinPath(userDataSyncHome, 'settings.json'), keybindingsResource: joinPath(userDataDirectory, 'keybindings.json'), keybindingsSyncPreviewResource: joinPath(userDataSyncHome, 'keybindings.json'), argvResource: joinPath(userDataDirectory, 'argv.json'), }); const logService = new NullLogService(); this.instantiationService.stub(ILogService, logService); this.instantiationService.stub(IProductService, { _serviceBrand: undefined, ...product, ...{ 'configurationSync.store': { url: this.testServer.url, authenticationProviderId: 'test' } } }); const fileService = this._register(new FileService(logService)); fileService.registerProvider(Schemas.inMemory, new InMemoryFileSystemProvider()); this.instantiationService.stub(IFileService, fileService); this.instantiationService.stub(IStorageService, new InMemoryStorageService()); const configurationService = new ConfigurationService(environmentService.settingsResource, fileService); await configurationService.initialize(); this.instantiationService.stub(IConfigurationService, configurationService); this.instantiationService.stub(IRequestService, this.testServer); this.instantiationService.stub(IAuthenticationTokenService, <Partial<IAuthenticationTokenService>>{ onDidChangeToken: new Emitter<string | undefined>().event, async getToken() { return 'token'; } }); this.instantiationService.stub(IUserDataSyncLogService, logService); this.instantiationService.stub(ITelemetryService, NullTelemetryService); this.instantiationService.stub(IUserDataSyncStoreService, this.instantiationService.createInstance(UserDataSyncStoreService)); this.instantiationService.stub(IUserDataSyncUtilService, new TestUserDataSyncUtilService()); this.instantiationService.stub(IUserDataSyncEnablementService, this.instantiationService.createInstance(UserDataSyncEnablementService)); this.instantiationService.stub(IGlobalExtensionEnablementService, this.instantiationService.createInstance(GlobalExtensionEnablementService)); this.instantiationService.stub(IExtensionManagementService, <Partial<IExtensionManagementService>>{ async getInstalled() { return []; }, onDidInstallExtension: new Emitter<DidInstallExtensionEvent>().event, onDidUninstallExtension: new Emitter<DidUninstallExtensionEvent>().event, }); this.instantiationService.stub(IExtensionGalleryService, <Partial<IExtensionGalleryService>>{ isEnabled() { return true; }, async getCompatibleExtension() { return null; } }); this.instantiationService.stub(ISettingsSyncService, this.instantiationService.createInstance(SettingsSynchroniser)); this.instantiationService.stub(IUserDataSyncService, this.instantiationService.createInstance(UserDataSyncService)); if (!empty) { await fileService.writeFile(environmentService.settingsResource, VSBuffer.fromString(JSON.stringify({}))); await fileService.writeFile(environmentService.keybindingsResource, VSBuffer.fromString(JSON.stringify([]))); await fileService.writeFile(environmentService.argvResource, VSBuffer.fromString(JSON.stringify({ 'locale': 'en' }))); } await configurationService.reloadConfiguration(); } } export class UserDataSyncTestServer implements IRequestService { _serviceBrand: any; readonly url: string = 'http://host:3000'; private session: string | null = null; private readonly data: Map<ResourceKey, IUserData> = new Map<ResourceKey, IUserData>(); private _requests: { url: string, type: string, headers?: IHeaders }[] = []; get requests(): { url: string, type: string, headers?: IHeaders }[] { return this._requests; } private _responses: { status: number }[] = []; get responses(): { status: number }[] { return this._responses; } reset(): void { this._requests = []; this._responses = []; } async resolveProxy(url: string): Promise<string | undefined> { return url; } async request(options: IRequestOptions, token: CancellationToken): Promise<IRequestContext> { const headers: IHeaders = {}; if (options.headers) { if (options.headers['If-None-Match']) { headers['If-None-Match'] = options.headers['If-None-Match']; } if (options.headers['If-Match']) { headers['If-Match'] = options.headers['If-Match']; } } this._requests.push({ url: options.url!, type: options.type!, headers }); const requestContext = await this.doRequest(options); this._responses.push({ status: requestContext.res.statusCode! }); return requestContext; } private async doRequest(options: IRequestOptions): Promise<IRequestContext> { const versionUrl = `${this.url}/v1/`; const relativePath = options.url!.indexOf(versionUrl) === 0 ? options.url!.substring(versionUrl.length) : undefined; const segments = relativePath ? relativePath.split('/') : []; if (options.type === 'GET' && segments.length === 1 && segments[0] === 'manifest') { return this.getManifest(options.headers); } if (options.type === 'GET' && segments.length === 3 && segments[0] === 'resource' && segments[2] === 'latest') { return this.getLatestData(segments[1], options.headers); } if (options.type === 'POST' && segments.length === 2 && segments[0] === 'resource') { return this.writeData(segments[1], options.data, options.headers); } if (options.type === 'DELETE' && segments.length === 1 && segments[0] === 'resource') { return this.clear(options.headers); } return this.toResponse(501); } private async getManifest(headers?: IHeaders): Promise<IRequestContext> { if (this.session) { const latest: Record<ResourceKey, string> = Object.create({}); const manifest: IUserDataManifest = { session: this.session, latest }; this.data.forEach((value, key) => latest[key] = value.ref); return this.toResponse(200, { 'Content-Type': 'application/json' }, JSON.stringify(manifest)); } return this.toResponse(204); } private async getLatestData(resource: string, headers: IHeaders = {}): Promise<IRequestContext> { const resourceKey = ALL_RESOURCE_KEYS.find(key => key === resource); if (resourceKey) { const data = this.data.get(resourceKey); if (!data) { return this.toResponse(204, { etag: '0' }); } if (headers['If-None-Match'] === data.ref) { return this.toResponse(304); } return this.toResponse(200, { etag: data.ref }, data.content || ''); } return this.toResponse(204); } private async writeData(resource: string, content: string = '', headers: IHeaders = {}): Promise<IRequestContext> { if (!headers['If-Match']) { return this.toResponse(428); } if (!this.session) { this.session = generateUuid(); } const resourceKey = ALL_RESOURCE_KEYS.find(key => key === resource); if (resourceKey) { const data = this.data.get(resourceKey); if (headers['If-Match'] !== (data ? data.ref : '0')) { return this.toResponse(412); } const ref = `${parseInt(data?.ref || '0') + 1}`; this.data.set(resourceKey, { ref, content }); return this.toResponse(200, { etag: ref }); } return this.toResponse(204); } private async clear(headers?: IHeaders): Promise<IRequestContext> { this.data.clear(); this.session = null; return this.toResponse(204); } private toResponse(statusCode: number, headers?: IHeaders, data?: string): IRequestContext { return { res: { headers: headers || {}, statusCode }, stream: bufferToStream(VSBuffer.fromString(data || '')) }; } } export class TestUserDataSyncUtilService implements IUserDataSyncUtilService { _serviceBrand: any; async resolveDefaultIgnoredSettings(): Promise<string[]> { return getDefaultIgnoredSettings(); } async resolveUserBindings(userbindings: string[]): Promise<IStringDictionary<string>> { const keys: IStringDictionary<string> = {}; for (const keybinding of userbindings) { keys[keybinding] = keybinding; } return keys; } async resolveFormattingOptions(file?: URI): Promise<FormattingOptions> { return { eol: '\n', insertSpaces: false, tabSize: 4 }; } }
src/vs/platform/userDataSync/test/common/userDataSyncClient.ts
0
https://github.com/microsoft/vscode/commit/7aca51e3d98c58ee8e418df6b525930d90375d9f
[ 0.00018022689619101584, 0.00017079766257666051, 0.00016577776113990694, 0.0001702395238680765, 0.0000029785405786242336 ]
{ "id": 0, "code_window": [ "\t\tdispose(this._onChange);\n", "\t}\n", "}\n", "\n", "class SelectionTrait<T> extends Trait<T> {\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "class FocusTrait<T> extends Trait<T> {\n" ], "file_path": "src/vs/base/browser/ui/list/listWidget.ts", "type": "replace", "edit_start_line_idx": 182 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { KeyboardLayoutContribution } from 'vs/workbench/services/keybinding/browser/keyboardLayouts/_.contribution'; KeyboardLayoutContribution.INSTANCE.registerKeyboardLayout({ layout: { name: '00000406', id: '', text: 'Danish' }, secondaryLayouts: [], mapping: { Sleep: [], WakeUp: [], KeyA: ['a', 'A', '', '', 0, 'VK_A'], KeyB: ['b', 'B', '', '', 0, 'VK_B'], KeyC: ['c', 'C', '', '', 0, 'VK_C'], KeyD: ['d', 'D', '', '', 0, 'VK_D'], KeyE: ['e', 'E', '€', '', 0, 'VK_E'], KeyF: ['f', 'F', '', '', 0, 'VK_F'], KeyG: ['g', 'G', '', '', 0, 'VK_G'], KeyH: ['h', 'H', '', '', 0, 'VK_H'], KeyI: ['i', 'I', '', '', 0, 'VK_I'], KeyJ: ['j', 'J', '', '', 0, 'VK_J'], KeyK: ['k', 'K', '', '', 0, 'VK_K'], KeyL: ['l', 'L', '', '', 0, 'VK_L'], KeyM: ['m', 'M', 'µ', '', 0, 'VK_M'], KeyN: ['n', 'N', '', '', 0, 'VK_N'], KeyO: ['o', 'O', '', '', 0, 'VK_O'], KeyP: ['p', 'P', '', '', 0, 'VK_P'], KeyQ: ['q', 'Q', '', '', 0, 'VK_Q'], KeyR: ['r', 'R', '', '', 0, 'VK_R'], KeyS: ['s', 'S', '', '', 0, 'VK_S'], KeyT: ['t', 'T', '', '', 0, 'VK_T'], KeyU: ['u', 'U', '', '', 0, 'VK_U'], KeyV: ['v', 'V', '', '', 0, 'VK_V'], KeyW: ['w', 'W', '', '', 0, 'VK_W'], KeyX: ['x', 'X', '', '', 0, 'VK_X'], KeyY: ['y', 'Y', '', '', 0, 'VK_Y'], KeyZ: ['z', 'Z', '', '', 0, 'VK_Z'], Digit1: ['1', '!', '', '', 0, 'VK_1'], Digit2: ['2', '"', '@', '', 0, 'VK_2'], Digit3: ['3', '#', '£', '', 0, 'VK_3'], Digit4: ['4', '¤', '$', '', 0, 'VK_4'], Digit5: ['5', '%', '€', '', 0, 'VK_5'], Digit6: ['6', '&', '', '', 0, 'VK_6'], Digit7: ['7', '/', '{', '', 0, 'VK_7'], Digit8: ['8', '(', '[', '', 0, 'VK_8'], Digit9: ['9', ')', ']', '', 0, 'VK_9'], Digit0: ['0', '=', '}', '', 0, 'VK_0'], Enter: [], Escape: [], Backspace: [], Tab: [], Space: [' ', ' ', '', '', 0, 'VK_SPACE'], Minus: ['+', '?', '', '', 0, 'VK_OEM_PLUS'], Equal: ['´', '`', '|', '', 0, 'VK_OEM_4'], BracketLeft: ['å', 'Å', '', '', 0, 'VK_OEM_6'], BracketRight: ['¨', '^', '~', '', 0, 'VK_OEM_1'], Backslash: ['\'', '*', '', '', 0, 'VK_OEM_2'], Semicolon: ['æ', 'Æ', '', '', 0, 'VK_OEM_3'], Quote: ['ø', 'Ø', '', '', 0, 'VK_OEM_7'], Backquote: ['½', '§', '', '', 0, 'VK_OEM_5'], Comma: [',', ';', '', '', 0, 'VK_OEM_COMMA'], Period: ['.', ':', '', '', 0, 'VK_OEM_PERIOD'], Slash: ['-', '_', '', '', 0, 'VK_OEM_MINUS'], CapsLock: [], F1: [], F2: [], F3: [], F4: [], F5: [], F6: [], F7: [], F8: [], F9: [], F10: [], F11: [], F12: [], PrintScreen: [], ScrollLock: [], Pause: [], Insert: [], Home: [], PageUp: [], Delete: [], End: [], PageDown: [], ArrowRight: [], ArrowLeft: [], ArrowDown: [], ArrowUp: [], NumLock: [], NumpadDivide: ['/', '/', '', '', 0, 'VK_DIVIDE'], NumpadMultiply: ['*', '*', '', '', 0, 'VK_MULTIPLY'], NumpadSubtract: ['-', '-', '', '', 0, 'VK_SUBTRACT'], NumpadAdd: ['+', '+', '', '', 0, 'VK_ADD'], NumpadEnter: [], Numpad1: [], Numpad2: [], Numpad3: [], Numpad4: [], Numpad5: [], Numpad6: [], Numpad7: [], Numpad8: [], Numpad9: [], Numpad0: [], NumpadDecimal: [], IntlBackslash: ['<', '>', '\\', '', 0, 'VK_OEM_102'], ContextMenu: [], Power: [], NumpadEqual: [], F13: [], F14: [], F15: [], F16: [], F17: [], F18: [], F19: [], F20: [], F21: [], F22: [], F23: [], F24: [], Help: [], Undo: [], Cut: [], Copy: [], Paste: [], AudioVolumeMute: [], AudioVolumeUp: [], AudioVolumeDown: [], NumpadComma: [], IntlRo: [], KanaMode: [], IntlYen: [], Convert: [], NonConvert: [], Lang1: [], Lang2: [], Lang3: [], Lang4: [], ControlLeft: [], ShiftLeft: [], AltLeft: [], MetaLeft: [], ControlRight: [], ShiftRight: [], AltRight: [], MetaRight: [], MediaTrackNext: [], MediaTrackPrevious: [], MediaStop: [], Eject: [], MediaPlayPause: [], MediaSelect: [], LaunchMail: [], LaunchApp2: [], LaunchApp1: [], BrowserSearch: [], BrowserHome: [], BrowserBack: [], BrowserForward: [], BrowserStop: [], BrowserRefresh: [], BrowserFavorites: [] } });
src/vs/workbench/services/keybinding/browser/keyboardLayouts/dk.win.ts
0
https://github.com/microsoft/vscode/commit/7aca51e3d98c58ee8e418df6b525930d90375d9f
[ 0.00017816356557887048, 0.00017100214608944952, 0.0001651953352848068, 0.0001707150659058243, 0.0000034778693134285277 ]
{ "id": 1, "code_window": [ "\n", "\tconstructor() {\n", "\t\tsuper('selected');\n", "\t}\n", "\n", "\trenderIndex(index: number, container: HTMLElement): void {\n" ], "labels": [ "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "\tconstructor(private isAriaSelected: (index: number) => boolean) {\n", "\t\tsuper('focused');\n" ], "file_path": "src/vs/base/browser/ui/list/listWidget.ts", "type": "replace", "edit_start_line_idx": 184 }
/*--------------------------------------------------------------------------------------------- * 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!./list'; import { localize } from 'vs/nls'; import { IDisposable, dispose, DisposableStore } from 'vs/base/common/lifecycle'; import { isNumber } from 'vs/base/common/types'; import { range, firstIndex, binarySearch } from 'vs/base/common/arrays'; import { memoize } from 'vs/base/common/decorators'; import * as DOM from 'vs/base/browser/dom'; import * as platform from 'vs/base/common/platform'; import { Gesture } from 'vs/base/browser/touch'; import { KeyCode } from 'vs/base/common/keyCodes'; import { StandardKeyboardEvent, IKeyboardEvent } from 'vs/base/browser/keyboardEvent'; import { Event, Emitter, EventBufferer } from 'vs/base/common/event'; import { domEvent } from 'vs/base/browser/event'; import { IListVirtualDelegate, IListRenderer, IListEvent, IListContextMenuEvent, IListMouseEvent, IListTouchEvent, IListGestureEvent, IIdentityProvider, IKeyboardNavigationLabelProvider, IListDragAndDrop, IListDragOverReaction, ListAriaRootRole, ListError, IKeyboardNavigationDelegate } from './list'; import { ListView, IListViewOptions, IListViewDragAndDrop, IAriaProvider } from './listView'; import { Color } from 'vs/base/common/color'; import { mixin } from 'vs/base/common/objects'; import { ScrollbarVisibility, ScrollEvent } from 'vs/base/common/scrollable'; import { ISpliceable } from 'vs/base/common/sequence'; import { CombinedSpliceable } from 'vs/base/browser/ui/list/splice'; import { clamp } from 'vs/base/common/numbers'; import { matchesPrefix } from 'vs/base/common/filters'; import { IDragAndDropData } from 'vs/base/browser/dnd'; interface ITraitChangeEvent { indexes: number[]; browserEvent?: UIEvent; } type ITraitTemplateData = HTMLElement; interface IRenderedContainer { templateData: ITraitTemplateData; index: number; } class TraitRenderer<T> implements IListRenderer<T, ITraitTemplateData> { private renderedElements: IRenderedContainer[] = []; constructor(private trait: Trait<T>) { } get templateId(): string { return `template:${this.trait.trait}`; } renderTemplate(container: HTMLElement): ITraitTemplateData { return container; } renderElement(element: T, index: number, templateData: ITraitTemplateData): void { const renderedElementIndex = firstIndex(this.renderedElements, el => el.templateData === templateData); if (renderedElementIndex >= 0) { const rendered = this.renderedElements[renderedElementIndex]; this.trait.unrender(templateData); rendered.index = index; } else { const rendered = { index, templateData }; this.renderedElements.push(rendered); } this.trait.renderIndex(index, templateData); } splice(start: number, deleteCount: number, insertCount: number): void { const rendered: IRenderedContainer[] = []; for (const renderedElement of this.renderedElements) { if (renderedElement.index < start) { rendered.push(renderedElement); } else if (renderedElement.index >= start + deleteCount) { rendered.push({ index: renderedElement.index + insertCount - deleteCount, templateData: renderedElement.templateData }); } } this.renderedElements = rendered; } renderIndexes(indexes: number[]): void { for (const { index, templateData } of this.renderedElements) { if (indexes.indexOf(index) > -1) { this.trait.renderIndex(index, templateData); } } } disposeTemplate(templateData: ITraitTemplateData): void { const index = firstIndex(this.renderedElements, el => el.templateData === templateData); if (index < 0) { return; } this.renderedElements.splice(index, 1); } } class Trait<T> implements ISpliceable<boolean>, IDisposable { private indexes: number[] = []; private sortedIndexes: number[] = []; private readonly _onChange = new Emitter<ITraitChangeEvent>(); readonly onChange: Event<ITraitChangeEvent> = this._onChange.event; get trait(): string { return this._trait; } @memoize get renderer(): TraitRenderer<T> { return new TraitRenderer<T>(this); } constructor(private _trait: string) { } splice(start: number, deleteCount: number, elements: boolean[]): void { const diff = elements.length - deleteCount; const end = start + deleteCount; const indexes = [ ...this.sortedIndexes.filter(i => i < start), ...elements.map((hasTrait, i) => hasTrait ? i + start : -1).filter(i => i !== -1), ...this.sortedIndexes.filter(i => i >= end).map(i => i + diff) ]; this.renderer.splice(start, deleteCount, elements.length); this._set(indexes, indexes); } renderIndex(index: number, container: HTMLElement): void { DOM.toggleClass(container, this._trait, this.contains(index)); } unrender(container: HTMLElement): void { DOM.removeClass(container, this._trait); } /** * Sets the indexes which should have this trait. * * @param indexes Indexes which should have this trait. * @return The old indexes which had this trait. */ set(indexes: number[], browserEvent?: UIEvent): number[] { return this._set(indexes, [...indexes].sort(numericSort), browserEvent); } private _set(indexes: number[], sortedIndexes: number[], browserEvent?: UIEvent): number[] { const result = this.indexes; const sortedResult = this.sortedIndexes; this.indexes = indexes; this.sortedIndexes = sortedIndexes; const toRender = disjunction(sortedResult, indexes); this.renderer.renderIndexes(toRender); this._onChange.fire({ indexes, browserEvent }); return result; } get(): number[] { return this.indexes; } contains(index: number): boolean { return binarySearch(this.sortedIndexes, index, numericSort) >= 0; } dispose() { dispose(this._onChange); } } class SelectionTrait<T> extends Trait<T> { constructor() { super('selected'); } renderIndex(index: number, container: HTMLElement): void { super.renderIndex(index, container); if (this.contains(index)) { container.setAttribute('aria-selected', 'true'); } else { container.removeAttribute('aria-selected'); } } } /** * The TraitSpliceable is used as a util class to be able * to preserve traits across splice calls, given an identity * provider. */ class TraitSpliceable<T> implements ISpliceable<T> { constructor( private trait: Trait<T>, private view: ListView<T>, private identityProvider?: IIdentityProvider<T> ) { } splice(start: number, deleteCount: number, elements: T[]): void { if (!this.identityProvider) { return this.trait.splice(start, deleteCount, elements.map(() => false)); } const pastElementsWithTrait = this.trait.get().map(i => this.identityProvider!.getId(this.view.element(i)).toString()); const elementsWithTrait = elements.map(e => pastElementsWithTrait.indexOf(this.identityProvider!.getId(e).toString()) > -1); this.trait.splice(start, deleteCount, elementsWithTrait); } } function isInputElement(e: HTMLElement): boolean { return e.tagName === 'INPUT' || e.tagName === 'TEXTAREA'; } class KeyboardController<T> implements IDisposable { private readonly disposables = new DisposableStore(); private openController: IOpenController; constructor( private list: List<T>, private view: ListView<T>, options: IListOptions<T> ) { const multipleSelectionSupport = options.multipleSelectionSupport !== false; this.openController = options.openController || DefaultOpenController; const onKeyDown = Event.chain(domEvent(view.domNode, 'keydown')) .filter(e => !isInputElement(e.target as HTMLElement)) .map(e => new StandardKeyboardEvent(e)); onKeyDown.filter(e => e.keyCode === KeyCode.Enter).on(this.onEnter, this, this.disposables); onKeyDown.filter(e => e.keyCode === KeyCode.UpArrow).on(this.onUpArrow, this, this.disposables); onKeyDown.filter(e => e.keyCode === KeyCode.DownArrow).on(this.onDownArrow, this, this.disposables); onKeyDown.filter(e => e.keyCode === KeyCode.PageUp).on(this.onPageUpArrow, this, this.disposables); onKeyDown.filter(e => e.keyCode === KeyCode.PageDown).on(this.onPageDownArrow, this, this.disposables); onKeyDown.filter(e => e.keyCode === KeyCode.Escape).on(this.onEscape, this, this.disposables); if (multipleSelectionSupport) { onKeyDown.filter(e => (platform.isMacintosh ? e.metaKey : e.ctrlKey) && e.keyCode === KeyCode.KEY_A).on(this.onCtrlA, this, this.disposables); } } private onEnter(e: StandardKeyboardEvent): void { e.preventDefault(); e.stopPropagation(); this.list.setSelection(this.list.getFocus(), e.browserEvent); if (this.openController.shouldOpen(e.browserEvent)) { this.list.open(this.list.getFocus(), e.browserEvent); } } private onUpArrow(e: StandardKeyboardEvent): void { e.preventDefault(); e.stopPropagation(); this.list.focusPrevious(1, false, e.browserEvent); this.list.reveal(this.list.getFocus()[0]); this.view.domNode.focus(); } private onDownArrow(e: StandardKeyboardEvent): void { e.preventDefault(); e.stopPropagation(); this.list.focusNext(1, false, e.browserEvent); this.list.reveal(this.list.getFocus()[0]); this.view.domNode.focus(); } private onPageUpArrow(e: StandardKeyboardEvent): void { e.preventDefault(); e.stopPropagation(); this.list.focusPreviousPage(e.browserEvent); this.list.reveal(this.list.getFocus()[0]); this.view.domNode.focus(); } private onPageDownArrow(e: StandardKeyboardEvent): void { e.preventDefault(); e.stopPropagation(); this.list.focusNextPage(e.browserEvent); this.list.reveal(this.list.getFocus()[0]); this.view.domNode.focus(); } private onCtrlA(e: StandardKeyboardEvent): void { e.preventDefault(); e.stopPropagation(); this.list.setSelection(range(this.list.length), e.browserEvent); this.view.domNode.focus(); } private onEscape(e: StandardKeyboardEvent): void { e.preventDefault(); e.stopPropagation(); this.list.setSelection([], e.browserEvent); this.view.domNode.focus(); } dispose() { this.disposables.dispose(); } } enum TypeLabelControllerState { Idle, Typing } export const DefaultKeyboardNavigationDelegate = new class implements IKeyboardNavigationDelegate { mightProducePrintableCharacter(event: IKeyboardEvent): boolean { if (event.ctrlKey || event.metaKey || event.altKey) { return false; } return (event.keyCode >= KeyCode.KEY_A && event.keyCode <= KeyCode.KEY_Z) || (event.keyCode >= KeyCode.KEY_0 && event.keyCode <= KeyCode.KEY_9) || (event.keyCode >= KeyCode.NUMPAD_0 && event.keyCode <= KeyCode.NUMPAD_9) || (event.keyCode >= KeyCode.US_SEMICOLON && event.keyCode <= KeyCode.US_QUOTE); } }; class TypeLabelController<T> implements IDisposable { private enabled = false; private state: TypeLabelControllerState = TypeLabelControllerState.Idle; private automaticKeyboardNavigation = true; private triggered = false; private readonly enabledDisposables = new DisposableStore(); private readonly disposables = new DisposableStore(); constructor( private list: List<T>, private view: ListView<T>, private keyboardNavigationLabelProvider: IKeyboardNavigationLabelProvider<T>, private delegate: IKeyboardNavigationDelegate ) { this.updateOptions(list.options); } updateOptions(options: IListOptions<T>): void { const enableKeyboardNavigation = typeof options.enableKeyboardNavigation === 'undefined' ? true : !!options.enableKeyboardNavigation; if (enableKeyboardNavigation) { this.enable(); } else { this.disable(); } if (typeof options.automaticKeyboardNavigation !== 'undefined') { this.automaticKeyboardNavigation = options.automaticKeyboardNavigation; } } toggle(): void { this.triggered = !this.triggered; } private enable(): void { if (this.enabled) { return; } const onChar = Event.chain(domEvent(this.view.domNode, 'keydown')) .filter(e => !isInputElement(e.target as HTMLElement)) .filter(() => this.automaticKeyboardNavigation || this.triggered) .map(event => new StandardKeyboardEvent(event)) .filter(e => this.delegate.mightProducePrintableCharacter(e)) .forEach(e => { e.stopPropagation(); e.preventDefault(); }) .map(event => event.browserEvent.key) .event; const onClear = Event.debounce<string, null>(onChar, () => null, 800); const onInput = Event.reduce<string | null, string | null>(Event.any(onChar, onClear), (r, i) => i === null ? null : ((r || '') + i)); onInput(this.onInput, this, this.enabledDisposables); this.enabled = true; this.triggered = false; } private disable(): void { if (!this.enabled) { return; } this.enabledDisposables.clear(); this.enabled = false; this.triggered = false; } private onInput(word: string | null): void { if (!word) { this.state = TypeLabelControllerState.Idle; this.triggered = false; return; } const focus = this.list.getFocus(); const start = focus.length > 0 ? focus[0] : 0; const delta = this.state === TypeLabelControllerState.Idle ? 1 : 0; this.state = TypeLabelControllerState.Typing; for (let i = 0; i < this.list.length; i++) { const index = (start + i + delta) % this.list.length; const label = this.keyboardNavigationLabelProvider.getKeyboardNavigationLabel(this.view.element(index)); const labelStr = label && label.toString(); if (typeof labelStr === 'undefined' || matchesPrefix(word, labelStr)) { this.list.setFocus([index]); this.list.reveal(index); return; } } } dispose() { this.disable(); this.enabledDisposables.dispose(); this.disposables.dispose(); } } class DOMFocusController<T> implements IDisposable { private readonly disposables = new DisposableStore(); constructor( private list: List<T>, private view: ListView<T> ) { const onKeyDown = Event.chain(domEvent(view.domNode, 'keydown')) .filter(e => !isInputElement(e.target as HTMLElement)) .map(e => new StandardKeyboardEvent(e)); onKeyDown.filter(e => e.keyCode === KeyCode.Tab && !e.ctrlKey && !e.metaKey && !e.shiftKey && !e.altKey) .on(this.onTab, this, this.disposables); } private onTab(e: StandardKeyboardEvent): void { if (e.target !== this.view.domNode) { return; } const focus = this.list.getFocus(); if (focus.length === 0) { return; } const focusedDomElement = this.view.domElement(focus[0]); if (!focusedDomElement) { return; } const tabIndexElement = focusedDomElement.querySelector('[tabIndex]'); if (!tabIndexElement || !(tabIndexElement instanceof HTMLElement) || tabIndexElement.tabIndex === -1) { return; } const style = window.getComputedStyle(tabIndexElement); if (style.visibility === 'hidden' || style.display === 'none') { return; } e.preventDefault(); e.stopPropagation(); tabIndexElement.focus(); } dispose() { this.disposables.dispose(); } } export function isSelectionSingleChangeEvent(event: IListMouseEvent<any> | IListTouchEvent<any>): boolean { return platform.isMacintosh ? event.browserEvent.metaKey : event.browserEvent.ctrlKey; } export function isSelectionRangeChangeEvent(event: IListMouseEvent<any> | IListTouchEvent<any>): boolean { return event.browserEvent.shiftKey; } function isMouseRightClick(event: UIEvent): boolean { return event instanceof MouseEvent && event.button === 2; } const DefaultMultipleSelectionController = { isSelectionSingleChangeEvent, isSelectionRangeChangeEvent }; const DefaultOpenController: IOpenController = { shouldOpen: (event: UIEvent) => { if (event instanceof MouseEvent) { return !isMouseRightClick(event); } return true; } }; export class MouseController<T> implements IDisposable { private multipleSelectionSupport: boolean; readonly multipleSelectionController: IMultipleSelectionController<T> | undefined; private openController: IOpenController; private mouseSupport: boolean; private readonly disposables = new DisposableStore(); constructor(protected list: List<T>) { this.multipleSelectionSupport = !(list.options.multipleSelectionSupport === false); if (this.multipleSelectionSupport) { this.multipleSelectionController = list.options.multipleSelectionController || DefaultMultipleSelectionController; } this.openController = list.options.openController || DefaultOpenController; this.mouseSupport = typeof list.options.mouseSupport === 'undefined' || !!list.options.mouseSupport; if (this.mouseSupport) { list.onMouseDown(this.onMouseDown, this, this.disposables); list.onContextMenu(this.onContextMenu, this, this.disposables); list.onMouseDblClick(this.onDoubleClick, this, this.disposables); list.onTouchStart(this.onMouseDown, this, this.disposables); this.disposables.add(Gesture.addTarget(list.getHTMLElement())); } list.onMouseClick(this.onPointer, this, this.disposables); list.onMouseMiddleClick(this.onPointer, this, this.disposables); list.onTap(this.onPointer, this, this.disposables); } protected isSelectionSingleChangeEvent(event: IListMouseEvent<any> | IListTouchEvent<any>): boolean { if (this.multipleSelectionController) { return this.multipleSelectionController.isSelectionSingleChangeEvent(event); } return platform.isMacintosh ? event.browserEvent.metaKey : event.browserEvent.ctrlKey; } protected isSelectionRangeChangeEvent(event: IListMouseEvent<any> | IListTouchEvent<any>): boolean { if (this.multipleSelectionController) { return this.multipleSelectionController.isSelectionRangeChangeEvent(event); } return event.browserEvent.shiftKey; } private isSelectionChangeEvent(event: IListMouseEvent<any> | IListTouchEvent<any>): boolean { return this.isSelectionSingleChangeEvent(event) || this.isSelectionRangeChangeEvent(event); } private onMouseDown(e: IListMouseEvent<T> | IListTouchEvent<T>): void { if (document.activeElement !== e.browserEvent.target) { this.list.domFocus(); } } private onContextMenu(e: IListContextMenuEvent<T>): void { const focus = typeof e.index === 'undefined' ? [] : [e.index]; this.list.setFocus(focus, e.browserEvent); } protected onPointer(e: IListMouseEvent<T>): void { if (!this.mouseSupport) { return; } if (isInputElement(e.browserEvent.target as HTMLElement)) { return; } let reference = this.list.getFocus()[0]; const selection = this.list.getSelection(); reference = reference === undefined ? selection[0] : reference; const focus = e.index; if (typeof focus === 'undefined') { this.list.setFocus([], e.browserEvent); this.list.setSelection([], e.browserEvent); return; } if (this.multipleSelectionSupport && this.isSelectionRangeChangeEvent(e)) { return this.changeSelection(e, reference); } if (this.multipleSelectionSupport && this.isSelectionChangeEvent(e)) { return this.changeSelection(e, reference); } this.list.setFocus([focus], e.browserEvent); if (!isMouseRightClick(e.browserEvent)) { this.list.setSelection([focus], e.browserEvent); if (this.openController.shouldOpen(e.browserEvent)) { this.list.open([focus], e.browserEvent); } } } protected onDoubleClick(e: IListMouseEvent<T>): void { if (isInputElement(e.browserEvent.target as HTMLElement)) { return; } if (this.multipleSelectionSupport && this.isSelectionChangeEvent(e)) { return; } const focus = this.list.getFocus(); this.list.setSelection(focus, e.browserEvent); this.list.pin(focus); } private changeSelection(e: IListMouseEvent<T> | IListTouchEvent<T>, reference: number | undefined): void { const focus = e.index!; if (this.isSelectionRangeChangeEvent(e) && reference !== undefined) { const min = Math.min(reference, focus); const max = Math.max(reference, focus); const rangeSelection = range(min, max + 1); const selection = this.list.getSelection(); const contiguousRange = getContiguousRangeContaining(disjunction(selection, [reference]), reference); if (contiguousRange.length === 0) { return; } const newSelection = disjunction(rangeSelection, relativeComplement(selection, contiguousRange)); this.list.setSelection(newSelection, e.browserEvent); } else if (this.isSelectionSingleChangeEvent(e)) { const selection = this.list.getSelection(); const newSelection = selection.filter(i => i !== focus); this.list.setFocus([focus]); if (selection.length === newSelection.length) { this.list.setSelection([...newSelection, focus], e.browserEvent); } else { this.list.setSelection(newSelection, e.browserEvent); } } } dispose() { this.disposables.dispose(); } } export interface IMultipleSelectionController<T> { isSelectionSingleChangeEvent(event: IListMouseEvent<T> | IListTouchEvent<T>): boolean; isSelectionRangeChangeEvent(event: IListMouseEvent<T> | IListTouchEvent<T>): boolean; } export interface IOpenController { shouldOpen(event: UIEvent): boolean; } export interface IStyleController { style(styles: IListStyles): void; } export interface IAccessibilityProvider<T> { /** * Given an element in the tree, return the ARIA label that should be associated with the * item. This helps screen readers to provide a meaningful label for the currently focused * tree element. * * Returning null will not disable ARIA for the element. Instead it is up to the screen reader * to compute a meaningful label based on the contents of the element in the DOM * * See also: https://www.w3.org/TR/wai-aria/#aria-label */ getAriaLabel(element: T): string | null; /** * https://www.w3.org/TR/wai-aria/#aria-level */ getAriaLevel?(element: T): number | undefined; onDidChangeActiveDescendant?: Event<void>; getActiveDescendantId?(element: T): string | undefined; } export class DefaultStyleController implements IStyleController { constructor(private styleElement: HTMLStyleElement, private selectorSuffix: string) { } style(styles: IListStyles): void { const suffix = this.selectorSuffix && `.${this.selectorSuffix}`; const content: string[] = []; if (styles.listBackground) { if (styles.listBackground.isOpaque()) { content.push(`.monaco-list${suffix} .monaco-list-rows { background: ${styles.listBackground}; }`); } else if (!platform.isMacintosh) { // subpixel AA doesn't exist in macOS console.warn(`List with id '${this.selectorSuffix}' was styled with a non-opaque background color. This will break sub-pixel antialiasing.`); } } if (styles.listFocusBackground) { content.push(`.monaco-list${suffix}:focus .monaco-list-row.focused { background-color: ${styles.listFocusBackground}; }`); content.push(`.monaco-list${suffix}:focus .monaco-list-row.focused:hover { background-color: ${styles.listFocusBackground}; }`); // overwrite :hover style in this case! } if (styles.listFocusForeground) { content.push(`.monaco-list${suffix}:focus .monaco-list-row.focused { color: ${styles.listFocusForeground}; }`); } if (styles.listActiveSelectionBackground) { content.push(`.monaco-list${suffix}:focus .monaco-list-row.selected { background-color: ${styles.listActiveSelectionBackground}; }`); content.push(`.monaco-list${suffix}:focus .monaco-list-row.selected:hover { background-color: ${styles.listActiveSelectionBackground}; }`); // overwrite :hover style in this case! } if (styles.listActiveSelectionForeground) { content.push(`.monaco-list${suffix}:focus .monaco-list-row.selected { color: ${styles.listActiveSelectionForeground}; }`); } if (styles.listFocusAndSelectionBackground) { content.push(` .monaco-drag-image, .monaco-list${suffix}:focus .monaco-list-row.selected.focused { background-color: ${styles.listFocusAndSelectionBackground}; } `); } if (styles.listFocusAndSelectionForeground) { content.push(` .monaco-drag-image, .monaco-list${suffix}:focus .monaco-list-row.selected.focused { color: ${styles.listFocusAndSelectionForeground}; } `); } if (styles.listInactiveFocusBackground) { content.push(`.monaco-list${suffix} .monaco-list-row.focused { background-color: ${styles.listInactiveFocusBackground}; }`); content.push(`.monaco-list${suffix} .monaco-list-row.focused:hover { background-color: ${styles.listInactiveFocusBackground}; }`); // overwrite :hover style in this case! } if (styles.listInactiveSelectionBackground) { content.push(`.monaco-list${suffix} .monaco-list-row.selected { background-color: ${styles.listInactiveSelectionBackground}; }`); content.push(`.monaco-list${suffix} .monaco-list-row.selected:hover { background-color: ${styles.listInactiveSelectionBackground}; }`); // overwrite :hover style in this case! } if (styles.listInactiveSelectionForeground) { content.push(`.monaco-list${suffix} .monaco-list-row.selected { color: ${styles.listInactiveSelectionForeground}; }`); } if (styles.listHoverBackground) { content.push(`.monaco-list${suffix}:not(.drop-target) .monaco-list-row:hover:not(.selected):not(.focused) { background-color: ${styles.listHoverBackground}; }`); } if (styles.listHoverForeground) { content.push(`.monaco-list${suffix} .monaco-list-row:hover:not(.selected):not(.focused) { color: ${styles.listHoverForeground}; }`); } if (styles.listSelectionOutline) { content.push(`.monaco-list${suffix} .monaco-list-row.selected { outline: 1px dotted ${styles.listSelectionOutline}; outline-offset: -1px; }`); } if (styles.listFocusOutline) { content.push(` .monaco-drag-image, .monaco-list${suffix}:focus .monaco-list-row.focused { outline: 1px solid ${styles.listFocusOutline}; outline-offset: -1px; } `); } if (styles.listInactiveFocusOutline) { content.push(`.monaco-list${suffix} .monaco-list-row.focused { outline: 1px dotted ${styles.listInactiveFocusOutline}; outline-offset: -1px; }`); } if (styles.listHoverOutline) { content.push(`.monaco-list${suffix} .monaco-list-row:hover { outline: 1px dashed ${styles.listHoverOutline}; outline-offset: -1px; }`); } if (styles.listDropBackground) { content.push(` .monaco-list${suffix}.drop-target, .monaco-list${suffix} .monaco-list-rows.drop-target, .monaco-list${suffix} .monaco-list-row.drop-target { background-color: ${styles.listDropBackground} !important; color: inherit !important; } `); } if (styles.listFilterWidgetBackground) { content.push(`.monaco-list-type-filter { background-color: ${styles.listFilterWidgetBackground} }`); } if (styles.listFilterWidgetOutline) { content.push(`.monaco-list-type-filter { border: 1px solid ${styles.listFilterWidgetOutline}; }`); } if (styles.listFilterWidgetNoMatchesOutline) { content.push(`.monaco-list-type-filter.no-matches { border: 1px solid ${styles.listFilterWidgetNoMatchesOutline}; }`); } if (styles.listMatchesShadow) { content.push(`.monaco-list-type-filter { box-shadow: 1px 1px 1px ${styles.listMatchesShadow}; }`); } const newStyles = content.join('\n'); if (newStyles !== this.styleElement.innerHTML) { this.styleElement.innerHTML = newStyles; } } } export interface IListOptions<T> { readonly identityProvider?: IIdentityProvider<T>; readonly dnd?: IListDragAndDrop<T>; readonly enableKeyboardNavigation?: boolean; readonly automaticKeyboardNavigation?: boolean; readonly keyboardNavigationLabelProvider?: IKeyboardNavigationLabelProvider<T>; readonly keyboardNavigationDelegate?: IKeyboardNavigationDelegate; readonly ariaRole?: ListAriaRootRole | string; readonly ariaLabel?: string; readonly keyboardSupport?: boolean; readonly multipleSelectionSupport?: boolean; readonly multipleSelectionController?: IMultipleSelectionController<T>; readonly openController?: IOpenController; readonly styleController?: (suffix: string) => IStyleController; readonly accessibilityProvider?: IAccessibilityProvider<T>; // list view options readonly useShadows?: boolean; readonly verticalScrollMode?: ScrollbarVisibility; readonly setRowLineHeight?: boolean; readonly setRowHeight?: boolean; readonly supportDynamicHeights?: boolean; readonly mouseSupport?: boolean; readonly horizontalScrolling?: boolean; readonly ariaProvider?: IAriaProvider<T>; } export interface IListStyles { listBackground?: Color; listFocusBackground?: Color; listFocusForeground?: Color; listActiveSelectionBackground?: Color; listActiveSelectionForeground?: Color; listFocusAndSelectionBackground?: Color; listFocusAndSelectionForeground?: Color; listInactiveSelectionBackground?: Color; listInactiveSelectionForeground?: Color; listInactiveFocusBackground?: Color; listHoverBackground?: Color; listHoverForeground?: Color; listDropBackground?: Color; listFocusOutline?: Color; listInactiveFocusOutline?: Color; listSelectionOutline?: Color; listHoverOutline?: Color; listFilterWidgetBackground?: Color; listFilterWidgetOutline?: Color; listFilterWidgetNoMatchesOutline?: Color; listMatchesShadow?: Color; treeIndentGuidesStroke?: Color; } const defaultStyles: IListStyles = { listFocusBackground: Color.fromHex('#7FB0D0'), listActiveSelectionBackground: Color.fromHex('#0E639C'), listActiveSelectionForeground: Color.fromHex('#FFFFFF'), listFocusAndSelectionBackground: Color.fromHex('#094771'), listFocusAndSelectionForeground: Color.fromHex('#FFFFFF'), listInactiveSelectionBackground: Color.fromHex('#3F3F46'), listHoverBackground: Color.fromHex('#2A2D2E'), listDropBackground: Color.fromHex('#383B3D'), treeIndentGuidesStroke: Color.fromHex('#a9a9a9') }; const DefaultOptions = { keyboardSupport: true, mouseSupport: true, multipleSelectionSupport: true, dnd: { getDragURI() { return null; }, onDragStart(): void { }, onDragOver() { return false; }, drop() { } }, ariaRootRole: ListAriaRootRole.TREE }; // TODO@Joao: move these utils into a SortedArray class function getContiguousRangeContaining(range: number[], value: number): number[] { const index = range.indexOf(value); if (index === -1) { return []; } const result: number[] = []; let i = index - 1; while (i >= 0 && range[i] === value - (index - i)) { result.push(range[i--]); } result.reverse(); i = index; while (i < range.length && range[i] === value + (i - index)) { result.push(range[i++]); } return result; } /** * Given two sorted collections of numbers, returns the intersection * between them (OR). */ function disjunction(one: number[], other: number[]): number[] { const result: number[] = []; let i = 0, j = 0; while (i < one.length || j < other.length) { if (i >= one.length) { result.push(other[j++]); } else if (j >= other.length) { result.push(one[i++]); } else if (one[i] === other[j]) { result.push(one[i]); i++; j++; continue; } else if (one[i] < other[j]) { result.push(one[i++]); } else { result.push(other[j++]); } } return result; } /** * Given two sorted collections of numbers, returns the relative * complement between them (XOR). */ function relativeComplement(one: number[], other: number[]): number[] { const result: number[] = []; let i = 0, j = 0; while (i < one.length || j < other.length) { if (i >= one.length) { result.push(other[j++]); } else if (j >= other.length) { result.push(one[i++]); } else if (one[i] === other[j]) { i++; j++; continue; } else if (one[i] < other[j]) { result.push(one[i++]); } else { j++; } } return result; } const numericSort = (a: number, b: number) => a - b; class PipelineRenderer<T> implements IListRenderer<T, any> { constructor( private _templateId: string, private renderers: IListRenderer<any /* TODO@joao */, any>[] ) { } get templateId(): string { return this._templateId; } renderTemplate(container: HTMLElement): any[] { return this.renderers.map(r => r.renderTemplate(container)); } renderElement(element: T, index: number, templateData: any[], height: number | undefined): void { let i = 0; for (const renderer of this.renderers) { renderer.renderElement(element, index, templateData[i++], height); } } disposeElement(element: T, index: number, templateData: any[], height: number | undefined): void { let i = 0; for (const renderer of this.renderers) { if (renderer.disposeElement) { renderer.disposeElement(element, index, templateData[i], height); } i += 1; } } disposeTemplate(templateData: any[]): void { let i = 0; for (const renderer of this.renderers) { renderer.disposeTemplate(templateData[i++]); } } } class AccessibiltyRenderer<T> implements IListRenderer<T, HTMLElement> { templateId: string = 'a18n'; constructor(private accessibilityProvider: IAccessibilityProvider<T>) { } renderTemplate(container: HTMLElement): HTMLElement { return container; } renderElement(element: T, index: number, container: HTMLElement): void { const ariaLabel = this.accessibilityProvider.getAriaLabel(element); if (ariaLabel) { container.setAttribute('aria-label', ariaLabel); } else { container.removeAttribute('aria-label'); } const ariaLevel = this.accessibilityProvider.getAriaLevel && this.accessibilityProvider.getAriaLevel(element); if (typeof ariaLevel === 'number') { container.setAttribute('aria-level', `${ariaLevel}`); } else { container.removeAttribute('aria-level'); } } disposeTemplate(templateData: any): void { // noop } } class ListViewDragAndDrop<T> implements IListViewDragAndDrop<T> { constructor(private list: List<T>, private dnd: IListDragAndDrop<T>) { } getDragElements(element: T): T[] { const selection = this.list.getSelectedElements(); const elements = selection.indexOf(element) > -1 ? selection : [element]; return elements; } getDragURI(element: T): string | null { return this.dnd.getDragURI(element); } getDragLabel?(elements: T[], originalEvent: DragEvent): string | undefined { if (this.dnd.getDragLabel) { return this.dnd.getDragLabel(elements, originalEvent); } return undefined; } onDragStart(data: IDragAndDropData, originalEvent: DragEvent): void { if (this.dnd.onDragStart) { this.dnd.onDragStart(data, originalEvent); } } onDragOver(data: IDragAndDropData, targetElement: T, targetIndex: number, originalEvent: DragEvent): boolean | IListDragOverReaction { return this.dnd.onDragOver(data, targetElement, targetIndex, originalEvent); } onDragEnd(originalEvent: DragEvent): void { if (this.dnd.onDragEnd) { this.dnd.onDragEnd(originalEvent); } } drop(data: IDragAndDropData, targetElement: T, targetIndex: number, originalEvent: DragEvent): void { this.dnd.drop(data, targetElement, targetIndex, originalEvent); } } export interface IListOptionsUpdate { readonly enableKeyboardNavigation?: boolean; readonly automaticKeyboardNavigation?: boolean; } export class List<T> implements ISpliceable<T>, IDisposable { private focus: Trait<T>; private selection: Trait<T>; private eventBufferer = new EventBufferer(); protected view: ListView<T>; private spliceable: ISpliceable<T>; private styleController: IStyleController; private typeLabelController?: TypeLabelController<T>; private accessibilityProvider?: IAccessibilityProvider<T>; protected readonly disposables = new DisposableStore(); @memoize get onDidChangeFocus(): Event<IListEvent<T>> { return Event.map(this.eventBufferer.wrapEvent(this.focus.onChange), e => this.toListEvent(e)); } @memoize get onDidChangeSelection(): Event<IListEvent<T>> { return Event.map(this.eventBufferer.wrapEvent(this.selection.onChange), e => this.toListEvent(e)); } private readonly _onDidOpen = new Emitter<IListEvent<T>>(); readonly onDidOpen: Event<IListEvent<T>> = this._onDidOpen.event; private readonly _onDidPin = new Emitter<IListEvent<T>>(); readonly onDidPin: Event<IListEvent<T>> = this._onDidPin.event; get domId(): string { return this.view.domId; } get onDidScroll(): Event<ScrollEvent> { return this.view.onDidScroll; } get onMouseClick(): Event<IListMouseEvent<T>> { return this.view.onMouseClick; } get onMouseDblClick(): Event<IListMouseEvent<T>> { return this.view.onMouseDblClick; } get onMouseMiddleClick(): Event<IListMouseEvent<T>> { return this.view.onMouseMiddleClick; } get onMouseUp(): Event<IListMouseEvent<T>> { return this.view.onMouseUp; } get onMouseDown(): Event<IListMouseEvent<T>> { return this.view.onMouseDown; } get onMouseOver(): Event<IListMouseEvent<T>> { return this.view.onMouseOver; } get onMouseMove(): Event<IListMouseEvent<T>> { return this.view.onMouseMove; } get onMouseOut(): Event<IListMouseEvent<T>> { return this.view.onMouseOut; } get onTouchStart(): Event<IListTouchEvent<T>> { return this.view.onTouchStart; } get onTap(): Event<IListGestureEvent<T>> { return this.view.onTap; } private didJustPressContextMenuKey: boolean = false; @memoize get onContextMenu(): Event<IListContextMenuEvent<T>> { const fromKeydown = Event.chain(domEvent(this.view.domNode, 'keydown')) .map(e => new StandardKeyboardEvent(e)) .filter(e => this.didJustPressContextMenuKey = e.keyCode === KeyCode.ContextMenu || (e.shiftKey && e.keyCode === KeyCode.F10)) .filter(e => { e.preventDefault(); e.stopPropagation(); return false; }) .event as Event<any>; const fromKeyup = Event.chain(domEvent(this.view.domNode, 'keyup')) .filter(() => { const didJustPressContextMenuKey = this.didJustPressContextMenuKey; this.didJustPressContextMenuKey = false; return didJustPressContextMenuKey; }) .filter(() => this.getFocus().length > 0 && !!this.view.domElement(this.getFocus()[0])) .map(browserEvent => { const index = this.getFocus()[0]; const element = this.view.element(index); const anchor = this.view.domElement(index) as HTMLElement; return { index, element, anchor, browserEvent }; }) .event; const fromMouse = Event.chain(this.view.onContextMenu) .filter(() => !this.didJustPressContextMenuKey) .map(({ element, index, browserEvent }) => ({ element, index, anchor: { x: browserEvent.clientX + 1, y: browserEvent.clientY }, browserEvent })) .event; return Event.any<IListContextMenuEvent<T>>(fromKeydown, fromKeyup, fromMouse); } get onKeyDown(): Event<KeyboardEvent> { return domEvent(this.view.domNode, 'keydown'); } get onKeyUp(): Event<KeyboardEvent> { return domEvent(this.view.domNode, 'keyup'); } get onKeyPress(): Event<KeyboardEvent> { return domEvent(this.view.domNode, 'keypress'); } readonly onDidFocus: Event<void>; readonly onDidBlur: Event<void>; private readonly _onDidDispose = new Emitter<void>(); readonly onDidDispose: Event<void> = this._onDidDispose.event; constructor( private user: string, container: HTMLElement, virtualDelegate: IListVirtualDelegate<T>, renderers: IListRenderer<any /* TODO@joao */, any>[], private _options: IListOptions<T> = DefaultOptions ) { this.focus = new Trait('focused'); this.selection = new SelectionTrait(); mixin(_options, defaultStyles, false); const baseRenderers: IListRenderer<T, ITraitTemplateData>[] = [this.focus.renderer, this.selection.renderer]; this.accessibilityProvider = _options.accessibilityProvider; if (this.accessibilityProvider) { baseRenderers.push(new AccessibiltyRenderer<T>(this.accessibilityProvider)); if (this.accessibilityProvider.onDidChangeActiveDescendant) { this.accessibilityProvider.onDidChangeActiveDescendant(this.onDidChangeActiveDescendant, this, this.disposables); } } renderers = renderers.map(r => new PipelineRenderer(r.templateId, [...baseRenderers, r])); const viewOptions: IListViewOptions<T> = { ..._options, dnd: _options.dnd && new ListViewDragAndDrop(this, _options.dnd) }; this.view = new ListView(container, virtualDelegate, renderers, viewOptions); if (typeof _options.ariaRole !== 'string') { this.view.domNode.setAttribute('role', ListAriaRootRole.TREE); } else { this.view.domNode.setAttribute('role', _options.ariaRole); } if (_options.styleController) { this.styleController = _options.styleController(this.view.domId); } else { const styleElement = DOM.createStyleSheet(this.view.domNode); this.styleController = new DefaultStyleController(styleElement, this.view.domId); } this.spliceable = new CombinedSpliceable([ new TraitSpliceable(this.focus, this.view, _options.identityProvider), new TraitSpliceable(this.selection, this.view, _options.identityProvider), this.view ]); this.disposables.add(this.focus); this.disposables.add(this.selection); this.disposables.add(this.view); this.disposables.add(this._onDidDispose); this.onDidFocus = Event.map(domEvent(this.view.domNode, 'focus', true), () => null!); this.onDidBlur = Event.map(domEvent(this.view.domNode, 'blur', true), () => null!); this.disposables.add(new DOMFocusController(this, this.view)); if (typeof _options.keyboardSupport !== 'boolean' || _options.keyboardSupport) { const controller = new KeyboardController(this, this.view, _options); this.disposables.add(controller); } if (_options.keyboardNavigationLabelProvider) { const delegate = _options.keyboardNavigationDelegate || DefaultKeyboardNavigationDelegate; this.typeLabelController = new TypeLabelController(this, this.view, _options.keyboardNavigationLabelProvider, delegate); this.disposables.add(this.typeLabelController); } this.disposables.add(this.createMouseController(_options)); this.onDidChangeFocus(this._onFocusChange, this, this.disposables); this.onDidChangeSelection(this._onSelectionChange, this, this.disposables); if (_options.ariaLabel) { this.view.domNode.setAttribute('aria-label', localize('aria list', "{0}. Use the navigation keys to navigate.", _options.ariaLabel)); } if (_options.multipleSelectionSupport) { this.view.domNode.setAttribute('aria-multiselectable', 'true'); } } protected createMouseController(options: IListOptions<T>): MouseController<T> { return new MouseController(this); } updateOptions(optionsUpdate: IListOptionsUpdate = {}): void { this._options = { ...this._options, ...optionsUpdate }; if (this.typeLabelController) { this.typeLabelController.updateOptions(this._options); } } get options(): IListOptions<T> { return this._options; } splice(start: number, deleteCount: number, elements: T[] = []): void { if (start < 0 || start > this.view.length) { throw new ListError(this.user, `Invalid start index: ${start}`); } if (deleteCount < 0) { throw new ListError(this.user, `Invalid delete count: ${deleteCount}`); } if (deleteCount === 0 && elements.length === 0) { return; } this.eventBufferer.bufferEvents(() => this.spliceable.splice(start, deleteCount, elements)); } updateWidth(index: number): void { this.view.updateWidth(index); } updateElementHeight(index: number, size: number): void { this.view.updateElementHeight(index, size); } rerender(): void { this.view.rerender(); } element(index: number): T { return this.view.element(index); } get length(): number { return this.view.length; } get contentHeight(): number { return this.view.contentHeight; } get onDidChangeContentHeight(): Event<number> { return this.view.onDidChangeContentHeight; } get scrollTop(): number { return this.view.getScrollTop(); } set scrollTop(scrollTop: number) { this.view.setScrollTop(scrollTop); } get scrollLeft(): number { return this.view.getScrollLeft(); } set scrollLeft(scrollLeft: number) { this.view.setScrollLeft(scrollLeft); } get scrollHeight(): number { return this.view.scrollHeight; } get renderHeight(): number { return this.view.renderHeight; } get firstVisibleIndex(): number { return this.view.firstVisibleIndex; } get lastVisibleIndex(): number { return this.view.lastVisibleIndex; } domFocus(): void { this.view.domNode.focus(); } layout(height?: number, width?: number): void { this.view.layout(height, width); } toggleKeyboardNavigation(): void { if (this.typeLabelController) { this.typeLabelController.toggle(); } } setSelection(indexes: number[], browserEvent?: UIEvent): void { for (const index of indexes) { if (index < 0 || index >= this.length) { throw new ListError(this.user, `Invalid index ${index}`); } } this.selection.set(indexes, browserEvent); } getSelection(): number[] { return this.selection.get(); } getSelectedElements(): T[] { return this.getSelection().map(i => this.view.element(i)); } setFocus(indexes: number[], browserEvent?: UIEvent): void { for (const index of indexes) { if (index < 0 || index >= this.length) { throw new ListError(this.user, `Invalid index ${index}`); } } this.focus.set(indexes, browserEvent); } focusNext(n = 1, loop = false, browserEvent?: UIEvent, filter?: (element: T) => boolean): void { if (this.length === 0) { return; } const focus = this.focus.get(); const index = this.findNextIndex(focus.length > 0 ? focus[0] + n : 0, loop, filter); if (index > -1) { this.setFocus([index], browserEvent); } } focusPrevious(n = 1, loop = false, browserEvent?: UIEvent, filter?: (element: T) => boolean): void { if (this.length === 0) { return; } const focus = this.focus.get(); const index = this.findPreviousIndex(focus.length > 0 ? focus[0] - n : 0, loop, filter); if (index > -1) { this.setFocus([index], browserEvent); } } focusNextPage(browserEvent?: UIEvent, filter?: (element: T) => boolean): void { let lastPageIndex = this.view.indexAt(this.view.getScrollTop() + this.view.renderHeight); lastPageIndex = lastPageIndex === 0 ? 0 : lastPageIndex - 1; const lastPageElement = this.view.element(lastPageIndex); const currentlyFocusedElement = this.getFocusedElements()[0]; if (currentlyFocusedElement !== lastPageElement) { const lastGoodPageIndex = this.findPreviousIndex(lastPageIndex, false, filter); if (lastGoodPageIndex > -1 && currentlyFocusedElement !== this.view.element(lastGoodPageIndex)) { this.setFocus([lastGoodPageIndex], browserEvent); } else { this.setFocus([lastPageIndex], browserEvent); } } else { const previousScrollTop = this.view.getScrollTop(); this.view.setScrollTop(previousScrollTop + this.view.renderHeight - this.view.elementHeight(lastPageIndex)); if (this.view.getScrollTop() !== previousScrollTop) { // Let the scroll event listener run setTimeout(() => this.focusNextPage(browserEvent, filter), 0); } } } focusPreviousPage(browserEvent?: UIEvent, filter?: (element: T) => boolean): void { let firstPageIndex: number; const scrollTop = this.view.getScrollTop(); if (scrollTop === 0) { firstPageIndex = this.view.indexAt(scrollTop); } else { firstPageIndex = this.view.indexAfter(scrollTop - 1); } const firstPageElement = this.view.element(firstPageIndex); const currentlyFocusedElement = this.getFocusedElements()[0]; if (currentlyFocusedElement !== firstPageElement) { const firstGoodPageIndex = this.findNextIndex(firstPageIndex, false, filter); if (firstGoodPageIndex > -1 && currentlyFocusedElement !== this.view.element(firstGoodPageIndex)) { this.setFocus([firstGoodPageIndex], browserEvent); } else { this.setFocus([firstPageIndex], browserEvent); } } else { const previousScrollTop = scrollTop; this.view.setScrollTop(scrollTop - this.view.renderHeight); if (this.view.getScrollTop() !== previousScrollTop) { // Let the scroll event listener run setTimeout(() => this.focusPreviousPage(browserEvent, filter), 0); } } } focusLast(browserEvent?: UIEvent, filter?: (element: T) => boolean): void { if (this.length === 0) { return; } const index = this.findPreviousIndex(this.length - 1, false, filter); if (index > -1) { this.setFocus([index], browserEvent); } } focusFirst(browserEvent?: UIEvent, filter?: (element: T) => boolean): void { if (this.length === 0) { return; } const index = this.findNextIndex(0, false, filter); if (index > -1) { this.setFocus([index], browserEvent); } } private findNextIndex(index: number, loop = false, filter?: (element: T) => boolean): number { for (let i = 0; i < this.length; i++) { if (index >= this.length && !loop) { return -1; } index = index % this.length; if (!filter || filter(this.element(index))) { return index; } index++; } return -1; } private findPreviousIndex(index: number, loop = false, filter?: (element: T) => boolean): number { for (let i = 0; i < this.length; i++) { if (index < 0 && !loop) { return -1; } index = (this.length + (index % this.length)) % this.length; if (!filter || filter(this.element(index))) { return index; } index--; } return -1; } getFocus(): number[] { return this.focus.get(); } getFocusedElements(): T[] { return this.getFocus().map(i => this.view.element(i)); } reveal(index: number, relativeTop?: number): void { if (index < 0 || index >= this.length) { throw new ListError(this.user, `Invalid index ${index}`); } const scrollTop = this.view.getScrollTop(); const elementTop = this.view.elementTop(index); const elementHeight = this.view.elementHeight(index); if (isNumber(relativeTop)) { // y = mx + b const m = elementHeight - this.view.renderHeight; this.view.setScrollTop(m * clamp(relativeTop, 0, 1) + elementTop); } else { const viewItemBottom = elementTop + elementHeight; const wrapperBottom = scrollTop + this.view.renderHeight; if (elementTop < scrollTop && viewItemBottom >= wrapperBottom) { // The element is already overflowing the viewport, no-op } else if (elementTop < scrollTop) { this.view.setScrollTop(elementTop); } else if (viewItemBottom >= wrapperBottom) { this.view.setScrollTop(viewItemBottom - this.view.renderHeight); } } } /** * Returns the relative position of an element rendered in the list. * Returns `null` if the element isn't *entirely* in the visible viewport. */ getRelativeTop(index: number): number | null { if (index < 0 || index >= this.length) { throw new ListError(this.user, `Invalid index ${index}`); } const scrollTop = this.view.getScrollTop(); const elementTop = this.view.elementTop(index); const elementHeight = this.view.elementHeight(index); if (elementTop < scrollTop || elementTop + elementHeight > scrollTop + this.view.renderHeight) { return null; } // y = mx + b const m = elementHeight - this.view.renderHeight; return Math.abs((scrollTop - elementTop) / m); } isDOMFocused(): boolean { return this.view.domNode === document.activeElement; } getHTMLElement(): HTMLElement { return this.view.domNode; } open(indexes: number[], browserEvent?: UIEvent): void { for (const index of indexes) { if (index < 0 || index >= this.length) { throw new ListError(this.user, `Invalid index ${index}`); } } this._onDidOpen.fire({ indexes, elements: indexes.map(i => this.view.element(i)), browserEvent }); } pin(indexes: number[], browserEvent?: UIEvent): void { for (const index of indexes) { if (index < 0 || index >= this.length) { throw new ListError(this.user, `Invalid index ${index}`); } } this._onDidPin.fire({ indexes, elements: indexes.map(i => this.view.element(i)), browserEvent }); } style(styles: IListStyles): void { this.styleController.style(styles); } private toListEvent({ indexes, browserEvent }: ITraitChangeEvent) { return { indexes, elements: indexes.map(i => this.view.element(i)), browserEvent }; } private _onFocusChange(): void { const focus = this.focus.get(); DOM.toggleClass(this.view.domNode, 'element-focused', focus.length > 0); this.onDidChangeActiveDescendant(); } private onDidChangeActiveDescendant(): void { const focus = this.focus.get(); if (focus.length > 0) { let id: string | undefined; if (this.accessibilityProvider?.getActiveDescendantId) { id = this.accessibilityProvider.getActiveDescendantId(this.view.element(focus[0])); } this.view.domNode.setAttribute('aria-activedescendant', id || this.view.getElementDomId(focus[0])); } else { this.view.domNode.removeAttribute('aria-activedescendant'); } } private _onSelectionChange(): void { const selection = this.selection.get(); DOM.toggleClass(this.view.domNode, 'selection-none', selection.length === 0); DOM.toggleClass(this.view.domNode, 'selection-single', selection.length === 1); DOM.toggleClass(this.view.domNode, 'selection-multiple', selection.length > 1); } dispose(): void { this._onDidDispose.fire(); this.disposables.dispose(); this._onDidOpen.dispose(); this._onDidPin.dispose(); this._onDidDispose.dispose(); } }
src/vs/base/browser/ui/list/listWidget.ts
1
https://github.com/microsoft/vscode/commit/7aca51e3d98c58ee8e418df6b525930d90375d9f
[ 0.49711406230926514, 0.003636719658970833, 0.00016441982006654143, 0.0001742415188346058, 0.03811044245958328 ]
{ "id": 1, "code_window": [ "\n", "\tconstructor() {\n", "\t\tsuper('selected');\n", "\t}\n", "\n", "\trenderIndex(index: number, container: HTMLElement): void {\n" ], "labels": [ "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "\tconstructor(private isAriaSelected: (index: number) => boolean) {\n", "\t\tsuper('focused');\n" ], "file_path": "src/vs/base/browser/ui/list/listWidget.ts", "type": "replace", "edit_start_line_idx": 184 }
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg"> <path fill-rule="evenodd" clip-rule="evenodd" d="M11.219 8.35484C11.6063 8.12309 12.049 8.00047 12.5003 8C12.8904 7.99939 13.2753 8.0901 13.6241 8.26486C13.9729 8.43963 14.276 8.6936 14.5091 9.00646C14.7421 9.31933 14.8987 9.6824 14.9664 10.0666C15.034 10.4509 15.0108 10.8456 14.8985 11.2192C14.7863 11.5929 14.5882 11.9351 14.32 12.2184C14.0518 12.5018 13.7211 12.7185 13.3542 12.8511C12.9873 12.9837 12.5944 13.0287 12.207 12.9823C11.8197 12.9359 11.4485 12.7995 11.1233 12.584L8.7683 14.9399L8.06055 14.2322L10.4163 11.877C10.1677 11.5003 10.0258 11.0634 10.0054 10.6126C9.98511 10.1618 10.0872 9.71384 10.3009 9.31634C10.5145 8.91885 10.8318 8.58659 11.219 8.35484ZM11.667 11.7472C11.9136 11.912 12.2036 12 12.5003 12C12.8981 12 13.2797 11.842 13.561 11.5607C13.8423 11.2794 14.0003 10.8978 14.0003 10.5C14.0003 10.2033 13.9123 9.91332 13.7475 9.66665C13.5827 9.41997 13.3484 9.22772 13.0743 9.11418C12.8002 9.00065 12.4986 8.97095 12.2077 9.02883C11.9167 9.0867 11.6494 9.22956 11.4396 9.43934C11.2299 9.64912 11.087 9.9164 11.0291 10.2074C10.9712 10.4983 11.001 10.7999 11.1145 11.074C11.228 11.3481 11.4203 11.5824 11.667 11.7472Z" fill="#C5C5C5"/> <path fill-rule="evenodd" clip-rule="evenodd" d="M13 1L14 2V7.33573C13.6829 7.18584 13.3457 7.08481 13 7.03533V2L8 2L8 12.8787L6.87837 14H2L1 13V2L2 1H13ZM9.70794 14H9.70785L10 13.7077V13.7079L9.70794 14ZM13 10.5174C13.0002 10.5116 13.0003 10.5058 13.0003 10.5C13.0003 10.4942 13.0002 10.4884 13 10.4826V10.5174ZM2 2L7 2L7 13H2L2 2Z" fill="#C5C5C5"/> </svg>
extensions/markdown-language-features/media/preview-right-dark.svg
0
https://github.com/microsoft/vscode/commit/7aca51e3d98c58ee8e418df6b525930d90375d9f
[ 0.0016612561885267496, 0.0016612561885267496, 0.0016612561885267496, 0.0016612561885267496, 0 ]
{ "id": 1, "code_window": [ "\n", "\tconstructor() {\n", "\t\tsuper('selected');\n", "\t}\n", "\n", "\trenderIndex(index: number, container: HTMLElement): void {\n" ], "labels": [ "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "\tconstructor(private isAriaSelected: (index: number) => boolean) {\n", "\t\tsuper('focused');\n" ], "file_path": "src/vs/base/browser/ui/list/listWidget.ts", "type": "replace", "edit_start_line_idx": 184 }
/*--------------------------------------------------------------------------------------------- * 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 { join } from 'path'; import * as vscode from 'vscode'; import { createRandomFile, testFs } from '../utils'; suite('languages namespace tests', () => { const isWindows = process.platform === 'win32'; function positionToString(p: vscode.Position) { return `[${p.character}/${p.line}]`; } function rangeToString(r: vscode.Range) { return `[${positionToString(r.start)}/${positionToString(r.end)}]`; } function assertEqualRange(actual: vscode.Range, expected: vscode.Range, message?: string) { assert.equal(rangeToString(actual), rangeToString(expected), message); } test('setTextDocumentLanguage -> close/open event', async function () { const file = await createRandomFile('foo\nbar\nbar'); const doc = await vscode.workspace.openTextDocument(file); const langIdNow = doc.languageId; let clock = 0; let close = new Promise(resolve => { vscode.workspace.onDidCloseTextDocument(e => { if (e === doc) { assert.equal(doc.languageId, langIdNow); assert.equal(clock, 0); clock += 1; resolve(); } }); }); let open = new Promise(resolve => { vscode.workspace.onDidOpenTextDocument(e => { if (e === doc) { // same instance! assert.equal(doc.languageId, 'json'); assert.equal(clock, 1); clock += 1; resolve(); } }); }); let change = vscode.languages.setTextDocumentLanguage(doc, 'json'); await Promise.all([change, close, open]); assert.equal(clock, 2); assert.equal(doc.languageId, 'json'); }); test('setTextDocumentLanguage -> error when language does not exist', async function () { const file = await createRandomFile('foo\nbar\nbar'); const doc = await vscode.workspace.openTextDocument(file); try { await vscode.languages.setTextDocumentLanguage(doc, 'fooLangDoesNotExist'); assert.ok(false); } catch (err) { assert.ok(err); } }); test('diagnostics, read & event', function () { let uri = vscode.Uri.file('/foo/bar.txt'); let col1 = vscode.languages.createDiagnosticCollection('foo1'); col1.set(uri, [new vscode.Diagnostic(new vscode.Range(0, 0, 0, 12), 'error1')]); let col2 = vscode.languages.createDiagnosticCollection('foo2'); col2.set(uri, [new vscode.Diagnostic(new vscode.Range(0, 0, 0, 12), 'error1')]); let diag = vscode.languages.getDiagnostics(uri); assert.equal(diag.length, 2); let tuples = vscode.languages.getDiagnostics(); let found = false; for (let [thisUri,] of tuples) { if (thisUri.toString() === uri.toString()) { found = true; break; } } assert.ok(tuples.length >= 1); assert.ok(found); }); test('link detector', async function () { const uri = await createRandomFile('class A { // http://a.com }', undefined, '.java'); const doc = await vscode.workspace.openTextDocument(uri); const target = vscode.Uri.file(isWindows ? 'c:\\foo\\bar' : '/foo/bar'); const range = new vscode.Range(new vscode.Position(0, 0), new vscode.Position(0, 5)); const linkProvider: vscode.DocumentLinkProvider = { provideDocumentLinks: _doc => { return [new vscode.DocumentLink(range, target)]; } }; vscode.languages.registerDocumentLinkProvider({ language: 'java', scheme: testFs.scheme }, linkProvider); const links = await vscode.commands.executeCommand<vscode.DocumentLink[]>('vscode.executeLinkProvider', doc.uri); assert.equal(2, links && links.length); let [link1, link2] = links!.sort((l1, l2) => l1.range.start.compareTo(l2.range.start)); assert.equal(target.toString(), link1.target && link1.target.toString()); assertEqualRange(range, link1.range); assert.equal('http://a.com/', link2.target && link2.target.toString()); assertEqualRange(new vscode.Range(new vscode.Position(0, 13), new vscode.Position(0, 25)), link2.range); }); test('diagnostics & CodeActionProvider', async function () { class D2 extends vscode.Diagnostic { customProp = { complex() { } }; constructor() { super(new vscode.Range(0, 2, 0, 7), 'sonntag'); } } let diag1 = new vscode.Diagnostic(new vscode.Range(0, 0, 0, 5), 'montag'); let diag2 = new D2(); let ran = false; let uri = vscode.Uri.parse('ttt:path.far'); let r1 = vscode.languages.registerCodeActionsProvider({ pattern: '*.far', scheme: 'ttt' }, { provideCodeActions(_document, _range, ctx): vscode.Command[] { assert.equal(ctx.diagnostics.length, 2); let [first, second] = ctx.diagnostics; assert.ok(first === diag1); assert.ok(second === diag2); assert.ok(diag2 instanceof D2); ran = true; return []; } }); let r2 = vscode.workspace.registerTextDocumentContentProvider('ttt', { provideTextDocumentContent() { return 'this is some text'; } }); let r3 = vscode.languages.createDiagnosticCollection(); r3.set(uri, [diag1]); let r4 = vscode.languages.createDiagnosticCollection(); r4.set(uri, [diag2]); await vscode.workspace.openTextDocument(uri); await vscode.commands.executeCommand('vscode.executeCodeActionProvider', uri, new vscode.Range(0, 0, 0, 10)); assert.ok(ran); vscode.Disposable.from(r1, r2, r3, r4).dispose(); }); test('completions with document filters', async function () { let ran = false; let uri = vscode.Uri.file(join(vscode.workspace.rootPath || '', './bower.json')); let jsonDocumentFilter = [{ language: 'json', pattern: '**/package.json' }, { language: 'json', pattern: '**/bower.json' }, { language: 'json', pattern: '**/.bower.json' }]; let r1 = vscode.languages.registerCompletionItemProvider(jsonDocumentFilter, { provideCompletionItems: (_document: vscode.TextDocument, _position: vscode.Position, _token: vscode.CancellationToken): vscode.CompletionItem[] => { let proposal = new vscode.CompletionItem('foo'); proposal.kind = vscode.CompletionItemKind.Property; ran = true; return [proposal]; } }); await vscode.workspace.openTextDocument(uri); const result = await vscode.commands.executeCommand<vscode.CompletionList>('vscode.executeCompletionItemProvider', uri, new vscode.Position(1, 0)); r1.dispose(); assert.ok(ran, 'Provider has not been invoked'); assert.ok(result!.items.some(i => i.label === 'foo'), 'Results do not include "foo"'); }); });
extensions/vscode-api-tests/src/singlefolder-tests/languages.test.ts
0
https://github.com/microsoft/vscode/commit/7aca51e3d98c58ee8e418df6b525930d90375d9f
[ 0.00035989974276162684, 0.0001811129186535254, 0.0001641004637349397, 0.00017222158203367144, 0.00004223127325531095 ]
{ "id": 1, "code_window": [ "\n", "\tconstructor() {\n", "\t\tsuper('selected');\n", "\t}\n", "\n", "\trenderIndex(index: number, container: HTMLElement): void {\n" ], "labels": [ "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "\tconstructor(private isAriaSelected: (index: number) => boolean) {\n", "\t\tsuper('focused');\n" ], "file_path": "src/vs/base/browser/ui/list/listWidget.ts", "type": "replace", "edit_start_line_idx": 184 }
/*--------------------------------------------------------------------------------------------- * 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 { ITextModelService, ITextModelContentProvider } from 'vs/editor/common/services/resolverService'; import { IModelService } from 'vs/editor/common/services/modelService'; import { ITextModel, DefaultEndOfLine, EndOfLinePreference } from 'vs/editor/common/model'; import { IModeService } from 'vs/editor/common/services/modeService'; import { IWorkbenchContribution } from 'vs/workbench/common/contributions'; import * as marked from 'vs/base/common/marked/marked'; import { Schemas } from 'vs/base/common/network'; import { Range } from 'vs/editor/common/core/range'; import { createTextBufferFactory } from 'vs/editor/common/model/textModel'; function requireToContent(resource: URI): Promise<string> { if (!resource.query) { throw new Error('Welcome: invalid resource'); } const query = JSON.parse(resource.query); if (!query.moduleId) { throw new Error('Welcome: invalid resource'); } const content: Promise<string> = new Promise<string>((resolve, reject) => { require([query.moduleId], content => { try { resolve(content.default()); } catch (err) { reject(err); } }); }); return content; } export class WalkThroughContentProvider implements ITextModelContentProvider, IWorkbenchContribution { constructor( @ITextModelService private readonly textModelResolverService: ITextModelService, @IModeService private readonly modeService: IModeService, @IModelService private readonly modelService: IModelService, ) { this.textModelResolverService.registerTextModelContentProvider(Schemas.walkThrough, this); } public async provideTextContent(resource: URI): Promise<ITextModel> { const content = await requireToContent(resource); let codeEditorModel = this.modelService.getModel(resource); if (!codeEditorModel) { codeEditorModel = this.modelService.createModel(content, this.modeService.createByFilepathOrFirstLine(resource), resource); } else { this.modelService.updateModel(codeEditorModel, content); } return codeEditorModel; } } export class WalkThroughSnippetContentProvider implements ITextModelContentProvider, IWorkbenchContribution { constructor( @ITextModelService private readonly textModelResolverService: ITextModelService, @IModeService private readonly modeService: IModeService, @IModelService private readonly modelService: IModelService, ) { this.textModelResolverService.registerTextModelContentProvider(Schemas.walkThroughSnippet, this); } public async provideTextContent(resource: URI): Promise<ITextModel> { const factory = createTextBufferFactory(await requireToContent(resource)); let codeEditorModel = this.modelService.getModel(resource); if (!codeEditorModel) { const j = parseInt(resource.fragment); let codeSnippet = ''; let languageName = ''; let i = 0; const renderer = new marked.Renderer(); renderer.code = (code, lang) => { if (i++ === j) { codeSnippet = code; languageName = lang; } return ''; }; const textBuffer = factory.create(DefaultEndOfLine.LF); const lineCount = textBuffer.getLineCount(); const range = new Range(1, 1, lineCount, textBuffer.getLineLength(lineCount) + 1); const markdown = textBuffer.getValueInRange(range, EndOfLinePreference.TextDefined); marked(markdown, { renderer }); const languageId = this.modeService.getModeIdForLanguageName(languageName) || ''; const languageSelection = this.modeService.create(languageId); codeEditorModel = this.modelService.createModel(codeSnippet, languageSelection, resource); } else { this.modelService.updateModel(codeEditorModel, factory); } return codeEditorModel; } }
src/vs/workbench/contrib/welcome/walkThrough/common/walkThroughContentProvider.ts
0
https://github.com/microsoft/vscode/commit/7aca51e3d98c58ee8e418df6b525930d90375d9f
[ 0.00018079504661727697, 0.00017128219769801944, 0.00016613997286185622, 0.00017055000353138894, 0.000003651956831163261 ]
{ "id": 2, "code_window": [ "\trenderIndex(index: number, container: HTMLElement): void {\n", "\t\tsuper.renderIndex(index, container);\n", "\n", "\t\tif (this.contains(index)) {\n", "\t\t\tcontainer.setAttribute('aria-selected', 'true');\n", "\t\t} else {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ "\t\tif (this.contains(index) || this.isAriaSelected(index)) {\n" ], "file_path": "src/vs/base/browser/ui/list/listWidget.ts", "type": "replace", "edit_start_line_idx": 191 }
/*--------------------------------------------------------------------------------------------- * 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!./list'; import { localize } from 'vs/nls'; import { IDisposable, dispose, DisposableStore } from 'vs/base/common/lifecycle'; import { isNumber } from 'vs/base/common/types'; import { range, firstIndex, binarySearch } from 'vs/base/common/arrays'; import { memoize } from 'vs/base/common/decorators'; import * as DOM from 'vs/base/browser/dom'; import * as platform from 'vs/base/common/platform'; import { Gesture } from 'vs/base/browser/touch'; import { KeyCode } from 'vs/base/common/keyCodes'; import { StandardKeyboardEvent, IKeyboardEvent } from 'vs/base/browser/keyboardEvent'; import { Event, Emitter, EventBufferer } from 'vs/base/common/event'; import { domEvent } from 'vs/base/browser/event'; import { IListVirtualDelegate, IListRenderer, IListEvent, IListContextMenuEvent, IListMouseEvent, IListTouchEvent, IListGestureEvent, IIdentityProvider, IKeyboardNavigationLabelProvider, IListDragAndDrop, IListDragOverReaction, ListAriaRootRole, ListError, IKeyboardNavigationDelegate } from './list'; import { ListView, IListViewOptions, IListViewDragAndDrop, IAriaProvider } from './listView'; import { Color } from 'vs/base/common/color'; import { mixin } from 'vs/base/common/objects'; import { ScrollbarVisibility, ScrollEvent } from 'vs/base/common/scrollable'; import { ISpliceable } from 'vs/base/common/sequence'; import { CombinedSpliceable } from 'vs/base/browser/ui/list/splice'; import { clamp } from 'vs/base/common/numbers'; import { matchesPrefix } from 'vs/base/common/filters'; import { IDragAndDropData } from 'vs/base/browser/dnd'; interface ITraitChangeEvent { indexes: number[]; browserEvent?: UIEvent; } type ITraitTemplateData = HTMLElement; interface IRenderedContainer { templateData: ITraitTemplateData; index: number; } class TraitRenderer<T> implements IListRenderer<T, ITraitTemplateData> { private renderedElements: IRenderedContainer[] = []; constructor(private trait: Trait<T>) { } get templateId(): string { return `template:${this.trait.trait}`; } renderTemplate(container: HTMLElement): ITraitTemplateData { return container; } renderElement(element: T, index: number, templateData: ITraitTemplateData): void { const renderedElementIndex = firstIndex(this.renderedElements, el => el.templateData === templateData); if (renderedElementIndex >= 0) { const rendered = this.renderedElements[renderedElementIndex]; this.trait.unrender(templateData); rendered.index = index; } else { const rendered = { index, templateData }; this.renderedElements.push(rendered); } this.trait.renderIndex(index, templateData); } splice(start: number, deleteCount: number, insertCount: number): void { const rendered: IRenderedContainer[] = []; for (const renderedElement of this.renderedElements) { if (renderedElement.index < start) { rendered.push(renderedElement); } else if (renderedElement.index >= start + deleteCount) { rendered.push({ index: renderedElement.index + insertCount - deleteCount, templateData: renderedElement.templateData }); } } this.renderedElements = rendered; } renderIndexes(indexes: number[]): void { for (const { index, templateData } of this.renderedElements) { if (indexes.indexOf(index) > -1) { this.trait.renderIndex(index, templateData); } } } disposeTemplate(templateData: ITraitTemplateData): void { const index = firstIndex(this.renderedElements, el => el.templateData === templateData); if (index < 0) { return; } this.renderedElements.splice(index, 1); } } class Trait<T> implements ISpliceable<boolean>, IDisposable { private indexes: number[] = []; private sortedIndexes: number[] = []; private readonly _onChange = new Emitter<ITraitChangeEvent>(); readonly onChange: Event<ITraitChangeEvent> = this._onChange.event; get trait(): string { return this._trait; } @memoize get renderer(): TraitRenderer<T> { return new TraitRenderer<T>(this); } constructor(private _trait: string) { } splice(start: number, deleteCount: number, elements: boolean[]): void { const diff = elements.length - deleteCount; const end = start + deleteCount; const indexes = [ ...this.sortedIndexes.filter(i => i < start), ...elements.map((hasTrait, i) => hasTrait ? i + start : -1).filter(i => i !== -1), ...this.sortedIndexes.filter(i => i >= end).map(i => i + diff) ]; this.renderer.splice(start, deleteCount, elements.length); this._set(indexes, indexes); } renderIndex(index: number, container: HTMLElement): void { DOM.toggleClass(container, this._trait, this.contains(index)); } unrender(container: HTMLElement): void { DOM.removeClass(container, this._trait); } /** * Sets the indexes which should have this trait. * * @param indexes Indexes which should have this trait. * @return The old indexes which had this trait. */ set(indexes: number[], browserEvent?: UIEvent): number[] { return this._set(indexes, [...indexes].sort(numericSort), browserEvent); } private _set(indexes: number[], sortedIndexes: number[], browserEvent?: UIEvent): number[] { const result = this.indexes; const sortedResult = this.sortedIndexes; this.indexes = indexes; this.sortedIndexes = sortedIndexes; const toRender = disjunction(sortedResult, indexes); this.renderer.renderIndexes(toRender); this._onChange.fire({ indexes, browserEvent }); return result; } get(): number[] { return this.indexes; } contains(index: number): boolean { return binarySearch(this.sortedIndexes, index, numericSort) >= 0; } dispose() { dispose(this._onChange); } } class SelectionTrait<T> extends Trait<T> { constructor() { super('selected'); } renderIndex(index: number, container: HTMLElement): void { super.renderIndex(index, container); if (this.contains(index)) { container.setAttribute('aria-selected', 'true'); } else { container.removeAttribute('aria-selected'); } } } /** * The TraitSpliceable is used as a util class to be able * to preserve traits across splice calls, given an identity * provider. */ class TraitSpliceable<T> implements ISpliceable<T> { constructor( private trait: Trait<T>, private view: ListView<T>, private identityProvider?: IIdentityProvider<T> ) { } splice(start: number, deleteCount: number, elements: T[]): void { if (!this.identityProvider) { return this.trait.splice(start, deleteCount, elements.map(() => false)); } const pastElementsWithTrait = this.trait.get().map(i => this.identityProvider!.getId(this.view.element(i)).toString()); const elementsWithTrait = elements.map(e => pastElementsWithTrait.indexOf(this.identityProvider!.getId(e).toString()) > -1); this.trait.splice(start, deleteCount, elementsWithTrait); } } function isInputElement(e: HTMLElement): boolean { return e.tagName === 'INPUT' || e.tagName === 'TEXTAREA'; } class KeyboardController<T> implements IDisposable { private readonly disposables = new DisposableStore(); private openController: IOpenController; constructor( private list: List<T>, private view: ListView<T>, options: IListOptions<T> ) { const multipleSelectionSupport = options.multipleSelectionSupport !== false; this.openController = options.openController || DefaultOpenController; const onKeyDown = Event.chain(domEvent(view.domNode, 'keydown')) .filter(e => !isInputElement(e.target as HTMLElement)) .map(e => new StandardKeyboardEvent(e)); onKeyDown.filter(e => e.keyCode === KeyCode.Enter).on(this.onEnter, this, this.disposables); onKeyDown.filter(e => e.keyCode === KeyCode.UpArrow).on(this.onUpArrow, this, this.disposables); onKeyDown.filter(e => e.keyCode === KeyCode.DownArrow).on(this.onDownArrow, this, this.disposables); onKeyDown.filter(e => e.keyCode === KeyCode.PageUp).on(this.onPageUpArrow, this, this.disposables); onKeyDown.filter(e => e.keyCode === KeyCode.PageDown).on(this.onPageDownArrow, this, this.disposables); onKeyDown.filter(e => e.keyCode === KeyCode.Escape).on(this.onEscape, this, this.disposables); if (multipleSelectionSupport) { onKeyDown.filter(e => (platform.isMacintosh ? e.metaKey : e.ctrlKey) && e.keyCode === KeyCode.KEY_A).on(this.onCtrlA, this, this.disposables); } } private onEnter(e: StandardKeyboardEvent): void { e.preventDefault(); e.stopPropagation(); this.list.setSelection(this.list.getFocus(), e.browserEvent); if (this.openController.shouldOpen(e.browserEvent)) { this.list.open(this.list.getFocus(), e.browserEvent); } } private onUpArrow(e: StandardKeyboardEvent): void { e.preventDefault(); e.stopPropagation(); this.list.focusPrevious(1, false, e.browserEvent); this.list.reveal(this.list.getFocus()[0]); this.view.domNode.focus(); } private onDownArrow(e: StandardKeyboardEvent): void { e.preventDefault(); e.stopPropagation(); this.list.focusNext(1, false, e.browserEvent); this.list.reveal(this.list.getFocus()[0]); this.view.domNode.focus(); } private onPageUpArrow(e: StandardKeyboardEvent): void { e.preventDefault(); e.stopPropagation(); this.list.focusPreviousPage(e.browserEvent); this.list.reveal(this.list.getFocus()[0]); this.view.domNode.focus(); } private onPageDownArrow(e: StandardKeyboardEvent): void { e.preventDefault(); e.stopPropagation(); this.list.focusNextPage(e.browserEvent); this.list.reveal(this.list.getFocus()[0]); this.view.domNode.focus(); } private onCtrlA(e: StandardKeyboardEvent): void { e.preventDefault(); e.stopPropagation(); this.list.setSelection(range(this.list.length), e.browserEvent); this.view.domNode.focus(); } private onEscape(e: StandardKeyboardEvent): void { e.preventDefault(); e.stopPropagation(); this.list.setSelection([], e.browserEvent); this.view.domNode.focus(); } dispose() { this.disposables.dispose(); } } enum TypeLabelControllerState { Idle, Typing } export const DefaultKeyboardNavigationDelegate = new class implements IKeyboardNavigationDelegate { mightProducePrintableCharacter(event: IKeyboardEvent): boolean { if (event.ctrlKey || event.metaKey || event.altKey) { return false; } return (event.keyCode >= KeyCode.KEY_A && event.keyCode <= KeyCode.KEY_Z) || (event.keyCode >= KeyCode.KEY_0 && event.keyCode <= KeyCode.KEY_9) || (event.keyCode >= KeyCode.NUMPAD_0 && event.keyCode <= KeyCode.NUMPAD_9) || (event.keyCode >= KeyCode.US_SEMICOLON && event.keyCode <= KeyCode.US_QUOTE); } }; class TypeLabelController<T> implements IDisposable { private enabled = false; private state: TypeLabelControllerState = TypeLabelControllerState.Idle; private automaticKeyboardNavigation = true; private triggered = false; private readonly enabledDisposables = new DisposableStore(); private readonly disposables = new DisposableStore(); constructor( private list: List<T>, private view: ListView<T>, private keyboardNavigationLabelProvider: IKeyboardNavigationLabelProvider<T>, private delegate: IKeyboardNavigationDelegate ) { this.updateOptions(list.options); } updateOptions(options: IListOptions<T>): void { const enableKeyboardNavigation = typeof options.enableKeyboardNavigation === 'undefined' ? true : !!options.enableKeyboardNavigation; if (enableKeyboardNavigation) { this.enable(); } else { this.disable(); } if (typeof options.automaticKeyboardNavigation !== 'undefined') { this.automaticKeyboardNavigation = options.automaticKeyboardNavigation; } } toggle(): void { this.triggered = !this.triggered; } private enable(): void { if (this.enabled) { return; } const onChar = Event.chain(domEvent(this.view.domNode, 'keydown')) .filter(e => !isInputElement(e.target as HTMLElement)) .filter(() => this.automaticKeyboardNavigation || this.triggered) .map(event => new StandardKeyboardEvent(event)) .filter(e => this.delegate.mightProducePrintableCharacter(e)) .forEach(e => { e.stopPropagation(); e.preventDefault(); }) .map(event => event.browserEvent.key) .event; const onClear = Event.debounce<string, null>(onChar, () => null, 800); const onInput = Event.reduce<string | null, string | null>(Event.any(onChar, onClear), (r, i) => i === null ? null : ((r || '') + i)); onInput(this.onInput, this, this.enabledDisposables); this.enabled = true; this.triggered = false; } private disable(): void { if (!this.enabled) { return; } this.enabledDisposables.clear(); this.enabled = false; this.triggered = false; } private onInput(word: string | null): void { if (!word) { this.state = TypeLabelControllerState.Idle; this.triggered = false; return; } const focus = this.list.getFocus(); const start = focus.length > 0 ? focus[0] : 0; const delta = this.state === TypeLabelControllerState.Idle ? 1 : 0; this.state = TypeLabelControllerState.Typing; for (let i = 0; i < this.list.length; i++) { const index = (start + i + delta) % this.list.length; const label = this.keyboardNavigationLabelProvider.getKeyboardNavigationLabel(this.view.element(index)); const labelStr = label && label.toString(); if (typeof labelStr === 'undefined' || matchesPrefix(word, labelStr)) { this.list.setFocus([index]); this.list.reveal(index); return; } } } dispose() { this.disable(); this.enabledDisposables.dispose(); this.disposables.dispose(); } } class DOMFocusController<T> implements IDisposable { private readonly disposables = new DisposableStore(); constructor( private list: List<T>, private view: ListView<T> ) { const onKeyDown = Event.chain(domEvent(view.domNode, 'keydown')) .filter(e => !isInputElement(e.target as HTMLElement)) .map(e => new StandardKeyboardEvent(e)); onKeyDown.filter(e => e.keyCode === KeyCode.Tab && !e.ctrlKey && !e.metaKey && !e.shiftKey && !e.altKey) .on(this.onTab, this, this.disposables); } private onTab(e: StandardKeyboardEvent): void { if (e.target !== this.view.domNode) { return; } const focus = this.list.getFocus(); if (focus.length === 0) { return; } const focusedDomElement = this.view.domElement(focus[0]); if (!focusedDomElement) { return; } const tabIndexElement = focusedDomElement.querySelector('[tabIndex]'); if (!tabIndexElement || !(tabIndexElement instanceof HTMLElement) || tabIndexElement.tabIndex === -1) { return; } const style = window.getComputedStyle(tabIndexElement); if (style.visibility === 'hidden' || style.display === 'none') { return; } e.preventDefault(); e.stopPropagation(); tabIndexElement.focus(); } dispose() { this.disposables.dispose(); } } export function isSelectionSingleChangeEvent(event: IListMouseEvent<any> | IListTouchEvent<any>): boolean { return platform.isMacintosh ? event.browserEvent.metaKey : event.browserEvent.ctrlKey; } export function isSelectionRangeChangeEvent(event: IListMouseEvent<any> | IListTouchEvent<any>): boolean { return event.browserEvent.shiftKey; } function isMouseRightClick(event: UIEvent): boolean { return event instanceof MouseEvent && event.button === 2; } const DefaultMultipleSelectionController = { isSelectionSingleChangeEvent, isSelectionRangeChangeEvent }; const DefaultOpenController: IOpenController = { shouldOpen: (event: UIEvent) => { if (event instanceof MouseEvent) { return !isMouseRightClick(event); } return true; } }; export class MouseController<T> implements IDisposable { private multipleSelectionSupport: boolean; readonly multipleSelectionController: IMultipleSelectionController<T> | undefined; private openController: IOpenController; private mouseSupport: boolean; private readonly disposables = new DisposableStore(); constructor(protected list: List<T>) { this.multipleSelectionSupport = !(list.options.multipleSelectionSupport === false); if (this.multipleSelectionSupport) { this.multipleSelectionController = list.options.multipleSelectionController || DefaultMultipleSelectionController; } this.openController = list.options.openController || DefaultOpenController; this.mouseSupport = typeof list.options.mouseSupport === 'undefined' || !!list.options.mouseSupport; if (this.mouseSupport) { list.onMouseDown(this.onMouseDown, this, this.disposables); list.onContextMenu(this.onContextMenu, this, this.disposables); list.onMouseDblClick(this.onDoubleClick, this, this.disposables); list.onTouchStart(this.onMouseDown, this, this.disposables); this.disposables.add(Gesture.addTarget(list.getHTMLElement())); } list.onMouseClick(this.onPointer, this, this.disposables); list.onMouseMiddleClick(this.onPointer, this, this.disposables); list.onTap(this.onPointer, this, this.disposables); } protected isSelectionSingleChangeEvent(event: IListMouseEvent<any> | IListTouchEvent<any>): boolean { if (this.multipleSelectionController) { return this.multipleSelectionController.isSelectionSingleChangeEvent(event); } return platform.isMacintosh ? event.browserEvent.metaKey : event.browserEvent.ctrlKey; } protected isSelectionRangeChangeEvent(event: IListMouseEvent<any> | IListTouchEvent<any>): boolean { if (this.multipleSelectionController) { return this.multipleSelectionController.isSelectionRangeChangeEvent(event); } return event.browserEvent.shiftKey; } private isSelectionChangeEvent(event: IListMouseEvent<any> | IListTouchEvent<any>): boolean { return this.isSelectionSingleChangeEvent(event) || this.isSelectionRangeChangeEvent(event); } private onMouseDown(e: IListMouseEvent<T> | IListTouchEvent<T>): void { if (document.activeElement !== e.browserEvent.target) { this.list.domFocus(); } } private onContextMenu(e: IListContextMenuEvent<T>): void { const focus = typeof e.index === 'undefined' ? [] : [e.index]; this.list.setFocus(focus, e.browserEvent); } protected onPointer(e: IListMouseEvent<T>): void { if (!this.mouseSupport) { return; } if (isInputElement(e.browserEvent.target as HTMLElement)) { return; } let reference = this.list.getFocus()[0]; const selection = this.list.getSelection(); reference = reference === undefined ? selection[0] : reference; const focus = e.index; if (typeof focus === 'undefined') { this.list.setFocus([], e.browserEvent); this.list.setSelection([], e.browserEvent); return; } if (this.multipleSelectionSupport && this.isSelectionRangeChangeEvent(e)) { return this.changeSelection(e, reference); } if (this.multipleSelectionSupport && this.isSelectionChangeEvent(e)) { return this.changeSelection(e, reference); } this.list.setFocus([focus], e.browserEvent); if (!isMouseRightClick(e.browserEvent)) { this.list.setSelection([focus], e.browserEvent); if (this.openController.shouldOpen(e.browserEvent)) { this.list.open([focus], e.browserEvent); } } } protected onDoubleClick(e: IListMouseEvent<T>): void { if (isInputElement(e.browserEvent.target as HTMLElement)) { return; } if (this.multipleSelectionSupport && this.isSelectionChangeEvent(e)) { return; } const focus = this.list.getFocus(); this.list.setSelection(focus, e.browserEvent); this.list.pin(focus); } private changeSelection(e: IListMouseEvent<T> | IListTouchEvent<T>, reference: number | undefined): void { const focus = e.index!; if (this.isSelectionRangeChangeEvent(e) && reference !== undefined) { const min = Math.min(reference, focus); const max = Math.max(reference, focus); const rangeSelection = range(min, max + 1); const selection = this.list.getSelection(); const contiguousRange = getContiguousRangeContaining(disjunction(selection, [reference]), reference); if (contiguousRange.length === 0) { return; } const newSelection = disjunction(rangeSelection, relativeComplement(selection, contiguousRange)); this.list.setSelection(newSelection, e.browserEvent); } else if (this.isSelectionSingleChangeEvent(e)) { const selection = this.list.getSelection(); const newSelection = selection.filter(i => i !== focus); this.list.setFocus([focus]); if (selection.length === newSelection.length) { this.list.setSelection([...newSelection, focus], e.browserEvent); } else { this.list.setSelection(newSelection, e.browserEvent); } } } dispose() { this.disposables.dispose(); } } export interface IMultipleSelectionController<T> { isSelectionSingleChangeEvent(event: IListMouseEvent<T> | IListTouchEvent<T>): boolean; isSelectionRangeChangeEvent(event: IListMouseEvent<T> | IListTouchEvent<T>): boolean; } export interface IOpenController { shouldOpen(event: UIEvent): boolean; } export interface IStyleController { style(styles: IListStyles): void; } export interface IAccessibilityProvider<T> { /** * Given an element in the tree, return the ARIA label that should be associated with the * item. This helps screen readers to provide a meaningful label for the currently focused * tree element. * * Returning null will not disable ARIA for the element. Instead it is up to the screen reader * to compute a meaningful label based on the contents of the element in the DOM * * See also: https://www.w3.org/TR/wai-aria/#aria-label */ getAriaLabel(element: T): string | null; /** * https://www.w3.org/TR/wai-aria/#aria-level */ getAriaLevel?(element: T): number | undefined; onDidChangeActiveDescendant?: Event<void>; getActiveDescendantId?(element: T): string | undefined; } export class DefaultStyleController implements IStyleController { constructor(private styleElement: HTMLStyleElement, private selectorSuffix: string) { } style(styles: IListStyles): void { const suffix = this.selectorSuffix && `.${this.selectorSuffix}`; const content: string[] = []; if (styles.listBackground) { if (styles.listBackground.isOpaque()) { content.push(`.monaco-list${suffix} .monaco-list-rows { background: ${styles.listBackground}; }`); } else if (!platform.isMacintosh) { // subpixel AA doesn't exist in macOS console.warn(`List with id '${this.selectorSuffix}' was styled with a non-opaque background color. This will break sub-pixel antialiasing.`); } } if (styles.listFocusBackground) { content.push(`.monaco-list${suffix}:focus .monaco-list-row.focused { background-color: ${styles.listFocusBackground}; }`); content.push(`.monaco-list${suffix}:focus .monaco-list-row.focused:hover { background-color: ${styles.listFocusBackground}; }`); // overwrite :hover style in this case! } if (styles.listFocusForeground) { content.push(`.monaco-list${suffix}:focus .monaco-list-row.focused { color: ${styles.listFocusForeground}; }`); } if (styles.listActiveSelectionBackground) { content.push(`.monaco-list${suffix}:focus .monaco-list-row.selected { background-color: ${styles.listActiveSelectionBackground}; }`); content.push(`.monaco-list${suffix}:focus .monaco-list-row.selected:hover { background-color: ${styles.listActiveSelectionBackground}; }`); // overwrite :hover style in this case! } if (styles.listActiveSelectionForeground) { content.push(`.monaco-list${suffix}:focus .monaco-list-row.selected { color: ${styles.listActiveSelectionForeground}; }`); } if (styles.listFocusAndSelectionBackground) { content.push(` .monaco-drag-image, .monaco-list${suffix}:focus .monaco-list-row.selected.focused { background-color: ${styles.listFocusAndSelectionBackground}; } `); } if (styles.listFocusAndSelectionForeground) { content.push(` .monaco-drag-image, .monaco-list${suffix}:focus .monaco-list-row.selected.focused { color: ${styles.listFocusAndSelectionForeground}; } `); } if (styles.listInactiveFocusBackground) { content.push(`.monaco-list${suffix} .monaco-list-row.focused { background-color: ${styles.listInactiveFocusBackground}; }`); content.push(`.monaco-list${suffix} .monaco-list-row.focused:hover { background-color: ${styles.listInactiveFocusBackground}; }`); // overwrite :hover style in this case! } if (styles.listInactiveSelectionBackground) { content.push(`.monaco-list${suffix} .monaco-list-row.selected { background-color: ${styles.listInactiveSelectionBackground}; }`); content.push(`.monaco-list${suffix} .monaco-list-row.selected:hover { background-color: ${styles.listInactiveSelectionBackground}; }`); // overwrite :hover style in this case! } if (styles.listInactiveSelectionForeground) { content.push(`.monaco-list${suffix} .monaco-list-row.selected { color: ${styles.listInactiveSelectionForeground}; }`); } if (styles.listHoverBackground) { content.push(`.monaco-list${suffix}:not(.drop-target) .monaco-list-row:hover:not(.selected):not(.focused) { background-color: ${styles.listHoverBackground}; }`); } if (styles.listHoverForeground) { content.push(`.monaco-list${suffix} .monaco-list-row:hover:not(.selected):not(.focused) { color: ${styles.listHoverForeground}; }`); } if (styles.listSelectionOutline) { content.push(`.monaco-list${suffix} .monaco-list-row.selected { outline: 1px dotted ${styles.listSelectionOutline}; outline-offset: -1px; }`); } if (styles.listFocusOutline) { content.push(` .monaco-drag-image, .monaco-list${suffix}:focus .monaco-list-row.focused { outline: 1px solid ${styles.listFocusOutline}; outline-offset: -1px; } `); } if (styles.listInactiveFocusOutline) { content.push(`.monaco-list${suffix} .monaco-list-row.focused { outline: 1px dotted ${styles.listInactiveFocusOutline}; outline-offset: -1px; }`); } if (styles.listHoverOutline) { content.push(`.monaco-list${suffix} .monaco-list-row:hover { outline: 1px dashed ${styles.listHoverOutline}; outline-offset: -1px; }`); } if (styles.listDropBackground) { content.push(` .monaco-list${suffix}.drop-target, .monaco-list${suffix} .monaco-list-rows.drop-target, .monaco-list${suffix} .monaco-list-row.drop-target { background-color: ${styles.listDropBackground} !important; color: inherit !important; } `); } if (styles.listFilterWidgetBackground) { content.push(`.monaco-list-type-filter { background-color: ${styles.listFilterWidgetBackground} }`); } if (styles.listFilterWidgetOutline) { content.push(`.monaco-list-type-filter { border: 1px solid ${styles.listFilterWidgetOutline}; }`); } if (styles.listFilterWidgetNoMatchesOutline) { content.push(`.monaco-list-type-filter.no-matches { border: 1px solid ${styles.listFilterWidgetNoMatchesOutline}; }`); } if (styles.listMatchesShadow) { content.push(`.monaco-list-type-filter { box-shadow: 1px 1px 1px ${styles.listMatchesShadow}; }`); } const newStyles = content.join('\n'); if (newStyles !== this.styleElement.innerHTML) { this.styleElement.innerHTML = newStyles; } } } export interface IListOptions<T> { readonly identityProvider?: IIdentityProvider<T>; readonly dnd?: IListDragAndDrop<T>; readonly enableKeyboardNavigation?: boolean; readonly automaticKeyboardNavigation?: boolean; readonly keyboardNavigationLabelProvider?: IKeyboardNavigationLabelProvider<T>; readonly keyboardNavigationDelegate?: IKeyboardNavigationDelegate; readonly ariaRole?: ListAriaRootRole | string; readonly ariaLabel?: string; readonly keyboardSupport?: boolean; readonly multipleSelectionSupport?: boolean; readonly multipleSelectionController?: IMultipleSelectionController<T>; readonly openController?: IOpenController; readonly styleController?: (suffix: string) => IStyleController; readonly accessibilityProvider?: IAccessibilityProvider<T>; // list view options readonly useShadows?: boolean; readonly verticalScrollMode?: ScrollbarVisibility; readonly setRowLineHeight?: boolean; readonly setRowHeight?: boolean; readonly supportDynamicHeights?: boolean; readonly mouseSupport?: boolean; readonly horizontalScrolling?: boolean; readonly ariaProvider?: IAriaProvider<T>; } export interface IListStyles { listBackground?: Color; listFocusBackground?: Color; listFocusForeground?: Color; listActiveSelectionBackground?: Color; listActiveSelectionForeground?: Color; listFocusAndSelectionBackground?: Color; listFocusAndSelectionForeground?: Color; listInactiveSelectionBackground?: Color; listInactiveSelectionForeground?: Color; listInactiveFocusBackground?: Color; listHoverBackground?: Color; listHoverForeground?: Color; listDropBackground?: Color; listFocusOutline?: Color; listInactiveFocusOutline?: Color; listSelectionOutline?: Color; listHoverOutline?: Color; listFilterWidgetBackground?: Color; listFilterWidgetOutline?: Color; listFilterWidgetNoMatchesOutline?: Color; listMatchesShadow?: Color; treeIndentGuidesStroke?: Color; } const defaultStyles: IListStyles = { listFocusBackground: Color.fromHex('#7FB0D0'), listActiveSelectionBackground: Color.fromHex('#0E639C'), listActiveSelectionForeground: Color.fromHex('#FFFFFF'), listFocusAndSelectionBackground: Color.fromHex('#094771'), listFocusAndSelectionForeground: Color.fromHex('#FFFFFF'), listInactiveSelectionBackground: Color.fromHex('#3F3F46'), listHoverBackground: Color.fromHex('#2A2D2E'), listDropBackground: Color.fromHex('#383B3D'), treeIndentGuidesStroke: Color.fromHex('#a9a9a9') }; const DefaultOptions = { keyboardSupport: true, mouseSupport: true, multipleSelectionSupport: true, dnd: { getDragURI() { return null; }, onDragStart(): void { }, onDragOver() { return false; }, drop() { } }, ariaRootRole: ListAriaRootRole.TREE }; // TODO@Joao: move these utils into a SortedArray class function getContiguousRangeContaining(range: number[], value: number): number[] { const index = range.indexOf(value); if (index === -1) { return []; } const result: number[] = []; let i = index - 1; while (i >= 0 && range[i] === value - (index - i)) { result.push(range[i--]); } result.reverse(); i = index; while (i < range.length && range[i] === value + (i - index)) { result.push(range[i++]); } return result; } /** * Given two sorted collections of numbers, returns the intersection * between them (OR). */ function disjunction(one: number[], other: number[]): number[] { const result: number[] = []; let i = 0, j = 0; while (i < one.length || j < other.length) { if (i >= one.length) { result.push(other[j++]); } else if (j >= other.length) { result.push(one[i++]); } else if (one[i] === other[j]) { result.push(one[i]); i++; j++; continue; } else if (one[i] < other[j]) { result.push(one[i++]); } else { result.push(other[j++]); } } return result; } /** * Given two sorted collections of numbers, returns the relative * complement between them (XOR). */ function relativeComplement(one: number[], other: number[]): number[] { const result: number[] = []; let i = 0, j = 0; while (i < one.length || j < other.length) { if (i >= one.length) { result.push(other[j++]); } else if (j >= other.length) { result.push(one[i++]); } else if (one[i] === other[j]) { i++; j++; continue; } else if (one[i] < other[j]) { result.push(one[i++]); } else { j++; } } return result; } const numericSort = (a: number, b: number) => a - b; class PipelineRenderer<T> implements IListRenderer<T, any> { constructor( private _templateId: string, private renderers: IListRenderer<any /* TODO@joao */, any>[] ) { } get templateId(): string { return this._templateId; } renderTemplate(container: HTMLElement): any[] { return this.renderers.map(r => r.renderTemplate(container)); } renderElement(element: T, index: number, templateData: any[], height: number | undefined): void { let i = 0; for (const renderer of this.renderers) { renderer.renderElement(element, index, templateData[i++], height); } } disposeElement(element: T, index: number, templateData: any[], height: number | undefined): void { let i = 0; for (const renderer of this.renderers) { if (renderer.disposeElement) { renderer.disposeElement(element, index, templateData[i], height); } i += 1; } } disposeTemplate(templateData: any[]): void { let i = 0; for (const renderer of this.renderers) { renderer.disposeTemplate(templateData[i++]); } } } class AccessibiltyRenderer<T> implements IListRenderer<T, HTMLElement> { templateId: string = 'a18n'; constructor(private accessibilityProvider: IAccessibilityProvider<T>) { } renderTemplate(container: HTMLElement): HTMLElement { return container; } renderElement(element: T, index: number, container: HTMLElement): void { const ariaLabel = this.accessibilityProvider.getAriaLabel(element); if (ariaLabel) { container.setAttribute('aria-label', ariaLabel); } else { container.removeAttribute('aria-label'); } const ariaLevel = this.accessibilityProvider.getAriaLevel && this.accessibilityProvider.getAriaLevel(element); if (typeof ariaLevel === 'number') { container.setAttribute('aria-level', `${ariaLevel}`); } else { container.removeAttribute('aria-level'); } } disposeTemplate(templateData: any): void { // noop } } class ListViewDragAndDrop<T> implements IListViewDragAndDrop<T> { constructor(private list: List<T>, private dnd: IListDragAndDrop<T>) { } getDragElements(element: T): T[] { const selection = this.list.getSelectedElements(); const elements = selection.indexOf(element) > -1 ? selection : [element]; return elements; } getDragURI(element: T): string | null { return this.dnd.getDragURI(element); } getDragLabel?(elements: T[], originalEvent: DragEvent): string | undefined { if (this.dnd.getDragLabel) { return this.dnd.getDragLabel(elements, originalEvent); } return undefined; } onDragStart(data: IDragAndDropData, originalEvent: DragEvent): void { if (this.dnd.onDragStart) { this.dnd.onDragStart(data, originalEvent); } } onDragOver(data: IDragAndDropData, targetElement: T, targetIndex: number, originalEvent: DragEvent): boolean | IListDragOverReaction { return this.dnd.onDragOver(data, targetElement, targetIndex, originalEvent); } onDragEnd(originalEvent: DragEvent): void { if (this.dnd.onDragEnd) { this.dnd.onDragEnd(originalEvent); } } drop(data: IDragAndDropData, targetElement: T, targetIndex: number, originalEvent: DragEvent): void { this.dnd.drop(data, targetElement, targetIndex, originalEvent); } } export interface IListOptionsUpdate { readonly enableKeyboardNavigation?: boolean; readonly automaticKeyboardNavigation?: boolean; } export class List<T> implements ISpliceable<T>, IDisposable { private focus: Trait<T>; private selection: Trait<T>; private eventBufferer = new EventBufferer(); protected view: ListView<T>; private spliceable: ISpliceable<T>; private styleController: IStyleController; private typeLabelController?: TypeLabelController<T>; private accessibilityProvider?: IAccessibilityProvider<T>; protected readonly disposables = new DisposableStore(); @memoize get onDidChangeFocus(): Event<IListEvent<T>> { return Event.map(this.eventBufferer.wrapEvent(this.focus.onChange), e => this.toListEvent(e)); } @memoize get onDidChangeSelection(): Event<IListEvent<T>> { return Event.map(this.eventBufferer.wrapEvent(this.selection.onChange), e => this.toListEvent(e)); } private readonly _onDidOpen = new Emitter<IListEvent<T>>(); readonly onDidOpen: Event<IListEvent<T>> = this._onDidOpen.event; private readonly _onDidPin = new Emitter<IListEvent<T>>(); readonly onDidPin: Event<IListEvent<T>> = this._onDidPin.event; get domId(): string { return this.view.domId; } get onDidScroll(): Event<ScrollEvent> { return this.view.onDidScroll; } get onMouseClick(): Event<IListMouseEvent<T>> { return this.view.onMouseClick; } get onMouseDblClick(): Event<IListMouseEvent<T>> { return this.view.onMouseDblClick; } get onMouseMiddleClick(): Event<IListMouseEvent<T>> { return this.view.onMouseMiddleClick; } get onMouseUp(): Event<IListMouseEvent<T>> { return this.view.onMouseUp; } get onMouseDown(): Event<IListMouseEvent<T>> { return this.view.onMouseDown; } get onMouseOver(): Event<IListMouseEvent<T>> { return this.view.onMouseOver; } get onMouseMove(): Event<IListMouseEvent<T>> { return this.view.onMouseMove; } get onMouseOut(): Event<IListMouseEvent<T>> { return this.view.onMouseOut; } get onTouchStart(): Event<IListTouchEvent<T>> { return this.view.onTouchStart; } get onTap(): Event<IListGestureEvent<T>> { return this.view.onTap; } private didJustPressContextMenuKey: boolean = false; @memoize get onContextMenu(): Event<IListContextMenuEvent<T>> { const fromKeydown = Event.chain(domEvent(this.view.domNode, 'keydown')) .map(e => new StandardKeyboardEvent(e)) .filter(e => this.didJustPressContextMenuKey = e.keyCode === KeyCode.ContextMenu || (e.shiftKey && e.keyCode === KeyCode.F10)) .filter(e => { e.preventDefault(); e.stopPropagation(); return false; }) .event as Event<any>; const fromKeyup = Event.chain(domEvent(this.view.domNode, 'keyup')) .filter(() => { const didJustPressContextMenuKey = this.didJustPressContextMenuKey; this.didJustPressContextMenuKey = false; return didJustPressContextMenuKey; }) .filter(() => this.getFocus().length > 0 && !!this.view.domElement(this.getFocus()[0])) .map(browserEvent => { const index = this.getFocus()[0]; const element = this.view.element(index); const anchor = this.view.domElement(index) as HTMLElement; return { index, element, anchor, browserEvent }; }) .event; const fromMouse = Event.chain(this.view.onContextMenu) .filter(() => !this.didJustPressContextMenuKey) .map(({ element, index, browserEvent }) => ({ element, index, anchor: { x: browserEvent.clientX + 1, y: browserEvent.clientY }, browserEvent })) .event; return Event.any<IListContextMenuEvent<T>>(fromKeydown, fromKeyup, fromMouse); } get onKeyDown(): Event<KeyboardEvent> { return domEvent(this.view.domNode, 'keydown'); } get onKeyUp(): Event<KeyboardEvent> { return domEvent(this.view.domNode, 'keyup'); } get onKeyPress(): Event<KeyboardEvent> { return domEvent(this.view.domNode, 'keypress'); } readonly onDidFocus: Event<void>; readonly onDidBlur: Event<void>; private readonly _onDidDispose = new Emitter<void>(); readonly onDidDispose: Event<void> = this._onDidDispose.event; constructor( private user: string, container: HTMLElement, virtualDelegate: IListVirtualDelegate<T>, renderers: IListRenderer<any /* TODO@joao */, any>[], private _options: IListOptions<T> = DefaultOptions ) { this.focus = new Trait('focused'); this.selection = new SelectionTrait(); mixin(_options, defaultStyles, false); const baseRenderers: IListRenderer<T, ITraitTemplateData>[] = [this.focus.renderer, this.selection.renderer]; this.accessibilityProvider = _options.accessibilityProvider; if (this.accessibilityProvider) { baseRenderers.push(new AccessibiltyRenderer<T>(this.accessibilityProvider)); if (this.accessibilityProvider.onDidChangeActiveDescendant) { this.accessibilityProvider.onDidChangeActiveDescendant(this.onDidChangeActiveDescendant, this, this.disposables); } } renderers = renderers.map(r => new PipelineRenderer(r.templateId, [...baseRenderers, r])); const viewOptions: IListViewOptions<T> = { ..._options, dnd: _options.dnd && new ListViewDragAndDrop(this, _options.dnd) }; this.view = new ListView(container, virtualDelegate, renderers, viewOptions); if (typeof _options.ariaRole !== 'string') { this.view.domNode.setAttribute('role', ListAriaRootRole.TREE); } else { this.view.domNode.setAttribute('role', _options.ariaRole); } if (_options.styleController) { this.styleController = _options.styleController(this.view.domId); } else { const styleElement = DOM.createStyleSheet(this.view.domNode); this.styleController = new DefaultStyleController(styleElement, this.view.domId); } this.spliceable = new CombinedSpliceable([ new TraitSpliceable(this.focus, this.view, _options.identityProvider), new TraitSpliceable(this.selection, this.view, _options.identityProvider), this.view ]); this.disposables.add(this.focus); this.disposables.add(this.selection); this.disposables.add(this.view); this.disposables.add(this._onDidDispose); this.onDidFocus = Event.map(domEvent(this.view.domNode, 'focus', true), () => null!); this.onDidBlur = Event.map(domEvent(this.view.domNode, 'blur', true), () => null!); this.disposables.add(new DOMFocusController(this, this.view)); if (typeof _options.keyboardSupport !== 'boolean' || _options.keyboardSupport) { const controller = new KeyboardController(this, this.view, _options); this.disposables.add(controller); } if (_options.keyboardNavigationLabelProvider) { const delegate = _options.keyboardNavigationDelegate || DefaultKeyboardNavigationDelegate; this.typeLabelController = new TypeLabelController(this, this.view, _options.keyboardNavigationLabelProvider, delegate); this.disposables.add(this.typeLabelController); } this.disposables.add(this.createMouseController(_options)); this.onDidChangeFocus(this._onFocusChange, this, this.disposables); this.onDidChangeSelection(this._onSelectionChange, this, this.disposables); if (_options.ariaLabel) { this.view.domNode.setAttribute('aria-label', localize('aria list', "{0}. Use the navigation keys to navigate.", _options.ariaLabel)); } if (_options.multipleSelectionSupport) { this.view.domNode.setAttribute('aria-multiselectable', 'true'); } } protected createMouseController(options: IListOptions<T>): MouseController<T> { return new MouseController(this); } updateOptions(optionsUpdate: IListOptionsUpdate = {}): void { this._options = { ...this._options, ...optionsUpdate }; if (this.typeLabelController) { this.typeLabelController.updateOptions(this._options); } } get options(): IListOptions<T> { return this._options; } splice(start: number, deleteCount: number, elements: T[] = []): void { if (start < 0 || start > this.view.length) { throw new ListError(this.user, `Invalid start index: ${start}`); } if (deleteCount < 0) { throw new ListError(this.user, `Invalid delete count: ${deleteCount}`); } if (deleteCount === 0 && elements.length === 0) { return; } this.eventBufferer.bufferEvents(() => this.spliceable.splice(start, deleteCount, elements)); } updateWidth(index: number): void { this.view.updateWidth(index); } updateElementHeight(index: number, size: number): void { this.view.updateElementHeight(index, size); } rerender(): void { this.view.rerender(); } element(index: number): T { return this.view.element(index); } get length(): number { return this.view.length; } get contentHeight(): number { return this.view.contentHeight; } get onDidChangeContentHeight(): Event<number> { return this.view.onDidChangeContentHeight; } get scrollTop(): number { return this.view.getScrollTop(); } set scrollTop(scrollTop: number) { this.view.setScrollTop(scrollTop); } get scrollLeft(): number { return this.view.getScrollLeft(); } set scrollLeft(scrollLeft: number) { this.view.setScrollLeft(scrollLeft); } get scrollHeight(): number { return this.view.scrollHeight; } get renderHeight(): number { return this.view.renderHeight; } get firstVisibleIndex(): number { return this.view.firstVisibleIndex; } get lastVisibleIndex(): number { return this.view.lastVisibleIndex; } domFocus(): void { this.view.domNode.focus(); } layout(height?: number, width?: number): void { this.view.layout(height, width); } toggleKeyboardNavigation(): void { if (this.typeLabelController) { this.typeLabelController.toggle(); } } setSelection(indexes: number[], browserEvent?: UIEvent): void { for (const index of indexes) { if (index < 0 || index >= this.length) { throw new ListError(this.user, `Invalid index ${index}`); } } this.selection.set(indexes, browserEvent); } getSelection(): number[] { return this.selection.get(); } getSelectedElements(): T[] { return this.getSelection().map(i => this.view.element(i)); } setFocus(indexes: number[], browserEvent?: UIEvent): void { for (const index of indexes) { if (index < 0 || index >= this.length) { throw new ListError(this.user, `Invalid index ${index}`); } } this.focus.set(indexes, browserEvent); } focusNext(n = 1, loop = false, browserEvent?: UIEvent, filter?: (element: T) => boolean): void { if (this.length === 0) { return; } const focus = this.focus.get(); const index = this.findNextIndex(focus.length > 0 ? focus[0] + n : 0, loop, filter); if (index > -1) { this.setFocus([index], browserEvent); } } focusPrevious(n = 1, loop = false, browserEvent?: UIEvent, filter?: (element: T) => boolean): void { if (this.length === 0) { return; } const focus = this.focus.get(); const index = this.findPreviousIndex(focus.length > 0 ? focus[0] - n : 0, loop, filter); if (index > -1) { this.setFocus([index], browserEvent); } } focusNextPage(browserEvent?: UIEvent, filter?: (element: T) => boolean): void { let lastPageIndex = this.view.indexAt(this.view.getScrollTop() + this.view.renderHeight); lastPageIndex = lastPageIndex === 0 ? 0 : lastPageIndex - 1; const lastPageElement = this.view.element(lastPageIndex); const currentlyFocusedElement = this.getFocusedElements()[0]; if (currentlyFocusedElement !== lastPageElement) { const lastGoodPageIndex = this.findPreviousIndex(lastPageIndex, false, filter); if (lastGoodPageIndex > -1 && currentlyFocusedElement !== this.view.element(lastGoodPageIndex)) { this.setFocus([lastGoodPageIndex], browserEvent); } else { this.setFocus([lastPageIndex], browserEvent); } } else { const previousScrollTop = this.view.getScrollTop(); this.view.setScrollTop(previousScrollTop + this.view.renderHeight - this.view.elementHeight(lastPageIndex)); if (this.view.getScrollTop() !== previousScrollTop) { // Let the scroll event listener run setTimeout(() => this.focusNextPage(browserEvent, filter), 0); } } } focusPreviousPage(browserEvent?: UIEvent, filter?: (element: T) => boolean): void { let firstPageIndex: number; const scrollTop = this.view.getScrollTop(); if (scrollTop === 0) { firstPageIndex = this.view.indexAt(scrollTop); } else { firstPageIndex = this.view.indexAfter(scrollTop - 1); } const firstPageElement = this.view.element(firstPageIndex); const currentlyFocusedElement = this.getFocusedElements()[0]; if (currentlyFocusedElement !== firstPageElement) { const firstGoodPageIndex = this.findNextIndex(firstPageIndex, false, filter); if (firstGoodPageIndex > -1 && currentlyFocusedElement !== this.view.element(firstGoodPageIndex)) { this.setFocus([firstGoodPageIndex], browserEvent); } else { this.setFocus([firstPageIndex], browserEvent); } } else { const previousScrollTop = scrollTop; this.view.setScrollTop(scrollTop - this.view.renderHeight); if (this.view.getScrollTop() !== previousScrollTop) { // Let the scroll event listener run setTimeout(() => this.focusPreviousPage(browserEvent, filter), 0); } } } focusLast(browserEvent?: UIEvent, filter?: (element: T) => boolean): void { if (this.length === 0) { return; } const index = this.findPreviousIndex(this.length - 1, false, filter); if (index > -1) { this.setFocus([index], browserEvent); } } focusFirst(browserEvent?: UIEvent, filter?: (element: T) => boolean): void { if (this.length === 0) { return; } const index = this.findNextIndex(0, false, filter); if (index > -1) { this.setFocus([index], browserEvent); } } private findNextIndex(index: number, loop = false, filter?: (element: T) => boolean): number { for (let i = 0; i < this.length; i++) { if (index >= this.length && !loop) { return -1; } index = index % this.length; if (!filter || filter(this.element(index))) { return index; } index++; } return -1; } private findPreviousIndex(index: number, loop = false, filter?: (element: T) => boolean): number { for (let i = 0; i < this.length; i++) { if (index < 0 && !loop) { return -1; } index = (this.length + (index % this.length)) % this.length; if (!filter || filter(this.element(index))) { return index; } index--; } return -1; } getFocus(): number[] { return this.focus.get(); } getFocusedElements(): T[] { return this.getFocus().map(i => this.view.element(i)); } reveal(index: number, relativeTop?: number): void { if (index < 0 || index >= this.length) { throw new ListError(this.user, `Invalid index ${index}`); } const scrollTop = this.view.getScrollTop(); const elementTop = this.view.elementTop(index); const elementHeight = this.view.elementHeight(index); if (isNumber(relativeTop)) { // y = mx + b const m = elementHeight - this.view.renderHeight; this.view.setScrollTop(m * clamp(relativeTop, 0, 1) + elementTop); } else { const viewItemBottom = elementTop + elementHeight; const wrapperBottom = scrollTop + this.view.renderHeight; if (elementTop < scrollTop && viewItemBottom >= wrapperBottom) { // The element is already overflowing the viewport, no-op } else if (elementTop < scrollTop) { this.view.setScrollTop(elementTop); } else if (viewItemBottom >= wrapperBottom) { this.view.setScrollTop(viewItemBottom - this.view.renderHeight); } } } /** * Returns the relative position of an element rendered in the list. * Returns `null` if the element isn't *entirely* in the visible viewport. */ getRelativeTop(index: number): number | null { if (index < 0 || index >= this.length) { throw new ListError(this.user, `Invalid index ${index}`); } const scrollTop = this.view.getScrollTop(); const elementTop = this.view.elementTop(index); const elementHeight = this.view.elementHeight(index); if (elementTop < scrollTop || elementTop + elementHeight > scrollTop + this.view.renderHeight) { return null; } // y = mx + b const m = elementHeight - this.view.renderHeight; return Math.abs((scrollTop - elementTop) / m); } isDOMFocused(): boolean { return this.view.domNode === document.activeElement; } getHTMLElement(): HTMLElement { return this.view.domNode; } open(indexes: number[], browserEvent?: UIEvent): void { for (const index of indexes) { if (index < 0 || index >= this.length) { throw new ListError(this.user, `Invalid index ${index}`); } } this._onDidOpen.fire({ indexes, elements: indexes.map(i => this.view.element(i)), browserEvent }); } pin(indexes: number[], browserEvent?: UIEvent): void { for (const index of indexes) { if (index < 0 || index >= this.length) { throw new ListError(this.user, `Invalid index ${index}`); } } this._onDidPin.fire({ indexes, elements: indexes.map(i => this.view.element(i)), browserEvent }); } style(styles: IListStyles): void { this.styleController.style(styles); } private toListEvent({ indexes, browserEvent }: ITraitChangeEvent) { return { indexes, elements: indexes.map(i => this.view.element(i)), browserEvent }; } private _onFocusChange(): void { const focus = this.focus.get(); DOM.toggleClass(this.view.domNode, 'element-focused', focus.length > 0); this.onDidChangeActiveDescendant(); } private onDidChangeActiveDescendant(): void { const focus = this.focus.get(); if (focus.length > 0) { let id: string | undefined; if (this.accessibilityProvider?.getActiveDescendantId) { id = this.accessibilityProvider.getActiveDescendantId(this.view.element(focus[0])); } this.view.domNode.setAttribute('aria-activedescendant', id || this.view.getElementDomId(focus[0])); } else { this.view.domNode.removeAttribute('aria-activedescendant'); } } private _onSelectionChange(): void { const selection = this.selection.get(); DOM.toggleClass(this.view.domNode, 'selection-none', selection.length === 0); DOM.toggleClass(this.view.domNode, 'selection-single', selection.length === 1); DOM.toggleClass(this.view.domNode, 'selection-multiple', selection.length > 1); } dispose(): void { this._onDidDispose.fire(); this.disposables.dispose(); this._onDidOpen.dispose(); this._onDidPin.dispose(); this._onDidDispose.dispose(); } }
src/vs/base/browser/ui/list/listWidget.ts
1
https://github.com/microsoft/vscode/commit/7aca51e3d98c58ee8e418df6b525930d90375d9f
[ 0.9962069988250732, 0.03664163872599602, 0.00016304470773320645, 0.00017354711599182338, 0.17999319732189178 ]
{ "id": 2, "code_window": [ "\trenderIndex(index: number, container: HTMLElement): void {\n", "\t\tsuper.renderIndex(index, container);\n", "\n", "\t\tif (this.contains(index)) {\n", "\t\t\tcontainer.setAttribute('aria-selected', 'true');\n", "\t\t} else {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ "\t\tif (this.contains(index) || this.isAriaSelected(index)) {\n" ], "file_path": "src/vs/base/browser/ui/list/listWidget.ts", "type": "replace", "edit_start_line_idx": 191 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { CancellationToken } from 'vs/base/common/cancellation'; import * as pfs from 'vs/base/node/pfs'; import { IFileMatch, IProgressMessage, ITextQuery, ITextSearchStats, ITextSearchMatch, ISerializedFileMatch, ISerializedSearchSuccess } from 'vs/workbench/services/search/common/search'; import { RipgrepTextSearchEngine } from 'vs/workbench/services/search/node/ripgrepTextSearchEngine'; import { NativeTextSearchManager } from 'vs/workbench/services/search/node/textSearchManager'; export class TextSearchEngineAdapter { constructor(private query: ITextQuery) { } search(token: CancellationToken, onResult: (matches: ISerializedFileMatch[]) => void, onMessage: (message: IProgressMessage) => void): Promise<ISerializedSearchSuccess> { if ((!this.query.folderQueries || !this.query.folderQueries.length) && (!this.query.extraFileResources || !this.query.extraFileResources.length)) { return Promise.resolve(<ISerializedSearchSuccess>{ type: 'success', limitHit: false, stats: <ITextSearchStats>{ type: 'searchProcess' } }); } const pretendOutputChannel = { appendLine(msg: string) { onMessage({ message: msg }); } }; const textSearchManager = new NativeTextSearchManager(this.query, new RipgrepTextSearchEngine(pretendOutputChannel), pfs); return new Promise((resolve, reject) => { return textSearchManager .search( matches => { onResult(matches.map(fileMatchToSerialized)); }, token) .then( c => resolve({ limitHit: c.limitHit, type: 'success' } as ISerializedSearchSuccess), reject); }); } } function fileMatchToSerialized(match: IFileMatch): ISerializedFileMatch { return { path: match.resource && match.resource.fsPath, results: match.results, numMatches: (match.results || []).reduce((sum, r) => { if (!!(<ITextSearchMatch>r).ranges) { const m = <ITextSearchMatch>r; return sum + (Array.isArray(m.ranges) ? m.ranges.length : 1); } else { return sum + 1; } }, 0) }; }
src/vs/workbench/services/search/node/textSearchAdapter.ts
0
https://github.com/microsoft/vscode/commit/7aca51e3d98c58ee8e418df6b525930d90375d9f
[ 0.0001758060825522989, 0.00017144477169495076, 0.00016599018999841064, 0.00017106662562582642, 0.000002896501882787561 ]
{ "id": 2, "code_window": [ "\trenderIndex(index: number, container: HTMLElement): void {\n", "\t\tsuper.renderIndex(index, container);\n", "\n", "\t\tif (this.contains(index)) {\n", "\t\t\tcontainer.setAttribute('aria-selected', 'true');\n", "\t\t} else {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ "\t\tif (this.contains(index) || this.isAriaSelected(index)) {\n" ], "file_path": "src/vs/base/browser/ui/list/listWidget.ts", "type": "replace", "edit_start_line_idx": 191 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import * as cp from 'child_process'; let tag = ''; try { tag = cp .execSync('git describe --tags `git rev-list --tags --max-count=1`') .toString() .trim(); if (!isValidTag(tag)) { throw Error(`Invalid tag ${tag}`); } } catch (err) { console.error(err); console.error('Failed to update types'); process.exit(1); } function isValidTag(t: string) { if (t.split('.').length !== 3) { return false; } const [major, minor, bug] = t.split('.'); // Only release for tags like 1.34.0 if (bug !== '0') { return false; } if (isNaN(parseInt(major, 10)) || isNaN(parseInt(minor, 10))) { return false; } return true; }
build/azure-pipelines/publish-types/check-version.ts
0
https://github.com/microsoft/vscode/commit/7aca51e3d98c58ee8e418df6b525930d90375d9f
[ 0.00017561056301929057, 0.00017296777514275163, 0.0001715234393486753, 0.00017236336134374142, 0.0000015338758885263815 ]
{ "id": 2, "code_window": [ "\trenderIndex(index: number, container: HTMLElement): void {\n", "\t\tsuper.renderIndex(index, container);\n", "\n", "\t\tif (this.contains(index)) {\n", "\t\t\tcontainer.setAttribute('aria-selected', 'true');\n", "\t\t} else {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ "\t\tif (this.contains(index) || this.isAriaSelected(index)) {\n" ], "file_path": "src/vs/base/browser/ui/list/listWidget.ts", "type": "replace", "edit_start_line_idx": 191 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Disposable, DisposableStore } from 'vs/base/common/lifecycle'; import { URI } from 'vs/base/common/uri'; import { Event, Emitter } from 'vs/base/common/event'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; import { IRange } from 'vs/editor/common/core/range'; import { CursorChangeReason, ICursorPositionChangedEvent } from 'vs/editor/common/controller/cursorEvents'; import { ModelDecorationOptions } from 'vs/editor/common/model/textModel'; import { ICodeEditor } from 'vs/editor/browser/editorBrowser'; import { TrackedRangeStickiness, IModelDecorationsChangeAccessor } from 'vs/editor/common/model'; export interface IRangeHighlightDecoration { resource: URI; range: IRange; isWholeLine?: boolean; } export class RangeHighlightDecorations extends Disposable { private rangeHighlightDecorationId: string | null = null; private editor: ICodeEditor | null = null; private readonly editorDisposables = this._register(new DisposableStore()); private readonly _onHighlightRemoved: Emitter<void> = this._register(new Emitter<void>()); readonly onHighlightRemoved: Event<void> = this._onHighlightRemoved.event; constructor(@IEditorService private readonly editorService: IEditorService) { super(); } removeHighlightRange() { if (this.editor && this.editor.getModel() && this.rangeHighlightDecorationId) { this.editor.deltaDecorations([this.rangeHighlightDecorationId], []); this._onHighlightRemoved.fire(); } this.rangeHighlightDecorationId = null; } highlightRange(range: IRangeHighlightDecoration, editor?: ICodeEditor) { editor = editor ? editor : this.getEditor(range); if (editor) { this.doHighlightRange(editor, range); } } private doHighlightRange(editor: ICodeEditor, selectionRange: IRangeHighlightDecoration) { this.removeHighlightRange(); editor.changeDecorations((changeAccessor: IModelDecorationsChangeAccessor) => { this.rangeHighlightDecorationId = changeAccessor.addDecoration(selectionRange.range, this.createRangeHighlightDecoration(selectionRange.isWholeLine)); }); this.setEditor(editor); } private getEditor(resourceRange: IRangeHighlightDecoration): ICodeEditor | undefined { const activeEditor = this.editorService.activeEditor; const resource = activeEditor && activeEditor.resource; if (resource) { if (resource.toString() === resourceRange.resource.toString()) { return this.editorService.activeTextEditorControl as ICodeEditor; } } return undefined; } private setEditor(editor: ICodeEditor) { if (this.editor !== editor) { this.editorDisposables.clear(); this.editor = editor; this.editorDisposables.add(this.editor.onDidChangeCursorPosition((e: ICursorPositionChangedEvent) => { if ( e.reason === CursorChangeReason.NotSet || e.reason === CursorChangeReason.Explicit || e.reason === CursorChangeReason.Undo || e.reason === CursorChangeReason.Redo ) { this.removeHighlightRange(); } })); this.editorDisposables.add(this.editor.onDidChangeModel(() => { this.removeHighlightRange(); })); this.editorDisposables.add(this.editor.onDidDispose(() => { this.removeHighlightRange(); this.editor = null; })); } } private static readonly _WHOLE_LINE_RANGE_HIGHLIGHT = ModelDecorationOptions.register({ stickiness: TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges, className: 'rangeHighlight', isWholeLine: true }); private static readonly _RANGE_HIGHLIGHT = ModelDecorationOptions.register({ stickiness: TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges, className: 'rangeHighlight' }); private createRangeHighlightDecoration(isWholeLine: boolean = true): ModelDecorationOptions { return (isWholeLine ? RangeHighlightDecorations._WHOLE_LINE_RANGE_HIGHLIGHT : RangeHighlightDecorations._RANGE_HIGHLIGHT); } dispose() { super.dispose(); if (this.editor && this.editor.getModel()) { this.removeHighlightRange(); this.editor = null; } } }
src/vs/workbench/browser/parts/editor/rangeDecorations.ts
0
https://github.com/microsoft/vscode/commit/7aca51e3d98c58ee8e418df6b525930d90375d9f
[ 0.00024285349354613572, 0.00017458245565649122, 0.00016276542737614363, 0.00016957850311882794, 0.000020909299564664252 ]
{ "id": 3, "code_window": [ "\t\t\tcontainer.setAttribute('aria-selected', 'true');\n", "\t\t} else {\n", "\t\t\tcontainer.removeAttribute('aria-selected');\n", "\t\t}\n", "\t}\n", "}\n", "\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tcontainer.setAttribute('aria-selected', 'false');\n" ], "file_path": "src/vs/base/browser/ui/list/listWidget.ts", "type": "replace", "edit_start_line_idx": 194 }
/*--------------------------------------------------------------------------------------------- * 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!./list'; import { localize } from 'vs/nls'; import { IDisposable, dispose, DisposableStore } from 'vs/base/common/lifecycle'; import { isNumber } from 'vs/base/common/types'; import { range, firstIndex, binarySearch } from 'vs/base/common/arrays'; import { memoize } from 'vs/base/common/decorators'; import * as DOM from 'vs/base/browser/dom'; import * as platform from 'vs/base/common/platform'; import { Gesture } from 'vs/base/browser/touch'; import { KeyCode } from 'vs/base/common/keyCodes'; import { StandardKeyboardEvent, IKeyboardEvent } from 'vs/base/browser/keyboardEvent'; import { Event, Emitter, EventBufferer } from 'vs/base/common/event'; import { domEvent } from 'vs/base/browser/event'; import { IListVirtualDelegate, IListRenderer, IListEvent, IListContextMenuEvent, IListMouseEvent, IListTouchEvent, IListGestureEvent, IIdentityProvider, IKeyboardNavigationLabelProvider, IListDragAndDrop, IListDragOverReaction, ListAriaRootRole, ListError, IKeyboardNavigationDelegate } from './list'; import { ListView, IListViewOptions, IListViewDragAndDrop, IAriaProvider } from './listView'; import { Color } from 'vs/base/common/color'; import { mixin } from 'vs/base/common/objects'; import { ScrollbarVisibility, ScrollEvent } from 'vs/base/common/scrollable'; import { ISpliceable } from 'vs/base/common/sequence'; import { CombinedSpliceable } from 'vs/base/browser/ui/list/splice'; import { clamp } from 'vs/base/common/numbers'; import { matchesPrefix } from 'vs/base/common/filters'; import { IDragAndDropData } from 'vs/base/browser/dnd'; interface ITraitChangeEvent { indexes: number[]; browserEvent?: UIEvent; } type ITraitTemplateData = HTMLElement; interface IRenderedContainer { templateData: ITraitTemplateData; index: number; } class TraitRenderer<T> implements IListRenderer<T, ITraitTemplateData> { private renderedElements: IRenderedContainer[] = []; constructor(private trait: Trait<T>) { } get templateId(): string { return `template:${this.trait.trait}`; } renderTemplate(container: HTMLElement): ITraitTemplateData { return container; } renderElement(element: T, index: number, templateData: ITraitTemplateData): void { const renderedElementIndex = firstIndex(this.renderedElements, el => el.templateData === templateData); if (renderedElementIndex >= 0) { const rendered = this.renderedElements[renderedElementIndex]; this.trait.unrender(templateData); rendered.index = index; } else { const rendered = { index, templateData }; this.renderedElements.push(rendered); } this.trait.renderIndex(index, templateData); } splice(start: number, deleteCount: number, insertCount: number): void { const rendered: IRenderedContainer[] = []; for (const renderedElement of this.renderedElements) { if (renderedElement.index < start) { rendered.push(renderedElement); } else if (renderedElement.index >= start + deleteCount) { rendered.push({ index: renderedElement.index + insertCount - deleteCount, templateData: renderedElement.templateData }); } } this.renderedElements = rendered; } renderIndexes(indexes: number[]): void { for (const { index, templateData } of this.renderedElements) { if (indexes.indexOf(index) > -1) { this.trait.renderIndex(index, templateData); } } } disposeTemplate(templateData: ITraitTemplateData): void { const index = firstIndex(this.renderedElements, el => el.templateData === templateData); if (index < 0) { return; } this.renderedElements.splice(index, 1); } } class Trait<T> implements ISpliceable<boolean>, IDisposable { private indexes: number[] = []; private sortedIndexes: number[] = []; private readonly _onChange = new Emitter<ITraitChangeEvent>(); readonly onChange: Event<ITraitChangeEvent> = this._onChange.event; get trait(): string { return this._trait; } @memoize get renderer(): TraitRenderer<T> { return new TraitRenderer<T>(this); } constructor(private _trait: string) { } splice(start: number, deleteCount: number, elements: boolean[]): void { const diff = elements.length - deleteCount; const end = start + deleteCount; const indexes = [ ...this.sortedIndexes.filter(i => i < start), ...elements.map((hasTrait, i) => hasTrait ? i + start : -1).filter(i => i !== -1), ...this.sortedIndexes.filter(i => i >= end).map(i => i + diff) ]; this.renderer.splice(start, deleteCount, elements.length); this._set(indexes, indexes); } renderIndex(index: number, container: HTMLElement): void { DOM.toggleClass(container, this._trait, this.contains(index)); } unrender(container: HTMLElement): void { DOM.removeClass(container, this._trait); } /** * Sets the indexes which should have this trait. * * @param indexes Indexes which should have this trait. * @return The old indexes which had this trait. */ set(indexes: number[], browserEvent?: UIEvent): number[] { return this._set(indexes, [...indexes].sort(numericSort), browserEvent); } private _set(indexes: number[], sortedIndexes: number[], browserEvent?: UIEvent): number[] { const result = this.indexes; const sortedResult = this.sortedIndexes; this.indexes = indexes; this.sortedIndexes = sortedIndexes; const toRender = disjunction(sortedResult, indexes); this.renderer.renderIndexes(toRender); this._onChange.fire({ indexes, browserEvent }); return result; } get(): number[] { return this.indexes; } contains(index: number): boolean { return binarySearch(this.sortedIndexes, index, numericSort) >= 0; } dispose() { dispose(this._onChange); } } class SelectionTrait<T> extends Trait<T> { constructor() { super('selected'); } renderIndex(index: number, container: HTMLElement): void { super.renderIndex(index, container); if (this.contains(index)) { container.setAttribute('aria-selected', 'true'); } else { container.removeAttribute('aria-selected'); } } } /** * The TraitSpliceable is used as a util class to be able * to preserve traits across splice calls, given an identity * provider. */ class TraitSpliceable<T> implements ISpliceable<T> { constructor( private trait: Trait<T>, private view: ListView<T>, private identityProvider?: IIdentityProvider<T> ) { } splice(start: number, deleteCount: number, elements: T[]): void { if (!this.identityProvider) { return this.trait.splice(start, deleteCount, elements.map(() => false)); } const pastElementsWithTrait = this.trait.get().map(i => this.identityProvider!.getId(this.view.element(i)).toString()); const elementsWithTrait = elements.map(e => pastElementsWithTrait.indexOf(this.identityProvider!.getId(e).toString()) > -1); this.trait.splice(start, deleteCount, elementsWithTrait); } } function isInputElement(e: HTMLElement): boolean { return e.tagName === 'INPUT' || e.tagName === 'TEXTAREA'; } class KeyboardController<T> implements IDisposable { private readonly disposables = new DisposableStore(); private openController: IOpenController; constructor( private list: List<T>, private view: ListView<T>, options: IListOptions<T> ) { const multipleSelectionSupport = options.multipleSelectionSupport !== false; this.openController = options.openController || DefaultOpenController; const onKeyDown = Event.chain(domEvent(view.domNode, 'keydown')) .filter(e => !isInputElement(e.target as HTMLElement)) .map(e => new StandardKeyboardEvent(e)); onKeyDown.filter(e => e.keyCode === KeyCode.Enter).on(this.onEnter, this, this.disposables); onKeyDown.filter(e => e.keyCode === KeyCode.UpArrow).on(this.onUpArrow, this, this.disposables); onKeyDown.filter(e => e.keyCode === KeyCode.DownArrow).on(this.onDownArrow, this, this.disposables); onKeyDown.filter(e => e.keyCode === KeyCode.PageUp).on(this.onPageUpArrow, this, this.disposables); onKeyDown.filter(e => e.keyCode === KeyCode.PageDown).on(this.onPageDownArrow, this, this.disposables); onKeyDown.filter(e => e.keyCode === KeyCode.Escape).on(this.onEscape, this, this.disposables); if (multipleSelectionSupport) { onKeyDown.filter(e => (platform.isMacintosh ? e.metaKey : e.ctrlKey) && e.keyCode === KeyCode.KEY_A).on(this.onCtrlA, this, this.disposables); } } private onEnter(e: StandardKeyboardEvent): void { e.preventDefault(); e.stopPropagation(); this.list.setSelection(this.list.getFocus(), e.browserEvent); if (this.openController.shouldOpen(e.browserEvent)) { this.list.open(this.list.getFocus(), e.browserEvent); } } private onUpArrow(e: StandardKeyboardEvent): void { e.preventDefault(); e.stopPropagation(); this.list.focusPrevious(1, false, e.browserEvent); this.list.reveal(this.list.getFocus()[0]); this.view.domNode.focus(); } private onDownArrow(e: StandardKeyboardEvent): void { e.preventDefault(); e.stopPropagation(); this.list.focusNext(1, false, e.browserEvent); this.list.reveal(this.list.getFocus()[0]); this.view.domNode.focus(); } private onPageUpArrow(e: StandardKeyboardEvent): void { e.preventDefault(); e.stopPropagation(); this.list.focusPreviousPage(e.browserEvent); this.list.reveal(this.list.getFocus()[0]); this.view.domNode.focus(); } private onPageDownArrow(e: StandardKeyboardEvent): void { e.preventDefault(); e.stopPropagation(); this.list.focusNextPage(e.browserEvent); this.list.reveal(this.list.getFocus()[0]); this.view.domNode.focus(); } private onCtrlA(e: StandardKeyboardEvent): void { e.preventDefault(); e.stopPropagation(); this.list.setSelection(range(this.list.length), e.browserEvent); this.view.domNode.focus(); } private onEscape(e: StandardKeyboardEvent): void { e.preventDefault(); e.stopPropagation(); this.list.setSelection([], e.browserEvent); this.view.domNode.focus(); } dispose() { this.disposables.dispose(); } } enum TypeLabelControllerState { Idle, Typing } export const DefaultKeyboardNavigationDelegate = new class implements IKeyboardNavigationDelegate { mightProducePrintableCharacter(event: IKeyboardEvent): boolean { if (event.ctrlKey || event.metaKey || event.altKey) { return false; } return (event.keyCode >= KeyCode.KEY_A && event.keyCode <= KeyCode.KEY_Z) || (event.keyCode >= KeyCode.KEY_0 && event.keyCode <= KeyCode.KEY_9) || (event.keyCode >= KeyCode.NUMPAD_0 && event.keyCode <= KeyCode.NUMPAD_9) || (event.keyCode >= KeyCode.US_SEMICOLON && event.keyCode <= KeyCode.US_QUOTE); } }; class TypeLabelController<T> implements IDisposable { private enabled = false; private state: TypeLabelControllerState = TypeLabelControllerState.Idle; private automaticKeyboardNavigation = true; private triggered = false; private readonly enabledDisposables = new DisposableStore(); private readonly disposables = new DisposableStore(); constructor( private list: List<T>, private view: ListView<T>, private keyboardNavigationLabelProvider: IKeyboardNavigationLabelProvider<T>, private delegate: IKeyboardNavigationDelegate ) { this.updateOptions(list.options); } updateOptions(options: IListOptions<T>): void { const enableKeyboardNavigation = typeof options.enableKeyboardNavigation === 'undefined' ? true : !!options.enableKeyboardNavigation; if (enableKeyboardNavigation) { this.enable(); } else { this.disable(); } if (typeof options.automaticKeyboardNavigation !== 'undefined') { this.automaticKeyboardNavigation = options.automaticKeyboardNavigation; } } toggle(): void { this.triggered = !this.triggered; } private enable(): void { if (this.enabled) { return; } const onChar = Event.chain(domEvent(this.view.domNode, 'keydown')) .filter(e => !isInputElement(e.target as HTMLElement)) .filter(() => this.automaticKeyboardNavigation || this.triggered) .map(event => new StandardKeyboardEvent(event)) .filter(e => this.delegate.mightProducePrintableCharacter(e)) .forEach(e => { e.stopPropagation(); e.preventDefault(); }) .map(event => event.browserEvent.key) .event; const onClear = Event.debounce<string, null>(onChar, () => null, 800); const onInput = Event.reduce<string | null, string | null>(Event.any(onChar, onClear), (r, i) => i === null ? null : ((r || '') + i)); onInput(this.onInput, this, this.enabledDisposables); this.enabled = true; this.triggered = false; } private disable(): void { if (!this.enabled) { return; } this.enabledDisposables.clear(); this.enabled = false; this.triggered = false; } private onInput(word: string | null): void { if (!word) { this.state = TypeLabelControllerState.Idle; this.triggered = false; return; } const focus = this.list.getFocus(); const start = focus.length > 0 ? focus[0] : 0; const delta = this.state === TypeLabelControllerState.Idle ? 1 : 0; this.state = TypeLabelControllerState.Typing; for (let i = 0; i < this.list.length; i++) { const index = (start + i + delta) % this.list.length; const label = this.keyboardNavigationLabelProvider.getKeyboardNavigationLabel(this.view.element(index)); const labelStr = label && label.toString(); if (typeof labelStr === 'undefined' || matchesPrefix(word, labelStr)) { this.list.setFocus([index]); this.list.reveal(index); return; } } } dispose() { this.disable(); this.enabledDisposables.dispose(); this.disposables.dispose(); } } class DOMFocusController<T> implements IDisposable { private readonly disposables = new DisposableStore(); constructor( private list: List<T>, private view: ListView<T> ) { const onKeyDown = Event.chain(domEvent(view.domNode, 'keydown')) .filter(e => !isInputElement(e.target as HTMLElement)) .map(e => new StandardKeyboardEvent(e)); onKeyDown.filter(e => e.keyCode === KeyCode.Tab && !e.ctrlKey && !e.metaKey && !e.shiftKey && !e.altKey) .on(this.onTab, this, this.disposables); } private onTab(e: StandardKeyboardEvent): void { if (e.target !== this.view.domNode) { return; } const focus = this.list.getFocus(); if (focus.length === 0) { return; } const focusedDomElement = this.view.domElement(focus[0]); if (!focusedDomElement) { return; } const tabIndexElement = focusedDomElement.querySelector('[tabIndex]'); if (!tabIndexElement || !(tabIndexElement instanceof HTMLElement) || tabIndexElement.tabIndex === -1) { return; } const style = window.getComputedStyle(tabIndexElement); if (style.visibility === 'hidden' || style.display === 'none') { return; } e.preventDefault(); e.stopPropagation(); tabIndexElement.focus(); } dispose() { this.disposables.dispose(); } } export function isSelectionSingleChangeEvent(event: IListMouseEvent<any> | IListTouchEvent<any>): boolean { return platform.isMacintosh ? event.browserEvent.metaKey : event.browserEvent.ctrlKey; } export function isSelectionRangeChangeEvent(event: IListMouseEvent<any> | IListTouchEvent<any>): boolean { return event.browserEvent.shiftKey; } function isMouseRightClick(event: UIEvent): boolean { return event instanceof MouseEvent && event.button === 2; } const DefaultMultipleSelectionController = { isSelectionSingleChangeEvent, isSelectionRangeChangeEvent }; const DefaultOpenController: IOpenController = { shouldOpen: (event: UIEvent) => { if (event instanceof MouseEvent) { return !isMouseRightClick(event); } return true; } }; export class MouseController<T> implements IDisposable { private multipleSelectionSupport: boolean; readonly multipleSelectionController: IMultipleSelectionController<T> | undefined; private openController: IOpenController; private mouseSupport: boolean; private readonly disposables = new DisposableStore(); constructor(protected list: List<T>) { this.multipleSelectionSupport = !(list.options.multipleSelectionSupport === false); if (this.multipleSelectionSupport) { this.multipleSelectionController = list.options.multipleSelectionController || DefaultMultipleSelectionController; } this.openController = list.options.openController || DefaultOpenController; this.mouseSupport = typeof list.options.mouseSupport === 'undefined' || !!list.options.mouseSupport; if (this.mouseSupport) { list.onMouseDown(this.onMouseDown, this, this.disposables); list.onContextMenu(this.onContextMenu, this, this.disposables); list.onMouseDblClick(this.onDoubleClick, this, this.disposables); list.onTouchStart(this.onMouseDown, this, this.disposables); this.disposables.add(Gesture.addTarget(list.getHTMLElement())); } list.onMouseClick(this.onPointer, this, this.disposables); list.onMouseMiddleClick(this.onPointer, this, this.disposables); list.onTap(this.onPointer, this, this.disposables); } protected isSelectionSingleChangeEvent(event: IListMouseEvent<any> | IListTouchEvent<any>): boolean { if (this.multipleSelectionController) { return this.multipleSelectionController.isSelectionSingleChangeEvent(event); } return platform.isMacintosh ? event.browserEvent.metaKey : event.browserEvent.ctrlKey; } protected isSelectionRangeChangeEvent(event: IListMouseEvent<any> | IListTouchEvent<any>): boolean { if (this.multipleSelectionController) { return this.multipleSelectionController.isSelectionRangeChangeEvent(event); } return event.browserEvent.shiftKey; } private isSelectionChangeEvent(event: IListMouseEvent<any> | IListTouchEvent<any>): boolean { return this.isSelectionSingleChangeEvent(event) || this.isSelectionRangeChangeEvent(event); } private onMouseDown(e: IListMouseEvent<T> | IListTouchEvent<T>): void { if (document.activeElement !== e.browserEvent.target) { this.list.domFocus(); } } private onContextMenu(e: IListContextMenuEvent<T>): void { const focus = typeof e.index === 'undefined' ? [] : [e.index]; this.list.setFocus(focus, e.browserEvent); } protected onPointer(e: IListMouseEvent<T>): void { if (!this.mouseSupport) { return; } if (isInputElement(e.browserEvent.target as HTMLElement)) { return; } let reference = this.list.getFocus()[0]; const selection = this.list.getSelection(); reference = reference === undefined ? selection[0] : reference; const focus = e.index; if (typeof focus === 'undefined') { this.list.setFocus([], e.browserEvent); this.list.setSelection([], e.browserEvent); return; } if (this.multipleSelectionSupport && this.isSelectionRangeChangeEvent(e)) { return this.changeSelection(e, reference); } if (this.multipleSelectionSupport && this.isSelectionChangeEvent(e)) { return this.changeSelection(e, reference); } this.list.setFocus([focus], e.browserEvent); if (!isMouseRightClick(e.browserEvent)) { this.list.setSelection([focus], e.browserEvent); if (this.openController.shouldOpen(e.browserEvent)) { this.list.open([focus], e.browserEvent); } } } protected onDoubleClick(e: IListMouseEvent<T>): void { if (isInputElement(e.browserEvent.target as HTMLElement)) { return; } if (this.multipleSelectionSupport && this.isSelectionChangeEvent(e)) { return; } const focus = this.list.getFocus(); this.list.setSelection(focus, e.browserEvent); this.list.pin(focus); } private changeSelection(e: IListMouseEvent<T> | IListTouchEvent<T>, reference: number | undefined): void { const focus = e.index!; if (this.isSelectionRangeChangeEvent(e) && reference !== undefined) { const min = Math.min(reference, focus); const max = Math.max(reference, focus); const rangeSelection = range(min, max + 1); const selection = this.list.getSelection(); const contiguousRange = getContiguousRangeContaining(disjunction(selection, [reference]), reference); if (contiguousRange.length === 0) { return; } const newSelection = disjunction(rangeSelection, relativeComplement(selection, contiguousRange)); this.list.setSelection(newSelection, e.browserEvent); } else if (this.isSelectionSingleChangeEvent(e)) { const selection = this.list.getSelection(); const newSelection = selection.filter(i => i !== focus); this.list.setFocus([focus]); if (selection.length === newSelection.length) { this.list.setSelection([...newSelection, focus], e.browserEvent); } else { this.list.setSelection(newSelection, e.browserEvent); } } } dispose() { this.disposables.dispose(); } } export interface IMultipleSelectionController<T> { isSelectionSingleChangeEvent(event: IListMouseEvent<T> | IListTouchEvent<T>): boolean; isSelectionRangeChangeEvent(event: IListMouseEvent<T> | IListTouchEvent<T>): boolean; } export interface IOpenController { shouldOpen(event: UIEvent): boolean; } export interface IStyleController { style(styles: IListStyles): void; } export interface IAccessibilityProvider<T> { /** * Given an element in the tree, return the ARIA label that should be associated with the * item. This helps screen readers to provide a meaningful label for the currently focused * tree element. * * Returning null will not disable ARIA for the element. Instead it is up to the screen reader * to compute a meaningful label based on the contents of the element in the DOM * * See also: https://www.w3.org/TR/wai-aria/#aria-label */ getAriaLabel(element: T): string | null; /** * https://www.w3.org/TR/wai-aria/#aria-level */ getAriaLevel?(element: T): number | undefined; onDidChangeActiveDescendant?: Event<void>; getActiveDescendantId?(element: T): string | undefined; } export class DefaultStyleController implements IStyleController { constructor(private styleElement: HTMLStyleElement, private selectorSuffix: string) { } style(styles: IListStyles): void { const suffix = this.selectorSuffix && `.${this.selectorSuffix}`; const content: string[] = []; if (styles.listBackground) { if (styles.listBackground.isOpaque()) { content.push(`.monaco-list${suffix} .monaco-list-rows { background: ${styles.listBackground}; }`); } else if (!platform.isMacintosh) { // subpixel AA doesn't exist in macOS console.warn(`List with id '${this.selectorSuffix}' was styled with a non-opaque background color. This will break sub-pixel antialiasing.`); } } if (styles.listFocusBackground) { content.push(`.monaco-list${suffix}:focus .monaco-list-row.focused { background-color: ${styles.listFocusBackground}; }`); content.push(`.monaco-list${suffix}:focus .monaco-list-row.focused:hover { background-color: ${styles.listFocusBackground}; }`); // overwrite :hover style in this case! } if (styles.listFocusForeground) { content.push(`.monaco-list${suffix}:focus .monaco-list-row.focused { color: ${styles.listFocusForeground}; }`); } if (styles.listActiveSelectionBackground) { content.push(`.monaco-list${suffix}:focus .monaco-list-row.selected { background-color: ${styles.listActiveSelectionBackground}; }`); content.push(`.monaco-list${suffix}:focus .monaco-list-row.selected:hover { background-color: ${styles.listActiveSelectionBackground}; }`); // overwrite :hover style in this case! } if (styles.listActiveSelectionForeground) { content.push(`.monaco-list${suffix}:focus .monaco-list-row.selected { color: ${styles.listActiveSelectionForeground}; }`); } if (styles.listFocusAndSelectionBackground) { content.push(` .monaco-drag-image, .monaco-list${suffix}:focus .monaco-list-row.selected.focused { background-color: ${styles.listFocusAndSelectionBackground}; } `); } if (styles.listFocusAndSelectionForeground) { content.push(` .monaco-drag-image, .monaco-list${suffix}:focus .monaco-list-row.selected.focused { color: ${styles.listFocusAndSelectionForeground}; } `); } if (styles.listInactiveFocusBackground) { content.push(`.monaco-list${suffix} .monaco-list-row.focused { background-color: ${styles.listInactiveFocusBackground}; }`); content.push(`.monaco-list${suffix} .monaco-list-row.focused:hover { background-color: ${styles.listInactiveFocusBackground}; }`); // overwrite :hover style in this case! } if (styles.listInactiveSelectionBackground) { content.push(`.monaco-list${suffix} .monaco-list-row.selected { background-color: ${styles.listInactiveSelectionBackground}; }`); content.push(`.monaco-list${suffix} .monaco-list-row.selected:hover { background-color: ${styles.listInactiveSelectionBackground}; }`); // overwrite :hover style in this case! } if (styles.listInactiveSelectionForeground) { content.push(`.monaco-list${suffix} .monaco-list-row.selected { color: ${styles.listInactiveSelectionForeground}; }`); } if (styles.listHoverBackground) { content.push(`.monaco-list${suffix}:not(.drop-target) .monaco-list-row:hover:not(.selected):not(.focused) { background-color: ${styles.listHoverBackground}; }`); } if (styles.listHoverForeground) { content.push(`.monaco-list${suffix} .monaco-list-row:hover:not(.selected):not(.focused) { color: ${styles.listHoverForeground}; }`); } if (styles.listSelectionOutline) { content.push(`.monaco-list${suffix} .monaco-list-row.selected { outline: 1px dotted ${styles.listSelectionOutline}; outline-offset: -1px; }`); } if (styles.listFocusOutline) { content.push(` .monaco-drag-image, .monaco-list${suffix}:focus .monaco-list-row.focused { outline: 1px solid ${styles.listFocusOutline}; outline-offset: -1px; } `); } if (styles.listInactiveFocusOutline) { content.push(`.monaco-list${suffix} .monaco-list-row.focused { outline: 1px dotted ${styles.listInactiveFocusOutline}; outline-offset: -1px; }`); } if (styles.listHoverOutline) { content.push(`.monaco-list${suffix} .monaco-list-row:hover { outline: 1px dashed ${styles.listHoverOutline}; outline-offset: -1px; }`); } if (styles.listDropBackground) { content.push(` .monaco-list${suffix}.drop-target, .monaco-list${suffix} .monaco-list-rows.drop-target, .monaco-list${suffix} .monaco-list-row.drop-target { background-color: ${styles.listDropBackground} !important; color: inherit !important; } `); } if (styles.listFilterWidgetBackground) { content.push(`.monaco-list-type-filter { background-color: ${styles.listFilterWidgetBackground} }`); } if (styles.listFilterWidgetOutline) { content.push(`.monaco-list-type-filter { border: 1px solid ${styles.listFilterWidgetOutline}; }`); } if (styles.listFilterWidgetNoMatchesOutline) { content.push(`.monaco-list-type-filter.no-matches { border: 1px solid ${styles.listFilterWidgetNoMatchesOutline}; }`); } if (styles.listMatchesShadow) { content.push(`.monaco-list-type-filter { box-shadow: 1px 1px 1px ${styles.listMatchesShadow}; }`); } const newStyles = content.join('\n'); if (newStyles !== this.styleElement.innerHTML) { this.styleElement.innerHTML = newStyles; } } } export interface IListOptions<T> { readonly identityProvider?: IIdentityProvider<T>; readonly dnd?: IListDragAndDrop<T>; readonly enableKeyboardNavigation?: boolean; readonly automaticKeyboardNavigation?: boolean; readonly keyboardNavigationLabelProvider?: IKeyboardNavigationLabelProvider<T>; readonly keyboardNavigationDelegate?: IKeyboardNavigationDelegate; readonly ariaRole?: ListAriaRootRole | string; readonly ariaLabel?: string; readonly keyboardSupport?: boolean; readonly multipleSelectionSupport?: boolean; readonly multipleSelectionController?: IMultipleSelectionController<T>; readonly openController?: IOpenController; readonly styleController?: (suffix: string) => IStyleController; readonly accessibilityProvider?: IAccessibilityProvider<T>; // list view options readonly useShadows?: boolean; readonly verticalScrollMode?: ScrollbarVisibility; readonly setRowLineHeight?: boolean; readonly setRowHeight?: boolean; readonly supportDynamicHeights?: boolean; readonly mouseSupport?: boolean; readonly horizontalScrolling?: boolean; readonly ariaProvider?: IAriaProvider<T>; } export interface IListStyles { listBackground?: Color; listFocusBackground?: Color; listFocusForeground?: Color; listActiveSelectionBackground?: Color; listActiveSelectionForeground?: Color; listFocusAndSelectionBackground?: Color; listFocusAndSelectionForeground?: Color; listInactiveSelectionBackground?: Color; listInactiveSelectionForeground?: Color; listInactiveFocusBackground?: Color; listHoverBackground?: Color; listHoverForeground?: Color; listDropBackground?: Color; listFocusOutline?: Color; listInactiveFocusOutline?: Color; listSelectionOutline?: Color; listHoverOutline?: Color; listFilterWidgetBackground?: Color; listFilterWidgetOutline?: Color; listFilterWidgetNoMatchesOutline?: Color; listMatchesShadow?: Color; treeIndentGuidesStroke?: Color; } const defaultStyles: IListStyles = { listFocusBackground: Color.fromHex('#7FB0D0'), listActiveSelectionBackground: Color.fromHex('#0E639C'), listActiveSelectionForeground: Color.fromHex('#FFFFFF'), listFocusAndSelectionBackground: Color.fromHex('#094771'), listFocusAndSelectionForeground: Color.fromHex('#FFFFFF'), listInactiveSelectionBackground: Color.fromHex('#3F3F46'), listHoverBackground: Color.fromHex('#2A2D2E'), listDropBackground: Color.fromHex('#383B3D'), treeIndentGuidesStroke: Color.fromHex('#a9a9a9') }; const DefaultOptions = { keyboardSupport: true, mouseSupport: true, multipleSelectionSupport: true, dnd: { getDragURI() { return null; }, onDragStart(): void { }, onDragOver() { return false; }, drop() { } }, ariaRootRole: ListAriaRootRole.TREE }; // TODO@Joao: move these utils into a SortedArray class function getContiguousRangeContaining(range: number[], value: number): number[] { const index = range.indexOf(value); if (index === -1) { return []; } const result: number[] = []; let i = index - 1; while (i >= 0 && range[i] === value - (index - i)) { result.push(range[i--]); } result.reverse(); i = index; while (i < range.length && range[i] === value + (i - index)) { result.push(range[i++]); } return result; } /** * Given two sorted collections of numbers, returns the intersection * between them (OR). */ function disjunction(one: number[], other: number[]): number[] { const result: number[] = []; let i = 0, j = 0; while (i < one.length || j < other.length) { if (i >= one.length) { result.push(other[j++]); } else if (j >= other.length) { result.push(one[i++]); } else if (one[i] === other[j]) { result.push(one[i]); i++; j++; continue; } else if (one[i] < other[j]) { result.push(one[i++]); } else { result.push(other[j++]); } } return result; } /** * Given two sorted collections of numbers, returns the relative * complement between them (XOR). */ function relativeComplement(one: number[], other: number[]): number[] { const result: number[] = []; let i = 0, j = 0; while (i < one.length || j < other.length) { if (i >= one.length) { result.push(other[j++]); } else if (j >= other.length) { result.push(one[i++]); } else if (one[i] === other[j]) { i++; j++; continue; } else if (one[i] < other[j]) { result.push(one[i++]); } else { j++; } } return result; } const numericSort = (a: number, b: number) => a - b; class PipelineRenderer<T> implements IListRenderer<T, any> { constructor( private _templateId: string, private renderers: IListRenderer<any /* TODO@joao */, any>[] ) { } get templateId(): string { return this._templateId; } renderTemplate(container: HTMLElement): any[] { return this.renderers.map(r => r.renderTemplate(container)); } renderElement(element: T, index: number, templateData: any[], height: number | undefined): void { let i = 0; for (const renderer of this.renderers) { renderer.renderElement(element, index, templateData[i++], height); } } disposeElement(element: T, index: number, templateData: any[], height: number | undefined): void { let i = 0; for (const renderer of this.renderers) { if (renderer.disposeElement) { renderer.disposeElement(element, index, templateData[i], height); } i += 1; } } disposeTemplate(templateData: any[]): void { let i = 0; for (const renderer of this.renderers) { renderer.disposeTemplate(templateData[i++]); } } } class AccessibiltyRenderer<T> implements IListRenderer<T, HTMLElement> { templateId: string = 'a18n'; constructor(private accessibilityProvider: IAccessibilityProvider<T>) { } renderTemplate(container: HTMLElement): HTMLElement { return container; } renderElement(element: T, index: number, container: HTMLElement): void { const ariaLabel = this.accessibilityProvider.getAriaLabel(element); if (ariaLabel) { container.setAttribute('aria-label', ariaLabel); } else { container.removeAttribute('aria-label'); } const ariaLevel = this.accessibilityProvider.getAriaLevel && this.accessibilityProvider.getAriaLevel(element); if (typeof ariaLevel === 'number') { container.setAttribute('aria-level', `${ariaLevel}`); } else { container.removeAttribute('aria-level'); } } disposeTemplate(templateData: any): void { // noop } } class ListViewDragAndDrop<T> implements IListViewDragAndDrop<T> { constructor(private list: List<T>, private dnd: IListDragAndDrop<T>) { } getDragElements(element: T): T[] { const selection = this.list.getSelectedElements(); const elements = selection.indexOf(element) > -1 ? selection : [element]; return elements; } getDragURI(element: T): string | null { return this.dnd.getDragURI(element); } getDragLabel?(elements: T[], originalEvent: DragEvent): string | undefined { if (this.dnd.getDragLabel) { return this.dnd.getDragLabel(elements, originalEvent); } return undefined; } onDragStart(data: IDragAndDropData, originalEvent: DragEvent): void { if (this.dnd.onDragStart) { this.dnd.onDragStart(data, originalEvent); } } onDragOver(data: IDragAndDropData, targetElement: T, targetIndex: number, originalEvent: DragEvent): boolean | IListDragOverReaction { return this.dnd.onDragOver(data, targetElement, targetIndex, originalEvent); } onDragEnd(originalEvent: DragEvent): void { if (this.dnd.onDragEnd) { this.dnd.onDragEnd(originalEvent); } } drop(data: IDragAndDropData, targetElement: T, targetIndex: number, originalEvent: DragEvent): void { this.dnd.drop(data, targetElement, targetIndex, originalEvent); } } export interface IListOptionsUpdate { readonly enableKeyboardNavigation?: boolean; readonly automaticKeyboardNavigation?: boolean; } export class List<T> implements ISpliceable<T>, IDisposable { private focus: Trait<T>; private selection: Trait<T>; private eventBufferer = new EventBufferer(); protected view: ListView<T>; private spliceable: ISpliceable<T>; private styleController: IStyleController; private typeLabelController?: TypeLabelController<T>; private accessibilityProvider?: IAccessibilityProvider<T>; protected readonly disposables = new DisposableStore(); @memoize get onDidChangeFocus(): Event<IListEvent<T>> { return Event.map(this.eventBufferer.wrapEvent(this.focus.onChange), e => this.toListEvent(e)); } @memoize get onDidChangeSelection(): Event<IListEvent<T>> { return Event.map(this.eventBufferer.wrapEvent(this.selection.onChange), e => this.toListEvent(e)); } private readonly _onDidOpen = new Emitter<IListEvent<T>>(); readonly onDidOpen: Event<IListEvent<T>> = this._onDidOpen.event; private readonly _onDidPin = new Emitter<IListEvent<T>>(); readonly onDidPin: Event<IListEvent<T>> = this._onDidPin.event; get domId(): string { return this.view.domId; } get onDidScroll(): Event<ScrollEvent> { return this.view.onDidScroll; } get onMouseClick(): Event<IListMouseEvent<T>> { return this.view.onMouseClick; } get onMouseDblClick(): Event<IListMouseEvent<T>> { return this.view.onMouseDblClick; } get onMouseMiddleClick(): Event<IListMouseEvent<T>> { return this.view.onMouseMiddleClick; } get onMouseUp(): Event<IListMouseEvent<T>> { return this.view.onMouseUp; } get onMouseDown(): Event<IListMouseEvent<T>> { return this.view.onMouseDown; } get onMouseOver(): Event<IListMouseEvent<T>> { return this.view.onMouseOver; } get onMouseMove(): Event<IListMouseEvent<T>> { return this.view.onMouseMove; } get onMouseOut(): Event<IListMouseEvent<T>> { return this.view.onMouseOut; } get onTouchStart(): Event<IListTouchEvent<T>> { return this.view.onTouchStart; } get onTap(): Event<IListGestureEvent<T>> { return this.view.onTap; } private didJustPressContextMenuKey: boolean = false; @memoize get onContextMenu(): Event<IListContextMenuEvent<T>> { const fromKeydown = Event.chain(domEvent(this.view.domNode, 'keydown')) .map(e => new StandardKeyboardEvent(e)) .filter(e => this.didJustPressContextMenuKey = e.keyCode === KeyCode.ContextMenu || (e.shiftKey && e.keyCode === KeyCode.F10)) .filter(e => { e.preventDefault(); e.stopPropagation(); return false; }) .event as Event<any>; const fromKeyup = Event.chain(domEvent(this.view.domNode, 'keyup')) .filter(() => { const didJustPressContextMenuKey = this.didJustPressContextMenuKey; this.didJustPressContextMenuKey = false; return didJustPressContextMenuKey; }) .filter(() => this.getFocus().length > 0 && !!this.view.domElement(this.getFocus()[0])) .map(browserEvent => { const index = this.getFocus()[0]; const element = this.view.element(index); const anchor = this.view.domElement(index) as HTMLElement; return { index, element, anchor, browserEvent }; }) .event; const fromMouse = Event.chain(this.view.onContextMenu) .filter(() => !this.didJustPressContextMenuKey) .map(({ element, index, browserEvent }) => ({ element, index, anchor: { x: browserEvent.clientX + 1, y: browserEvent.clientY }, browserEvent })) .event; return Event.any<IListContextMenuEvent<T>>(fromKeydown, fromKeyup, fromMouse); } get onKeyDown(): Event<KeyboardEvent> { return domEvent(this.view.domNode, 'keydown'); } get onKeyUp(): Event<KeyboardEvent> { return domEvent(this.view.domNode, 'keyup'); } get onKeyPress(): Event<KeyboardEvent> { return domEvent(this.view.domNode, 'keypress'); } readonly onDidFocus: Event<void>; readonly onDidBlur: Event<void>; private readonly _onDidDispose = new Emitter<void>(); readonly onDidDispose: Event<void> = this._onDidDispose.event; constructor( private user: string, container: HTMLElement, virtualDelegate: IListVirtualDelegate<T>, renderers: IListRenderer<any /* TODO@joao */, any>[], private _options: IListOptions<T> = DefaultOptions ) { this.focus = new Trait('focused'); this.selection = new SelectionTrait(); mixin(_options, defaultStyles, false); const baseRenderers: IListRenderer<T, ITraitTemplateData>[] = [this.focus.renderer, this.selection.renderer]; this.accessibilityProvider = _options.accessibilityProvider; if (this.accessibilityProvider) { baseRenderers.push(new AccessibiltyRenderer<T>(this.accessibilityProvider)); if (this.accessibilityProvider.onDidChangeActiveDescendant) { this.accessibilityProvider.onDidChangeActiveDescendant(this.onDidChangeActiveDescendant, this, this.disposables); } } renderers = renderers.map(r => new PipelineRenderer(r.templateId, [...baseRenderers, r])); const viewOptions: IListViewOptions<T> = { ..._options, dnd: _options.dnd && new ListViewDragAndDrop(this, _options.dnd) }; this.view = new ListView(container, virtualDelegate, renderers, viewOptions); if (typeof _options.ariaRole !== 'string') { this.view.domNode.setAttribute('role', ListAriaRootRole.TREE); } else { this.view.domNode.setAttribute('role', _options.ariaRole); } if (_options.styleController) { this.styleController = _options.styleController(this.view.domId); } else { const styleElement = DOM.createStyleSheet(this.view.domNode); this.styleController = new DefaultStyleController(styleElement, this.view.domId); } this.spliceable = new CombinedSpliceable([ new TraitSpliceable(this.focus, this.view, _options.identityProvider), new TraitSpliceable(this.selection, this.view, _options.identityProvider), this.view ]); this.disposables.add(this.focus); this.disposables.add(this.selection); this.disposables.add(this.view); this.disposables.add(this._onDidDispose); this.onDidFocus = Event.map(domEvent(this.view.domNode, 'focus', true), () => null!); this.onDidBlur = Event.map(domEvent(this.view.domNode, 'blur', true), () => null!); this.disposables.add(new DOMFocusController(this, this.view)); if (typeof _options.keyboardSupport !== 'boolean' || _options.keyboardSupport) { const controller = new KeyboardController(this, this.view, _options); this.disposables.add(controller); } if (_options.keyboardNavigationLabelProvider) { const delegate = _options.keyboardNavigationDelegate || DefaultKeyboardNavigationDelegate; this.typeLabelController = new TypeLabelController(this, this.view, _options.keyboardNavigationLabelProvider, delegate); this.disposables.add(this.typeLabelController); } this.disposables.add(this.createMouseController(_options)); this.onDidChangeFocus(this._onFocusChange, this, this.disposables); this.onDidChangeSelection(this._onSelectionChange, this, this.disposables); if (_options.ariaLabel) { this.view.domNode.setAttribute('aria-label', localize('aria list', "{0}. Use the navigation keys to navigate.", _options.ariaLabel)); } if (_options.multipleSelectionSupport) { this.view.domNode.setAttribute('aria-multiselectable', 'true'); } } protected createMouseController(options: IListOptions<T>): MouseController<T> { return new MouseController(this); } updateOptions(optionsUpdate: IListOptionsUpdate = {}): void { this._options = { ...this._options, ...optionsUpdate }; if (this.typeLabelController) { this.typeLabelController.updateOptions(this._options); } } get options(): IListOptions<T> { return this._options; } splice(start: number, deleteCount: number, elements: T[] = []): void { if (start < 0 || start > this.view.length) { throw new ListError(this.user, `Invalid start index: ${start}`); } if (deleteCount < 0) { throw new ListError(this.user, `Invalid delete count: ${deleteCount}`); } if (deleteCount === 0 && elements.length === 0) { return; } this.eventBufferer.bufferEvents(() => this.spliceable.splice(start, deleteCount, elements)); } updateWidth(index: number): void { this.view.updateWidth(index); } updateElementHeight(index: number, size: number): void { this.view.updateElementHeight(index, size); } rerender(): void { this.view.rerender(); } element(index: number): T { return this.view.element(index); } get length(): number { return this.view.length; } get contentHeight(): number { return this.view.contentHeight; } get onDidChangeContentHeight(): Event<number> { return this.view.onDidChangeContentHeight; } get scrollTop(): number { return this.view.getScrollTop(); } set scrollTop(scrollTop: number) { this.view.setScrollTop(scrollTop); } get scrollLeft(): number { return this.view.getScrollLeft(); } set scrollLeft(scrollLeft: number) { this.view.setScrollLeft(scrollLeft); } get scrollHeight(): number { return this.view.scrollHeight; } get renderHeight(): number { return this.view.renderHeight; } get firstVisibleIndex(): number { return this.view.firstVisibleIndex; } get lastVisibleIndex(): number { return this.view.lastVisibleIndex; } domFocus(): void { this.view.domNode.focus(); } layout(height?: number, width?: number): void { this.view.layout(height, width); } toggleKeyboardNavigation(): void { if (this.typeLabelController) { this.typeLabelController.toggle(); } } setSelection(indexes: number[], browserEvent?: UIEvent): void { for (const index of indexes) { if (index < 0 || index >= this.length) { throw new ListError(this.user, `Invalid index ${index}`); } } this.selection.set(indexes, browserEvent); } getSelection(): number[] { return this.selection.get(); } getSelectedElements(): T[] { return this.getSelection().map(i => this.view.element(i)); } setFocus(indexes: number[], browserEvent?: UIEvent): void { for (const index of indexes) { if (index < 0 || index >= this.length) { throw new ListError(this.user, `Invalid index ${index}`); } } this.focus.set(indexes, browserEvent); } focusNext(n = 1, loop = false, browserEvent?: UIEvent, filter?: (element: T) => boolean): void { if (this.length === 0) { return; } const focus = this.focus.get(); const index = this.findNextIndex(focus.length > 0 ? focus[0] + n : 0, loop, filter); if (index > -1) { this.setFocus([index], browserEvent); } } focusPrevious(n = 1, loop = false, browserEvent?: UIEvent, filter?: (element: T) => boolean): void { if (this.length === 0) { return; } const focus = this.focus.get(); const index = this.findPreviousIndex(focus.length > 0 ? focus[0] - n : 0, loop, filter); if (index > -1) { this.setFocus([index], browserEvent); } } focusNextPage(browserEvent?: UIEvent, filter?: (element: T) => boolean): void { let lastPageIndex = this.view.indexAt(this.view.getScrollTop() + this.view.renderHeight); lastPageIndex = lastPageIndex === 0 ? 0 : lastPageIndex - 1; const lastPageElement = this.view.element(lastPageIndex); const currentlyFocusedElement = this.getFocusedElements()[0]; if (currentlyFocusedElement !== lastPageElement) { const lastGoodPageIndex = this.findPreviousIndex(lastPageIndex, false, filter); if (lastGoodPageIndex > -1 && currentlyFocusedElement !== this.view.element(lastGoodPageIndex)) { this.setFocus([lastGoodPageIndex], browserEvent); } else { this.setFocus([lastPageIndex], browserEvent); } } else { const previousScrollTop = this.view.getScrollTop(); this.view.setScrollTop(previousScrollTop + this.view.renderHeight - this.view.elementHeight(lastPageIndex)); if (this.view.getScrollTop() !== previousScrollTop) { // Let the scroll event listener run setTimeout(() => this.focusNextPage(browserEvent, filter), 0); } } } focusPreviousPage(browserEvent?: UIEvent, filter?: (element: T) => boolean): void { let firstPageIndex: number; const scrollTop = this.view.getScrollTop(); if (scrollTop === 0) { firstPageIndex = this.view.indexAt(scrollTop); } else { firstPageIndex = this.view.indexAfter(scrollTop - 1); } const firstPageElement = this.view.element(firstPageIndex); const currentlyFocusedElement = this.getFocusedElements()[0]; if (currentlyFocusedElement !== firstPageElement) { const firstGoodPageIndex = this.findNextIndex(firstPageIndex, false, filter); if (firstGoodPageIndex > -1 && currentlyFocusedElement !== this.view.element(firstGoodPageIndex)) { this.setFocus([firstGoodPageIndex], browserEvent); } else { this.setFocus([firstPageIndex], browserEvent); } } else { const previousScrollTop = scrollTop; this.view.setScrollTop(scrollTop - this.view.renderHeight); if (this.view.getScrollTop() !== previousScrollTop) { // Let the scroll event listener run setTimeout(() => this.focusPreviousPage(browserEvent, filter), 0); } } } focusLast(browserEvent?: UIEvent, filter?: (element: T) => boolean): void { if (this.length === 0) { return; } const index = this.findPreviousIndex(this.length - 1, false, filter); if (index > -1) { this.setFocus([index], browserEvent); } } focusFirst(browserEvent?: UIEvent, filter?: (element: T) => boolean): void { if (this.length === 0) { return; } const index = this.findNextIndex(0, false, filter); if (index > -1) { this.setFocus([index], browserEvent); } } private findNextIndex(index: number, loop = false, filter?: (element: T) => boolean): number { for (let i = 0; i < this.length; i++) { if (index >= this.length && !loop) { return -1; } index = index % this.length; if (!filter || filter(this.element(index))) { return index; } index++; } return -1; } private findPreviousIndex(index: number, loop = false, filter?: (element: T) => boolean): number { for (let i = 0; i < this.length; i++) { if (index < 0 && !loop) { return -1; } index = (this.length + (index % this.length)) % this.length; if (!filter || filter(this.element(index))) { return index; } index--; } return -1; } getFocus(): number[] { return this.focus.get(); } getFocusedElements(): T[] { return this.getFocus().map(i => this.view.element(i)); } reveal(index: number, relativeTop?: number): void { if (index < 0 || index >= this.length) { throw new ListError(this.user, `Invalid index ${index}`); } const scrollTop = this.view.getScrollTop(); const elementTop = this.view.elementTop(index); const elementHeight = this.view.elementHeight(index); if (isNumber(relativeTop)) { // y = mx + b const m = elementHeight - this.view.renderHeight; this.view.setScrollTop(m * clamp(relativeTop, 0, 1) + elementTop); } else { const viewItemBottom = elementTop + elementHeight; const wrapperBottom = scrollTop + this.view.renderHeight; if (elementTop < scrollTop && viewItemBottom >= wrapperBottom) { // The element is already overflowing the viewport, no-op } else if (elementTop < scrollTop) { this.view.setScrollTop(elementTop); } else if (viewItemBottom >= wrapperBottom) { this.view.setScrollTop(viewItemBottom - this.view.renderHeight); } } } /** * Returns the relative position of an element rendered in the list. * Returns `null` if the element isn't *entirely* in the visible viewport. */ getRelativeTop(index: number): number | null { if (index < 0 || index >= this.length) { throw new ListError(this.user, `Invalid index ${index}`); } const scrollTop = this.view.getScrollTop(); const elementTop = this.view.elementTop(index); const elementHeight = this.view.elementHeight(index); if (elementTop < scrollTop || elementTop + elementHeight > scrollTop + this.view.renderHeight) { return null; } // y = mx + b const m = elementHeight - this.view.renderHeight; return Math.abs((scrollTop - elementTop) / m); } isDOMFocused(): boolean { return this.view.domNode === document.activeElement; } getHTMLElement(): HTMLElement { return this.view.domNode; } open(indexes: number[], browserEvent?: UIEvent): void { for (const index of indexes) { if (index < 0 || index >= this.length) { throw new ListError(this.user, `Invalid index ${index}`); } } this._onDidOpen.fire({ indexes, elements: indexes.map(i => this.view.element(i)), browserEvent }); } pin(indexes: number[], browserEvent?: UIEvent): void { for (const index of indexes) { if (index < 0 || index >= this.length) { throw new ListError(this.user, `Invalid index ${index}`); } } this._onDidPin.fire({ indexes, elements: indexes.map(i => this.view.element(i)), browserEvent }); } style(styles: IListStyles): void { this.styleController.style(styles); } private toListEvent({ indexes, browserEvent }: ITraitChangeEvent) { return { indexes, elements: indexes.map(i => this.view.element(i)), browserEvent }; } private _onFocusChange(): void { const focus = this.focus.get(); DOM.toggleClass(this.view.domNode, 'element-focused', focus.length > 0); this.onDidChangeActiveDescendant(); } private onDidChangeActiveDescendant(): void { const focus = this.focus.get(); if (focus.length > 0) { let id: string | undefined; if (this.accessibilityProvider?.getActiveDescendantId) { id = this.accessibilityProvider.getActiveDescendantId(this.view.element(focus[0])); } this.view.domNode.setAttribute('aria-activedescendant', id || this.view.getElementDomId(focus[0])); } else { this.view.domNode.removeAttribute('aria-activedescendant'); } } private _onSelectionChange(): void { const selection = this.selection.get(); DOM.toggleClass(this.view.domNode, 'selection-none', selection.length === 0); DOM.toggleClass(this.view.domNode, 'selection-single', selection.length === 1); DOM.toggleClass(this.view.domNode, 'selection-multiple', selection.length > 1); } dispose(): void { this._onDidDispose.fire(); this.disposables.dispose(); this._onDidOpen.dispose(); this._onDidPin.dispose(); this._onDidDispose.dispose(); } }
src/vs/base/browser/ui/list/listWidget.ts
1
https://github.com/microsoft/vscode/commit/7aca51e3d98c58ee8e418df6b525930d90375d9f
[ 0.998161256313324, 0.007155910134315491, 0.0001615120709175244, 0.0001692991645541042, 0.07698763161897659 ]
{ "id": 3, "code_window": [ "\t\t\tcontainer.setAttribute('aria-selected', 'true');\n", "\t\t} else {\n", "\t\t\tcontainer.removeAttribute('aria-selected');\n", "\t\t}\n", "\t}\n", "}\n", "\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tcontainer.setAttribute('aria-selected', 'false');\n" ], "file_path": "src/vs/base/browser/ui/list/listWidget.ts", "type": "replace", "edit_start_line_idx": 194 }
--- name: Feature request about: Suggest an idea for this project --- <!-- Please read our Rules of Conduct: https://opensource.microsoft.com/codeofconduct/ --> <!-- Please search existing issues to avoid creating duplicates. --> <!-- Describe the feature you'd like. -->
.github/ISSUE_TEMPLATE/feature_request.md
0
https://github.com/microsoft/vscode/commit/7aca51e3d98c58ee8e418df6b525930d90375d9f
[ 0.0001756360288709402, 0.00017431846936233342, 0.00017300090985372663, 0.00017431846936233342, 0.0000013175595086067915 ]
{ "id": 3, "code_window": [ "\t\t\tcontainer.setAttribute('aria-selected', 'true');\n", "\t\t} else {\n", "\t\t\tcontainer.removeAttribute('aria-selected');\n", "\t\t}\n", "\t}\n", "}\n", "\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tcontainer.setAttribute('aria-selected', 'false');\n" ], "file_path": "src/vs/base/browser/ui/list/listWidget.ts", "type": "replace", "edit_start_line_idx": 194 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { RawContextKey, IContextKeyService, IContextKey } from 'vs/platform/contextkey/common/contextkey'; import { IDisposable, dispose, Disposable } from 'vs/base/common/lifecycle'; import { ICodeEditor } from 'vs/editor/browser/editorBrowser'; import { EditorOption } from 'vs/editor/common/config/editorOptions'; export class WordContextKey extends Disposable { static readonly AtEnd = new RawContextKey<boolean>('atEndOfWord', false); private readonly _ckAtEnd: IContextKey<boolean>; private _enabled: boolean = false; private _selectionListener?: IDisposable; constructor( private readonly _editor: ICodeEditor, @IContextKeyService contextKeyService: IContextKeyService, ) { super(); this._ckAtEnd = WordContextKey.AtEnd.bindTo(contextKeyService); this._register(this._editor.onDidChangeConfiguration(e => e.hasChanged(EditorOption.tabCompletion) && this._update())); this._update(); } dispose(): void { super.dispose(); dispose(this._selectionListener); this._ckAtEnd.reset(); } private _update(): void { // only update this when tab completions are enabled const enabled = this._editor.getOption(EditorOption.tabCompletion) === 'on'; if (this._enabled === enabled) { return; } this._enabled = enabled; if (this._enabled) { const checkForWordEnd = () => { if (!this._editor.hasModel()) { this._ckAtEnd.set(false); return; } const model = this._editor.getModel(); const selection = this._editor.getSelection(); const word = model.getWordAtPosition(selection.getStartPosition()); if (!word) { this._ckAtEnd.set(false); return; } this._ckAtEnd.set(word.endColumn === selection.getStartPosition().column); }; this._selectionListener = this._editor.onDidChangeCursorSelection(checkForWordEnd); checkForWordEnd(); } else if (this._selectionListener) { this._ckAtEnd.reset(); this._selectionListener.dispose(); this._selectionListener = undefined; } } }
src/vs/editor/contrib/suggest/wordContextKey.ts
0
https://github.com/microsoft/vscode/commit/7aca51e3d98c58ee8e418df6b525930d90375d9f
[ 0.00017434325127396733, 0.00016816022980492562, 0.0001650194899411872, 0.00016663101268932223, 0.0000031337974633061094 ]
{ "id": 3, "code_window": [ "\t\t\tcontainer.setAttribute('aria-selected', 'true');\n", "\t\t} else {\n", "\t\t\tcontainer.removeAttribute('aria-selected');\n", "\t\t}\n", "\t}\n", "}\n", "\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tcontainer.setAttribute('aria-selected', 'false');\n" ], "file_path": "src/vs/base/browser/ui/list/listWidget.ts", "type": "replace", "edit_start_line_idx": 194 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as browser from 'vs/base/browser/browser'; import { FastDomNode, createFastDomNode } from 'vs/base/browser/fastDomNode'; import * as platform from 'vs/base/common/platform'; import { IVisibleLine } from 'vs/editor/browser/view/viewLayer'; import { RangeUtil } from 'vs/editor/browser/viewParts/lines/rangeUtil'; import { IStringBuilder } from 'vs/editor/common/core/stringBuilder'; import { IConfiguration } from 'vs/editor/common/editorCommon'; import { HorizontalRange, VisibleRanges } from 'vs/editor/common/view/renderingContext'; import { LineDecoration } from 'vs/editor/common/viewLayout/lineDecorations'; import { CharacterMapping, ForeignElementType, RenderLineInput, renderViewLine, LineRange } from 'vs/editor/common/viewLayout/viewLineRenderer'; import { ViewportData } from 'vs/editor/common/viewLayout/viewLinesViewportData'; import { InlineDecorationType } from 'vs/editor/common/viewModel/viewModel'; import { HIGH_CONTRAST, ThemeType } from 'vs/platform/theme/common/themeService'; import { EditorOption, EditorFontLigatures } from 'vs/editor/common/config/editorOptions'; const canUseFastRenderedViewLine = (function () { if (platform.isNative) { // In VSCode we know very well when the zoom level changes return true; } if (platform.isLinux || browser.isFirefox || browser.isSafari) { // On Linux, it appears that zooming affects char widths (in pixels), which is unexpected. // -- // Even though we read character widths correctly, having read them at a specific zoom level // does not mean they are the same at the current zoom level. // -- // This could be improved if we ever figure out how to get an event when browsers zoom, // but until then we have to stick with reading client rects. // -- // The same has been observed with Firefox on Windows7 // -- // The same has been oversved with Safari return false; } return true; })(); const alwaysRenderInlineSelection = (browser.isEdge); export class DomReadingContext { private readonly _domNode: HTMLElement; private _clientRectDeltaLeft: number; private _clientRectDeltaLeftRead: boolean; public get clientRectDeltaLeft(): number { if (!this._clientRectDeltaLeftRead) { this._clientRectDeltaLeftRead = true; this._clientRectDeltaLeft = this._domNode.getBoundingClientRect().left; } return this._clientRectDeltaLeft; } public readonly endNode: HTMLElement; constructor(domNode: HTMLElement, endNode: HTMLElement) { this._domNode = domNode; this._clientRectDeltaLeft = 0; this._clientRectDeltaLeftRead = false; this.endNode = endNode; } } export class ViewLineOptions { public readonly themeType: ThemeType; public readonly renderWhitespace: 'none' | 'boundary' | 'selection' | 'all'; public readonly renderControlCharacters: boolean; public readonly spaceWidth: number; public readonly middotWidth: number; public readonly wsmiddotWidth: number; public readonly useMonospaceOptimizations: boolean; public readonly canUseHalfwidthRightwardsArrow: boolean; public readonly lineHeight: number; public readonly stopRenderingLineAfter: number; public readonly fontLigatures: string; constructor(config: IConfiguration, themeType: ThemeType) { this.themeType = themeType; const options = config.options; const fontInfo = options.get(EditorOption.fontInfo); this.renderWhitespace = options.get(EditorOption.renderWhitespace); this.renderControlCharacters = options.get(EditorOption.renderControlCharacters); this.spaceWidth = fontInfo.spaceWidth; this.middotWidth = fontInfo.middotWidth; this.wsmiddotWidth = fontInfo.wsmiddotWidth; this.useMonospaceOptimizations = ( fontInfo.isMonospace && !options.get(EditorOption.disableMonospaceOptimizations) ); this.canUseHalfwidthRightwardsArrow = fontInfo.canUseHalfwidthRightwardsArrow; this.lineHeight = options.get(EditorOption.lineHeight); this.stopRenderingLineAfter = options.get(EditorOption.stopRenderingLineAfter); this.fontLigatures = options.get(EditorOption.fontLigatures); } public equals(other: ViewLineOptions): boolean { return ( this.themeType === other.themeType && this.renderWhitespace === other.renderWhitespace && this.renderControlCharacters === other.renderControlCharacters && this.spaceWidth === other.spaceWidth && this.middotWidth === other.middotWidth && this.wsmiddotWidth === other.wsmiddotWidth && this.useMonospaceOptimizations === other.useMonospaceOptimizations && this.canUseHalfwidthRightwardsArrow === other.canUseHalfwidthRightwardsArrow && this.lineHeight === other.lineHeight && this.stopRenderingLineAfter === other.stopRenderingLineAfter && this.fontLigatures === other.fontLigatures ); } } export class ViewLine implements IVisibleLine { public static readonly CLASS_NAME = 'view-line'; private _options: ViewLineOptions; private _isMaybeInvalid: boolean; private _renderedViewLine: IRenderedViewLine | null; constructor(options: ViewLineOptions) { this._options = options; this._isMaybeInvalid = true; this._renderedViewLine = null; } // --- begin IVisibleLineData public getDomNode(): HTMLElement | null { if (this._renderedViewLine && this._renderedViewLine.domNode) { return this._renderedViewLine.domNode.domNode; } return null; } public setDomNode(domNode: HTMLElement): void { if (this._renderedViewLine) { this._renderedViewLine.domNode = createFastDomNode(domNode); } else { throw new Error('I have no rendered view line to set the dom node to...'); } } public onContentChanged(): void { this._isMaybeInvalid = true; } public onTokensChanged(): void { this._isMaybeInvalid = true; } public onDecorationsChanged(): void { this._isMaybeInvalid = true; } public onOptionsChanged(newOptions: ViewLineOptions): void { this._isMaybeInvalid = true; this._options = newOptions; } public onSelectionChanged(): boolean { if (alwaysRenderInlineSelection || this._options.themeType === HIGH_CONTRAST || this._options.renderWhitespace === 'selection') { this._isMaybeInvalid = true; return true; } return false; } public renderLine(lineNumber: number, deltaTop: number, viewportData: ViewportData, sb: IStringBuilder): boolean { if (this._isMaybeInvalid === false) { // it appears that nothing relevant has changed return false; } this._isMaybeInvalid = false; const lineData = viewportData.getViewLineRenderingData(lineNumber); const options = this._options; const actualInlineDecorations = LineDecoration.filter(lineData.inlineDecorations, lineNumber, lineData.minColumn, lineData.maxColumn); // Only send selection information when needed for rendering whitespace let selectionsOnLine: LineRange[] | null = null; if (alwaysRenderInlineSelection || options.themeType === HIGH_CONTRAST || this._options.renderWhitespace === 'selection') { const selections = viewportData.selections; for (const selection of selections) { if (selection.endLineNumber < lineNumber || selection.startLineNumber > lineNumber) { // Selection does not intersect line continue; } const startColumn = (selection.startLineNumber === lineNumber ? selection.startColumn : lineData.minColumn); const endColumn = (selection.endLineNumber === lineNumber ? selection.endColumn : lineData.maxColumn); if (startColumn < endColumn) { if (options.themeType === HIGH_CONTRAST || this._options.renderWhitespace !== 'selection') { actualInlineDecorations.push(new LineDecoration(startColumn, endColumn, 'inline-selected-text', InlineDecorationType.Regular)); } else { if (!selectionsOnLine) { selectionsOnLine = []; } selectionsOnLine.push(new LineRange(startColumn - 1, endColumn - 1)); } } } } const renderLineInput = new RenderLineInput( options.useMonospaceOptimizations, options.canUseHalfwidthRightwardsArrow, lineData.content, lineData.continuesWithWrappedLine, lineData.isBasicASCII, lineData.containsRTL, lineData.minColumn - 1, lineData.tokens, actualInlineDecorations, lineData.tabSize, lineData.startVisibleColumn, options.spaceWidth, options.middotWidth, options.wsmiddotWidth, options.stopRenderingLineAfter, options.renderWhitespace, options.renderControlCharacters, options.fontLigatures !== EditorFontLigatures.OFF, selectionsOnLine ); if (this._renderedViewLine && this._renderedViewLine.input.equals(renderLineInput)) { // no need to do anything, we have the same render input return false; } sb.appendASCIIString('<div style="top:'); sb.appendASCIIString(String(deltaTop)); sb.appendASCIIString('px;height:'); sb.appendASCIIString(String(this._options.lineHeight)); sb.appendASCIIString('px;" class="'); sb.appendASCIIString(ViewLine.CLASS_NAME); sb.appendASCIIString('">'); const output = renderViewLine(renderLineInput, sb); sb.appendASCIIString('</div>'); let renderedViewLine: IRenderedViewLine | null = null; if (canUseFastRenderedViewLine && lineData.isBasicASCII && options.useMonospaceOptimizations && output.containsForeignElements === ForeignElementType.None) { if (lineData.content.length < 300 && renderLineInput.lineTokens.getCount() < 100) { // Browser rounding errors have been observed in Chrome and IE, so using the fast // view line only for short lines. Please test before removing the length check... // --- // Another rounding error has been observed on Linux in VSCode, where <span> width // rounding errors add up to an observable large number... // --- // Also see another example of rounding errors on Windows in // https://github.com/Microsoft/vscode/issues/33178 renderedViewLine = new FastRenderedViewLine( this._renderedViewLine ? this._renderedViewLine.domNode : null, renderLineInput, output.characterMapping ); } } if (!renderedViewLine) { renderedViewLine = createRenderedLine( this._renderedViewLine ? this._renderedViewLine.domNode : null, renderLineInput, output.characterMapping, output.containsRTL, output.containsForeignElements ); } this._renderedViewLine = renderedViewLine; return true; } public layoutLine(lineNumber: number, deltaTop: number): void { if (this._renderedViewLine && this._renderedViewLine.domNode) { this._renderedViewLine.domNode.setTop(deltaTop); this._renderedViewLine.domNode.setHeight(this._options.lineHeight); } } // --- end IVisibleLineData public getWidth(): number { if (!this._renderedViewLine) { return 0; } return this._renderedViewLine.getWidth(); } public getWidthIsFast(): boolean { if (!this._renderedViewLine) { return true; } return this._renderedViewLine.getWidthIsFast(); } public getVisibleRangesForRange(startColumn: number, endColumn: number, context: DomReadingContext): VisibleRanges | null { if (!this._renderedViewLine) { return null; } startColumn = startColumn | 0; // @perf endColumn = endColumn | 0; // @perf startColumn = Math.min(this._renderedViewLine.input.lineContent.length + 1, Math.max(1, startColumn)); endColumn = Math.min(this._renderedViewLine.input.lineContent.length + 1, Math.max(1, endColumn)); const stopRenderingLineAfter = this._renderedViewLine.input.stopRenderingLineAfter | 0; // @perf let outsideRenderedLine = false; if (stopRenderingLineAfter !== -1 && startColumn > stopRenderingLineAfter + 1 && endColumn > stopRenderingLineAfter + 1) { // This range is obviously not visible outsideRenderedLine = true; } if (stopRenderingLineAfter !== -1 && startColumn > stopRenderingLineAfter + 1) { startColumn = stopRenderingLineAfter + 1; } if (stopRenderingLineAfter !== -1 && endColumn > stopRenderingLineAfter + 1) { endColumn = stopRenderingLineAfter + 1; } const horizontalRanges = this._renderedViewLine.getVisibleRangesForRange(startColumn, endColumn, context); if (horizontalRanges && horizontalRanges.length > 0) { return new VisibleRanges(outsideRenderedLine, horizontalRanges); } return null; } public getColumnOfNodeOffset(lineNumber: number, spanNode: HTMLElement, offset: number): number { if (!this._renderedViewLine) { return 1; } return this._renderedViewLine.getColumnOfNodeOffset(lineNumber, spanNode, offset); } } interface IRenderedViewLine { domNode: FastDomNode<HTMLElement> | null; readonly input: RenderLineInput; getWidth(): number; getWidthIsFast(): boolean; getVisibleRangesForRange(startColumn: number, endColumn: number, context: DomReadingContext): HorizontalRange[] | null; getColumnOfNodeOffset(lineNumber: number, spanNode: HTMLElement, offset: number): number; } /** * A rendered line which is guaranteed to contain only regular ASCII and is rendered with a monospace font. */ class FastRenderedViewLine implements IRenderedViewLine { public domNode: FastDomNode<HTMLElement> | null; public readonly input: RenderLineInput; private readonly _characterMapping: CharacterMapping; private readonly _charWidth: number; constructor(domNode: FastDomNode<HTMLElement> | null, renderLineInput: RenderLineInput, characterMapping: CharacterMapping) { this.domNode = domNode; this.input = renderLineInput; this._characterMapping = characterMapping; this._charWidth = renderLineInput.spaceWidth; } public getWidth(): number { return this._getCharPosition(this._characterMapping.length); } public getWidthIsFast(): boolean { return true; } public getVisibleRangesForRange(startColumn: number, endColumn: number, context: DomReadingContext): HorizontalRange[] | null { const startPosition = this._getCharPosition(startColumn); const endPosition = this._getCharPosition(endColumn); return [new HorizontalRange(startPosition, endPosition - startPosition)]; } private _getCharPosition(column: number): number { const charOffset = this._characterMapping.getAbsoluteOffsets(); if (charOffset.length === 0) { // No characters on this line return 0; } return Math.round(this._charWidth * charOffset[column - 1]); } public getColumnOfNodeOffset(lineNumber: number, spanNode: HTMLElement, offset: number): number { const spanNodeTextContentLength = spanNode.textContent!.length; let spanIndex = -1; while (spanNode) { spanNode = <HTMLElement>spanNode.previousSibling; spanIndex++; } const charOffset = this._characterMapping.partDataToCharOffset(spanIndex, spanNodeTextContentLength, offset); return charOffset + 1; } } /** * Every time we render a line, we save what we have rendered in an instance of this class. */ class RenderedViewLine implements IRenderedViewLine { public domNode: FastDomNode<HTMLElement> | null; public readonly input: RenderLineInput; protected readonly _characterMapping: CharacterMapping; private readonly _isWhitespaceOnly: boolean; private readonly _containsForeignElements: ForeignElementType; private _cachedWidth: number; /** * This is a map that is used only when the line is guaranteed to have no RTL text. */ private readonly _pixelOffsetCache: Int32Array | null; constructor(domNode: FastDomNode<HTMLElement> | null, renderLineInput: RenderLineInput, characterMapping: CharacterMapping, containsRTL: boolean, containsForeignElements: ForeignElementType) { this.domNode = domNode; this.input = renderLineInput; this._characterMapping = characterMapping; this._isWhitespaceOnly = /^\s*$/.test(renderLineInput.lineContent); this._containsForeignElements = containsForeignElements; this._cachedWidth = -1; this._pixelOffsetCache = null; if (!containsRTL || this._characterMapping.length === 0 /* the line is empty */) { this._pixelOffsetCache = new Int32Array(Math.max(2, this._characterMapping.length + 1)); for (let column = 0, len = this._characterMapping.length; column <= len; column++) { this._pixelOffsetCache[column] = -1; } } } // --- Reading from the DOM methods protected _getReadingTarget(myDomNode: FastDomNode<HTMLElement>): HTMLElement { return <HTMLSpanElement>myDomNode.domNode.firstChild; } /** * Width of the line in pixels */ public getWidth(): number { if (!this.domNode) { return 0; } if (this._cachedWidth === -1) { this._cachedWidth = this._getReadingTarget(this.domNode).offsetWidth; } return this._cachedWidth; } public getWidthIsFast(): boolean { if (this._cachedWidth === -1) { return false; } return true; } /** * Visible ranges for a model range */ public getVisibleRangesForRange(startColumn: number, endColumn: number, context: DomReadingContext): HorizontalRange[] | null { if (!this.domNode) { return null; } if (this._pixelOffsetCache !== null) { // the text is LTR const startOffset = this._readPixelOffset(this.domNode, startColumn, context); if (startOffset === -1) { return null; } const endOffset = this._readPixelOffset(this.domNode, endColumn, context); if (endOffset === -1) { return null; } return [new HorizontalRange(startOffset, endOffset - startOffset)]; } return this._readVisibleRangesForRange(this.domNode, startColumn, endColumn, context); } protected _readVisibleRangesForRange(domNode: FastDomNode<HTMLElement>, startColumn: number, endColumn: number, context: DomReadingContext): HorizontalRange[] | null { if (startColumn === endColumn) { const pixelOffset = this._readPixelOffset(domNode, startColumn, context); if (pixelOffset === -1) { return null; } else { return [new HorizontalRange(pixelOffset, 0)]; } } else { return this._readRawVisibleRangesForRange(domNode, startColumn, endColumn, context); } } protected _readPixelOffset(domNode: FastDomNode<HTMLElement>, column: number, context: DomReadingContext): number { if (this._characterMapping.length === 0) { // This line has no content if (this._containsForeignElements === ForeignElementType.None) { // We can assume the line is really empty return 0; } if (this._containsForeignElements === ForeignElementType.After) { // We have foreign elements after the (empty) line return 0; } if (this._containsForeignElements === ForeignElementType.Before) { // We have foreign elements before the (empty) line return this.getWidth(); } // We have foreign elements before & after the (empty) line const readingTarget = this._getReadingTarget(domNode); if (readingTarget.firstChild) { return (<HTMLSpanElement>readingTarget.firstChild).offsetWidth; } else { return 0; } } if (this._pixelOffsetCache !== null) { // the text is LTR const cachedPixelOffset = this._pixelOffsetCache[column]; if (cachedPixelOffset !== -1) { return cachedPixelOffset; } const result = this._actualReadPixelOffset(domNode, column, context); this._pixelOffsetCache[column] = result; return result; } return this._actualReadPixelOffset(domNode, column, context); } private _actualReadPixelOffset(domNode: FastDomNode<HTMLElement>, column: number, context: DomReadingContext): number { if (this._characterMapping.length === 0) { // This line has no content const r = RangeUtil.readHorizontalRanges(this._getReadingTarget(domNode), 0, 0, 0, 0, context.clientRectDeltaLeft, context.endNode); if (!r || r.length === 0) { return -1; } return r[0].left; } if (column === this._characterMapping.length && this._isWhitespaceOnly && this._containsForeignElements === ForeignElementType.None) { // This branch helps in the case of whitespace only lines which have a width set return this.getWidth(); } const partData = this._characterMapping.charOffsetToPartData(column - 1); const partIndex = CharacterMapping.getPartIndex(partData); const charOffsetInPart = CharacterMapping.getCharIndex(partData); const r = RangeUtil.readHorizontalRanges(this._getReadingTarget(domNode), partIndex, charOffsetInPart, partIndex, charOffsetInPart, context.clientRectDeltaLeft, context.endNode); if (!r || r.length === 0) { return -1; } return r[0].left; } private _readRawVisibleRangesForRange(domNode: FastDomNode<HTMLElement>, startColumn: number, endColumn: number, context: DomReadingContext): HorizontalRange[] | null { if (startColumn === 1 && endColumn === this._characterMapping.length) { // This branch helps IE with bidi text & gives a performance boost to other browsers when reading visible ranges for an entire line return [new HorizontalRange(0, this.getWidth())]; } const startPartData = this._characterMapping.charOffsetToPartData(startColumn - 1); const startPartIndex = CharacterMapping.getPartIndex(startPartData); const startCharOffsetInPart = CharacterMapping.getCharIndex(startPartData); const endPartData = this._characterMapping.charOffsetToPartData(endColumn - 1); const endPartIndex = CharacterMapping.getPartIndex(endPartData); const endCharOffsetInPart = CharacterMapping.getCharIndex(endPartData); return RangeUtil.readHorizontalRanges(this._getReadingTarget(domNode), startPartIndex, startCharOffsetInPart, endPartIndex, endCharOffsetInPart, context.clientRectDeltaLeft, context.endNode); } /** * Returns the column for the text found at a specific offset inside a rendered dom node */ public getColumnOfNodeOffset(lineNumber: number, spanNode: HTMLElement, offset: number): number { const spanNodeTextContentLength = spanNode.textContent!.length; let spanIndex = -1; while (spanNode) { spanNode = <HTMLElement>spanNode.previousSibling; spanIndex++; } const charOffset = this._characterMapping.partDataToCharOffset(spanIndex, spanNodeTextContentLength, offset); return charOffset + 1; } } class WebKitRenderedViewLine extends RenderedViewLine { protected _readVisibleRangesForRange(domNode: FastDomNode<HTMLElement>, startColumn: number, endColumn: number, context: DomReadingContext): HorizontalRange[] | null { const output = super._readVisibleRangesForRange(domNode, startColumn, endColumn, context); if (!output || output.length === 0 || startColumn === endColumn || (startColumn === 1 && endColumn === this._characterMapping.length)) { return output; } // WebKit is buggy and returns an expanded range (to contain words in some cases) // The last client rect is enlarged (I think) if (!this.input.containsRTL) { // This is an attempt to patch things up // Find position of last column const endPixelOffset = this._readPixelOffset(domNode, endColumn, context); if (endPixelOffset !== -1) { const lastRange = output[output.length - 1]; if (lastRange.left < endPixelOffset) { // Trim down the width of the last visible range to not go after the last column's position lastRange.width = endPixelOffset - lastRange.left; } } } return output; } } const createRenderedLine: (domNode: FastDomNode<HTMLElement> | null, renderLineInput: RenderLineInput, characterMapping: CharacterMapping, containsRTL: boolean, containsForeignElements: ForeignElementType) => RenderedViewLine = (function () { if (browser.isWebKit) { return createWebKitRenderedLine; } return createNormalRenderedLine; })(); function createWebKitRenderedLine(domNode: FastDomNode<HTMLElement> | null, renderLineInput: RenderLineInput, characterMapping: CharacterMapping, containsRTL: boolean, containsForeignElements: ForeignElementType): RenderedViewLine { return new WebKitRenderedViewLine(domNode, renderLineInput, characterMapping, containsRTL, containsForeignElements); } function createNormalRenderedLine(domNode: FastDomNode<HTMLElement> | null, renderLineInput: RenderLineInput, characterMapping: CharacterMapping, containsRTL: boolean, containsForeignElements: ForeignElementType): RenderedViewLine { return new RenderedViewLine(domNode, renderLineInput, characterMapping, containsRTL, containsForeignElements); }
src/vs/editor/browser/viewParts/lines/viewLine.ts
0
https://github.com/microsoft/vscode/commit/7aca51e3d98c58ee8e418df6b525930d90375d9f
[ 0.00019675210933201015, 0.00016961821529548615, 0.00016326438344549388, 0.00016925446107052267, 0.000004503104719333351 ]
{ "id": 4, "code_window": [ "\t\tvirtualDelegate: IListVirtualDelegate<T>,\n", "\t\trenderers: IListRenderer<any /* TODO@joao */, any>[],\n", "\t\tprivate _options: IListOptions<T> = DefaultOptions\n", "\t) {\n", "\t\tthis.focus = new Trait('focused');\n", "\t\tthis.selection = new SelectionTrait();\n", "\n", "\t\tmixin(_options, defaultStyles, false);\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis.selection = new Trait('selected');\n", "\t\tthis.focus = new FocusTrait(this.selection.contains);\n" ], "file_path": "src/vs/base/browser/ui/list/listWidget.ts", "type": "replace", "edit_start_line_idx": 1200 }
/*--------------------------------------------------------------------------------------------- * 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!./list'; import { localize } from 'vs/nls'; import { IDisposable, dispose, DisposableStore } from 'vs/base/common/lifecycle'; import { isNumber } from 'vs/base/common/types'; import { range, firstIndex, binarySearch } from 'vs/base/common/arrays'; import { memoize } from 'vs/base/common/decorators'; import * as DOM from 'vs/base/browser/dom'; import * as platform from 'vs/base/common/platform'; import { Gesture } from 'vs/base/browser/touch'; import { KeyCode } from 'vs/base/common/keyCodes'; import { StandardKeyboardEvent, IKeyboardEvent } from 'vs/base/browser/keyboardEvent'; import { Event, Emitter, EventBufferer } from 'vs/base/common/event'; import { domEvent } from 'vs/base/browser/event'; import { IListVirtualDelegate, IListRenderer, IListEvent, IListContextMenuEvent, IListMouseEvent, IListTouchEvent, IListGestureEvent, IIdentityProvider, IKeyboardNavigationLabelProvider, IListDragAndDrop, IListDragOverReaction, ListAriaRootRole, ListError, IKeyboardNavigationDelegate } from './list'; import { ListView, IListViewOptions, IListViewDragAndDrop, IAriaProvider } from './listView'; import { Color } from 'vs/base/common/color'; import { mixin } from 'vs/base/common/objects'; import { ScrollbarVisibility, ScrollEvent } from 'vs/base/common/scrollable'; import { ISpliceable } from 'vs/base/common/sequence'; import { CombinedSpliceable } from 'vs/base/browser/ui/list/splice'; import { clamp } from 'vs/base/common/numbers'; import { matchesPrefix } from 'vs/base/common/filters'; import { IDragAndDropData } from 'vs/base/browser/dnd'; interface ITraitChangeEvent { indexes: number[]; browserEvent?: UIEvent; } type ITraitTemplateData = HTMLElement; interface IRenderedContainer { templateData: ITraitTemplateData; index: number; } class TraitRenderer<T> implements IListRenderer<T, ITraitTemplateData> { private renderedElements: IRenderedContainer[] = []; constructor(private trait: Trait<T>) { } get templateId(): string { return `template:${this.trait.trait}`; } renderTemplate(container: HTMLElement): ITraitTemplateData { return container; } renderElement(element: T, index: number, templateData: ITraitTemplateData): void { const renderedElementIndex = firstIndex(this.renderedElements, el => el.templateData === templateData); if (renderedElementIndex >= 0) { const rendered = this.renderedElements[renderedElementIndex]; this.trait.unrender(templateData); rendered.index = index; } else { const rendered = { index, templateData }; this.renderedElements.push(rendered); } this.trait.renderIndex(index, templateData); } splice(start: number, deleteCount: number, insertCount: number): void { const rendered: IRenderedContainer[] = []; for (const renderedElement of this.renderedElements) { if (renderedElement.index < start) { rendered.push(renderedElement); } else if (renderedElement.index >= start + deleteCount) { rendered.push({ index: renderedElement.index + insertCount - deleteCount, templateData: renderedElement.templateData }); } } this.renderedElements = rendered; } renderIndexes(indexes: number[]): void { for (const { index, templateData } of this.renderedElements) { if (indexes.indexOf(index) > -1) { this.trait.renderIndex(index, templateData); } } } disposeTemplate(templateData: ITraitTemplateData): void { const index = firstIndex(this.renderedElements, el => el.templateData === templateData); if (index < 0) { return; } this.renderedElements.splice(index, 1); } } class Trait<T> implements ISpliceable<boolean>, IDisposable { private indexes: number[] = []; private sortedIndexes: number[] = []; private readonly _onChange = new Emitter<ITraitChangeEvent>(); readonly onChange: Event<ITraitChangeEvent> = this._onChange.event; get trait(): string { return this._trait; } @memoize get renderer(): TraitRenderer<T> { return new TraitRenderer<T>(this); } constructor(private _trait: string) { } splice(start: number, deleteCount: number, elements: boolean[]): void { const diff = elements.length - deleteCount; const end = start + deleteCount; const indexes = [ ...this.sortedIndexes.filter(i => i < start), ...elements.map((hasTrait, i) => hasTrait ? i + start : -1).filter(i => i !== -1), ...this.sortedIndexes.filter(i => i >= end).map(i => i + diff) ]; this.renderer.splice(start, deleteCount, elements.length); this._set(indexes, indexes); } renderIndex(index: number, container: HTMLElement): void { DOM.toggleClass(container, this._trait, this.contains(index)); } unrender(container: HTMLElement): void { DOM.removeClass(container, this._trait); } /** * Sets the indexes which should have this trait. * * @param indexes Indexes which should have this trait. * @return The old indexes which had this trait. */ set(indexes: number[], browserEvent?: UIEvent): number[] { return this._set(indexes, [...indexes].sort(numericSort), browserEvent); } private _set(indexes: number[], sortedIndexes: number[], browserEvent?: UIEvent): number[] { const result = this.indexes; const sortedResult = this.sortedIndexes; this.indexes = indexes; this.sortedIndexes = sortedIndexes; const toRender = disjunction(sortedResult, indexes); this.renderer.renderIndexes(toRender); this._onChange.fire({ indexes, browserEvent }); return result; } get(): number[] { return this.indexes; } contains(index: number): boolean { return binarySearch(this.sortedIndexes, index, numericSort) >= 0; } dispose() { dispose(this._onChange); } } class SelectionTrait<T> extends Trait<T> { constructor() { super('selected'); } renderIndex(index: number, container: HTMLElement): void { super.renderIndex(index, container); if (this.contains(index)) { container.setAttribute('aria-selected', 'true'); } else { container.removeAttribute('aria-selected'); } } } /** * The TraitSpliceable is used as a util class to be able * to preserve traits across splice calls, given an identity * provider. */ class TraitSpliceable<T> implements ISpliceable<T> { constructor( private trait: Trait<T>, private view: ListView<T>, private identityProvider?: IIdentityProvider<T> ) { } splice(start: number, deleteCount: number, elements: T[]): void { if (!this.identityProvider) { return this.trait.splice(start, deleteCount, elements.map(() => false)); } const pastElementsWithTrait = this.trait.get().map(i => this.identityProvider!.getId(this.view.element(i)).toString()); const elementsWithTrait = elements.map(e => pastElementsWithTrait.indexOf(this.identityProvider!.getId(e).toString()) > -1); this.trait.splice(start, deleteCount, elementsWithTrait); } } function isInputElement(e: HTMLElement): boolean { return e.tagName === 'INPUT' || e.tagName === 'TEXTAREA'; } class KeyboardController<T> implements IDisposable { private readonly disposables = new DisposableStore(); private openController: IOpenController; constructor( private list: List<T>, private view: ListView<T>, options: IListOptions<T> ) { const multipleSelectionSupport = options.multipleSelectionSupport !== false; this.openController = options.openController || DefaultOpenController; const onKeyDown = Event.chain(domEvent(view.domNode, 'keydown')) .filter(e => !isInputElement(e.target as HTMLElement)) .map(e => new StandardKeyboardEvent(e)); onKeyDown.filter(e => e.keyCode === KeyCode.Enter).on(this.onEnter, this, this.disposables); onKeyDown.filter(e => e.keyCode === KeyCode.UpArrow).on(this.onUpArrow, this, this.disposables); onKeyDown.filter(e => e.keyCode === KeyCode.DownArrow).on(this.onDownArrow, this, this.disposables); onKeyDown.filter(e => e.keyCode === KeyCode.PageUp).on(this.onPageUpArrow, this, this.disposables); onKeyDown.filter(e => e.keyCode === KeyCode.PageDown).on(this.onPageDownArrow, this, this.disposables); onKeyDown.filter(e => e.keyCode === KeyCode.Escape).on(this.onEscape, this, this.disposables); if (multipleSelectionSupport) { onKeyDown.filter(e => (platform.isMacintosh ? e.metaKey : e.ctrlKey) && e.keyCode === KeyCode.KEY_A).on(this.onCtrlA, this, this.disposables); } } private onEnter(e: StandardKeyboardEvent): void { e.preventDefault(); e.stopPropagation(); this.list.setSelection(this.list.getFocus(), e.browserEvent); if (this.openController.shouldOpen(e.browserEvent)) { this.list.open(this.list.getFocus(), e.browserEvent); } } private onUpArrow(e: StandardKeyboardEvent): void { e.preventDefault(); e.stopPropagation(); this.list.focusPrevious(1, false, e.browserEvent); this.list.reveal(this.list.getFocus()[0]); this.view.domNode.focus(); } private onDownArrow(e: StandardKeyboardEvent): void { e.preventDefault(); e.stopPropagation(); this.list.focusNext(1, false, e.browserEvent); this.list.reveal(this.list.getFocus()[0]); this.view.domNode.focus(); } private onPageUpArrow(e: StandardKeyboardEvent): void { e.preventDefault(); e.stopPropagation(); this.list.focusPreviousPage(e.browserEvent); this.list.reveal(this.list.getFocus()[0]); this.view.domNode.focus(); } private onPageDownArrow(e: StandardKeyboardEvent): void { e.preventDefault(); e.stopPropagation(); this.list.focusNextPage(e.browserEvent); this.list.reveal(this.list.getFocus()[0]); this.view.domNode.focus(); } private onCtrlA(e: StandardKeyboardEvent): void { e.preventDefault(); e.stopPropagation(); this.list.setSelection(range(this.list.length), e.browserEvent); this.view.domNode.focus(); } private onEscape(e: StandardKeyboardEvent): void { e.preventDefault(); e.stopPropagation(); this.list.setSelection([], e.browserEvent); this.view.domNode.focus(); } dispose() { this.disposables.dispose(); } } enum TypeLabelControllerState { Idle, Typing } export const DefaultKeyboardNavigationDelegate = new class implements IKeyboardNavigationDelegate { mightProducePrintableCharacter(event: IKeyboardEvent): boolean { if (event.ctrlKey || event.metaKey || event.altKey) { return false; } return (event.keyCode >= KeyCode.KEY_A && event.keyCode <= KeyCode.KEY_Z) || (event.keyCode >= KeyCode.KEY_0 && event.keyCode <= KeyCode.KEY_9) || (event.keyCode >= KeyCode.NUMPAD_0 && event.keyCode <= KeyCode.NUMPAD_9) || (event.keyCode >= KeyCode.US_SEMICOLON && event.keyCode <= KeyCode.US_QUOTE); } }; class TypeLabelController<T> implements IDisposable { private enabled = false; private state: TypeLabelControllerState = TypeLabelControllerState.Idle; private automaticKeyboardNavigation = true; private triggered = false; private readonly enabledDisposables = new DisposableStore(); private readonly disposables = new DisposableStore(); constructor( private list: List<T>, private view: ListView<T>, private keyboardNavigationLabelProvider: IKeyboardNavigationLabelProvider<T>, private delegate: IKeyboardNavigationDelegate ) { this.updateOptions(list.options); } updateOptions(options: IListOptions<T>): void { const enableKeyboardNavigation = typeof options.enableKeyboardNavigation === 'undefined' ? true : !!options.enableKeyboardNavigation; if (enableKeyboardNavigation) { this.enable(); } else { this.disable(); } if (typeof options.automaticKeyboardNavigation !== 'undefined') { this.automaticKeyboardNavigation = options.automaticKeyboardNavigation; } } toggle(): void { this.triggered = !this.triggered; } private enable(): void { if (this.enabled) { return; } const onChar = Event.chain(domEvent(this.view.domNode, 'keydown')) .filter(e => !isInputElement(e.target as HTMLElement)) .filter(() => this.automaticKeyboardNavigation || this.triggered) .map(event => new StandardKeyboardEvent(event)) .filter(e => this.delegate.mightProducePrintableCharacter(e)) .forEach(e => { e.stopPropagation(); e.preventDefault(); }) .map(event => event.browserEvent.key) .event; const onClear = Event.debounce<string, null>(onChar, () => null, 800); const onInput = Event.reduce<string | null, string | null>(Event.any(onChar, onClear), (r, i) => i === null ? null : ((r || '') + i)); onInput(this.onInput, this, this.enabledDisposables); this.enabled = true; this.triggered = false; } private disable(): void { if (!this.enabled) { return; } this.enabledDisposables.clear(); this.enabled = false; this.triggered = false; } private onInput(word: string | null): void { if (!word) { this.state = TypeLabelControllerState.Idle; this.triggered = false; return; } const focus = this.list.getFocus(); const start = focus.length > 0 ? focus[0] : 0; const delta = this.state === TypeLabelControllerState.Idle ? 1 : 0; this.state = TypeLabelControllerState.Typing; for (let i = 0; i < this.list.length; i++) { const index = (start + i + delta) % this.list.length; const label = this.keyboardNavigationLabelProvider.getKeyboardNavigationLabel(this.view.element(index)); const labelStr = label && label.toString(); if (typeof labelStr === 'undefined' || matchesPrefix(word, labelStr)) { this.list.setFocus([index]); this.list.reveal(index); return; } } } dispose() { this.disable(); this.enabledDisposables.dispose(); this.disposables.dispose(); } } class DOMFocusController<T> implements IDisposable { private readonly disposables = new DisposableStore(); constructor( private list: List<T>, private view: ListView<T> ) { const onKeyDown = Event.chain(domEvent(view.domNode, 'keydown')) .filter(e => !isInputElement(e.target as HTMLElement)) .map(e => new StandardKeyboardEvent(e)); onKeyDown.filter(e => e.keyCode === KeyCode.Tab && !e.ctrlKey && !e.metaKey && !e.shiftKey && !e.altKey) .on(this.onTab, this, this.disposables); } private onTab(e: StandardKeyboardEvent): void { if (e.target !== this.view.domNode) { return; } const focus = this.list.getFocus(); if (focus.length === 0) { return; } const focusedDomElement = this.view.domElement(focus[0]); if (!focusedDomElement) { return; } const tabIndexElement = focusedDomElement.querySelector('[tabIndex]'); if (!tabIndexElement || !(tabIndexElement instanceof HTMLElement) || tabIndexElement.tabIndex === -1) { return; } const style = window.getComputedStyle(tabIndexElement); if (style.visibility === 'hidden' || style.display === 'none') { return; } e.preventDefault(); e.stopPropagation(); tabIndexElement.focus(); } dispose() { this.disposables.dispose(); } } export function isSelectionSingleChangeEvent(event: IListMouseEvent<any> | IListTouchEvent<any>): boolean { return platform.isMacintosh ? event.browserEvent.metaKey : event.browserEvent.ctrlKey; } export function isSelectionRangeChangeEvent(event: IListMouseEvent<any> | IListTouchEvent<any>): boolean { return event.browserEvent.shiftKey; } function isMouseRightClick(event: UIEvent): boolean { return event instanceof MouseEvent && event.button === 2; } const DefaultMultipleSelectionController = { isSelectionSingleChangeEvent, isSelectionRangeChangeEvent }; const DefaultOpenController: IOpenController = { shouldOpen: (event: UIEvent) => { if (event instanceof MouseEvent) { return !isMouseRightClick(event); } return true; } }; export class MouseController<T> implements IDisposable { private multipleSelectionSupport: boolean; readonly multipleSelectionController: IMultipleSelectionController<T> | undefined; private openController: IOpenController; private mouseSupport: boolean; private readonly disposables = new DisposableStore(); constructor(protected list: List<T>) { this.multipleSelectionSupport = !(list.options.multipleSelectionSupport === false); if (this.multipleSelectionSupport) { this.multipleSelectionController = list.options.multipleSelectionController || DefaultMultipleSelectionController; } this.openController = list.options.openController || DefaultOpenController; this.mouseSupport = typeof list.options.mouseSupport === 'undefined' || !!list.options.mouseSupport; if (this.mouseSupport) { list.onMouseDown(this.onMouseDown, this, this.disposables); list.onContextMenu(this.onContextMenu, this, this.disposables); list.onMouseDblClick(this.onDoubleClick, this, this.disposables); list.onTouchStart(this.onMouseDown, this, this.disposables); this.disposables.add(Gesture.addTarget(list.getHTMLElement())); } list.onMouseClick(this.onPointer, this, this.disposables); list.onMouseMiddleClick(this.onPointer, this, this.disposables); list.onTap(this.onPointer, this, this.disposables); } protected isSelectionSingleChangeEvent(event: IListMouseEvent<any> | IListTouchEvent<any>): boolean { if (this.multipleSelectionController) { return this.multipleSelectionController.isSelectionSingleChangeEvent(event); } return platform.isMacintosh ? event.browserEvent.metaKey : event.browserEvent.ctrlKey; } protected isSelectionRangeChangeEvent(event: IListMouseEvent<any> | IListTouchEvent<any>): boolean { if (this.multipleSelectionController) { return this.multipleSelectionController.isSelectionRangeChangeEvent(event); } return event.browserEvent.shiftKey; } private isSelectionChangeEvent(event: IListMouseEvent<any> | IListTouchEvent<any>): boolean { return this.isSelectionSingleChangeEvent(event) || this.isSelectionRangeChangeEvent(event); } private onMouseDown(e: IListMouseEvent<T> | IListTouchEvent<T>): void { if (document.activeElement !== e.browserEvent.target) { this.list.domFocus(); } } private onContextMenu(e: IListContextMenuEvent<T>): void { const focus = typeof e.index === 'undefined' ? [] : [e.index]; this.list.setFocus(focus, e.browserEvent); } protected onPointer(e: IListMouseEvent<T>): void { if (!this.mouseSupport) { return; } if (isInputElement(e.browserEvent.target as HTMLElement)) { return; } let reference = this.list.getFocus()[0]; const selection = this.list.getSelection(); reference = reference === undefined ? selection[0] : reference; const focus = e.index; if (typeof focus === 'undefined') { this.list.setFocus([], e.browserEvent); this.list.setSelection([], e.browserEvent); return; } if (this.multipleSelectionSupport && this.isSelectionRangeChangeEvent(e)) { return this.changeSelection(e, reference); } if (this.multipleSelectionSupport && this.isSelectionChangeEvent(e)) { return this.changeSelection(e, reference); } this.list.setFocus([focus], e.browserEvent); if (!isMouseRightClick(e.browserEvent)) { this.list.setSelection([focus], e.browserEvent); if (this.openController.shouldOpen(e.browserEvent)) { this.list.open([focus], e.browserEvent); } } } protected onDoubleClick(e: IListMouseEvent<T>): void { if (isInputElement(e.browserEvent.target as HTMLElement)) { return; } if (this.multipleSelectionSupport && this.isSelectionChangeEvent(e)) { return; } const focus = this.list.getFocus(); this.list.setSelection(focus, e.browserEvent); this.list.pin(focus); } private changeSelection(e: IListMouseEvent<T> | IListTouchEvent<T>, reference: number | undefined): void { const focus = e.index!; if (this.isSelectionRangeChangeEvent(e) && reference !== undefined) { const min = Math.min(reference, focus); const max = Math.max(reference, focus); const rangeSelection = range(min, max + 1); const selection = this.list.getSelection(); const contiguousRange = getContiguousRangeContaining(disjunction(selection, [reference]), reference); if (contiguousRange.length === 0) { return; } const newSelection = disjunction(rangeSelection, relativeComplement(selection, contiguousRange)); this.list.setSelection(newSelection, e.browserEvent); } else if (this.isSelectionSingleChangeEvent(e)) { const selection = this.list.getSelection(); const newSelection = selection.filter(i => i !== focus); this.list.setFocus([focus]); if (selection.length === newSelection.length) { this.list.setSelection([...newSelection, focus], e.browserEvent); } else { this.list.setSelection(newSelection, e.browserEvent); } } } dispose() { this.disposables.dispose(); } } export interface IMultipleSelectionController<T> { isSelectionSingleChangeEvent(event: IListMouseEvent<T> | IListTouchEvent<T>): boolean; isSelectionRangeChangeEvent(event: IListMouseEvent<T> | IListTouchEvent<T>): boolean; } export interface IOpenController { shouldOpen(event: UIEvent): boolean; } export interface IStyleController { style(styles: IListStyles): void; } export interface IAccessibilityProvider<T> { /** * Given an element in the tree, return the ARIA label that should be associated with the * item. This helps screen readers to provide a meaningful label for the currently focused * tree element. * * Returning null will not disable ARIA for the element. Instead it is up to the screen reader * to compute a meaningful label based on the contents of the element in the DOM * * See also: https://www.w3.org/TR/wai-aria/#aria-label */ getAriaLabel(element: T): string | null; /** * https://www.w3.org/TR/wai-aria/#aria-level */ getAriaLevel?(element: T): number | undefined; onDidChangeActiveDescendant?: Event<void>; getActiveDescendantId?(element: T): string | undefined; } export class DefaultStyleController implements IStyleController { constructor(private styleElement: HTMLStyleElement, private selectorSuffix: string) { } style(styles: IListStyles): void { const suffix = this.selectorSuffix && `.${this.selectorSuffix}`; const content: string[] = []; if (styles.listBackground) { if (styles.listBackground.isOpaque()) { content.push(`.monaco-list${suffix} .monaco-list-rows { background: ${styles.listBackground}; }`); } else if (!platform.isMacintosh) { // subpixel AA doesn't exist in macOS console.warn(`List with id '${this.selectorSuffix}' was styled with a non-opaque background color. This will break sub-pixel antialiasing.`); } } if (styles.listFocusBackground) { content.push(`.monaco-list${suffix}:focus .monaco-list-row.focused { background-color: ${styles.listFocusBackground}; }`); content.push(`.monaco-list${suffix}:focus .monaco-list-row.focused:hover { background-color: ${styles.listFocusBackground}; }`); // overwrite :hover style in this case! } if (styles.listFocusForeground) { content.push(`.monaco-list${suffix}:focus .monaco-list-row.focused { color: ${styles.listFocusForeground}; }`); } if (styles.listActiveSelectionBackground) { content.push(`.monaco-list${suffix}:focus .monaco-list-row.selected { background-color: ${styles.listActiveSelectionBackground}; }`); content.push(`.monaco-list${suffix}:focus .monaco-list-row.selected:hover { background-color: ${styles.listActiveSelectionBackground}; }`); // overwrite :hover style in this case! } if (styles.listActiveSelectionForeground) { content.push(`.monaco-list${suffix}:focus .monaco-list-row.selected { color: ${styles.listActiveSelectionForeground}; }`); } if (styles.listFocusAndSelectionBackground) { content.push(` .monaco-drag-image, .monaco-list${suffix}:focus .monaco-list-row.selected.focused { background-color: ${styles.listFocusAndSelectionBackground}; } `); } if (styles.listFocusAndSelectionForeground) { content.push(` .monaco-drag-image, .monaco-list${suffix}:focus .monaco-list-row.selected.focused { color: ${styles.listFocusAndSelectionForeground}; } `); } if (styles.listInactiveFocusBackground) { content.push(`.monaco-list${suffix} .monaco-list-row.focused { background-color: ${styles.listInactiveFocusBackground}; }`); content.push(`.monaco-list${suffix} .monaco-list-row.focused:hover { background-color: ${styles.listInactiveFocusBackground}; }`); // overwrite :hover style in this case! } if (styles.listInactiveSelectionBackground) { content.push(`.monaco-list${suffix} .monaco-list-row.selected { background-color: ${styles.listInactiveSelectionBackground}; }`); content.push(`.monaco-list${suffix} .monaco-list-row.selected:hover { background-color: ${styles.listInactiveSelectionBackground}; }`); // overwrite :hover style in this case! } if (styles.listInactiveSelectionForeground) { content.push(`.monaco-list${suffix} .monaco-list-row.selected { color: ${styles.listInactiveSelectionForeground}; }`); } if (styles.listHoverBackground) { content.push(`.monaco-list${suffix}:not(.drop-target) .monaco-list-row:hover:not(.selected):not(.focused) { background-color: ${styles.listHoverBackground}; }`); } if (styles.listHoverForeground) { content.push(`.monaco-list${suffix} .monaco-list-row:hover:not(.selected):not(.focused) { color: ${styles.listHoverForeground}; }`); } if (styles.listSelectionOutline) { content.push(`.monaco-list${suffix} .monaco-list-row.selected { outline: 1px dotted ${styles.listSelectionOutline}; outline-offset: -1px; }`); } if (styles.listFocusOutline) { content.push(` .monaco-drag-image, .monaco-list${suffix}:focus .monaco-list-row.focused { outline: 1px solid ${styles.listFocusOutline}; outline-offset: -1px; } `); } if (styles.listInactiveFocusOutline) { content.push(`.monaco-list${suffix} .monaco-list-row.focused { outline: 1px dotted ${styles.listInactiveFocusOutline}; outline-offset: -1px; }`); } if (styles.listHoverOutline) { content.push(`.monaco-list${suffix} .monaco-list-row:hover { outline: 1px dashed ${styles.listHoverOutline}; outline-offset: -1px; }`); } if (styles.listDropBackground) { content.push(` .monaco-list${suffix}.drop-target, .monaco-list${suffix} .monaco-list-rows.drop-target, .monaco-list${suffix} .monaco-list-row.drop-target { background-color: ${styles.listDropBackground} !important; color: inherit !important; } `); } if (styles.listFilterWidgetBackground) { content.push(`.monaco-list-type-filter { background-color: ${styles.listFilterWidgetBackground} }`); } if (styles.listFilterWidgetOutline) { content.push(`.monaco-list-type-filter { border: 1px solid ${styles.listFilterWidgetOutline}; }`); } if (styles.listFilterWidgetNoMatchesOutline) { content.push(`.monaco-list-type-filter.no-matches { border: 1px solid ${styles.listFilterWidgetNoMatchesOutline}; }`); } if (styles.listMatchesShadow) { content.push(`.monaco-list-type-filter { box-shadow: 1px 1px 1px ${styles.listMatchesShadow}; }`); } const newStyles = content.join('\n'); if (newStyles !== this.styleElement.innerHTML) { this.styleElement.innerHTML = newStyles; } } } export interface IListOptions<T> { readonly identityProvider?: IIdentityProvider<T>; readonly dnd?: IListDragAndDrop<T>; readonly enableKeyboardNavigation?: boolean; readonly automaticKeyboardNavigation?: boolean; readonly keyboardNavigationLabelProvider?: IKeyboardNavigationLabelProvider<T>; readonly keyboardNavigationDelegate?: IKeyboardNavigationDelegate; readonly ariaRole?: ListAriaRootRole | string; readonly ariaLabel?: string; readonly keyboardSupport?: boolean; readonly multipleSelectionSupport?: boolean; readonly multipleSelectionController?: IMultipleSelectionController<T>; readonly openController?: IOpenController; readonly styleController?: (suffix: string) => IStyleController; readonly accessibilityProvider?: IAccessibilityProvider<T>; // list view options readonly useShadows?: boolean; readonly verticalScrollMode?: ScrollbarVisibility; readonly setRowLineHeight?: boolean; readonly setRowHeight?: boolean; readonly supportDynamicHeights?: boolean; readonly mouseSupport?: boolean; readonly horizontalScrolling?: boolean; readonly ariaProvider?: IAriaProvider<T>; } export interface IListStyles { listBackground?: Color; listFocusBackground?: Color; listFocusForeground?: Color; listActiveSelectionBackground?: Color; listActiveSelectionForeground?: Color; listFocusAndSelectionBackground?: Color; listFocusAndSelectionForeground?: Color; listInactiveSelectionBackground?: Color; listInactiveSelectionForeground?: Color; listInactiveFocusBackground?: Color; listHoverBackground?: Color; listHoverForeground?: Color; listDropBackground?: Color; listFocusOutline?: Color; listInactiveFocusOutline?: Color; listSelectionOutline?: Color; listHoverOutline?: Color; listFilterWidgetBackground?: Color; listFilterWidgetOutline?: Color; listFilterWidgetNoMatchesOutline?: Color; listMatchesShadow?: Color; treeIndentGuidesStroke?: Color; } const defaultStyles: IListStyles = { listFocusBackground: Color.fromHex('#7FB0D0'), listActiveSelectionBackground: Color.fromHex('#0E639C'), listActiveSelectionForeground: Color.fromHex('#FFFFFF'), listFocusAndSelectionBackground: Color.fromHex('#094771'), listFocusAndSelectionForeground: Color.fromHex('#FFFFFF'), listInactiveSelectionBackground: Color.fromHex('#3F3F46'), listHoverBackground: Color.fromHex('#2A2D2E'), listDropBackground: Color.fromHex('#383B3D'), treeIndentGuidesStroke: Color.fromHex('#a9a9a9') }; const DefaultOptions = { keyboardSupport: true, mouseSupport: true, multipleSelectionSupport: true, dnd: { getDragURI() { return null; }, onDragStart(): void { }, onDragOver() { return false; }, drop() { } }, ariaRootRole: ListAriaRootRole.TREE }; // TODO@Joao: move these utils into a SortedArray class function getContiguousRangeContaining(range: number[], value: number): number[] { const index = range.indexOf(value); if (index === -1) { return []; } const result: number[] = []; let i = index - 1; while (i >= 0 && range[i] === value - (index - i)) { result.push(range[i--]); } result.reverse(); i = index; while (i < range.length && range[i] === value + (i - index)) { result.push(range[i++]); } return result; } /** * Given two sorted collections of numbers, returns the intersection * between them (OR). */ function disjunction(one: number[], other: number[]): number[] { const result: number[] = []; let i = 0, j = 0; while (i < one.length || j < other.length) { if (i >= one.length) { result.push(other[j++]); } else if (j >= other.length) { result.push(one[i++]); } else if (one[i] === other[j]) { result.push(one[i]); i++; j++; continue; } else if (one[i] < other[j]) { result.push(one[i++]); } else { result.push(other[j++]); } } return result; } /** * Given two sorted collections of numbers, returns the relative * complement between them (XOR). */ function relativeComplement(one: number[], other: number[]): number[] { const result: number[] = []; let i = 0, j = 0; while (i < one.length || j < other.length) { if (i >= one.length) { result.push(other[j++]); } else if (j >= other.length) { result.push(one[i++]); } else if (one[i] === other[j]) { i++; j++; continue; } else if (one[i] < other[j]) { result.push(one[i++]); } else { j++; } } return result; } const numericSort = (a: number, b: number) => a - b; class PipelineRenderer<T> implements IListRenderer<T, any> { constructor( private _templateId: string, private renderers: IListRenderer<any /* TODO@joao */, any>[] ) { } get templateId(): string { return this._templateId; } renderTemplate(container: HTMLElement): any[] { return this.renderers.map(r => r.renderTemplate(container)); } renderElement(element: T, index: number, templateData: any[], height: number | undefined): void { let i = 0; for (const renderer of this.renderers) { renderer.renderElement(element, index, templateData[i++], height); } } disposeElement(element: T, index: number, templateData: any[], height: number | undefined): void { let i = 0; for (const renderer of this.renderers) { if (renderer.disposeElement) { renderer.disposeElement(element, index, templateData[i], height); } i += 1; } } disposeTemplate(templateData: any[]): void { let i = 0; for (const renderer of this.renderers) { renderer.disposeTemplate(templateData[i++]); } } } class AccessibiltyRenderer<T> implements IListRenderer<T, HTMLElement> { templateId: string = 'a18n'; constructor(private accessibilityProvider: IAccessibilityProvider<T>) { } renderTemplate(container: HTMLElement): HTMLElement { return container; } renderElement(element: T, index: number, container: HTMLElement): void { const ariaLabel = this.accessibilityProvider.getAriaLabel(element); if (ariaLabel) { container.setAttribute('aria-label', ariaLabel); } else { container.removeAttribute('aria-label'); } const ariaLevel = this.accessibilityProvider.getAriaLevel && this.accessibilityProvider.getAriaLevel(element); if (typeof ariaLevel === 'number') { container.setAttribute('aria-level', `${ariaLevel}`); } else { container.removeAttribute('aria-level'); } } disposeTemplate(templateData: any): void { // noop } } class ListViewDragAndDrop<T> implements IListViewDragAndDrop<T> { constructor(private list: List<T>, private dnd: IListDragAndDrop<T>) { } getDragElements(element: T): T[] { const selection = this.list.getSelectedElements(); const elements = selection.indexOf(element) > -1 ? selection : [element]; return elements; } getDragURI(element: T): string | null { return this.dnd.getDragURI(element); } getDragLabel?(elements: T[], originalEvent: DragEvent): string | undefined { if (this.dnd.getDragLabel) { return this.dnd.getDragLabel(elements, originalEvent); } return undefined; } onDragStart(data: IDragAndDropData, originalEvent: DragEvent): void { if (this.dnd.onDragStart) { this.dnd.onDragStart(data, originalEvent); } } onDragOver(data: IDragAndDropData, targetElement: T, targetIndex: number, originalEvent: DragEvent): boolean | IListDragOverReaction { return this.dnd.onDragOver(data, targetElement, targetIndex, originalEvent); } onDragEnd(originalEvent: DragEvent): void { if (this.dnd.onDragEnd) { this.dnd.onDragEnd(originalEvent); } } drop(data: IDragAndDropData, targetElement: T, targetIndex: number, originalEvent: DragEvent): void { this.dnd.drop(data, targetElement, targetIndex, originalEvent); } } export interface IListOptionsUpdate { readonly enableKeyboardNavigation?: boolean; readonly automaticKeyboardNavigation?: boolean; } export class List<T> implements ISpliceable<T>, IDisposable { private focus: Trait<T>; private selection: Trait<T>; private eventBufferer = new EventBufferer(); protected view: ListView<T>; private spliceable: ISpliceable<T>; private styleController: IStyleController; private typeLabelController?: TypeLabelController<T>; private accessibilityProvider?: IAccessibilityProvider<T>; protected readonly disposables = new DisposableStore(); @memoize get onDidChangeFocus(): Event<IListEvent<T>> { return Event.map(this.eventBufferer.wrapEvent(this.focus.onChange), e => this.toListEvent(e)); } @memoize get onDidChangeSelection(): Event<IListEvent<T>> { return Event.map(this.eventBufferer.wrapEvent(this.selection.onChange), e => this.toListEvent(e)); } private readonly _onDidOpen = new Emitter<IListEvent<T>>(); readonly onDidOpen: Event<IListEvent<T>> = this._onDidOpen.event; private readonly _onDidPin = new Emitter<IListEvent<T>>(); readonly onDidPin: Event<IListEvent<T>> = this._onDidPin.event; get domId(): string { return this.view.domId; } get onDidScroll(): Event<ScrollEvent> { return this.view.onDidScroll; } get onMouseClick(): Event<IListMouseEvent<T>> { return this.view.onMouseClick; } get onMouseDblClick(): Event<IListMouseEvent<T>> { return this.view.onMouseDblClick; } get onMouseMiddleClick(): Event<IListMouseEvent<T>> { return this.view.onMouseMiddleClick; } get onMouseUp(): Event<IListMouseEvent<T>> { return this.view.onMouseUp; } get onMouseDown(): Event<IListMouseEvent<T>> { return this.view.onMouseDown; } get onMouseOver(): Event<IListMouseEvent<T>> { return this.view.onMouseOver; } get onMouseMove(): Event<IListMouseEvent<T>> { return this.view.onMouseMove; } get onMouseOut(): Event<IListMouseEvent<T>> { return this.view.onMouseOut; } get onTouchStart(): Event<IListTouchEvent<T>> { return this.view.onTouchStart; } get onTap(): Event<IListGestureEvent<T>> { return this.view.onTap; } private didJustPressContextMenuKey: boolean = false; @memoize get onContextMenu(): Event<IListContextMenuEvent<T>> { const fromKeydown = Event.chain(domEvent(this.view.domNode, 'keydown')) .map(e => new StandardKeyboardEvent(e)) .filter(e => this.didJustPressContextMenuKey = e.keyCode === KeyCode.ContextMenu || (e.shiftKey && e.keyCode === KeyCode.F10)) .filter(e => { e.preventDefault(); e.stopPropagation(); return false; }) .event as Event<any>; const fromKeyup = Event.chain(domEvent(this.view.domNode, 'keyup')) .filter(() => { const didJustPressContextMenuKey = this.didJustPressContextMenuKey; this.didJustPressContextMenuKey = false; return didJustPressContextMenuKey; }) .filter(() => this.getFocus().length > 0 && !!this.view.domElement(this.getFocus()[0])) .map(browserEvent => { const index = this.getFocus()[0]; const element = this.view.element(index); const anchor = this.view.domElement(index) as HTMLElement; return { index, element, anchor, browserEvent }; }) .event; const fromMouse = Event.chain(this.view.onContextMenu) .filter(() => !this.didJustPressContextMenuKey) .map(({ element, index, browserEvent }) => ({ element, index, anchor: { x: browserEvent.clientX + 1, y: browserEvent.clientY }, browserEvent })) .event; return Event.any<IListContextMenuEvent<T>>(fromKeydown, fromKeyup, fromMouse); } get onKeyDown(): Event<KeyboardEvent> { return domEvent(this.view.domNode, 'keydown'); } get onKeyUp(): Event<KeyboardEvent> { return domEvent(this.view.domNode, 'keyup'); } get onKeyPress(): Event<KeyboardEvent> { return domEvent(this.view.domNode, 'keypress'); } readonly onDidFocus: Event<void>; readonly onDidBlur: Event<void>; private readonly _onDidDispose = new Emitter<void>(); readonly onDidDispose: Event<void> = this._onDidDispose.event; constructor( private user: string, container: HTMLElement, virtualDelegate: IListVirtualDelegate<T>, renderers: IListRenderer<any /* TODO@joao */, any>[], private _options: IListOptions<T> = DefaultOptions ) { this.focus = new Trait('focused'); this.selection = new SelectionTrait(); mixin(_options, defaultStyles, false); const baseRenderers: IListRenderer<T, ITraitTemplateData>[] = [this.focus.renderer, this.selection.renderer]; this.accessibilityProvider = _options.accessibilityProvider; if (this.accessibilityProvider) { baseRenderers.push(new AccessibiltyRenderer<T>(this.accessibilityProvider)); if (this.accessibilityProvider.onDidChangeActiveDescendant) { this.accessibilityProvider.onDidChangeActiveDescendant(this.onDidChangeActiveDescendant, this, this.disposables); } } renderers = renderers.map(r => new PipelineRenderer(r.templateId, [...baseRenderers, r])); const viewOptions: IListViewOptions<T> = { ..._options, dnd: _options.dnd && new ListViewDragAndDrop(this, _options.dnd) }; this.view = new ListView(container, virtualDelegate, renderers, viewOptions); if (typeof _options.ariaRole !== 'string') { this.view.domNode.setAttribute('role', ListAriaRootRole.TREE); } else { this.view.domNode.setAttribute('role', _options.ariaRole); } if (_options.styleController) { this.styleController = _options.styleController(this.view.domId); } else { const styleElement = DOM.createStyleSheet(this.view.domNode); this.styleController = new DefaultStyleController(styleElement, this.view.domId); } this.spliceable = new CombinedSpliceable([ new TraitSpliceable(this.focus, this.view, _options.identityProvider), new TraitSpliceable(this.selection, this.view, _options.identityProvider), this.view ]); this.disposables.add(this.focus); this.disposables.add(this.selection); this.disposables.add(this.view); this.disposables.add(this._onDidDispose); this.onDidFocus = Event.map(domEvent(this.view.domNode, 'focus', true), () => null!); this.onDidBlur = Event.map(domEvent(this.view.domNode, 'blur', true), () => null!); this.disposables.add(new DOMFocusController(this, this.view)); if (typeof _options.keyboardSupport !== 'boolean' || _options.keyboardSupport) { const controller = new KeyboardController(this, this.view, _options); this.disposables.add(controller); } if (_options.keyboardNavigationLabelProvider) { const delegate = _options.keyboardNavigationDelegate || DefaultKeyboardNavigationDelegate; this.typeLabelController = new TypeLabelController(this, this.view, _options.keyboardNavigationLabelProvider, delegate); this.disposables.add(this.typeLabelController); } this.disposables.add(this.createMouseController(_options)); this.onDidChangeFocus(this._onFocusChange, this, this.disposables); this.onDidChangeSelection(this._onSelectionChange, this, this.disposables); if (_options.ariaLabel) { this.view.domNode.setAttribute('aria-label', localize('aria list', "{0}. Use the navigation keys to navigate.", _options.ariaLabel)); } if (_options.multipleSelectionSupport) { this.view.domNode.setAttribute('aria-multiselectable', 'true'); } } protected createMouseController(options: IListOptions<T>): MouseController<T> { return new MouseController(this); } updateOptions(optionsUpdate: IListOptionsUpdate = {}): void { this._options = { ...this._options, ...optionsUpdate }; if (this.typeLabelController) { this.typeLabelController.updateOptions(this._options); } } get options(): IListOptions<T> { return this._options; } splice(start: number, deleteCount: number, elements: T[] = []): void { if (start < 0 || start > this.view.length) { throw new ListError(this.user, `Invalid start index: ${start}`); } if (deleteCount < 0) { throw new ListError(this.user, `Invalid delete count: ${deleteCount}`); } if (deleteCount === 0 && elements.length === 0) { return; } this.eventBufferer.bufferEvents(() => this.spliceable.splice(start, deleteCount, elements)); } updateWidth(index: number): void { this.view.updateWidth(index); } updateElementHeight(index: number, size: number): void { this.view.updateElementHeight(index, size); } rerender(): void { this.view.rerender(); } element(index: number): T { return this.view.element(index); } get length(): number { return this.view.length; } get contentHeight(): number { return this.view.contentHeight; } get onDidChangeContentHeight(): Event<number> { return this.view.onDidChangeContentHeight; } get scrollTop(): number { return this.view.getScrollTop(); } set scrollTop(scrollTop: number) { this.view.setScrollTop(scrollTop); } get scrollLeft(): number { return this.view.getScrollLeft(); } set scrollLeft(scrollLeft: number) { this.view.setScrollLeft(scrollLeft); } get scrollHeight(): number { return this.view.scrollHeight; } get renderHeight(): number { return this.view.renderHeight; } get firstVisibleIndex(): number { return this.view.firstVisibleIndex; } get lastVisibleIndex(): number { return this.view.lastVisibleIndex; } domFocus(): void { this.view.domNode.focus(); } layout(height?: number, width?: number): void { this.view.layout(height, width); } toggleKeyboardNavigation(): void { if (this.typeLabelController) { this.typeLabelController.toggle(); } } setSelection(indexes: number[], browserEvent?: UIEvent): void { for (const index of indexes) { if (index < 0 || index >= this.length) { throw new ListError(this.user, `Invalid index ${index}`); } } this.selection.set(indexes, browserEvent); } getSelection(): number[] { return this.selection.get(); } getSelectedElements(): T[] { return this.getSelection().map(i => this.view.element(i)); } setFocus(indexes: number[], browserEvent?: UIEvent): void { for (const index of indexes) { if (index < 0 || index >= this.length) { throw new ListError(this.user, `Invalid index ${index}`); } } this.focus.set(indexes, browserEvent); } focusNext(n = 1, loop = false, browserEvent?: UIEvent, filter?: (element: T) => boolean): void { if (this.length === 0) { return; } const focus = this.focus.get(); const index = this.findNextIndex(focus.length > 0 ? focus[0] + n : 0, loop, filter); if (index > -1) { this.setFocus([index], browserEvent); } } focusPrevious(n = 1, loop = false, browserEvent?: UIEvent, filter?: (element: T) => boolean): void { if (this.length === 0) { return; } const focus = this.focus.get(); const index = this.findPreviousIndex(focus.length > 0 ? focus[0] - n : 0, loop, filter); if (index > -1) { this.setFocus([index], browserEvent); } } focusNextPage(browserEvent?: UIEvent, filter?: (element: T) => boolean): void { let lastPageIndex = this.view.indexAt(this.view.getScrollTop() + this.view.renderHeight); lastPageIndex = lastPageIndex === 0 ? 0 : lastPageIndex - 1; const lastPageElement = this.view.element(lastPageIndex); const currentlyFocusedElement = this.getFocusedElements()[0]; if (currentlyFocusedElement !== lastPageElement) { const lastGoodPageIndex = this.findPreviousIndex(lastPageIndex, false, filter); if (lastGoodPageIndex > -1 && currentlyFocusedElement !== this.view.element(lastGoodPageIndex)) { this.setFocus([lastGoodPageIndex], browserEvent); } else { this.setFocus([lastPageIndex], browserEvent); } } else { const previousScrollTop = this.view.getScrollTop(); this.view.setScrollTop(previousScrollTop + this.view.renderHeight - this.view.elementHeight(lastPageIndex)); if (this.view.getScrollTop() !== previousScrollTop) { // Let the scroll event listener run setTimeout(() => this.focusNextPage(browserEvent, filter), 0); } } } focusPreviousPage(browserEvent?: UIEvent, filter?: (element: T) => boolean): void { let firstPageIndex: number; const scrollTop = this.view.getScrollTop(); if (scrollTop === 0) { firstPageIndex = this.view.indexAt(scrollTop); } else { firstPageIndex = this.view.indexAfter(scrollTop - 1); } const firstPageElement = this.view.element(firstPageIndex); const currentlyFocusedElement = this.getFocusedElements()[0]; if (currentlyFocusedElement !== firstPageElement) { const firstGoodPageIndex = this.findNextIndex(firstPageIndex, false, filter); if (firstGoodPageIndex > -1 && currentlyFocusedElement !== this.view.element(firstGoodPageIndex)) { this.setFocus([firstGoodPageIndex], browserEvent); } else { this.setFocus([firstPageIndex], browserEvent); } } else { const previousScrollTop = scrollTop; this.view.setScrollTop(scrollTop - this.view.renderHeight); if (this.view.getScrollTop() !== previousScrollTop) { // Let the scroll event listener run setTimeout(() => this.focusPreviousPage(browserEvent, filter), 0); } } } focusLast(browserEvent?: UIEvent, filter?: (element: T) => boolean): void { if (this.length === 0) { return; } const index = this.findPreviousIndex(this.length - 1, false, filter); if (index > -1) { this.setFocus([index], browserEvent); } } focusFirst(browserEvent?: UIEvent, filter?: (element: T) => boolean): void { if (this.length === 0) { return; } const index = this.findNextIndex(0, false, filter); if (index > -1) { this.setFocus([index], browserEvent); } } private findNextIndex(index: number, loop = false, filter?: (element: T) => boolean): number { for (let i = 0; i < this.length; i++) { if (index >= this.length && !loop) { return -1; } index = index % this.length; if (!filter || filter(this.element(index))) { return index; } index++; } return -1; } private findPreviousIndex(index: number, loop = false, filter?: (element: T) => boolean): number { for (let i = 0; i < this.length; i++) { if (index < 0 && !loop) { return -1; } index = (this.length + (index % this.length)) % this.length; if (!filter || filter(this.element(index))) { return index; } index--; } return -1; } getFocus(): number[] { return this.focus.get(); } getFocusedElements(): T[] { return this.getFocus().map(i => this.view.element(i)); } reveal(index: number, relativeTop?: number): void { if (index < 0 || index >= this.length) { throw new ListError(this.user, `Invalid index ${index}`); } const scrollTop = this.view.getScrollTop(); const elementTop = this.view.elementTop(index); const elementHeight = this.view.elementHeight(index); if (isNumber(relativeTop)) { // y = mx + b const m = elementHeight - this.view.renderHeight; this.view.setScrollTop(m * clamp(relativeTop, 0, 1) + elementTop); } else { const viewItemBottom = elementTop + elementHeight; const wrapperBottom = scrollTop + this.view.renderHeight; if (elementTop < scrollTop && viewItemBottom >= wrapperBottom) { // The element is already overflowing the viewport, no-op } else if (elementTop < scrollTop) { this.view.setScrollTop(elementTop); } else if (viewItemBottom >= wrapperBottom) { this.view.setScrollTop(viewItemBottom - this.view.renderHeight); } } } /** * Returns the relative position of an element rendered in the list. * Returns `null` if the element isn't *entirely* in the visible viewport. */ getRelativeTop(index: number): number | null { if (index < 0 || index >= this.length) { throw new ListError(this.user, `Invalid index ${index}`); } const scrollTop = this.view.getScrollTop(); const elementTop = this.view.elementTop(index); const elementHeight = this.view.elementHeight(index); if (elementTop < scrollTop || elementTop + elementHeight > scrollTop + this.view.renderHeight) { return null; } // y = mx + b const m = elementHeight - this.view.renderHeight; return Math.abs((scrollTop - elementTop) / m); } isDOMFocused(): boolean { return this.view.domNode === document.activeElement; } getHTMLElement(): HTMLElement { return this.view.domNode; } open(indexes: number[], browserEvent?: UIEvent): void { for (const index of indexes) { if (index < 0 || index >= this.length) { throw new ListError(this.user, `Invalid index ${index}`); } } this._onDidOpen.fire({ indexes, elements: indexes.map(i => this.view.element(i)), browserEvent }); } pin(indexes: number[], browserEvent?: UIEvent): void { for (const index of indexes) { if (index < 0 || index >= this.length) { throw new ListError(this.user, `Invalid index ${index}`); } } this._onDidPin.fire({ indexes, elements: indexes.map(i => this.view.element(i)), browserEvent }); } style(styles: IListStyles): void { this.styleController.style(styles); } private toListEvent({ indexes, browserEvent }: ITraitChangeEvent) { return { indexes, elements: indexes.map(i => this.view.element(i)), browserEvent }; } private _onFocusChange(): void { const focus = this.focus.get(); DOM.toggleClass(this.view.domNode, 'element-focused', focus.length > 0); this.onDidChangeActiveDescendant(); } private onDidChangeActiveDescendant(): void { const focus = this.focus.get(); if (focus.length > 0) { let id: string | undefined; if (this.accessibilityProvider?.getActiveDescendantId) { id = this.accessibilityProvider.getActiveDescendantId(this.view.element(focus[0])); } this.view.domNode.setAttribute('aria-activedescendant', id || this.view.getElementDomId(focus[0])); } else { this.view.domNode.removeAttribute('aria-activedescendant'); } } private _onSelectionChange(): void { const selection = this.selection.get(); DOM.toggleClass(this.view.domNode, 'selection-none', selection.length === 0); DOM.toggleClass(this.view.domNode, 'selection-single', selection.length === 1); DOM.toggleClass(this.view.domNode, 'selection-multiple', selection.length > 1); } dispose(): void { this._onDidDispose.fire(); this.disposables.dispose(); this._onDidOpen.dispose(); this._onDidPin.dispose(); this._onDidDispose.dispose(); } }
src/vs/base/browser/ui/list/listWidget.ts
1
https://github.com/microsoft/vscode/commit/7aca51e3d98c58ee8e418df6b525930d90375d9f
[ 0.9990315437316895, 0.04421790689229965, 0.0001633360079722479, 0.00017642958846408874, 0.1926371306180954 ]
{ "id": 4, "code_window": [ "\t\tvirtualDelegate: IListVirtualDelegate<T>,\n", "\t\trenderers: IListRenderer<any /* TODO@joao */, any>[],\n", "\t\tprivate _options: IListOptions<T> = DefaultOptions\n", "\t) {\n", "\t\tthis.focus = new Trait('focused');\n", "\t\tthis.selection = new SelectionTrait();\n", "\n", "\t\tmixin(_options, defaultStyles, false);\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis.selection = new Trait('selected');\n", "\t\tthis.focus = new FocusTrait(this.selection.contains);\n" ], "file_path": "src/vs/base/browser/ui/list/listWidget.ts", "type": "replace", "edit_start_line_idx": 1200 }
<svg width="53" height="36" viewBox="0 0 53 36" fill="none" xmlns="http://www.w3.org/2000/svg"> <g clip-path="url(#clip0)"> <path fill-rule="evenodd" clip-rule="evenodd" d="M48.0364 4.01042H4.00779L4.00779 32.0286H48.0364V4.01042ZM4.00779 0.0078125C1.79721 0.0078125 0.00518799 1.79984 0.00518799 4.01042V32.0286C0.00518799 34.2392 1.79721 36.0312 4.00779 36.0312H48.0364C50.247 36.0312 52.039 34.2392 52.039 32.0286V4.01042C52.039 1.79984 50.247 0.0078125 48.0364 0.0078125H4.00779ZM8.01042 8.01302H12.013V12.0156H8.01042V8.01302ZM20.0182 8.01302H16.0156V12.0156H20.0182V8.01302ZM24.0208 8.01302H28.0234V12.0156H24.0208V8.01302ZM36.0286 8.01302H32.026V12.0156H36.0286V8.01302ZM40.0312 8.01302H44.0339V12.0156H40.0312V8.01302ZM16.0156 16.0182H8.01042V20.0208H16.0156V16.0182ZM20.0182 16.0182H24.0208V20.0208H20.0182V16.0182ZM32.026 16.0182H28.0234V20.0208H32.026V16.0182ZM44.0339 16.0182V20.0208H36.0286V16.0182H44.0339ZM12.013 24.0234H8.01042V28.026H12.013V24.0234ZM16.0156 24.0234H36.0286V28.026H16.0156V24.0234ZM44.0339 24.0234H40.0312V28.026H44.0339V24.0234Z" fill="#C5C5C5"/> </g> <defs> <clipPath id="clip0"> <rect width="53" height="36" fill="white"/> </clipPath> </defs> </svg>
src/vs/editor/standalone/browser/iPadShowKeyboard/keyboard-dark.svg
0
https://github.com/microsoft/vscode/commit/7aca51e3d98c58ee8e418df6b525930d90375d9f
[ 0.0003852808440569788, 0.00028050196124240756, 0.00017572310753166676, 0.00028050196124240756, 0.00010477886826265603 ]