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": 1,
"code_window": [
"import { INTERACTIVE_SESSION_CATEGORY } from 'vs/workbench/contrib/interactiveSession/browser/actions/interactiveSessionActions';\n",
"import { CONTEXT_RESPONSE_HAS_PROVIDER_ID, CONTEXT_RESPONSE_VOTE } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionContextKeys';\n",
"import { IInteractiveSessionService, IInteractiveSessionUserActionEvent, InteractiveSessionVoteDirection } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionService';\n",
"import { isResponseVM } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionViewModel';\n",
"\n",
"export function registerInteractiveSessionTitleActions() {\n",
"\tregisterAction2(class VoteUpAction extends Action2 {\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { CONTEXT_RESPONSE_VOTE } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionContextKeys';\n"
],
"file_path": "src/vs/workbench/contrib/interactiveSession/browser/actions/interactiveSessionTitleActions.ts",
"type": "replace",
"edit_start_line_idx": 11
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
.monaco-editor .mwh {
position: absolute;
color: var(--vscode-editorWhitespace-foreground) !important;
}
| src/vs/editor/browser/viewParts/whitespace/whitespace.css | 0 | https://github.com/microsoft/vscode/commit/c2bf6225a12e7f7d8afada6ec39560bb38e5838a | [
0.00017453402688261122,
0.00017453402688261122,
0.00017453402688261122,
0.00017453402688261122,
0
] |
{
"id": 1,
"code_window": [
"import { INTERACTIVE_SESSION_CATEGORY } from 'vs/workbench/contrib/interactiveSession/browser/actions/interactiveSessionActions';\n",
"import { CONTEXT_RESPONSE_HAS_PROVIDER_ID, CONTEXT_RESPONSE_VOTE } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionContextKeys';\n",
"import { IInteractiveSessionService, IInteractiveSessionUserActionEvent, InteractiveSessionVoteDirection } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionService';\n",
"import { isResponseVM } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionViewModel';\n",
"\n",
"export function registerInteractiveSessionTitleActions() {\n",
"\tregisterAction2(class VoteUpAction extends Action2 {\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { CONTEXT_RESPONSE_VOTE } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionContextKeys';\n"
],
"file_path": "src/vs/workbench/contrib/interactiveSession/browser/actions/interactiveSessionTitleActions.ts",
"type": "replace",
"edit_start_line_idx": 11
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { IBuiltinExtensionsScannerService, ExtensionType, IExtensionManifest, TargetPlatform, IExtension } from 'vs/platform/extensions/common/extensions';
import { isWeb, Language } from 'vs/base/common/platform';
import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService';
import { IUriIdentityService } from 'vs/platform/uriIdentity/common/uriIdentity';
import { InstantiationType, registerSingleton } from 'vs/platform/instantiation/common/extensions';
import { getGalleryExtensionId } from 'vs/platform/extensionManagement/common/extensionManagementUtil';
import { builtinExtensionsPath, FileAccess } from 'vs/base/common/network';
import { URI } from 'vs/base/common/uri';
import { IExtensionResourceLoaderService } from 'vs/platform/extensionResourceLoader/common/extensionResourceLoader';
import { IProductService } from 'vs/platform/product/common/productService';
import { ITranslations, localizeManifest } from 'vs/platform/extensionManagement/common/extensionNls';
import { ILogService } from 'vs/platform/log/common/log';
interface IBundledExtension {
extensionPath: string;
packageJSON: IExtensionManifest;
packageNLS?: any;
readmePath?: string;
changelogPath?: string;
}
export class BuiltinExtensionsScannerService implements IBuiltinExtensionsScannerService {
declare readonly _serviceBrand: undefined;
private readonly builtinExtensionsPromises: Promise<IExtension>[] = [];
private nlsUrl: URI | undefined;
constructor(
@IWorkbenchEnvironmentService environmentService: IWorkbenchEnvironmentService,
@IUriIdentityService uriIdentityService: IUriIdentityService,
@IExtensionResourceLoaderService private readonly extensionResourceLoaderService: IExtensionResourceLoaderService,
@IProductService productService: IProductService,
@ILogService private readonly logService: ILogService
) {
if (isWeb) {
const nlsBaseUrl = productService.extensionsGallery?.nlsBaseUrl;
// Only use the nlsBaseUrl if we are using a language other than the default, English.
if (nlsBaseUrl && productService.commit && !Language.isDefaultVariant()) {
this.nlsUrl = URI.joinPath(URI.parse(nlsBaseUrl), productService.commit, productService.version, Language.value());
}
const builtinExtensionsServiceUrl = FileAccess.asBrowserUri(builtinExtensionsPath);
if (builtinExtensionsServiceUrl) {
let bundledExtensions: IBundledExtension[] = [];
if (environmentService.isBuilt) {
// Built time configuration (do NOT modify)
bundledExtensions = [/*BUILD->INSERT_BUILTIN_EXTENSIONS*/];
} else {
// Find builtin extensions by checking for DOM
const builtinExtensionsElement = document.getElementById('vscode-workbench-builtin-extensions');
const builtinExtensionsElementAttribute = builtinExtensionsElement ? builtinExtensionsElement.getAttribute('data-settings') : undefined;
if (builtinExtensionsElementAttribute) {
try {
bundledExtensions = JSON.parse(builtinExtensionsElementAttribute);
} catch (error) { /* ignore error*/ }
}
}
this.builtinExtensionsPromises = bundledExtensions.map(async e => {
const id = getGalleryExtensionId(e.packageJSON.publisher, e.packageJSON.name);
return {
identifier: { id },
location: uriIdentityService.extUri.joinPath(builtinExtensionsServiceUrl!, e.extensionPath),
type: ExtensionType.System,
isBuiltin: true,
manifest: e.packageNLS ? await this.localizeManifest(id, e.packageJSON, e.packageNLS) : e.packageJSON,
readmeUrl: e.readmePath ? uriIdentityService.extUri.joinPath(builtinExtensionsServiceUrl!, e.readmePath) : undefined,
changelogUrl: e.changelogPath ? uriIdentityService.extUri.joinPath(builtinExtensionsServiceUrl!, e.changelogPath) : undefined,
targetPlatform: TargetPlatform.WEB,
validations: [],
isValid: true
};
});
}
}
}
async scanBuiltinExtensions(): Promise<IExtension[]> {
return [...await Promise.all(this.builtinExtensionsPromises)];
}
private async localizeManifest(extensionId: string, manifest: IExtensionManifest, fallbackTranslations: ITranslations): Promise<IExtensionManifest> {
if (!this.nlsUrl) {
return localizeManifest(manifest, fallbackTranslations);
}
// the `package` endpoint returns the translations in a key-value format similar to the package.nls.json file.
const uri = URI.joinPath(this.nlsUrl, extensionId, 'package');
try {
const res = await this.extensionResourceLoaderService.readExtensionResource(uri);
const json = JSON.parse(res.toString());
return localizeManifest(manifest, json, fallbackTranslations);
} catch (e) {
this.logService.error(e);
return localizeManifest(manifest, fallbackTranslations);
}
}
}
registerSingleton(IBuiltinExtensionsScannerService, BuiltinExtensionsScannerService, InstantiationType.Delayed);
| src/vs/workbench/services/extensionManagement/browser/builtinExtensionsScannerService.ts | 0 | https://github.com/microsoft/vscode/commit/c2bf6225a12e7f7d8afada6ec39560bb38e5838a | [
0.0001770637754816562,
0.0001710151700535789,
0.00016568419232498854,
0.0001708325435174629,
0.000003892970653396333
] |
{
"id": 2,
"code_window": [
"\t\t\t\t\toriginal: 'Vote Up'\n",
"\t\t\t\t},\n",
"\t\t\t\tf1: false,\n",
"\t\t\t\tcategory: INTERACTIVE_SESSION_CATEGORY,\n",
"\t\t\t\ticon: Codicon.thumbsup,\n",
"\t\t\t\tprecondition: CONTEXT_RESPONSE_VOTE.isEqualTo(''), // Should be disabled but visible when vote=down\n",
"\t\t\t\tmenu: {\n",
"\t\t\t\t\tid: MenuId.InteractiveSessionTitle,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\ttoggled: CONTEXT_RESPONSE_VOTE.isEqualTo('up'),\n"
],
"file_path": "src/vs/workbench/contrib/interactiveSession/browser/actions/interactiveSessionTitleActions.ts",
"type": "replace",
"edit_start_line_idx": 27
} | /*---------------------------------------------------------------------------------------------
* 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 { renderIcon } from 'vs/base/browser/ui/iconLabel/iconLabels';
import { IListVirtualDelegate } from 'vs/base/browser/ui/list/list';
import { IListAccessibilityProvider } from 'vs/base/browser/ui/list/listWidget';
import { ITreeNode, ITreeRenderer } from 'vs/base/browser/ui/tree/tree';
import { IntervalTimer } from 'vs/base/common/async';
import { Codicon } from 'vs/base/common/codicons';
import { Emitter, Event } from 'vs/base/common/event';
import { FuzzyScore } from 'vs/base/common/filters';
import { IMarkdownString, MarkdownString } from 'vs/base/common/htmlContent';
import { Disposable, DisposableStore, IDisposable } from 'vs/base/common/lifecycle';
import { ResourceMap } from 'vs/base/common/map';
import { FileAccess } from 'vs/base/common/network';
import { ThemeIcon } from 'vs/base/common/themables';
import { EditorExtensionsRegistry } from 'vs/editor/browser/editorExtensions';
import { CodeEditorWidget } from 'vs/editor/browser/widget/codeEditorWidget';
import { EDITOR_FONT_DEFAULTS, IEditorOptions } from 'vs/editor/common/config/editorOptions';
import { Range } from 'vs/editor/common/core/range';
import { ILanguageService } from 'vs/editor/common/languages/language';
import { ITextModel } from 'vs/editor/common/model';
import { IModelService } from 'vs/editor/common/services/model';
import { BracketMatchingController } from 'vs/editor/contrib/bracketMatching/browser/bracketMatching';
import { ContextMenuController } from 'vs/editor/contrib/contextmenu/browser/contextmenu';
import { IMarkdownRenderResult, MarkdownRenderer } from 'vs/editor/contrib/markdownRenderer/browser/markdownRenderer';
import { ViewportSemanticTokensContribution } from 'vs/editor/contrib/semanticTokens/browser/viewportSemanticTokens';
import { SmartSelectController } from 'vs/editor/contrib/smartSelect/browser/smartSelect';
import { WordHighlighterContribution } from 'vs/editor/contrib/wordHighlighter/browser/wordHighlighter';
import { localize } from 'vs/nls';
import { MenuWorkbenchToolBar } from 'vs/platform/actions/browser/toolbar';
import { MenuId } from 'vs/platform/actions/common/actions';
import { ICommandService } from 'vs/platform/commands/common/commands';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection';
import { ILogService } from 'vs/platform/log/common/log';
import { defaultButtonStyles } from 'vs/platform/theme/browser/defaultStyles';
import { MenuPreventer } from 'vs/workbench/contrib/codeEditor/browser/menuPreventer';
import { SelectionClipboardContributionID } from 'vs/workbench/contrib/codeEditor/browser/selectionClipboard';
import { getSimpleEditorOptions } from 'vs/workbench/contrib/codeEditor/browser/simpleEditorOptions';
import { IInteractiveSessionCodeBlockActionContext } from 'vs/workbench/contrib/interactiveSession/browser/actions/interactiveSessionCodeblockActions';
import { InteractiveSessionFollowups } from 'vs/workbench/contrib/interactiveSession/browser/interactiveSessionFollowups';
import { InteractiveSessionEditorOptions } from 'vs/workbench/contrib/interactiveSession/browser/interactiveSessionOptions';
import { CONTEXT_RESPONSE_HAS_PROVIDER_ID, CONTEXT_RESPONSE_VOTE } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionContextKeys';
import { IInteractiveSessionReplyFollowup, IInteractiveSessionService, IInteractiveSlashCommand, InteractiveSessionVoteDirection } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionService';
import { IInteractiveRequestViewModel, IInteractiveResponseViewModel, IInteractiveWelcomeMessageViewModel, isRequestVM, isResponseVM, isWelcomeVM } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionViewModel';
import { getNWords } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionWordCounter';
const $ = dom.$;
export type InteractiveTreeItem = IInteractiveRequestViewModel | IInteractiveResponseViewModel | IInteractiveWelcomeMessageViewModel;
interface IInteractiveListItemTemplate {
rowContainer: HTMLElement;
titleToolbar: MenuWorkbenchToolBar;
avatar: HTMLElement;
username: HTMLElement;
value: HTMLElement;
contextKeyService: IContextKeyService;
templateDisposables: IDisposable;
elementDisposables: DisposableStore;
}
interface IItemHeightChangeParams {
element: InteractiveTreeItem;
height: number;
}
const forceVerboseLayoutTracing = false;
export interface IInteractiveSessionRendererDelegate {
getListLength(): number;
getSlashCommands(): IInteractiveSlashCommand[];
}
export class InteractiveListItemRenderer extends Disposable implements ITreeRenderer<InteractiveTreeItem, FuzzyScore, IInteractiveListItemTemplate> {
static readonly cursorCharacter = '\u258c';
static readonly ID = 'item';
private readonly renderer: MarkdownRenderer;
protected readonly _onDidClickFollowup = this._register(new Emitter<IInteractiveSessionReplyFollowup>());
readonly onDidClickFollowup: Event<IInteractiveSessionReplyFollowup> = this._onDidClickFollowup.event;
protected readonly _onDidChangeItemHeight = this._register(new Emitter<IItemHeightChangeParams>());
readonly onDidChangeItemHeight: Event<IItemHeightChangeParams> = this._onDidChangeItemHeight.event;
private readonly _editorPool: EditorPool;
private _currentLayoutWidth: number = 0;
constructor(
private readonly editorOptions: InteractiveSessionEditorOptions,
private readonly delegate: IInteractiveSessionRendererDelegate,
@IInstantiationService private readonly instantiationService: IInstantiationService,
@IConfigurationService private readonly configService: IConfigurationService,
@ILogService private readonly logService: ILogService,
@ICommandService private readonly commandService: ICommandService,
@IContextKeyService private readonly contextKeyService: IContextKeyService,
@IInteractiveSessionService private readonly interactiveSessionService: IInteractiveSessionService,
) {
super();
this.renderer = this.instantiationService.createInstance(MarkdownRenderer, {});
this._editorPool = this._register(this.instantiationService.createInstance(EditorPool, this.editorOptions));
}
get templateId(): string {
return InteractiveListItemRenderer.ID;
}
private traceLayout(method: string, message: string) {
if (forceVerboseLayoutTracing) {
this.logService.info(`InteractiveListItemRenderer#${method}: ${message}`);
} else {
this.logService.trace(`InteractiveListItemRenderer#${method}: ${message}`);
}
}
private shouldRenderProgressively(element: IInteractiveResponseViewModel): boolean {
return !this.configService.getValue('interactive.experimental.disableProgressiveRendering') && element.progressiveResponseRenderingEnabled;
}
private getProgressiveRenderRate(element: IInteractiveResponseViewModel): number {
const configuredRate = this.configService.getValue('interactive.experimental.progressiveRenderingRate');
if (typeof configuredRate === 'number') {
return configuredRate;
}
if (element.isComplete) {
return 60;
}
if (element.contentUpdateTimings && element.contentUpdateTimings.impliedWordLoadRate) {
// This doesn't account for dead time after the last update. When the previous update is the final one and the model is only waiting for followupQuestions, that's good.
// When there was one quick update and then you are waiting longer for the next one, that's not good since the rate should be decreasing.
// If it's an issue, we can change this to be based on the total time from now to the beginning.
const rateBoost = 1.5;
return element.contentUpdateTimings.impliedWordLoadRate * rateBoost;
}
return 8;
}
layout(width: number): void {
this._currentLayoutWidth = width - 40; // TODO Padding
this._editorPool.inUse.forEach(editor => {
editor.layout(this._currentLayoutWidth);
});
}
renderTemplate(container: HTMLElement): IInteractiveListItemTemplate {
const templateDisposables = new DisposableStore();
const rowContainer = dom.append(container, $('.interactive-item-container'));
const header = dom.append(rowContainer, $('.header'));
const user = dom.append(header, $('.user'));
const avatar = dom.append(user, $('.avatar'));
const username = dom.append(user, $('h3.username'));
const value = dom.append(rowContainer, $('.value'));
const elementDisposables = new DisposableStore();
const contextKeyService = templateDisposables.add(this.contextKeyService.createScoped(rowContainer));
const scopedInstantiationService = this.instantiationService.createChild(new ServiceCollection([IContextKeyService, contextKeyService]));
const titleToolbar = templateDisposables.add(scopedInstantiationService.createInstance(MenuWorkbenchToolBar, header, MenuId.InteractiveSessionTitle, {
menuOptions: {
shouldForwardArgs: true
}
}));
const template: IInteractiveListItemTemplate = { avatar, username, value, rowContainer, elementDisposables, titleToolbar, templateDisposables, contextKeyService };
return template;
}
renderElement(node: ITreeNode<InteractiveTreeItem, FuzzyScore>, index: number, templateData: IInteractiveListItemTemplate): void {
const { element } = node;
const kind = isRequestVM(element) ? 'request' :
isResponseVM(element) ? 'response' :
'welcome';
this.traceLayout('renderElement', `${kind}, index=${index}`);
CONTEXT_RESPONSE_HAS_PROVIDER_ID.bindTo(templateData.contextKeyService).set(isResponseVM(element) && !!element.providerResponseId && !element.isPlaceholder);
if (isResponseVM(element)) {
CONTEXT_RESPONSE_VOTE.bindTo(templateData.contextKeyService).set(element.vote === InteractiveSessionVoteDirection.Up ? 'up' : element.vote === InteractiveSessionVoteDirection.Down ? 'down' : '');
} else {
CONTEXT_RESPONSE_VOTE.bindTo(templateData.contextKeyService).set('');
}
templateData.titleToolbar.context = element;
templateData.rowContainer.classList.toggle('interactive-request', isRequestVM(element));
templateData.rowContainer.classList.toggle('interactive-response', isResponseVM(element));
templateData.rowContainer.classList.toggle('interactive-welcome', isWelcomeVM(element));
templateData.rowContainer.classList.toggle('filtered-response', !!(isResponseVM(element) && element.errorDetails?.responseIsFiltered));
templateData.username.textContent = element.username;
if (element.avatarIconUri) {
const avatarIcon = dom.$<HTMLImageElement>('img.icon');
avatarIcon.src = FileAccess.uriToBrowserUri(element.avatarIconUri).toString(true);
templateData.avatar.replaceChildren(avatarIcon);
} else {
const defaultIcon = isRequestVM(element) ? Codicon.account : Codicon.hubot;
const avatarIcon = dom.$(ThemeIcon.asCSSSelector(defaultIcon));
templateData.avatar.replaceChildren(avatarIcon);
}
// Do a progressive render if
// - This the last response in the list
// - And the response is not complete
// - Or, we previously started a progressive rendering of this element (if the element is complete, we will finish progressive rendering with a very fast rate)
// - And, the feature is not disabled in configuration
if (isResponseVM(element) && index === this.delegate.getListLength() - 1 && (!element.isComplete || element.renderData) && this.shouldRenderProgressively(element)) {
this.traceLayout('renderElement', `start progressive render ${kind}, index=${index}`);
const progressiveRenderingDisposables = templateData.elementDisposables.add(new DisposableStore());
const timer = templateData.elementDisposables.add(new IntervalTimer());
const runProgressiveRender = (initial?: boolean) => {
try {
if (this.doNextProgressiveRender(element, index, templateData, !!initial, progressiveRenderingDisposables)) {
timer.cancel();
}
} catch (err) {
// Kill the timer if anything went wrong, avoid getting stuck in a nasty rendering loop.
timer.cancel();
throw err;
}
};
runProgressiveRender(true);
timer.cancelAndSet(runProgressiveRender, 50);
} else if (isResponseVM(element)) {
this.basicRenderElement(element.response.value, element, index, templateData);
} else if (isRequestVM(element)) {
this.basicRenderElement(element.messageText, element, index, templateData);
} else {
this.renderWelcomeMessage(element, templateData);
}
}
private basicRenderElement(markdownValue: string, element: InteractiveTreeItem, index: number, templateData: IInteractiveListItemTemplate) {
const fillInIncompleteTokens = isResponseVM(element) && (!element.isComplete || element.isCanceled || element.errorDetails?.responseIsFiltered || element.errorDetails?.responseIsIncomplete);
const result = this.renderMarkdown(new MarkdownString(markdownValue), element, templateData.elementDisposables, templateData, fillInIncompleteTokens);
dom.clearNode(templateData.value);
templateData.value.appendChild(result.element);
templateData.elementDisposables.add(result);
if (isResponseVM(element) && element.errorDetails?.message) {
const errorDetails = dom.append(templateData.value, $('.interactive-response-error-details', undefined, renderIcon(Codicon.error)));
errorDetails.appendChild($('span', undefined, element.errorDetails.message));
}
if (isResponseVM(element) && element.commandFollowups?.length) {
const followupsContainer = dom.append(templateData.value, $('.interactive-response-followups'));
templateData.elementDisposables.add(new InteractiveSessionFollowups(
followupsContainer,
element.commandFollowups,
defaultButtonStyles,
followup => {
this.interactiveSessionService.notifyUserAction({
providerId: element.providerId,
action: {
kind: 'command',
command: followup
}
});
return this.commandService.executeCommand(followup.commandId, ...(followup.args ?? []));
}));
}
}
private renderWelcomeMessage(element: IInteractiveWelcomeMessageViewModel, templateData: IInteractiveListItemTemplate) {
dom.clearNode(templateData.value);
const slashCommands = this.delegate.getSlashCommands();
for (const item of element.content) {
if (Array.isArray(item)) {
templateData.elementDisposables.add(new InteractiveSessionFollowups(
templateData.value,
item,
undefined,
followup => this._onDidClickFollowup.fire(followup)));
} else {
const result = this.renderMarkdown(item as IMarkdownString, element, templateData.elementDisposables, templateData);
for (const codeElement of result.element.querySelectorAll('code')) {
if (codeElement.textContent && slashCommands.find(command => codeElement.textContent === `/${command.command}`)) {
codeElement.classList.add('interactive-slash-command');
}
}
templateData.value.appendChild(result.element);
templateData.elementDisposables.add(result);
}
}
}
private doNextProgressiveRender(element: IInteractiveResponseViewModel, index: number, templateData: IInteractiveListItemTemplate, isInRenderElement: boolean, disposables: DisposableStore): boolean {
disposables.clear();
let isFullyRendered = false;
if (element.isCanceled) {
this.traceLayout('runProgressiveRender', `canceled, index=${index}`);
element.renderData = undefined;
this.basicRenderElement(element.response.value, element, index, templateData);
isFullyRendered = true;
} else {
// TODO- this method has the side effect of updating element.renderData
const toRender = this.getProgressiveMarkdownToRender(element);
isFullyRendered = !!element.renderData?.isFullyRendered;
if (isFullyRendered) {
// We've reached the end of the available content, so do a normal render
this.traceLayout('runProgressiveRender', `end progressive render, index=${index}`);
if (element.isComplete) {
this.traceLayout('runProgressiveRender', `and disposing renderData, response is complete, index=${index}`);
element.renderData = undefined;
} else {
this.traceLayout('runProgressiveRender', `Rendered all available words, but model is not complete.`);
}
disposables.clear();
this.basicRenderElement(element.response.value, element, index, templateData);
} else if (toRender) {
// Doing the progressive render
const plusCursor = toRender.match(/```.*$/) ? toRender + `\n${InteractiveListItemRenderer.cursorCharacter}` : toRender + ` ${InteractiveListItemRenderer.cursorCharacter}`;
const result = this.renderMarkdown(new MarkdownString(plusCursor), element, disposables, templateData, true);
dom.clearNode(templateData.value);
templateData.value.appendChild(result.element);
disposables.add(result);
} else {
// Nothing new to render, not done, keep waiting
return false;
}
}
// Some render happened - update the height
const height = templateData.rowContainer.offsetHeight;
element.currentRenderedHeight = height;
if (!isInRenderElement) {
this._onDidChangeItemHeight.fire({ element, height: templateData.rowContainer.offsetHeight });
}
return !!isFullyRendered;
}
private renderMarkdown(markdown: IMarkdownString, element: InteractiveTreeItem, disposables: DisposableStore, templateData: IInteractiveListItemTemplate, fillInIncompleteTokens = false): IMarkdownRenderResult {
const disposablesList: IDisposable[] = [];
let codeBlockIndex = 0;
// TODO if the slash commands stay completely dynamic, this isn't quite right
const slashCommands = this.delegate.getSlashCommands();
const usedSlashCommand = slashCommands.find(s => markdown.value.startsWith(`/${s.command} `));
const toRender = usedSlashCommand ? markdown.value.slice(usedSlashCommand.command.length + 2) : markdown.value;
markdown = new MarkdownString(toRender);
const result = this.renderer.render(markdown, {
fillInIncompleteTokens,
codeBlockRendererSync: (languageId, text) => {
const ref = this.renderCodeBlock({ languageId, text, codeBlockIndex: codeBlockIndex++, element, parentContextKeyService: templateData.contextKeyService }, disposables);
// Attach this after updating text/layout of the editor, so it should only be fired when the size updates later (horizontal scrollbar, wrapping)
// not during a renderElement OR a progressive render (when we will be firing this event anyway at the end of the render)
disposables.add(ref.object.onDidChangeContentHeight(() => {
ref.object.layout(this._currentLayoutWidth);
this._onDidChangeItemHeight.fire({ element, height: templateData.rowContainer.offsetHeight });
}));
disposablesList.push(ref);
return ref.object.element;
}
});
if (usedSlashCommand) {
const slashCommandElement = $('span.interactive-slash-command', { title: usedSlashCommand.detail }, `/${usedSlashCommand.command} `);
if (result.element.firstChild?.nodeName.toLowerCase() === 'p') {
result.element.firstChild.insertBefore(slashCommandElement, result.element.firstChild.firstChild);
} else {
result.element.insertBefore($('p', undefined, slashCommandElement), result.element.firstChild);
}
}
disposablesList.reverse().forEach(d => disposables.add(d));
return result;
}
private renderCodeBlock(data: IInteractiveResultCodeBlockData, disposables: DisposableStore): IDisposableReference<IInteractiveResultCodeBlockPart> {
const ref = this._editorPool.get();
const editorInfo = ref.object;
editorInfo.render(data, this._currentLayoutWidth);
return ref;
}
private getProgressiveMarkdownToRender(element: IInteractiveResponseViewModel): string | undefined {
const renderData = element.renderData ?? { renderedWordCount: 0, lastRenderTime: 0 };
const rate = this.getProgressiveRenderRate(element);
const numWordsToRender = renderData.lastRenderTime === 0 ?
1 :
renderData.renderedWordCount +
// Additional words to render beyond what's already rendered
Math.floor((Date.now() - renderData.lastRenderTime) / 1000 * rate);
if (numWordsToRender === renderData.renderedWordCount) {
return undefined;
}
const result = getNWords(element.response.value, numWordsToRender);
element.renderData = {
renderedWordCount: result.actualWordCount,
lastRenderTime: Date.now(),
isFullyRendered: result.isFullString
};
return result.value;
}
disposeElement(node: ITreeNode<InteractiveTreeItem, FuzzyScore>, index: number, templateData: IInteractiveListItemTemplate): void {
templateData.elementDisposables.clear();
}
disposeTemplate(templateData: IInteractiveListItemTemplate): void {
templateData.templateDisposables.dispose();
}
}
export class InteractiveSessionListDelegate implements IListVirtualDelegate<InteractiveTreeItem> {
constructor(
@ILogService private readonly logService: ILogService
) { }
private _traceLayout(method: string, message: string) {
if (forceVerboseLayoutTracing) {
this.logService.info(`InteractiveSessionListDelegate#${method}: ${message}`);
} else {
this.logService.trace(`InteractiveSessionListDelegate#${method}: ${message}`);
}
}
getHeight(element: InteractiveTreeItem): number {
const kind = isRequestVM(element) ? 'request' : 'response';
const height = ('currentRenderedHeight' in element ? element.currentRenderedHeight : undefined) ?? 200;
this._traceLayout('getHeight', `${kind}, height=${height}`);
return height;
}
getTemplateId(element: InteractiveTreeItem): string {
return InteractiveListItemRenderer.ID;
}
hasDynamicHeight(element: InteractiveTreeItem): boolean {
return true;
}
}
export class InteractiveSessionAccessibilityProvider implements IListAccessibilityProvider<InteractiveTreeItem> {
getWidgetAriaLabel(): string {
return localize('interactiveSession', "Interactive Session");
}
getAriaLabel(element: InteractiveTreeItem): string {
if (isRequestVM(element)) {
return localize('interactiveRequest', "Request: {0}", element.messageText);
}
if (isResponseVM(element)) {
return localize('interactiveResponse', "Response: {0}", element.response.value);
}
return '';
}
}
interface IInteractiveResultCodeBlockData {
text: string;
languageId: string;
codeBlockIndex: number;
element: InteractiveTreeItem;
parentContextKeyService: IContextKeyService;
}
interface IInteractiveResultCodeBlockPart {
readonly onDidChangeContentHeight: Event<number>;
readonly element: HTMLElement;
readonly textModel: ITextModel;
layout(width: number): void;
render(data: IInteractiveResultCodeBlockData, width: number): void;
dispose(): void;
}
export interface IInteractiveResultCodeBlockInfo {
providerId: string;
responseId: string;
codeBlockIndex: number;
}
export const codeBlockInfosByModelUri = new ResourceMap<IInteractiveResultCodeBlockInfo>();
class CodeBlockPart extends Disposable implements IInteractiveResultCodeBlockPart {
private readonly _onDidChangeContentHeight = this._register(new Emitter<number>());
public readonly onDidChangeContentHeight = this._onDidChangeContentHeight.event;
private readonly editor: CodeEditorWidget;
private readonly toolbar: MenuWorkbenchToolBar;
private readonly contextKeyService: IContextKeyService;
public readonly textModel: ITextModel;
public readonly element: HTMLElement;
constructor(
private readonly options: InteractiveSessionEditorOptions,
@IInstantiationService instantiationService: IInstantiationService,
@IContextKeyService contextKeyService: IContextKeyService,
@ILanguageService private readonly languageService: ILanguageService,
@IModelService private readonly modelService: IModelService,
) {
super();
this.element = $('.interactive-result-editor-wrapper');
this.contextKeyService = this._register(contextKeyService.createScoped(this.element));
const scopedInstantiationService = instantiationService.createChild(new ServiceCollection([IContextKeyService, this.contextKeyService]));
this.toolbar = this._register(scopedInstantiationService.createInstance(MenuWorkbenchToolBar, this.element, MenuId.InteractiveSessionCodeBlock, {
menuOptions: {
shouldForwardArgs: true
}
}));
const editorElement = dom.append(this.element, $('.interactive-result-editor'));
this.editor = this._register(scopedInstantiationService.createInstance(CodeEditorWidget, editorElement, {
...getSimpleEditorOptions(),
readOnly: true,
lineNumbers: 'off',
selectOnLineNumbers: true,
scrollBeyondLastLine: false,
lineDecorationsWidth: 8,
dragAndDrop: false,
padding: { top: 2, bottom: 2 },
mouseWheelZoom: false,
scrollbar: {
alwaysConsumeMouseWheel: false
},
...this.getEditorOptionsFromConfig()
}, {
isSimpleWidget: true,
contributions: EditorExtensionsRegistry.getSomeEditorContributions([
MenuPreventer.ID,
SelectionClipboardContributionID,
ContextMenuController.ID,
WordHighlighterContribution.ID,
ViewportSemanticTokensContribution.ID,
BracketMatchingController.ID,
SmartSelectController.ID,
])
}));
this._register(this.options.onDidChange(() => {
this.editor.updateOptions(this.getEditorOptionsFromConfig());
}));
this._register(this.editor.onDidContentSizeChange(e => {
if (e.contentHeightChanged) {
this._onDidChangeContentHeight.fire(e.contentHeight);
}
}));
this._register(this.editor.onDidBlurEditorWidget(() => {
WordHighlighterContribution.get(this.editor)?.stopHighlighting();
}));
this._register(this.editor.onDidFocusEditorWidget(() => {
WordHighlighterContribution.get(this.editor)?.restoreViewState(true);
}));
const vscodeLanguageId = this.languageService.getLanguageIdByLanguageName('javascript');
this.textModel = this._register(this.modelService.createModel('', this.languageService.createById(vscodeLanguageId), undefined));
this.editor.setModel(this.textModel);
}
private getEditorOptionsFromConfig(): IEditorOptions {
return {
wordWrap: this.options.configuration.resultEditor.wordWrap,
fontLigatures: this.options.configuration.resultEditor.fontLigatures,
bracketPairColorization: this.options.configuration.resultEditor.bracketPairColorization,
fontFamily: this.options.configuration.resultEditor.fontFamily === 'default' ?
EDITOR_FONT_DEFAULTS.fontFamily :
this.options.configuration.resultEditor.fontFamily,
fontSize: this.options.configuration.resultEditor.fontSize,
fontWeight: this.options.configuration.resultEditor.fontWeight,
lineHeight: this.options.configuration.resultEditor.lineHeight,
};
}
layout(width: number): void {
const realContentHeight = this.editor.getContentHeight();
const editorBorder = 2;
this.editor.layout({ width: width - editorBorder, height: realContentHeight });
}
render(data: IInteractiveResultCodeBlockData, width: number): void {
this.contextKeyService.updateParent(data.parentContextKeyService);
if (this.options.configuration.resultEditor.wordWrap === 'on') {
// Intialize the editor with the new proper width so that getContentHeight
// will be computed correctly in the next call to layout()
this.layout(width);
}
this.setText(data.text);
this.setLanguage(data.languageId);
this.layout(width);
if (isResponseVM(data.element) && data.element.providerResponseId) {
// For telemetry reporting
codeBlockInfosByModelUri.set(this.textModel.uri, {
providerId: data.element.providerId,
responseId: data.element.providerResponseId,
codeBlockIndex: data.codeBlockIndex
});
} else {
codeBlockInfosByModelUri.delete(this.textModel.uri);
}
this.toolbar.context = <IInteractiveSessionCodeBlockActionContext>{
code: data.text,
codeBlockIndex: data.codeBlockIndex,
element: data.element
};
}
private setText(newText: string): void {
let currentText = this.textModel.getLinesContent().join('\n');
if (newText === currentText) {
return;
}
let removedChars = 0;
if (currentText.endsWith(` ${InteractiveListItemRenderer.cursorCharacter}`)) {
removedChars = 2;
} else if (currentText.endsWith(InteractiveListItemRenderer.cursorCharacter)) {
removedChars = 1;
}
if (removedChars > 0) {
currentText = currentText.slice(0, currentText.length - removedChars);
}
if (newText.startsWith(currentText)) {
const text = newText.slice(currentText.length);
const lastLine = this.textModel.getLineCount();
const lastCol = this.textModel.getLineMaxColumn(lastLine);
const insertAtCol = lastCol - removedChars;
this.textModel.applyEdits([{ range: new Range(lastLine, insertAtCol, lastLine, lastCol), text }]);
} else {
// console.log(`Failed to optimize setText`);
this.textModel.setValue(newText);
}
}
private setLanguage(languageId: string): void {
const vscodeLanguageId = this.languageService.getLanguageIdByLanguageName(languageId);
if (vscodeLanguageId) {
this.textModel.setLanguage(vscodeLanguageId);
}
}
}
interface IDisposableReference<T> extends IDisposable {
object: T;
}
class EditorPool extends Disposable {
private _pool: ResourcePool<IInteractiveResultCodeBlockPart>;
public get inUse(): ReadonlySet<IInteractiveResultCodeBlockPart> {
return this._pool.inUse;
}
constructor(
private readonly options: InteractiveSessionEditorOptions,
@IInstantiationService private readonly instantiationService: IInstantiationService,
) {
super();
this._pool = this._register(new ResourcePool(() => this.editorFactory()));
// TODO listen to changes on options
}
private editorFactory(): IInteractiveResultCodeBlockPart {
return this.instantiationService.createInstance(CodeBlockPart, this.options);
}
get(): IDisposableReference<IInteractiveResultCodeBlockPart> {
const object = this._pool.get();
return {
object,
dispose: () => this._pool.release(object)
};
}
}
// TODO does something in lifecycle.ts cover this?
class ResourcePool<T extends IDisposable> extends Disposable {
private readonly pool: T[] = [];
private _inUse = new Set<T>;
public get inUse(): ReadonlySet<T> {
return this._inUse;
}
constructor(
private readonly _itemFactory: () => T,
) {
super();
}
get(): T {
if (this.pool.length > 0) {
const item = this.pool.pop()!;
this._inUse.add(item);
return item;
}
const item = this._register(this._itemFactory());
this._inUse.add(item);
return item;
}
release(item: T): void {
this._inUse.delete(item);
this.pool.push(item);
}
}
| src/vs/workbench/contrib/interactiveSession/browser/interactiveSessionListRenderer.ts | 1 | https://github.com/microsoft/vscode/commit/c2bf6225a12e7f7d8afada6ec39560bb38e5838a | [
0.02110179141163826,
0.0007304639439098537,
0.00016214950301218778,
0.00017177010886371136,
0.002711988054215908
] |
{
"id": 2,
"code_window": [
"\t\t\t\t\toriginal: 'Vote Up'\n",
"\t\t\t\t},\n",
"\t\t\t\tf1: false,\n",
"\t\t\t\tcategory: INTERACTIVE_SESSION_CATEGORY,\n",
"\t\t\t\ticon: Codicon.thumbsup,\n",
"\t\t\t\tprecondition: CONTEXT_RESPONSE_VOTE.isEqualTo(''), // Should be disabled but visible when vote=down\n",
"\t\t\t\tmenu: {\n",
"\t\t\t\t\tid: MenuId.InteractiveSessionTitle,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\ttoggled: CONTEXT_RESPONSE_VOTE.isEqualTo('up'),\n"
],
"file_path": "src/vs/workbench/contrib/interactiveSession/browser/actions/interactiveSessionTitleActions.ts",
"type": "replace",
"edit_start_line_idx": 27
} | {
"comments": {
"lineComment": "#",
"blockComment": [ "#=", "=#" ]
},
"brackets": [
["{", "}"],
["[", "]"],
["(", ")"]
],
"autoClosingPairs": [
["{", "}"],
["[", "]"],
["(", ")"],
["`", "`"],
{ "open": "\"", "close": "\"", "notIn": ["string", "comment"] }
],
"surroundingPairs": [
["{", "}"],
["[", "]"],
["(", ")"],
["\"", "\""],
["`", "`"]
],
"folding": {
"markers": {
"start": "^\\s*#region",
"end": "^\\s*#endregion"
}
},
"indentationRules": {
"increaseIndentPattern": "^(\\s*|.*=\\s*|.*@\\w*\\s*)[\\w\\s]*(?:[\"'`][^\"'`]*[\"'`])*[\\w\\s]*\\b(if|while|for|function|macro|(mutable\\s+)?struct|abstract\\s+type|primitive\\s+type|let|quote|try|begin|.*\\)\\s*do|else|elseif|catch|finally)\\b(?!(?:.*\\bend\\b[^\\]]*)|(?:[^\\[]*\\].*)$).*$",
"decreaseIndentPattern": "^\\s*(end|else|elseif|catch|finally)\\b.*$"
}
}
| extensions/julia/language-configuration.json | 0 | https://github.com/microsoft/vscode/commit/c2bf6225a12e7f7d8afada6ec39560bb38e5838a | [
0.00017430949083063751,
0.0001735117839416489,
0.00017205106269102544,
0.00017384329112246633,
8.770304020799813e-7
] |
{
"id": 2,
"code_window": [
"\t\t\t\t\toriginal: 'Vote Up'\n",
"\t\t\t\t},\n",
"\t\t\t\tf1: false,\n",
"\t\t\t\tcategory: INTERACTIVE_SESSION_CATEGORY,\n",
"\t\t\t\ticon: Codicon.thumbsup,\n",
"\t\t\t\tprecondition: CONTEXT_RESPONSE_VOTE.isEqualTo(''), // Should be disabled but visible when vote=down\n",
"\t\t\t\tmenu: {\n",
"\t\t\t\t\tid: MenuId.InteractiveSessionTitle,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\ttoggled: CONTEXT_RESPONSE_VOTE.isEqualTo('up'),\n"
],
"file_path": "src/vs/workbench/contrib/interactiveSession/browser/actions/interactiveSessionTitleActions.ts",
"type": "replace",
"edit_start_line_idx": 27
} | <project>
<target name="jar">
<mkdir dir="build/jar"/>
<jar destfile="build/jar/HelloWorld.jar" basedir="build/classes">
<manifest>
<attribute name="Main-Class" value="oata.HelloWorld"/>
</manifest>
</jar>
</target>
<!-- The stuff below was added for extra tokenizer testing -->
<character id="Lucy">
<hr:name>Lucy</hr:name>
<hr:born>1952-03-03</hr:born>
<qualification>bossy, crabby and selfish</qualification>
</character>
<VisualState.Setters>
<Setter Target="inputPanel.Orientation" Value="Vertical"/>
<Setter Target="inputButton.Margin" Value="0,4,0,0"/>
</VisualState.Setters>
</project>
| extensions/vscode-colorize-tests/test/colorize-fixtures/test.xml | 0 | https://github.com/microsoft/vscode/commit/c2bf6225a12e7f7d8afada6ec39560bb38e5838a | [
0.00017712084809318185,
0.00017528685566503555,
0.000172970729181543,
0.00017576903337612748,
0.0000017282424096265459
] |
{
"id": 2,
"code_window": [
"\t\t\t\t\toriginal: 'Vote Up'\n",
"\t\t\t\t},\n",
"\t\t\t\tf1: false,\n",
"\t\t\t\tcategory: INTERACTIVE_SESSION_CATEGORY,\n",
"\t\t\t\ticon: Codicon.thumbsup,\n",
"\t\t\t\tprecondition: CONTEXT_RESPONSE_VOTE.isEqualTo(''), // Should be disabled but visible when vote=down\n",
"\t\t\t\tmenu: {\n",
"\t\t\t\t\tid: MenuId.InteractiveSessionTitle,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\ttoggled: CONTEXT_RESPONSE_VOTE.isEqualTo('up'),\n"
],
"file_path": "src/vs/workbench/contrib/interactiveSession/browser/actions/interactiveSessionTitleActions.ts",
"type": "replace",
"edit_start_line_idx": 27
} | /*---------------------------------------------------------------------------------------------
* 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 { IWorkspaceTextEditDto } from 'vs/workbench/api/common/extHost.protocol';
import { mock } from 'vs/base/test/common/mock';
import { Event } from 'vs/base/common/event';
import { URI } from 'vs/base/common/uri';
import { FileSystemProviderCapabilities, IFileService } from 'vs/platform/files/common/files';
import { reviveWorkspaceEditDto } from 'vs/workbench/api/browser/mainThreadBulkEdits';
import { UriIdentityService } from 'vs/platform/uriIdentity/common/uriIdentityService';
import { IWorkspaceTextEdit } from 'vs/editor/common/languages';
suite('MainThreadBulkEdits', function () {
test('"Rename failed to apply edits" in monorepo with pnpm #158845', function () {
const fileService = new class extends mock<IFileService>() {
override onDidChangeFileSystemProviderCapabilities = Event.None;
override onDidChangeFileSystemProviderRegistrations = Event.None;
override hasProvider(uri: URI) {
return true;
}
override hasCapability(resource: URI, capability: FileSystemProviderCapabilities): boolean {
// if (resource.scheme === 'case' && capability === FileSystemProviderCapabilities.PathCaseSensitive) {
// return false;
// }
// NO capabilities, esp not being case-sensitive
return false;
}
};
const uriIdentityService = new UriIdentityService(fileService);
const edits: IWorkspaceTextEditDto[] = [
{ resource: URI.from({ scheme: 'case', path: '/hello/WORLD/foo.txt' }), textEdit: { range: { startLineNumber: 1, startColumn: 1, endLineNumber: 1, endColumn: 1 }, text: 'sss' }, versionId: undefined },
{ resource: URI.from({ scheme: 'case', path: '/heLLO/world/fOO.txt' }), textEdit: { range: { startLineNumber: 1, startColumn: 1, endLineNumber: 1, endColumn: 1 }, text: 'sss' }, versionId: undefined },
{ resource: URI.from({ scheme: 'case', path: '/other/path.txt' }), textEdit: { range: { startLineNumber: 1, startColumn: 1, endLineNumber: 1, endColumn: 1 }, text: 'sss' }, versionId: undefined },
{ resource: URI.from({ scheme: 'foo', path: '/other/path.txt' }), textEdit: { range: { startLineNumber: 1, startColumn: 1, endLineNumber: 1, endColumn: 1 }, text: 'sss' }, versionId: undefined },
];
const out = reviveWorkspaceEditDto({ edits }, uriIdentityService);
assert.strictEqual((<IWorkspaceTextEdit>out.edits[0]).resource.path, '/hello/WORLD/foo.txt');
assert.strictEqual((<IWorkspaceTextEdit>out.edits[1]).resource.path, '/hello/WORLD/foo.txt'); // the FIRST occurrence defined the shape!
assert.strictEqual((<IWorkspaceTextEdit>out.edits[2]).resource.path, '/other/path.txt');
assert.strictEqual((<IWorkspaceTextEdit>out.edits[3]).resource.path, '/other/path.txt');
});
});
| src/vs/workbench/api/test/browser/mainThreadBulkEdits.test.ts | 0 | https://github.com/microsoft/vscode/commit/c2bf6225a12e7f7d8afada6ec39560bb38e5838a | [
0.00017629135982133448,
0.0001733946119202301,
0.0001679203996900469,
0.00017405574908480048,
0.000002895230181820807
] |
{
"id": 3,
"code_window": [
"\t\t\t\tmenu: {\n",
"\t\t\t\t\tid: MenuId.InteractiveSessionTitle,\n",
"\t\t\t\t\twhen: ContextKeyExpr.and(CONTEXT_RESPONSE_HAS_PROVIDER_ID, CONTEXT_RESPONSE_VOTE.notEqualsTo('down')),\n",
"\t\t\t\t\tgroup: 'navigation',\n",
"\t\t\t\t\torder: 1\n",
"\t\t\t\t}\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/workbench/contrib/interactiveSession/browser/actions/interactiveSessionTitleActions.ts",
"type": "replace",
"edit_start_line_idx": 30
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Codicon } from 'vs/base/common/codicons';
import { ServicesAccessor } from 'vs/editor/browser/editorExtensions';
import { localize } from 'vs/nls';
import { Action2, MenuId, registerAction2 } from 'vs/platform/actions/common/actions';
import { ContextKeyExpr } from 'vs/platform/contextkey/common/contextkey';
import { INTERACTIVE_SESSION_CATEGORY } from 'vs/workbench/contrib/interactiveSession/browser/actions/interactiveSessionActions';
import { CONTEXT_RESPONSE_HAS_PROVIDER_ID, CONTEXT_RESPONSE_VOTE } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionContextKeys';
import { IInteractiveSessionService, IInteractiveSessionUserActionEvent, InteractiveSessionVoteDirection } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionService';
import { isResponseVM } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionViewModel';
export function registerInteractiveSessionTitleActions() {
registerAction2(class VoteUpAction extends Action2 {
constructor() {
super({
id: 'workbench.action.interactiveSession.voteUp',
title: {
value: localize('interactive.voteUp.label', "Vote Up"),
original: 'Vote Up'
},
f1: false,
category: INTERACTIVE_SESSION_CATEGORY,
icon: Codicon.thumbsup,
precondition: CONTEXT_RESPONSE_VOTE.isEqualTo(''), // Should be disabled but visible when vote=down
menu: {
id: MenuId.InteractiveSessionTitle,
when: ContextKeyExpr.and(CONTEXT_RESPONSE_HAS_PROVIDER_ID, CONTEXT_RESPONSE_VOTE.notEqualsTo('down')),
group: 'navigation',
order: 1
}
});
}
run(accessor: ServicesAccessor, ...args: any[]) {
const item = args[0];
if (!isResponseVM(item)) {
return;
}
const interactiveSessionService = accessor.get(IInteractiveSessionService);
interactiveSessionService.notifyUserAction(<IInteractiveSessionUserActionEvent>{
providerId: item.providerId,
action: {
kind: 'vote',
direction: InteractiveSessionVoteDirection.Up,
responseId: item.providerResponseId
}
});
item.setVote(InteractiveSessionVoteDirection.Up);
}
});
registerAction2(class VoteDownAction extends Action2 {
constructor() {
super({
id: 'workbench.action.interactiveSession.voteDown',
title: {
value: localize('interactive.voteDown.label', "Vote Down"),
original: 'Vote Down'
},
f1: false,
category: INTERACTIVE_SESSION_CATEGORY,
icon: Codicon.thumbsdown,
precondition: CONTEXT_RESPONSE_VOTE.isEqualTo(''), // Should be disabled but visible when vote=down
menu: {
id: MenuId.InteractiveSessionTitle,
when: ContextKeyExpr.and(CONTEXT_RESPONSE_HAS_PROVIDER_ID, CONTEXT_RESPONSE_VOTE.notEqualsTo('up')),
group: 'navigation',
order: 2
}
});
}
run(accessor: ServicesAccessor, ...args: any[]) {
const item = args[0];
if (!isResponseVM(item)) {
return;
}
const interactiveSessionService = accessor.get(IInteractiveSessionService);
interactiveSessionService.notifyUserAction(<IInteractiveSessionUserActionEvent>{
providerId: item.providerId,
action: {
kind: 'vote',
direction: InteractiveSessionVoteDirection.Down,
responseId: item.providerResponseId
}
});
item.setVote(InteractiveSessionVoteDirection.Down);
}
});
}
| src/vs/workbench/contrib/interactiveSession/browser/actions/interactiveSessionTitleActions.ts | 1 | https://github.com/microsoft/vscode/commit/c2bf6225a12e7f7d8afada6ec39560bb38e5838a | [
0.01818385161459446,
0.0029290327802300453,
0.00016506134124938399,
0.0010199929820373654,
0.005226444453001022
] |
{
"id": 3,
"code_window": [
"\t\t\t\tmenu: {\n",
"\t\t\t\t\tid: MenuId.InteractiveSessionTitle,\n",
"\t\t\t\t\twhen: ContextKeyExpr.and(CONTEXT_RESPONSE_HAS_PROVIDER_ID, CONTEXT_RESPONSE_VOTE.notEqualsTo('down')),\n",
"\t\t\t\t\tgroup: 'navigation',\n",
"\t\t\t\t\torder: 1\n",
"\t\t\t\t}\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/workbench/contrib/interactiveSession/browser/actions/interactiveSessionTitleActions.ts",
"type": "replace",
"edit_start_line_idx": 30
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { LifecyclePhase } from 'vs/workbench/services/lifecycle/common/lifecycle';
import { Registry } from 'vs/platform/registry/common/platform';
import { Extensions as WorkbenchExtensions, IWorkbenchContribution, IWorkbenchContributionsRegistry } from 'vs/workbench/common/contributions';
import { ICodeEditorService } from 'vs/editor/browser/services/codeEditorService';
import { INativeHostService } from 'vs/platform/native/common/native';
import { Disposable } from 'vs/base/common/lifecycle';
class SleepResumeRepaintMinimap extends Disposable implements IWorkbenchContribution {
constructor(
@ICodeEditorService codeEditorService: ICodeEditorService,
@INativeHostService nativeHostService: INativeHostService
) {
super();
this._register(nativeHostService.onDidResumeOS(() => {
codeEditorService.listCodeEditors().forEach(editor => editor.render(true));
}));
}
}
Registry.as<IWorkbenchContributionsRegistry>(WorkbenchExtensions.Workbench).registerWorkbenchContribution(SleepResumeRepaintMinimap, LifecyclePhase.Eventually);
| src/vs/workbench/contrib/codeEditor/electron-sandbox/sleepResumeRepaintMinimap.ts | 0 | https://github.com/microsoft/vscode/commit/c2bf6225a12e7f7d8afada6ec39560bb38e5838a | [
0.00017314629803877324,
0.00017058395314961672,
0.00016600522212684155,
0.0001726003538351506,
0.000003245317657274427
] |
{
"id": 3,
"code_window": [
"\t\t\t\tmenu: {\n",
"\t\t\t\t\tid: MenuId.InteractiveSessionTitle,\n",
"\t\t\t\t\twhen: ContextKeyExpr.and(CONTEXT_RESPONSE_HAS_PROVIDER_ID, CONTEXT_RESPONSE_VOTE.notEqualsTo('down')),\n",
"\t\t\t\t\tgroup: 'navigation',\n",
"\t\t\t\t\torder: 1\n",
"\t\t\t\t}\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/workbench/contrib/interactiveSession/browser/actions/interactiveSessionTitleActions.ts",
"type": "replace",
"edit_start_line_idx": 30
} | {
"compilerOptions": {
"target": "es2022",
"lib": [
"ES2020"
],
"module": "commonjs",
"alwaysStrict": true,
"removeComments": false,
"preserveConstEnums": true,
"sourceMap": false,
"inlineSourceMap": true,
"resolveJsonModule": true,
// enable JavaScript type checking for the language service
// use the tsconfig.build.json for compiling which disable JavaScript
// type checking so that JavaScript file are not transpiled
"allowJs": true,
"strict": true,
"exactOptionalPropertyTypes": false,
"useUnknownInCatchVariables": false,
"noUnusedLocals": true,
"noUnusedParameters": true,
"newLine": "lf",
"noEmit": true
},
"include": [
"**/*.ts",
"**/*.js"
],
"exclude": [
"node_modules/**"
]
}
| build/tsconfig.json | 0 | https://github.com/microsoft/vscode/commit/c2bf6225a12e7f7d8afada6ec39560bb38e5838a | [
0.00017606660549063236,
0.0001734174438752234,
0.00017016289348248392,
0.00017372012371197343,
0.0000022542342321685283
] |
{
"id": 3,
"code_window": [
"\t\t\t\tmenu: {\n",
"\t\t\t\t\tid: MenuId.InteractiveSessionTitle,\n",
"\t\t\t\t\twhen: ContextKeyExpr.and(CONTEXT_RESPONSE_HAS_PROVIDER_ID, CONTEXT_RESPONSE_VOTE.notEqualsTo('down')),\n",
"\t\t\t\t\tgroup: 'navigation',\n",
"\t\t\t\t\torder: 1\n",
"\t\t\t\t}\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/workbench/contrib/interactiveSession/browser/actions/interactiveSessionTitleActions.ts",
"type": "replace",
"edit_start_line_idx": 30
} | /*---------------------------------------------------------------------------------------------
* 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 { KeyCode, KeyMod } from 'vs/base/common/keyCodes';
import { List } from 'vs/base/browser/ui/list/listWidget';
import { KeybindingsRegistry, KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry';
import { IListService } from 'vs/platform/list/browser/listService';
import { IDebugService, IEnablement, CONTEXT_BREAKPOINTS_FOCUSED, CONTEXT_WATCH_EXPRESSIONS_FOCUSED, CONTEXT_VARIABLES_FOCUSED, EDITOR_CONTRIBUTION_ID, IDebugEditorContribution, CONTEXT_IN_DEBUG_MODE, CONTEXT_EXPRESSION_SELECTED, IConfig, IStackFrame, IThread, IDebugSession, CONTEXT_DEBUG_STATE, IDebugConfiguration, CONTEXT_JUMP_TO_CURSOR_SUPPORTED, REPL_VIEW_ID, CONTEXT_DEBUGGERS_AVAILABLE, State, getStateLabel, CONTEXT_BREAKPOINT_INPUT_FOCUSED, CONTEXT_FOCUSED_SESSION_IS_ATTACH, VIEWLET_ID, CONTEXT_DISASSEMBLY_VIEW_FOCUS, CONTEXT_IN_DEBUG_REPL, CONTEXT_STEP_INTO_TARGETS_SUPPORTED } from 'vs/workbench/contrib/debug/common/debug';
import { Expression, Variable, Breakpoint, FunctionBreakpoint, DataBreakpoint, Thread } from 'vs/workbench/contrib/debug/common/debugModel';
import { IExtensionsViewPaneContainer, VIEWLET_ID as EXTENSIONS_VIEWLET_ID } from 'vs/workbench/contrib/extensions/common/extensions';
import { ICodeEditor, isCodeEditor } from 'vs/editor/browser/editorBrowser';
import { MenuRegistry, MenuId, Action2, registerAction2 } from 'vs/platform/actions/common/actions';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { EditorContextKeys } from 'vs/editor/common/editorContextKeys';
import { ContextKeyExpr, IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { openBreakpointSource } from 'vs/workbench/contrib/debug/browser/breakpointsView';
import { INotificationService } from 'vs/platform/notification/common/notification';
import { InputFocusedContext } from 'vs/platform/contextkey/common/contextkeys';
import { ServicesAccessor } from 'vs/editor/browser/editorExtensions';
import { ActiveEditorContext, PanelFocusContext, ResourceContextKey } from 'vs/workbench/common/contextkeys';
import { CommandsRegistry, ICommandService } from 'vs/platform/commands/common/commands';
import { ITextResourcePropertiesService } from 'vs/editor/common/services/textResourceConfiguration';
import { IClipboardService } from 'vs/platform/clipboard/common/clipboardService';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IQuickInputService, IQuickPickItem } from 'vs/platform/quickinput/common/quickInput';
import { IViewsService, ViewContainerLocation } from 'vs/workbench/common/views';
import { deepClone } from 'vs/base/common/objects';
import { isWeb, isWindows } from 'vs/base/common/platform';
import { saveAllBeforeDebugStart } from 'vs/workbench/contrib/debug/common/debugUtils';
import { IPaneCompositePartService } from 'vs/workbench/services/panecomposite/browser/panecomposite';
import { showLoadedScriptMenu } from 'vs/workbench/contrib/debug/common/loadedScriptsPicker';
import { showDebugSessionMenu } from 'vs/workbench/contrib/debug/browser/debugSessionPicker';
import { TEXT_FILE_EDITOR_ID } from 'vs/workbench/contrib/files/common/files';
import { ILocalizedString } from 'vs/platform/action/common/action';
export const ADD_CONFIGURATION_ID = 'debug.addConfiguration';
export const TOGGLE_INLINE_BREAKPOINT_ID = 'editor.debug.action.toggleInlineBreakpoint';
export const COPY_STACK_TRACE_ID = 'debug.copyStackTrace';
export const REVERSE_CONTINUE_ID = 'workbench.action.debug.reverseContinue';
export const STEP_BACK_ID = 'workbench.action.debug.stepBack';
export const RESTART_SESSION_ID = 'workbench.action.debug.restart';
export const TERMINATE_THREAD_ID = 'workbench.action.debug.terminateThread';
export const STEP_OVER_ID = 'workbench.action.debug.stepOver';
export const STEP_INTO_ID = 'workbench.action.debug.stepInto';
export const STEP_INTO_TARGET_ID = 'workbench.action.debug.stepIntoTarget';
export const STEP_OUT_ID = 'workbench.action.debug.stepOut';
export const PAUSE_ID = 'workbench.action.debug.pause';
export const DISCONNECT_ID = 'workbench.action.debug.disconnect';
export const DISCONNECT_AND_SUSPEND_ID = 'workbench.action.debug.disconnectAndSuspend';
export const STOP_ID = 'workbench.action.debug.stop';
export const RESTART_FRAME_ID = 'workbench.action.debug.restartFrame';
export const CONTINUE_ID = 'workbench.action.debug.continue';
export const FOCUS_REPL_ID = 'workbench.debug.action.focusRepl';
export const JUMP_TO_CURSOR_ID = 'debug.jumpToCursor';
export const FOCUS_SESSION_ID = 'workbench.action.debug.focusProcess';
export const SELECT_AND_START_ID = 'workbench.action.debug.selectandstart';
export const SELECT_DEBUG_CONSOLE_ID = 'workbench.action.debug.selectDebugConsole';
export const SELECT_DEBUG_SESSION_ID = 'workbench.action.debug.selectDebugSession';
export const DEBUG_CONFIGURE_COMMAND_ID = 'workbench.action.debug.configure';
export const DEBUG_START_COMMAND_ID = 'workbench.action.debug.start';
export const DEBUG_RUN_COMMAND_ID = 'workbench.action.debug.run';
export const EDIT_EXPRESSION_COMMAND_ID = 'debug.renameWatchExpression';
export const SET_EXPRESSION_COMMAND_ID = 'debug.setWatchExpression';
export const REMOVE_EXPRESSION_COMMAND_ID = 'debug.removeWatchExpression';
export const NEXT_DEBUG_CONSOLE_ID = 'workbench.action.debug.nextConsole';
export const PREV_DEBUG_CONSOLE_ID = 'workbench.action.debug.prevConsole';
export const SHOW_LOADED_SCRIPTS_ID = 'workbench.action.debug.showLoadedScripts';
export const CALLSTACK_TOP_ID = 'workbench.action.debug.callStackTop';
export const CALLSTACK_BOTTOM_ID = 'workbench.action.debug.callStackBottom';
export const CALLSTACK_UP_ID = 'workbench.action.debug.callStackUp';
export const CALLSTACK_DOWN_ID = 'workbench.action.debug.callStackDown';
export const DEBUG_COMMAND_CATEGORY: ILocalizedString = { original: 'Debug', value: nls.localize('debug', 'Debug') };
export const RESTART_LABEL = { value: nls.localize('restartDebug', "Restart"), original: 'Restart' };
export const STEP_OVER_LABEL = { value: nls.localize('stepOverDebug', "Step Over"), original: 'Step Over' };
export const STEP_INTO_LABEL = { value: nls.localize('stepIntoDebug', "Step Into"), original: 'Step Into' };
export const STEP_INTO_TARGET_LABEL = { value: nls.localize('stepIntoTargetDebug', "Step Into Target"), original: 'Step Into Target' };
export const STEP_OUT_LABEL = { value: nls.localize('stepOutDebug', "Step Out"), original: 'Step Out' };
export const PAUSE_LABEL = { value: nls.localize('pauseDebug', "Pause"), original: 'Pause' };
export const DISCONNECT_LABEL = { value: nls.localize('disconnect', "Disconnect"), original: 'Disconnect' };
export const DISCONNECT_AND_SUSPEND_LABEL = { value: nls.localize('disconnectSuspend', "Disconnect and Suspend"), original: 'Disconnect and Suspend' };
export const STOP_LABEL = { value: nls.localize('stop', "Stop"), original: 'Stop' };
export const CONTINUE_LABEL = { value: nls.localize('continueDebug', "Continue"), original: 'Continue' };
export const FOCUS_SESSION_LABEL = { value: nls.localize('focusSession', "Focus Session"), original: 'Focus Session' };
export const SELECT_AND_START_LABEL = { value: nls.localize('selectAndStartDebugging', "Select and Start Debugging"), original: 'Select and Start Debugging' };
export const DEBUG_CONFIGURE_LABEL = nls.localize('openLaunchJson', "Open '{0}'", 'launch.json');
export const DEBUG_START_LABEL = { value: nls.localize('startDebug', "Start Debugging"), original: 'Start Debugging' };
export const DEBUG_RUN_LABEL = { value: nls.localize('startWithoutDebugging', "Start Without Debugging"), original: 'Start Without Debugging' };
export const NEXT_DEBUG_CONSOLE_LABEL = { value: nls.localize('nextDebugConsole', "Focus Next Debug Console"), original: 'Focus Next Debug Console' };
export const PREV_DEBUG_CONSOLE_LABEL = { value: nls.localize('prevDebugConsole', "Focus Previous Debug Console"), original: 'Focus Previous Debug Console' };
export const OPEN_LOADED_SCRIPTS_LABEL = { value: nls.localize('openLoadedScript', "Open Loaded Script..."), original: 'Open Loaded Script...' };
export const CALLSTACK_TOP_LABEL = { value: nls.localize('callStackTop', "Navigate to Top of Call Stack"), original: 'Navigate to Top of Call Stack' };
export const CALLSTACK_BOTTOM_LABEL = { value: nls.localize('callStackBottom', "Navigate to Bottom of Call Stack"), original: 'Navigate to Bottom of Call Stack' };
export const CALLSTACK_UP_LABEL = { value: nls.localize('callStackUp', "Navigate Up Call Stack"), original: 'Navigate Up Call Stack' };
export const CALLSTACK_DOWN_LABEL = { value: nls.localize('callStackDown', "Navigate Down Call Stack"), original: 'Navigate Down Call Stack' };
export const SELECT_DEBUG_CONSOLE_LABEL = { value: nls.localize('selectDebugConsole', "Select Debug Console"), original: 'Select Debug Console' };
export const SELECT_DEBUG_SESSION_LABEL = { value: nls.localize('selectDebugSession', "Select Debug Session"), original: 'Select Debug Session' };
export const DEBUG_QUICK_ACCESS_PREFIX = 'debug ';
export const DEBUG_CONSOLE_QUICK_ACCESS_PREFIX = 'debug consoles ';
interface CallStackContext {
sessionId: string;
threadId: string;
frameId: string;
}
function isThreadContext(obj: any): obj is CallStackContext {
return obj && typeof obj.sessionId === 'string' && typeof obj.threadId === 'string';
}
async function getThreadAndRun(accessor: ServicesAccessor, sessionAndThreadId: CallStackContext | unknown, run: (thread: IThread) => Promise<void>): Promise<void> {
const debugService = accessor.get(IDebugService);
let thread: IThread | undefined;
if (isThreadContext(sessionAndThreadId)) {
const session = debugService.getModel().getSession(sessionAndThreadId.sessionId);
if (session) {
thread = session.getAllThreads().find(t => t.getId() === sessionAndThreadId.threadId);
}
} else if (isSessionContext(sessionAndThreadId)) {
const session = debugService.getModel().getSession(sessionAndThreadId.sessionId);
if (session) {
const threads = session.getAllThreads();
thread = threads.length > 0 ? threads[0] : undefined;
}
}
if (!thread) {
thread = debugService.getViewModel().focusedThread;
if (!thread) {
const focusedSession = debugService.getViewModel().focusedSession;
const threads = focusedSession ? focusedSession.getAllThreads() : undefined;
thread = threads && threads.length ? threads[0] : undefined;
}
}
if (thread) {
await run(thread);
}
}
function isStackFrameContext(obj: any): obj is CallStackContext {
return obj && typeof obj.sessionId === 'string' && typeof obj.threadId === 'string' && typeof obj.frameId === 'string';
}
function getFrame(debugService: IDebugService, context: CallStackContext | unknown): IStackFrame | undefined {
if (isStackFrameContext(context)) {
const session = debugService.getModel().getSession(context.sessionId);
if (session) {
const thread = session.getAllThreads().find(t => t.getId() === context.threadId);
if (thread) {
return thread.getCallStack().find(sf => sf.getId() === context.frameId);
}
}
} else {
return debugService.getViewModel().focusedStackFrame;
}
return undefined;
}
function isSessionContext(obj: any): obj is CallStackContext {
return obj && typeof obj.sessionId === 'string';
}
async function changeDebugConsoleFocus(accessor: ServicesAccessor, next: boolean) {
const debugService = accessor.get(IDebugService);
const viewsService = accessor.get(IViewsService);
const sessions = debugService.getModel().getSessions(true).filter(s => s.hasSeparateRepl());
let currSession = debugService.getViewModel().focusedSession;
let nextIndex = 0;
if (sessions.length > 0 && currSession) {
while (currSession && !currSession.hasSeparateRepl()) {
currSession = currSession.parentSession;
}
if (currSession) {
const currIndex = sessions.indexOf(currSession);
if (next) {
nextIndex = (currIndex === (sessions.length - 1) ? 0 : (currIndex + 1));
} else {
nextIndex = (currIndex === 0 ? (sessions.length - 1) : (currIndex - 1));
}
}
}
await debugService.focusStackFrame(undefined, undefined, sessions[nextIndex], { explicit: true });
if (!viewsService.isViewVisible(REPL_VIEW_ID)) {
await viewsService.openView(REPL_VIEW_ID, true);
}
}
async function navigateCallStack(debugService: IDebugService, down: boolean) {
const frame = debugService.getViewModel().focusedStackFrame;
if (frame) {
let callStack = frame.thread.getCallStack();
let index = callStack.findIndex(elem => elem.frameId === frame.frameId);
let nextVisibleFrame;
if (down) {
if (index >= callStack.length - 1) {
if ((<Thread>frame.thread).reachedEndOfCallStack) {
goToTopOfCallStack(debugService);
return;
} else {
await debugService.getModel().fetchCallstack(frame.thread, 20);
callStack = frame.thread.getCallStack();
index = callStack.findIndex(elem => elem.frameId === frame.frameId);
}
}
nextVisibleFrame = findNextVisibleFrame(true, callStack, index);
} else {
if (index <= 0) {
goToBottomOfCallStack(debugService);
return;
}
nextVisibleFrame = findNextVisibleFrame(false, callStack, index);
}
if (nextVisibleFrame) {
debugService.focusStackFrame(nextVisibleFrame);
}
}
}
async function goToBottomOfCallStack(debugService: IDebugService) {
const thread = debugService.getViewModel().focusedThread;
if (thread) {
await debugService.getModel().fetchCallstack(thread);
const callStack = thread.getCallStack();
if (callStack.length > 0) {
const nextVisibleFrame = findNextVisibleFrame(false, callStack, 0); // must consider the next frame up first, which will be the last frame
if (nextVisibleFrame) {
debugService.focusStackFrame(nextVisibleFrame);
}
}
}
}
function goToTopOfCallStack(debugService: IDebugService) {
const thread = debugService.getViewModel().focusedThread;
if (thread) {
debugService.focusStackFrame(thread.getTopStackFrame());
}
}
/**
* Finds next frame that is not skipped by SkipFiles. Skips frame at index and starts searching at next.
* Must satisfy `0 <= startIndex <= callStack - 1`
* @param down specifies whether to search downwards if the current file is skipped.
* @param callStack the call stack to search
* @param startIndex the index to start the search at
*/
function findNextVisibleFrame(down: boolean, callStack: readonly IStackFrame[], startIndex: number) {
if (startIndex >= callStack.length) {
startIndex = callStack.length - 1;
} else if (startIndex < 0) {
startIndex = 0;
}
let index = startIndex;
let currFrame;
do {
if (down) {
if (index === callStack.length - 1) {
index = 0;
} else {
index++;
}
} else {
if (index === 0) {
index = callStack.length - 1;
} else {
index--;
}
}
currFrame = callStack[index];
if (!(currFrame.source.presentationHint === 'deemphasize' || currFrame.presentationHint === 'deemphasize')) {
return currFrame;
}
} while (index !== startIndex); // end loop when we've just checked the start index, since that should be the last one checked
return undefined;
}
// These commands are used in call stack context menu, call stack inline actions, command palette, debug toolbar, mac native touch bar
// When the command is exectued in the context of a thread(context menu on a thread, inline call stack action) we pass the thread id
// Otherwise when it is executed "globaly"(using the touch bar, debug toolbar, command palette) we do not pass any id and just take whatever is the focussed thread
// Same for stackFrame commands and session commands.
CommandsRegistry.registerCommand({
id: COPY_STACK_TRACE_ID,
handler: async (accessor: ServicesAccessor, _: string, context: CallStackContext | unknown) => {
const textResourcePropertiesService = accessor.get(ITextResourcePropertiesService);
const clipboardService = accessor.get(IClipboardService);
const debugService = accessor.get(IDebugService);
const frame = getFrame(debugService, context);
if (frame) {
const eol = textResourcePropertiesService.getEOL(frame.source.uri);
await clipboardService.writeText(frame.thread.getCallStack().map(sf => sf.toString()).join(eol));
}
}
});
CommandsRegistry.registerCommand({
id: REVERSE_CONTINUE_ID,
handler: async (accessor: ServicesAccessor, _: string, context: CallStackContext | unknown) => {
await getThreadAndRun(accessor, context, thread => thread.reverseContinue());
}
});
CommandsRegistry.registerCommand({
id: STEP_BACK_ID,
handler: async (accessor: ServicesAccessor, _: string, context: CallStackContext | unknown) => {
const contextKeyService = accessor.get(IContextKeyService);
if (CONTEXT_DISASSEMBLY_VIEW_FOCUS.getValue(contextKeyService)) {
await getThreadAndRun(accessor, context, (thread: IThread) => thread.stepBack('instruction'));
} else {
await getThreadAndRun(accessor, context, (thread: IThread) => thread.stepBack());
}
}
});
CommandsRegistry.registerCommand({
id: TERMINATE_THREAD_ID,
handler: async (accessor: ServicesAccessor, _: string, context: CallStackContext | unknown) => {
await getThreadAndRun(accessor, context, thread => thread.terminate());
}
});
CommandsRegistry.registerCommand({
id: JUMP_TO_CURSOR_ID,
handler: async (accessor: ServicesAccessor) => {
const debugService = accessor.get(IDebugService);
const stackFrame = debugService.getViewModel().focusedStackFrame;
const editorService = accessor.get(IEditorService);
const activeEditorControl = editorService.activeTextEditorControl;
const notificationService = accessor.get(INotificationService);
const quickInputService = accessor.get(IQuickInputService);
if (stackFrame && isCodeEditor(activeEditorControl) && activeEditorControl.hasModel()) {
const position = activeEditorControl.getPosition();
const resource = activeEditorControl.getModel().uri;
const source = stackFrame.thread.session.getSourceForUri(resource);
if (source) {
const response = await stackFrame.thread.session.gotoTargets(source.raw, position.lineNumber, position.column);
const targets = response?.body.targets;
if (targets && targets.length) {
let id = targets[0].id;
if (targets.length > 1) {
const picks = targets.map(t => ({ label: t.label, _id: t.id }));
const pick = await quickInputService.pick(picks, { placeHolder: nls.localize('chooseLocation', "Choose the specific location") });
if (!pick) {
return;
}
id = pick._id;
}
return await stackFrame.thread.session.goto(stackFrame.thread.threadId, id).catch(e => notificationService.warn(e));
}
}
}
return notificationService.warn(nls.localize('noExecutableCode', "No executable code is associated at the current cursor position."));
}
});
CommandsRegistry.registerCommand({
id: CALLSTACK_TOP_ID,
handler: async (accessor: ServicesAccessor, _: string, context: CallStackContext | unknown) => {
const debugService = accessor.get(IDebugService);
goToTopOfCallStack(debugService);
}
});
CommandsRegistry.registerCommand({
id: CALLSTACK_BOTTOM_ID,
handler: async (accessor: ServicesAccessor, _: string, context: CallStackContext | unknown) => {
const debugService = accessor.get(IDebugService);
await goToBottomOfCallStack(debugService);
}
});
CommandsRegistry.registerCommand({
id: CALLSTACK_UP_ID,
handler: async (accessor: ServicesAccessor, _: string, context: CallStackContext | unknown) => {
const debugService = accessor.get(IDebugService);
navigateCallStack(debugService, false);
}
});
CommandsRegistry.registerCommand({
id: CALLSTACK_DOWN_ID,
handler: async (accessor: ServicesAccessor, _: string, context: CallStackContext | unknown) => {
const debugService = accessor.get(IDebugService);
navigateCallStack(debugService, true);
}
});
MenuRegistry.appendMenuItem(MenuId.EditorContext, {
command: {
id: JUMP_TO_CURSOR_ID,
title: nls.localize('jumpToCursor', "Jump to Cursor"),
category: DEBUG_COMMAND_CATEGORY
},
when: ContextKeyExpr.and(CONTEXT_JUMP_TO_CURSOR_SUPPORTED, EditorContextKeys.editorTextFocus),
group: 'debug',
order: 3
});
KeybindingsRegistry.registerCommandAndKeybindingRule({
id: NEXT_DEBUG_CONSOLE_ID,
weight: KeybindingWeight.WorkbenchContrib + 1,
when: CONTEXT_IN_DEBUG_REPL,
primary: KeyMod.CtrlCmd | KeyCode.PageDown,
mac: { primary: KeyMod.Shift | KeyMod.CtrlCmd | KeyCode.BracketRight },
handler: async (accessor: ServicesAccessor, _: string, context: CallStackContext | unknown) => {
changeDebugConsoleFocus(accessor, true);
}
});
KeybindingsRegistry.registerCommandAndKeybindingRule({
id: PREV_DEBUG_CONSOLE_ID,
weight: KeybindingWeight.WorkbenchContrib + 1,
when: CONTEXT_IN_DEBUG_REPL,
primary: KeyMod.CtrlCmd | KeyCode.PageUp,
mac: { primary: KeyMod.Shift | KeyMod.CtrlCmd | KeyCode.BracketLeft },
handler: async (accessor: ServicesAccessor, _: string, context: CallStackContext | unknown) => {
changeDebugConsoleFocus(accessor, false);
}
});
KeybindingsRegistry.registerCommandAndKeybindingRule({
id: RESTART_SESSION_ID,
weight: KeybindingWeight.WorkbenchContrib,
primary: KeyMod.Shift | KeyMod.CtrlCmd | KeyCode.F5,
when: CONTEXT_IN_DEBUG_MODE,
handler: async (accessor: ServicesAccessor, _: string, context: CallStackContext | unknown) => {
const debugService = accessor.get(IDebugService);
const configurationService = accessor.get(IConfigurationService);
let session: IDebugSession | undefined;
if (isSessionContext(context)) {
session = debugService.getModel().getSession(context.sessionId);
} else {
session = debugService.getViewModel().focusedSession;
}
if (!session) {
const { launch, name } = debugService.getConfigurationManager().selectedConfiguration;
await debugService.startDebugging(launch, name, { noDebug: false, startedByUser: true });
} else {
const showSubSessions = configurationService.getValue<IDebugConfiguration>('debug').showSubSessionsInToolBar;
// Stop should be sent to the root parent session
while (!showSubSessions && session.lifecycleManagedByParent && session.parentSession) {
session = session.parentSession;
}
session.removeReplExpressions();
await debugService.restartSession(session);
}
}
});
KeybindingsRegistry.registerCommandAndKeybindingRule({
id: STEP_OVER_ID,
weight: KeybindingWeight.WorkbenchContrib,
primary: isWeb ? (KeyMod.Alt | KeyCode.F10) : KeyCode.F10, // Browsers do not allow F10 to be binded so we have to bind an alternative
when: CONTEXT_DEBUG_STATE.isEqualTo('stopped'),
handler: async (accessor: ServicesAccessor, _: string, context: CallStackContext | unknown) => {
const contextKeyService = accessor.get(IContextKeyService);
if (CONTEXT_DISASSEMBLY_VIEW_FOCUS.getValue(contextKeyService)) {
await getThreadAndRun(accessor, context, (thread: IThread) => thread.next('instruction'));
} else {
await getThreadAndRun(accessor, context, (thread: IThread) => thread.next());
}
}
});
// Windows browsers use F11 for full screen, thus use alt+F11 as the default shortcut
const STEP_INTO_KEYBINDING = (isWeb && isWindows) ? (KeyMod.Alt | KeyCode.F11) : KeyCode.F11;
KeybindingsRegistry.registerCommandAndKeybindingRule({
id: STEP_INTO_ID,
weight: KeybindingWeight.WorkbenchContrib + 10, // Have a stronger weight to have priority over full screen when debugging
primary: STEP_INTO_KEYBINDING,
// Use a more flexible when clause to not allow full screen command to take over when F11 pressed a lot of times
when: CONTEXT_DEBUG_STATE.notEqualsTo('inactive'),
handler: async (accessor: ServicesAccessor, _: string, context: CallStackContext | unknown) => {
const contextKeyService = accessor.get(IContextKeyService);
if (CONTEXT_DISASSEMBLY_VIEW_FOCUS.getValue(contextKeyService)) {
await getThreadAndRun(accessor, context, (thread: IThread) => thread.stepIn('instruction'));
} else {
await getThreadAndRun(accessor, context, (thread: IThread) => thread.stepIn());
}
}
});
KeybindingsRegistry.registerCommandAndKeybindingRule({
id: STEP_OUT_ID,
weight: KeybindingWeight.WorkbenchContrib,
primary: KeyMod.Shift | KeyCode.F11,
when: CONTEXT_DEBUG_STATE.isEqualTo('stopped'),
handler: async (accessor: ServicesAccessor, _: string, context: CallStackContext | unknown) => {
const contextKeyService = accessor.get(IContextKeyService);
if (CONTEXT_DISASSEMBLY_VIEW_FOCUS.getValue(contextKeyService)) {
await getThreadAndRun(accessor, context, (thread: IThread) => thread.stepOut('instruction'));
} else {
await getThreadAndRun(accessor, context, (thread: IThread) => thread.stepOut());
}
}
});
KeybindingsRegistry.registerCommandAndKeybindingRule({
id: PAUSE_ID,
weight: KeybindingWeight.WorkbenchContrib + 2, // take priority over focus next part while we are debugging
primary: KeyCode.F6,
when: CONTEXT_DEBUG_STATE.isEqualTo('running'),
handler: async (accessor: ServicesAccessor, _: string, context: CallStackContext | unknown) => {
await getThreadAndRun(accessor, context, thread => thread.pause());
}
});
KeybindingsRegistry.registerCommandAndKeybindingRule({
id: STEP_INTO_TARGET_ID,
primary: STEP_INTO_KEYBINDING | KeyMod.CtrlCmd,
when: ContextKeyExpr.and(CONTEXT_STEP_INTO_TARGETS_SUPPORTED, CONTEXT_IN_DEBUG_MODE, CONTEXT_DEBUG_STATE.isEqualTo('stopped')),
weight: KeybindingWeight.WorkbenchContrib,
handler: async (accessor: ServicesAccessor, _: string, context: CallStackContext | unknown) => {
const quickInputService = accessor.get(IQuickInputService);
const debugService = accessor.get(IDebugService);
const session = debugService.getViewModel().focusedSession;
const frame = debugService.getViewModel().focusedStackFrame;
if (!frame || !session) {
return;
}
const editor = await accessor.get(IEditorService).openEditor({
resource: frame.source.uri,
options: { revealIfOpened: true }
});
let codeEditor: ICodeEditor | undefined;
if (editor) {
const ctrl = editor?.getControl();
if (isCodeEditor(ctrl)) {
codeEditor = ctrl;
}
}
interface ITargetItem extends IQuickPickItem {
target: DebugProtocol.StepInTarget;
}
const qp = quickInputService.createQuickPick<ITargetItem>();
qp.busy = true;
qp.show();
qp.onDidChangeActive(([item]) => {
if (codeEditor && item && item.target.line !== undefined) {
codeEditor.revealLineInCenterIfOutsideViewport(item.target.line);
codeEditor.setSelection({
startLineNumber: item.target.line,
startColumn: item.target.column || 1,
endLineNumber: item.target.endLine || item.target.line,
endColumn: item.target.endColumn || item.target.column || 1,
});
}
});
qp.onDidAccept(() => {
if (qp.activeItems.length) {
session.stepIn(frame.thread.threadId, qp.activeItems[0].target.id);
}
});
qp.onDidHide(() => qp.dispose());
session.stepInTargets(frame.frameId).then(targets => {
qp.busy = false;
if (targets?.length) {
qp.items = targets?.map(target => ({ target, label: target.label }));
} else {
qp.placeholder = nls.localize('editor.debug.action.stepIntoTargets.none', "No step targets available");
}
});
}
});
async function stopHandler(accessor: ServicesAccessor, _: string, context: CallStackContext | unknown, disconnect: boolean, suspend?: boolean): Promise<void> {
const debugService = accessor.get(IDebugService);
let session: IDebugSession | undefined;
if (isSessionContext(context)) {
session = debugService.getModel().getSession(context.sessionId);
} else {
session = debugService.getViewModel().focusedSession;
}
const configurationService = accessor.get(IConfigurationService);
const showSubSessions = configurationService.getValue<IDebugConfiguration>('debug').showSubSessionsInToolBar;
// Stop should be sent to the root parent session
while (!showSubSessions && session && session.lifecycleManagedByParent && session.parentSession) {
session = session.parentSession;
}
await debugService.stopSession(session, disconnect, suspend);
}
KeybindingsRegistry.registerCommandAndKeybindingRule({
id: DISCONNECT_ID,
weight: KeybindingWeight.WorkbenchContrib,
primary: KeyMod.Shift | KeyCode.F5,
when: ContextKeyExpr.and(CONTEXT_FOCUSED_SESSION_IS_ATTACH, CONTEXT_IN_DEBUG_MODE),
handler: (accessor, _, context) => stopHandler(accessor, _, context, true)
});
CommandsRegistry.registerCommand({
id: DISCONNECT_AND_SUSPEND_ID,
handler: (accessor, _, context) => stopHandler(accessor, _, context, true, true)
});
KeybindingsRegistry.registerCommandAndKeybindingRule({
id: STOP_ID,
weight: KeybindingWeight.WorkbenchContrib,
primary: KeyMod.Shift | KeyCode.F5,
when: ContextKeyExpr.and(CONTEXT_FOCUSED_SESSION_IS_ATTACH.toNegated(), CONTEXT_IN_DEBUG_MODE),
handler: (accessor, _, context) => stopHandler(accessor, _, context, false)
});
CommandsRegistry.registerCommand({
id: RESTART_FRAME_ID,
handler: async (accessor: ServicesAccessor, _: string, context: CallStackContext | unknown) => {
const debugService = accessor.get(IDebugService);
const notificationService = accessor.get(INotificationService);
const frame = getFrame(debugService, context);
if (frame) {
try {
await frame.restart();
} catch (e) {
notificationService.error(e);
}
}
}
});
KeybindingsRegistry.registerCommandAndKeybindingRule({
id: CONTINUE_ID,
weight: KeybindingWeight.WorkbenchContrib + 10, // Use a stronger weight to get priority over start debugging F5 shortcut
primary: KeyCode.F5,
when: CONTEXT_DEBUG_STATE.isEqualTo('stopped'),
handler: async (accessor: ServicesAccessor, _: string, context: CallStackContext | unknown) => {
await getThreadAndRun(accessor, context, thread => thread.continue());
}
});
CommandsRegistry.registerCommand({
id: SHOW_LOADED_SCRIPTS_ID,
handler: async (accessor) => {
await showLoadedScriptMenu(accessor);
}
});
CommandsRegistry.registerCommand({
id: FOCUS_REPL_ID,
handler: async (accessor) => {
const viewsService = accessor.get(IViewsService);
await viewsService.openView(REPL_VIEW_ID, true);
}
});
CommandsRegistry.registerCommand({
id: 'debug.startFromConfig',
handler: async (accessor, config: IConfig) => {
const debugService = accessor.get(IDebugService);
await debugService.startDebugging(undefined, config);
}
});
CommandsRegistry.registerCommand({
id: FOCUS_SESSION_ID,
handler: async (accessor: ServicesAccessor, session: IDebugSession) => {
const debugService = accessor.get(IDebugService);
const editorService = accessor.get(IEditorService);
const stoppedChildSession = debugService.getModel().getSessions().find(s => s.parentSession === session && s.state === State.Stopped);
if (stoppedChildSession && session.state !== State.Stopped) {
session = stoppedChildSession;
}
await debugService.focusStackFrame(undefined, undefined, session, { explicit: true });
const stackFrame = debugService.getViewModel().focusedStackFrame;
if (stackFrame) {
await stackFrame.openInEditor(editorService, true);
}
}
});
CommandsRegistry.registerCommand({
id: SELECT_AND_START_ID,
handler: async (accessor: ServicesAccessor) => {
const quickInputService = accessor.get(IQuickInputService);
quickInputService.quickAccess.show(DEBUG_QUICK_ACCESS_PREFIX);
}
});
CommandsRegistry.registerCommand({
id: SELECT_DEBUG_CONSOLE_ID,
handler: async (accessor: ServicesAccessor) => {
const quickInputService = accessor.get(IQuickInputService);
quickInputService.quickAccess.show(DEBUG_CONSOLE_QUICK_ACCESS_PREFIX);
}
});
CommandsRegistry.registerCommand({
id: SELECT_DEBUG_SESSION_ID,
handler: async (accessor: ServicesAccessor) => {
showDebugSessionMenu(accessor, SELECT_AND_START_ID);
}
});
KeybindingsRegistry.registerCommandAndKeybindingRule({
id: DEBUG_START_COMMAND_ID,
weight: KeybindingWeight.WorkbenchContrib,
primary: KeyCode.F5,
when: ContextKeyExpr.and(CONTEXT_DEBUGGERS_AVAILABLE, CONTEXT_DEBUG_STATE.isEqualTo('inactive')),
handler: async (accessor: ServicesAccessor, debugStartOptions?: { config?: Partial<IConfig>; noDebug?: boolean }) => {
const debugService = accessor.get(IDebugService);
await saveAllBeforeDebugStart(accessor.get(IConfigurationService), accessor.get(IEditorService));
const { launch, name, getConfig } = debugService.getConfigurationManager().selectedConfiguration;
const config = await getConfig();
const configOrName = config ? Object.assign(deepClone(config), debugStartOptions?.config) : name;
await debugService.startDebugging(launch, configOrName, { noDebug: debugStartOptions?.noDebug, startedByUser: true }, false);
}
});
KeybindingsRegistry.registerCommandAndKeybindingRule({
id: DEBUG_RUN_COMMAND_ID,
weight: KeybindingWeight.WorkbenchContrib,
primary: KeyMod.CtrlCmd | KeyCode.F5,
mac: { primary: KeyMod.WinCtrl | KeyCode.F5 },
when: ContextKeyExpr.and(CONTEXT_DEBUGGERS_AVAILABLE, CONTEXT_DEBUG_STATE.notEqualsTo(getStateLabel(State.Initializing))),
handler: async (accessor: ServicesAccessor) => {
const commandService = accessor.get(ICommandService);
await commandService.executeCommand(DEBUG_START_COMMAND_ID, { noDebug: true });
}
});
KeybindingsRegistry.registerCommandAndKeybindingRule({
id: 'debug.toggleBreakpoint',
weight: KeybindingWeight.WorkbenchContrib + 5,
when: ContextKeyExpr.and(CONTEXT_BREAKPOINTS_FOCUSED, InputFocusedContext.toNegated()),
primary: KeyCode.Space,
handler: (accessor) => {
const listService = accessor.get(IListService);
const debugService = accessor.get(IDebugService);
const list = listService.lastFocusedList;
if (list instanceof List) {
const focused = <IEnablement[]>list.getFocusedElements();
if (focused && focused.length) {
debugService.enableOrDisableBreakpoints(!focused[0].enabled, focused[0]);
}
}
}
});
KeybindingsRegistry.registerCommandAndKeybindingRule({
id: 'debug.enableOrDisableBreakpoint',
weight: KeybindingWeight.WorkbenchContrib,
primary: undefined,
when: EditorContextKeys.editorTextFocus,
handler: (accessor) => {
const debugService = accessor.get(IDebugService);
const editorService = accessor.get(IEditorService);
const control = editorService.activeTextEditorControl;
if (isCodeEditor(control)) {
const model = control.getModel();
if (model) {
const position = control.getPosition();
if (position) {
const bps = debugService.getModel().getBreakpoints({ uri: model.uri, lineNumber: position.lineNumber });
if (bps.length) {
debugService.enableOrDisableBreakpoints(!bps[0].enabled, bps[0]);
}
}
}
}
}
});
KeybindingsRegistry.registerCommandAndKeybindingRule({
id: EDIT_EXPRESSION_COMMAND_ID,
weight: KeybindingWeight.WorkbenchContrib + 5,
when: CONTEXT_WATCH_EXPRESSIONS_FOCUSED,
primary: KeyCode.F2,
mac: { primary: KeyCode.Enter },
handler: (accessor: ServicesAccessor, expression: Expression | unknown) => {
const debugService = accessor.get(IDebugService);
if (!(expression instanceof Expression)) {
const listService = accessor.get(IListService);
const focused = listService.lastFocusedList;
if (focused) {
const elements = focused.getFocus();
if (Array.isArray(elements) && elements[0] instanceof Expression) {
expression = elements[0];
}
}
}
if (expression instanceof Expression) {
debugService.getViewModel().setSelectedExpression(expression, false);
}
}
});
CommandsRegistry.registerCommand({
id: SET_EXPRESSION_COMMAND_ID,
handler: async (accessor: ServicesAccessor, expression: Expression | unknown) => {
const debugService = accessor.get(IDebugService);
if (expression instanceof Expression || expression instanceof Variable) {
debugService.getViewModel().setSelectedExpression(expression, true);
}
}
});
KeybindingsRegistry.registerCommandAndKeybindingRule({
id: 'debug.setVariable',
weight: KeybindingWeight.WorkbenchContrib + 5,
when: CONTEXT_VARIABLES_FOCUSED,
primary: KeyCode.F2,
mac: { primary: KeyCode.Enter },
handler: (accessor) => {
const listService = accessor.get(IListService);
const debugService = accessor.get(IDebugService);
const focused = listService.lastFocusedList;
if (focused) {
const elements = focused.getFocus();
if (Array.isArray(elements) && elements[0] instanceof Variable) {
debugService.getViewModel().setSelectedExpression(elements[0], false);
}
}
}
});
KeybindingsRegistry.registerCommandAndKeybindingRule({
id: REMOVE_EXPRESSION_COMMAND_ID,
weight: KeybindingWeight.WorkbenchContrib,
when: ContextKeyExpr.and(CONTEXT_WATCH_EXPRESSIONS_FOCUSED, CONTEXT_EXPRESSION_SELECTED.toNegated()),
primary: KeyCode.Delete,
mac: { primary: KeyMod.CtrlCmd | KeyCode.Backspace },
handler: (accessor: ServicesAccessor, expression: Expression | unknown) => {
const debugService = accessor.get(IDebugService);
if (expression instanceof Expression) {
debugService.removeWatchExpressions(expression.getId());
return;
}
const listService = accessor.get(IListService);
const focused = listService.lastFocusedList;
if (focused) {
let elements = focused.getFocus();
if (Array.isArray(elements) && elements[0] instanceof Expression) {
const selection = focused.getSelection();
if (selection && selection.indexOf(elements[0]) >= 0) {
elements = selection;
}
elements.forEach((e: Expression) => debugService.removeWatchExpressions(e.getId()));
}
}
}
});
KeybindingsRegistry.registerCommandAndKeybindingRule({
id: 'debug.removeBreakpoint',
weight: KeybindingWeight.WorkbenchContrib,
when: ContextKeyExpr.and(CONTEXT_BREAKPOINTS_FOCUSED, CONTEXT_BREAKPOINT_INPUT_FOCUSED.toNegated()),
primary: KeyCode.Delete,
mac: { primary: KeyMod.CtrlCmd | KeyCode.Backspace },
handler: (accessor) => {
const listService = accessor.get(IListService);
const debugService = accessor.get(IDebugService);
const list = listService.lastFocusedList;
if (list instanceof List) {
const focused = list.getFocusedElements();
const element = focused.length ? focused[0] : undefined;
if (element instanceof Breakpoint) {
debugService.removeBreakpoints(element.getId());
} else if (element instanceof FunctionBreakpoint) {
debugService.removeFunctionBreakpoints(element.getId());
} else if (element instanceof DataBreakpoint) {
debugService.removeDataBreakpoints(element.getId());
}
}
}
});
KeybindingsRegistry.registerCommandAndKeybindingRule({
id: 'debug.installAdditionalDebuggers',
weight: KeybindingWeight.WorkbenchContrib,
when: undefined,
primary: undefined,
handler: async (accessor, query: string) => {
const paneCompositeService = accessor.get(IPaneCompositePartService);
const viewlet = (await paneCompositeService.openPaneComposite(EXTENSIONS_VIEWLET_ID, ViewContainerLocation.Sidebar, true))?.getViewPaneContainer() as IExtensionsViewPaneContainer;
let searchFor = `@category:debuggers`;
if (typeof query === 'string') {
searchFor += ` ${query}`;
}
viewlet.search(searchFor);
viewlet.focus();
}
});
registerAction2(class AddConfigurationAction extends Action2 {
constructor() {
super({
id: ADD_CONFIGURATION_ID,
title: { value: nls.localize('addConfiguration', "Add Configuration..."), original: 'Add Configuration...' },
category: DEBUG_COMMAND_CATEGORY,
f1: true,
menu: {
id: MenuId.EditorContent,
when: ContextKeyExpr.and(
ContextKeyExpr.regex(ResourceContextKey.Path.key, /\.vscode[/\\]launch\.json$/),
ActiveEditorContext.isEqualTo(TEXT_FILE_EDITOR_ID))
}
});
}
async run(accessor: ServicesAccessor, launchUri: string): Promise<void> {
const manager = accessor.get(IDebugService).getConfigurationManager();
const launch = manager.getLaunches().find(l => l.uri.toString() === launchUri) || manager.selectedConfiguration.launch;
if (launch) {
const { editor, created } = await launch.openConfigFile({ preserveFocus: false });
if (editor && !created) {
const codeEditor = <ICodeEditor>editor.getControl();
if (codeEditor) {
await codeEditor.getContribution<IDebugEditorContribution>(EDITOR_CONTRIBUTION_ID)?.addLaunchConfiguration();
}
}
}
}
});
const inlineBreakpointHandler = (accessor: ServicesAccessor) => {
const debugService = accessor.get(IDebugService);
const editorService = accessor.get(IEditorService);
const control = editorService.activeTextEditorControl;
if (isCodeEditor(control)) {
const position = control.getPosition();
if (position && control.hasModel() && debugService.canSetBreakpointsIn(control.getModel())) {
const modelUri = control.getModel().uri;
const breakpointAlreadySet = debugService.getModel().getBreakpoints({ lineNumber: position.lineNumber, uri: modelUri })
.some(bp => (bp.sessionAgnosticData.column === position.column || (!bp.column && position.column <= 1)));
if (!breakpointAlreadySet) {
debugService.addBreakpoints(modelUri, [{ lineNumber: position.lineNumber, column: position.column > 1 ? position.column : undefined }]);
}
}
}
};
KeybindingsRegistry.registerCommandAndKeybindingRule({
weight: KeybindingWeight.WorkbenchContrib,
primary: KeyMod.Shift | KeyCode.F9,
when: EditorContextKeys.editorTextFocus,
id: TOGGLE_INLINE_BREAKPOINT_ID,
handler: inlineBreakpointHandler
});
MenuRegistry.appendMenuItem(MenuId.EditorContext, {
command: {
id: TOGGLE_INLINE_BREAKPOINT_ID,
title: nls.localize('addInlineBreakpoint', "Add Inline Breakpoint"),
category: DEBUG_COMMAND_CATEGORY
},
when: ContextKeyExpr.and(CONTEXT_IN_DEBUG_MODE, PanelFocusContext.toNegated(), EditorContextKeys.editorTextFocus),
group: 'debug',
order: 1
});
KeybindingsRegistry.registerCommandAndKeybindingRule({
id: 'debug.openBreakpointToSide',
weight: KeybindingWeight.WorkbenchContrib,
when: CONTEXT_BREAKPOINTS_FOCUSED,
primary: KeyMod.CtrlCmd | KeyCode.Enter,
secondary: [KeyMod.Alt | KeyCode.Enter],
handler: (accessor) => {
const listService = accessor.get(IListService);
const list = listService.lastFocusedList;
if (list instanceof List) {
const focus = list.getFocusedElements();
if (focus.length && focus[0] instanceof Breakpoint) {
return openBreakpointSource(focus[0], true, false, true, accessor.get(IDebugService), accessor.get(IEditorService));
}
}
return undefined;
}
});
// When there are no debug extensions, open the debug viewlet when F5 is pressed so the user can read the limitations
KeybindingsRegistry.registerCommandAndKeybindingRule({
id: 'debug.openView',
weight: KeybindingWeight.WorkbenchContrib,
when: CONTEXT_DEBUGGERS_AVAILABLE.toNegated(),
primary: KeyCode.F5,
secondary: [KeyMod.CtrlCmd | KeyCode.F5],
handler: async (accessor) => {
const paneCompositeService = accessor.get(IPaneCompositePartService);
await paneCompositeService.openPaneComposite(VIEWLET_ID, ViewContainerLocation.Sidebar, true);
}
});
| src/vs/workbench/contrib/debug/browser/debugCommands.ts | 0 | https://github.com/microsoft/vscode/commit/c2bf6225a12e7f7d8afada6ec39560bb38e5838a | [
0.02668878808617592,
0.0005821878439746797,
0.00016091056750155985,
0.0001718755956972018,
0.002738355193287134
] |
{
"id": 4,
"code_window": [
"\t\t\t\t},\n",
"\t\t\t\tf1: false,\n",
"\t\t\t\tcategory: INTERACTIVE_SESSION_CATEGORY,\n",
"\t\t\t\ticon: Codicon.thumbsdown,\n",
"\t\t\t\tprecondition: CONTEXT_RESPONSE_VOTE.isEqualTo(''), // Should be disabled but visible when vote=down\n",
"\t\t\t\tmenu: {\n",
"\t\t\t\t\tid: MenuId.InteractiveSessionTitle,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\ttoggled: CONTEXT_RESPONSE_VOTE.isEqualTo('down'),\n"
],
"file_path": "src/vs/workbench/contrib/interactiveSession/browser/actions/interactiveSessionTitleActions.ts",
"type": "replace",
"edit_start_line_idx": 67
} | /*---------------------------------------------------------------------------------------------
* 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 { renderIcon } from 'vs/base/browser/ui/iconLabel/iconLabels';
import { IListVirtualDelegate } from 'vs/base/browser/ui/list/list';
import { IListAccessibilityProvider } from 'vs/base/browser/ui/list/listWidget';
import { ITreeNode, ITreeRenderer } from 'vs/base/browser/ui/tree/tree';
import { IntervalTimer } from 'vs/base/common/async';
import { Codicon } from 'vs/base/common/codicons';
import { Emitter, Event } from 'vs/base/common/event';
import { FuzzyScore } from 'vs/base/common/filters';
import { IMarkdownString, MarkdownString } from 'vs/base/common/htmlContent';
import { Disposable, DisposableStore, IDisposable } from 'vs/base/common/lifecycle';
import { ResourceMap } from 'vs/base/common/map';
import { FileAccess } from 'vs/base/common/network';
import { ThemeIcon } from 'vs/base/common/themables';
import { EditorExtensionsRegistry } from 'vs/editor/browser/editorExtensions';
import { CodeEditorWidget } from 'vs/editor/browser/widget/codeEditorWidget';
import { EDITOR_FONT_DEFAULTS, IEditorOptions } from 'vs/editor/common/config/editorOptions';
import { Range } from 'vs/editor/common/core/range';
import { ILanguageService } from 'vs/editor/common/languages/language';
import { ITextModel } from 'vs/editor/common/model';
import { IModelService } from 'vs/editor/common/services/model';
import { BracketMatchingController } from 'vs/editor/contrib/bracketMatching/browser/bracketMatching';
import { ContextMenuController } from 'vs/editor/contrib/contextmenu/browser/contextmenu';
import { IMarkdownRenderResult, MarkdownRenderer } from 'vs/editor/contrib/markdownRenderer/browser/markdownRenderer';
import { ViewportSemanticTokensContribution } from 'vs/editor/contrib/semanticTokens/browser/viewportSemanticTokens';
import { SmartSelectController } from 'vs/editor/contrib/smartSelect/browser/smartSelect';
import { WordHighlighterContribution } from 'vs/editor/contrib/wordHighlighter/browser/wordHighlighter';
import { localize } from 'vs/nls';
import { MenuWorkbenchToolBar } from 'vs/platform/actions/browser/toolbar';
import { MenuId } from 'vs/platform/actions/common/actions';
import { ICommandService } from 'vs/platform/commands/common/commands';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection';
import { ILogService } from 'vs/platform/log/common/log';
import { defaultButtonStyles } from 'vs/platform/theme/browser/defaultStyles';
import { MenuPreventer } from 'vs/workbench/contrib/codeEditor/browser/menuPreventer';
import { SelectionClipboardContributionID } from 'vs/workbench/contrib/codeEditor/browser/selectionClipboard';
import { getSimpleEditorOptions } from 'vs/workbench/contrib/codeEditor/browser/simpleEditorOptions';
import { IInteractiveSessionCodeBlockActionContext } from 'vs/workbench/contrib/interactiveSession/browser/actions/interactiveSessionCodeblockActions';
import { InteractiveSessionFollowups } from 'vs/workbench/contrib/interactiveSession/browser/interactiveSessionFollowups';
import { InteractiveSessionEditorOptions } from 'vs/workbench/contrib/interactiveSession/browser/interactiveSessionOptions';
import { CONTEXT_RESPONSE_HAS_PROVIDER_ID, CONTEXT_RESPONSE_VOTE } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionContextKeys';
import { IInteractiveSessionReplyFollowup, IInteractiveSessionService, IInteractiveSlashCommand, InteractiveSessionVoteDirection } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionService';
import { IInteractiveRequestViewModel, IInteractiveResponseViewModel, IInteractiveWelcomeMessageViewModel, isRequestVM, isResponseVM, isWelcomeVM } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionViewModel';
import { getNWords } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionWordCounter';
const $ = dom.$;
export type InteractiveTreeItem = IInteractiveRequestViewModel | IInteractiveResponseViewModel | IInteractiveWelcomeMessageViewModel;
interface IInteractiveListItemTemplate {
rowContainer: HTMLElement;
titleToolbar: MenuWorkbenchToolBar;
avatar: HTMLElement;
username: HTMLElement;
value: HTMLElement;
contextKeyService: IContextKeyService;
templateDisposables: IDisposable;
elementDisposables: DisposableStore;
}
interface IItemHeightChangeParams {
element: InteractiveTreeItem;
height: number;
}
const forceVerboseLayoutTracing = false;
export interface IInteractiveSessionRendererDelegate {
getListLength(): number;
getSlashCommands(): IInteractiveSlashCommand[];
}
export class InteractiveListItemRenderer extends Disposable implements ITreeRenderer<InteractiveTreeItem, FuzzyScore, IInteractiveListItemTemplate> {
static readonly cursorCharacter = '\u258c';
static readonly ID = 'item';
private readonly renderer: MarkdownRenderer;
protected readonly _onDidClickFollowup = this._register(new Emitter<IInteractiveSessionReplyFollowup>());
readonly onDidClickFollowup: Event<IInteractiveSessionReplyFollowup> = this._onDidClickFollowup.event;
protected readonly _onDidChangeItemHeight = this._register(new Emitter<IItemHeightChangeParams>());
readonly onDidChangeItemHeight: Event<IItemHeightChangeParams> = this._onDidChangeItemHeight.event;
private readonly _editorPool: EditorPool;
private _currentLayoutWidth: number = 0;
constructor(
private readonly editorOptions: InteractiveSessionEditorOptions,
private readonly delegate: IInteractiveSessionRendererDelegate,
@IInstantiationService private readonly instantiationService: IInstantiationService,
@IConfigurationService private readonly configService: IConfigurationService,
@ILogService private readonly logService: ILogService,
@ICommandService private readonly commandService: ICommandService,
@IContextKeyService private readonly contextKeyService: IContextKeyService,
@IInteractiveSessionService private readonly interactiveSessionService: IInteractiveSessionService,
) {
super();
this.renderer = this.instantiationService.createInstance(MarkdownRenderer, {});
this._editorPool = this._register(this.instantiationService.createInstance(EditorPool, this.editorOptions));
}
get templateId(): string {
return InteractiveListItemRenderer.ID;
}
private traceLayout(method: string, message: string) {
if (forceVerboseLayoutTracing) {
this.logService.info(`InteractiveListItemRenderer#${method}: ${message}`);
} else {
this.logService.trace(`InteractiveListItemRenderer#${method}: ${message}`);
}
}
private shouldRenderProgressively(element: IInteractiveResponseViewModel): boolean {
return !this.configService.getValue('interactive.experimental.disableProgressiveRendering') && element.progressiveResponseRenderingEnabled;
}
private getProgressiveRenderRate(element: IInteractiveResponseViewModel): number {
const configuredRate = this.configService.getValue('interactive.experimental.progressiveRenderingRate');
if (typeof configuredRate === 'number') {
return configuredRate;
}
if (element.isComplete) {
return 60;
}
if (element.contentUpdateTimings && element.contentUpdateTimings.impliedWordLoadRate) {
// This doesn't account for dead time after the last update. When the previous update is the final one and the model is only waiting for followupQuestions, that's good.
// When there was one quick update and then you are waiting longer for the next one, that's not good since the rate should be decreasing.
// If it's an issue, we can change this to be based on the total time from now to the beginning.
const rateBoost = 1.5;
return element.contentUpdateTimings.impliedWordLoadRate * rateBoost;
}
return 8;
}
layout(width: number): void {
this._currentLayoutWidth = width - 40; // TODO Padding
this._editorPool.inUse.forEach(editor => {
editor.layout(this._currentLayoutWidth);
});
}
renderTemplate(container: HTMLElement): IInteractiveListItemTemplate {
const templateDisposables = new DisposableStore();
const rowContainer = dom.append(container, $('.interactive-item-container'));
const header = dom.append(rowContainer, $('.header'));
const user = dom.append(header, $('.user'));
const avatar = dom.append(user, $('.avatar'));
const username = dom.append(user, $('h3.username'));
const value = dom.append(rowContainer, $('.value'));
const elementDisposables = new DisposableStore();
const contextKeyService = templateDisposables.add(this.contextKeyService.createScoped(rowContainer));
const scopedInstantiationService = this.instantiationService.createChild(new ServiceCollection([IContextKeyService, contextKeyService]));
const titleToolbar = templateDisposables.add(scopedInstantiationService.createInstance(MenuWorkbenchToolBar, header, MenuId.InteractiveSessionTitle, {
menuOptions: {
shouldForwardArgs: true
}
}));
const template: IInteractiveListItemTemplate = { avatar, username, value, rowContainer, elementDisposables, titleToolbar, templateDisposables, contextKeyService };
return template;
}
renderElement(node: ITreeNode<InteractiveTreeItem, FuzzyScore>, index: number, templateData: IInteractiveListItemTemplate): void {
const { element } = node;
const kind = isRequestVM(element) ? 'request' :
isResponseVM(element) ? 'response' :
'welcome';
this.traceLayout('renderElement', `${kind}, index=${index}`);
CONTEXT_RESPONSE_HAS_PROVIDER_ID.bindTo(templateData.contextKeyService).set(isResponseVM(element) && !!element.providerResponseId && !element.isPlaceholder);
if (isResponseVM(element)) {
CONTEXT_RESPONSE_VOTE.bindTo(templateData.contextKeyService).set(element.vote === InteractiveSessionVoteDirection.Up ? 'up' : element.vote === InteractiveSessionVoteDirection.Down ? 'down' : '');
} else {
CONTEXT_RESPONSE_VOTE.bindTo(templateData.contextKeyService).set('');
}
templateData.titleToolbar.context = element;
templateData.rowContainer.classList.toggle('interactive-request', isRequestVM(element));
templateData.rowContainer.classList.toggle('interactive-response', isResponseVM(element));
templateData.rowContainer.classList.toggle('interactive-welcome', isWelcomeVM(element));
templateData.rowContainer.classList.toggle('filtered-response', !!(isResponseVM(element) && element.errorDetails?.responseIsFiltered));
templateData.username.textContent = element.username;
if (element.avatarIconUri) {
const avatarIcon = dom.$<HTMLImageElement>('img.icon');
avatarIcon.src = FileAccess.uriToBrowserUri(element.avatarIconUri).toString(true);
templateData.avatar.replaceChildren(avatarIcon);
} else {
const defaultIcon = isRequestVM(element) ? Codicon.account : Codicon.hubot;
const avatarIcon = dom.$(ThemeIcon.asCSSSelector(defaultIcon));
templateData.avatar.replaceChildren(avatarIcon);
}
// Do a progressive render if
// - This the last response in the list
// - And the response is not complete
// - Or, we previously started a progressive rendering of this element (if the element is complete, we will finish progressive rendering with a very fast rate)
// - And, the feature is not disabled in configuration
if (isResponseVM(element) && index === this.delegate.getListLength() - 1 && (!element.isComplete || element.renderData) && this.shouldRenderProgressively(element)) {
this.traceLayout('renderElement', `start progressive render ${kind}, index=${index}`);
const progressiveRenderingDisposables = templateData.elementDisposables.add(new DisposableStore());
const timer = templateData.elementDisposables.add(new IntervalTimer());
const runProgressiveRender = (initial?: boolean) => {
try {
if (this.doNextProgressiveRender(element, index, templateData, !!initial, progressiveRenderingDisposables)) {
timer.cancel();
}
} catch (err) {
// Kill the timer if anything went wrong, avoid getting stuck in a nasty rendering loop.
timer.cancel();
throw err;
}
};
runProgressiveRender(true);
timer.cancelAndSet(runProgressiveRender, 50);
} else if (isResponseVM(element)) {
this.basicRenderElement(element.response.value, element, index, templateData);
} else if (isRequestVM(element)) {
this.basicRenderElement(element.messageText, element, index, templateData);
} else {
this.renderWelcomeMessage(element, templateData);
}
}
private basicRenderElement(markdownValue: string, element: InteractiveTreeItem, index: number, templateData: IInteractiveListItemTemplate) {
const fillInIncompleteTokens = isResponseVM(element) && (!element.isComplete || element.isCanceled || element.errorDetails?.responseIsFiltered || element.errorDetails?.responseIsIncomplete);
const result = this.renderMarkdown(new MarkdownString(markdownValue), element, templateData.elementDisposables, templateData, fillInIncompleteTokens);
dom.clearNode(templateData.value);
templateData.value.appendChild(result.element);
templateData.elementDisposables.add(result);
if (isResponseVM(element) && element.errorDetails?.message) {
const errorDetails = dom.append(templateData.value, $('.interactive-response-error-details', undefined, renderIcon(Codicon.error)));
errorDetails.appendChild($('span', undefined, element.errorDetails.message));
}
if (isResponseVM(element) && element.commandFollowups?.length) {
const followupsContainer = dom.append(templateData.value, $('.interactive-response-followups'));
templateData.elementDisposables.add(new InteractiveSessionFollowups(
followupsContainer,
element.commandFollowups,
defaultButtonStyles,
followup => {
this.interactiveSessionService.notifyUserAction({
providerId: element.providerId,
action: {
kind: 'command',
command: followup
}
});
return this.commandService.executeCommand(followup.commandId, ...(followup.args ?? []));
}));
}
}
private renderWelcomeMessage(element: IInteractiveWelcomeMessageViewModel, templateData: IInteractiveListItemTemplate) {
dom.clearNode(templateData.value);
const slashCommands = this.delegate.getSlashCommands();
for (const item of element.content) {
if (Array.isArray(item)) {
templateData.elementDisposables.add(new InteractiveSessionFollowups(
templateData.value,
item,
undefined,
followup => this._onDidClickFollowup.fire(followup)));
} else {
const result = this.renderMarkdown(item as IMarkdownString, element, templateData.elementDisposables, templateData);
for (const codeElement of result.element.querySelectorAll('code')) {
if (codeElement.textContent && slashCommands.find(command => codeElement.textContent === `/${command.command}`)) {
codeElement.classList.add('interactive-slash-command');
}
}
templateData.value.appendChild(result.element);
templateData.elementDisposables.add(result);
}
}
}
private doNextProgressiveRender(element: IInteractiveResponseViewModel, index: number, templateData: IInteractiveListItemTemplate, isInRenderElement: boolean, disposables: DisposableStore): boolean {
disposables.clear();
let isFullyRendered = false;
if (element.isCanceled) {
this.traceLayout('runProgressiveRender', `canceled, index=${index}`);
element.renderData = undefined;
this.basicRenderElement(element.response.value, element, index, templateData);
isFullyRendered = true;
} else {
// TODO- this method has the side effect of updating element.renderData
const toRender = this.getProgressiveMarkdownToRender(element);
isFullyRendered = !!element.renderData?.isFullyRendered;
if (isFullyRendered) {
// We've reached the end of the available content, so do a normal render
this.traceLayout('runProgressiveRender', `end progressive render, index=${index}`);
if (element.isComplete) {
this.traceLayout('runProgressiveRender', `and disposing renderData, response is complete, index=${index}`);
element.renderData = undefined;
} else {
this.traceLayout('runProgressiveRender', `Rendered all available words, but model is not complete.`);
}
disposables.clear();
this.basicRenderElement(element.response.value, element, index, templateData);
} else if (toRender) {
// Doing the progressive render
const plusCursor = toRender.match(/```.*$/) ? toRender + `\n${InteractiveListItemRenderer.cursorCharacter}` : toRender + ` ${InteractiveListItemRenderer.cursorCharacter}`;
const result = this.renderMarkdown(new MarkdownString(plusCursor), element, disposables, templateData, true);
dom.clearNode(templateData.value);
templateData.value.appendChild(result.element);
disposables.add(result);
} else {
// Nothing new to render, not done, keep waiting
return false;
}
}
// Some render happened - update the height
const height = templateData.rowContainer.offsetHeight;
element.currentRenderedHeight = height;
if (!isInRenderElement) {
this._onDidChangeItemHeight.fire({ element, height: templateData.rowContainer.offsetHeight });
}
return !!isFullyRendered;
}
private renderMarkdown(markdown: IMarkdownString, element: InteractiveTreeItem, disposables: DisposableStore, templateData: IInteractiveListItemTemplate, fillInIncompleteTokens = false): IMarkdownRenderResult {
const disposablesList: IDisposable[] = [];
let codeBlockIndex = 0;
// TODO if the slash commands stay completely dynamic, this isn't quite right
const slashCommands = this.delegate.getSlashCommands();
const usedSlashCommand = slashCommands.find(s => markdown.value.startsWith(`/${s.command} `));
const toRender = usedSlashCommand ? markdown.value.slice(usedSlashCommand.command.length + 2) : markdown.value;
markdown = new MarkdownString(toRender);
const result = this.renderer.render(markdown, {
fillInIncompleteTokens,
codeBlockRendererSync: (languageId, text) => {
const ref = this.renderCodeBlock({ languageId, text, codeBlockIndex: codeBlockIndex++, element, parentContextKeyService: templateData.contextKeyService }, disposables);
// Attach this after updating text/layout of the editor, so it should only be fired when the size updates later (horizontal scrollbar, wrapping)
// not during a renderElement OR a progressive render (when we will be firing this event anyway at the end of the render)
disposables.add(ref.object.onDidChangeContentHeight(() => {
ref.object.layout(this._currentLayoutWidth);
this._onDidChangeItemHeight.fire({ element, height: templateData.rowContainer.offsetHeight });
}));
disposablesList.push(ref);
return ref.object.element;
}
});
if (usedSlashCommand) {
const slashCommandElement = $('span.interactive-slash-command', { title: usedSlashCommand.detail }, `/${usedSlashCommand.command} `);
if (result.element.firstChild?.nodeName.toLowerCase() === 'p') {
result.element.firstChild.insertBefore(slashCommandElement, result.element.firstChild.firstChild);
} else {
result.element.insertBefore($('p', undefined, slashCommandElement), result.element.firstChild);
}
}
disposablesList.reverse().forEach(d => disposables.add(d));
return result;
}
private renderCodeBlock(data: IInteractiveResultCodeBlockData, disposables: DisposableStore): IDisposableReference<IInteractiveResultCodeBlockPart> {
const ref = this._editorPool.get();
const editorInfo = ref.object;
editorInfo.render(data, this._currentLayoutWidth);
return ref;
}
private getProgressiveMarkdownToRender(element: IInteractiveResponseViewModel): string | undefined {
const renderData = element.renderData ?? { renderedWordCount: 0, lastRenderTime: 0 };
const rate = this.getProgressiveRenderRate(element);
const numWordsToRender = renderData.lastRenderTime === 0 ?
1 :
renderData.renderedWordCount +
// Additional words to render beyond what's already rendered
Math.floor((Date.now() - renderData.lastRenderTime) / 1000 * rate);
if (numWordsToRender === renderData.renderedWordCount) {
return undefined;
}
const result = getNWords(element.response.value, numWordsToRender);
element.renderData = {
renderedWordCount: result.actualWordCount,
lastRenderTime: Date.now(),
isFullyRendered: result.isFullString
};
return result.value;
}
disposeElement(node: ITreeNode<InteractiveTreeItem, FuzzyScore>, index: number, templateData: IInteractiveListItemTemplate): void {
templateData.elementDisposables.clear();
}
disposeTemplate(templateData: IInteractiveListItemTemplate): void {
templateData.templateDisposables.dispose();
}
}
export class InteractiveSessionListDelegate implements IListVirtualDelegate<InteractiveTreeItem> {
constructor(
@ILogService private readonly logService: ILogService
) { }
private _traceLayout(method: string, message: string) {
if (forceVerboseLayoutTracing) {
this.logService.info(`InteractiveSessionListDelegate#${method}: ${message}`);
} else {
this.logService.trace(`InteractiveSessionListDelegate#${method}: ${message}`);
}
}
getHeight(element: InteractiveTreeItem): number {
const kind = isRequestVM(element) ? 'request' : 'response';
const height = ('currentRenderedHeight' in element ? element.currentRenderedHeight : undefined) ?? 200;
this._traceLayout('getHeight', `${kind}, height=${height}`);
return height;
}
getTemplateId(element: InteractiveTreeItem): string {
return InteractiveListItemRenderer.ID;
}
hasDynamicHeight(element: InteractiveTreeItem): boolean {
return true;
}
}
export class InteractiveSessionAccessibilityProvider implements IListAccessibilityProvider<InteractiveTreeItem> {
getWidgetAriaLabel(): string {
return localize('interactiveSession', "Interactive Session");
}
getAriaLabel(element: InteractiveTreeItem): string {
if (isRequestVM(element)) {
return localize('interactiveRequest', "Request: {0}", element.messageText);
}
if (isResponseVM(element)) {
return localize('interactiveResponse', "Response: {0}", element.response.value);
}
return '';
}
}
interface IInteractiveResultCodeBlockData {
text: string;
languageId: string;
codeBlockIndex: number;
element: InteractiveTreeItem;
parentContextKeyService: IContextKeyService;
}
interface IInteractiveResultCodeBlockPart {
readonly onDidChangeContentHeight: Event<number>;
readonly element: HTMLElement;
readonly textModel: ITextModel;
layout(width: number): void;
render(data: IInteractiveResultCodeBlockData, width: number): void;
dispose(): void;
}
export interface IInteractiveResultCodeBlockInfo {
providerId: string;
responseId: string;
codeBlockIndex: number;
}
export const codeBlockInfosByModelUri = new ResourceMap<IInteractiveResultCodeBlockInfo>();
class CodeBlockPart extends Disposable implements IInteractiveResultCodeBlockPart {
private readonly _onDidChangeContentHeight = this._register(new Emitter<number>());
public readonly onDidChangeContentHeight = this._onDidChangeContentHeight.event;
private readonly editor: CodeEditorWidget;
private readonly toolbar: MenuWorkbenchToolBar;
private readonly contextKeyService: IContextKeyService;
public readonly textModel: ITextModel;
public readonly element: HTMLElement;
constructor(
private readonly options: InteractiveSessionEditorOptions,
@IInstantiationService instantiationService: IInstantiationService,
@IContextKeyService contextKeyService: IContextKeyService,
@ILanguageService private readonly languageService: ILanguageService,
@IModelService private readonly modelService: IModelService,
) {
super();
this.element = $('.interactive-result-editor-wrapper');
this.contextKeyService = this._register(contextKeyService.createScoped(this.element));
const scopedInstantiationService = instantiationService.createChild(new ServiceCollection([IContextKeyService, this.contextKeyService]));
this.toolbar = this._register(scopedInstantiationService.createInstance(MenuWorkbenchToolBar, this.element, MenuId.InteractiveSessionCodeBlock, {
menuOptions: {
shouldForwardArgs: true
}
}));
const editorElement = dom.append(this.element, $('.interactive-result-editor'));
this.editor = this._register(scopedInstantiationService.createInstance(CodeEditorWidget, editorElement, {
...getSimpleEditorOptions(),
readOnly: true,
lineNumbers: 'off',
selectOnLineNumbers: true,
scrollBeyondLastLine: false,
lineDecorationsWidth: 8,
dragAndDrop: false,
padding: { top: 2, bottom: 2 },
mouseWheelZoom: false,
scrollbar: {
alwaysConsumeMouseWheel: false
},
...this.getEditorOptionsFromConfig()
}, {
isSimpleWidget: true,
contributions: EditorExtensionsRegistry.getSomeEditorContributions([
MenuPreventer.ID,
SelectionClipboardContributionID,
ContextMenuController.ID,
WordHighlighterContribution.ID,
ViewportSemanticTokensContribution.ID,
BracketMatchingController.ID,
SmartSelectController.ID,
])
}));
this._register(this.options.onDidChange(() => {
this.editor.updateOptions(this.getEditorOptionsFromConfig());
}));
this._register(this.editor.onDidContentSizeChange(e => {
if (e.contentHeightChanged) {
this._onDidChangeContentHeight.fire(e.contentHeight);
}
}));
this._register(this.editor.onDidBlurEditorWidget(() => {
WordHighlighterContribution.get(this.editor)?.stopHighlighting();
}));
this._register(this.editor.onDidFocusEditorWidget(() => {
WordHighlighterContribution.get(this.editor)?.restoreViewState(true);
}));
const vscodeLanguageId = this.languageService.getLanguageIdByLanguageName('javascript');
this.textModel = this._register(this.modelService.createModel('', this.languageService.createById(vscodeLanguageId), undefined));
this.editor.setModel(this.textModel);
}
private getEditorOptionsFromConfig(): IEditorOptions {
return {
wordWrap: this.options.configuration.resultEditor.wordWrap,
fontLigatures: this.options.configuration.resultEditor.fontLigatures,
bracketPairColorization: this.options.configuration.resultEditor.bracketPairColorization,
fontFamily: this.options.configuration.resultEditor.fontFamily === 'default' ?
EDITOR_FONT_DEFAULTS.fontFamily :
this.options.configuration.resultEditor.fontFamily,
fontSize: this.options.configuration.resultEditor.fontSize,
fontWeight: this.options.configuration.resultEditor.fontWeight,
lineHeight: this.options.configuration.resultEditor.lineHeight,
};
}
layout(width: number): void {
const realContentHeight = this.editor.getContentHeight();
const editorBorder = 2;
this.editor.layout({ width: width - editorBorder, height: realContentHeight });
}
render(data: IInteractiveResultCodeBlockData, width: number): void {
this.contextKeyService.updateParent(data.parentContextKeyService);
if (this.options.configuration.resultEditor.wordWrap === 'on') {
// Intialize the editor with the new proper width so that getContentHeight
// will be computed correctly in the next call to layout()
this.layout(width);
}
this.setText(data.text);
this.setLanguage(data.languageId);
this.layout(width);
if (isResponseVM(data.element) && data.element.providerResponseId) {
// For telemetry reporting
codeBlockInfosByModelUri.set(this.textModel.uri, {
providerId: data.element.providerId,
responseId: data.element.providerResponseId,
codeBlockIndex: data.codeBlockIndex
});
} else {
codeBlockInfosByModelUri.delete(this.textModel.uri);
}
this.toolbar.context = <IInteractiveSessionCodeBlockActionContext>{
code: data.text,
codeBlockIndex: data.codeBlockIndex,
element: data.element
};
}
private setText(newText: string): void {
let currentText = this.textModel.getLinesContent().join('\n');
if (newText === currentText) {
return;
}
let removedChars = 0;
if (currentText.endsWith(` ${InteractiveListItemRenderer.cursorCharacter}`)) {
removedChars = 2;
} else if (currentText.endsWith(InteractiveListItemRenderer.cursorCharacter)) {
removedChars = 1;
}
if (removedChars > 0) {
currentText = currentText.slice(0, currentText.length - removedChars);
}
if (newText.startsWith(currentText)) {
const text = newText.slice(currentText.length);
const lastLine = this.textModel.getLineCount();
const lastCol = this.textModel.getLineMaxColumn(lastLine);
const insertAtCol = lastCol - removedChars;
this.textModel.applyEdits([{ range: new Range(lastLine, insertAtCol, lastLine, lastCol), text }]);
} else {
// console.log(`Failed to optimize setText`);
this.textModel.setValue(newText);
}
}
private setLanguage(languageId: string): void {
const vscodeLanguageId = this.languageService.getLanguageIdByLanguageName(languageId);
if (vscodeLanguageId) {
this.textModel.setLanguage(vscodeLanguageId);
}
}
}
interface IDisposableReference<T> extends IDisposable {
object: T;
}
class EditorPool extends Disposable {
private _pool: ResourcePool<IInteractiveResultCodeBlockPart>;
public get inUse(): ReadonlySet<IInteractiveResultCodeBlockPart> {
return this._pool.inUse;
}
constructor(
private readonly options: InteractiveSessionEditorOptions,
@IInstantiationService private readonly instantiationService: IInstantiationService,
) {
super();
this._pool = this._register(new ResourcePool(() => this.editorFactory()));
// TODO listen to changes on options
}
private editorFactory(): IInteractiveResultCodeBlockPart {
return this.instantiationService.createInstance(CodeBlockPart, this.options);
}
get(): IDisposableReference<IInteractiveResultCodeBlockPart> {
const object = this._pool.get();
return {
object,
dispose: () => this._pool.release(object)
};
}
}
// TODO does something in lifecycle.ts cover this?
class ResourcePool<T extends IDisposable> extends Disposable {
private readonly pool: T[] = [];
private _inUse = new Set<T>;
public get inUse(): ReadonlySet<T> {
return this._inUse;
}
constructor(
private readonly _itemFactory: () => T,
) {
super();
}
get(): T {
if (this.pool.length > 0) {
const item = this.pool.pop()!;
this._inUse.add(item);
return item;
}
const item = this._register(this._itemFactory());
this._inUse.add(item);
return item;
}
release(item: T): void {
this._inUse.delete(item);
this.pool.push(item);
}
}
| src/vs/workbench/contrib/interactiveSession/browser/interactiveSessionListRenderer.ts | 1 | https://github.com/microsoft/vscode/commit/c2bf6225a12e7f7d8afada6ec39560bb38e5838a | [
0.0169750414788723,
0.0008251701365225017,
0.0001620309631107375,
0.00017146457685157657,
0.002603220986202359
] |
{
"id": 4,
"code_window": [
"\t\t\t\t},\n",
"\t\t\t\tf1: false,\n",
"\t\t\t\tcategory: INTERACTIVE_SESSION_CATEGORY,\n",
"\t\t\t\ticon: Codicon.thumbsdown,\n",
"\t\t\t\tprecondition: CONTEXT_RESPONSE_VOTE.isEqualTo(''), // Should be disabled but visible when vote=down\n",
"\t\t\t\tmenu: {\n",
"\t\t\t\t\tid: MenuId.InteractiveSessionTitle,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\ttoggled: CONTEXT_RESPONSE_VOTE.isEqualTo('down'),\n"
],
"file_path": "src/vs/workbench/contrib/interactiveSession/browser/actions/interactiveSessionTitleActions.ts",
"type": "replace",
"edit_start_line_idx": 67
} | /*---------------------------------------------------------------------------------------------
* 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 { Disposable, DisposableStore } from 'vs/base/common/lifecycle';
import { Selection } from 'vs/editor/common/core/selection';
import { ICommand } from 'vs/editor/common/editorCommon';
import { EncodedTokenizationResult, IState, TokenizationRegistry } from 'vs/editor/common/languages';
import { ColorId, MetadataConsts } from 'vs/editor/common/encodedTokenAttributes';
import { CommentRule } from 'vs/editor/common/languages/languageConfiguration';
import { ILanguageConfigurationService } from 'vs/editor/common/languages/languageConfigurationRegistry';
import { NullState } from 'vs/editor/common/languages/nullTokenize';
import { ILanguageService } from 'vs/editor/common/languages/language';
import { ILinePreflightData, IPreflightData, ISimpleModel, LineCommentCommand, Type } from 'vs/editor/contrib/comment/browser/lineCommentCommand';
import { testCommand } from 'vs/editor/test/browser/testCommand';
import { IInstantiationService, ServicesAccessor } from 'vs/platform/instantiation/common/instantiation';
import { TestLanguageConfigurationService } from 'vs/editor/test/common/modes/testLanguageConfigurationService';
function createTestCommandHelper(commentsConfig: CommentRule, commandFactory: (accessor: ServicesAccessor, selection: Selection) => ICommand): (lines: string[], selection: Selection, expectedLines: string[], expectedSelection: Selection) => void {
return (lines: string[], selection: Selection, expectedLines: string[], expectedSelection: Selection) => {
const languageId = 'commentMode';
const prepare = (accessor: ServicesAccessor, disposables: DisposableStore) => {
const languageConfigurationService = accessor.get(ILanguageConfigurationService);
const languageService = accessor.get(ILanguageService);
disposables.add(languageService.registerLanguage({ id: languageId }));
disposables.add(languageConfigurationService.register(languageId, {
comments: commentsConfig
}));
};
testCommand(lines, languageId, selection, commandFactory, expectedLines, expectedSelection, false, prepare);
};
}
suite('Editor Contrib - Line Comment Command', () => {
const testLineCommentCommand = createTestCommandHelper(
{ lineComment: '!@#', blockComment: ['<!@#', '#@!>'] },
(accessor, sel) => new LineCommentCommand(accessor.get(ILanguageConfigurationService), sel, 4, Type.Toggle, true, true)
);
const testAddLineCommentCommand = createTestCommandHelper(
{ lineComment: '!@#', blockComment: ['<!@#', '#@!>'] },
(accessor, sel) => new LineCommentCommand(accessor.get(ILanguageConfigurationService), sel, 4, Type.ForceAdd, true, true)
);
test('comment single line', function () {
testLineCommentCommand(
[
'some text',
'\tsome more text'
],
new Selection(1, 1, 1, 1),
[
'!@# some text',
'\tsome more text'
],
new Selection(1, 5, 1, 5)
);
});
test('case insensitive', function () {
const testLineCommentCommand = createTestCommandHelper(
{ lineComment: 'rem' },
(accessor, sel) => new LineCommentCommand(accessor.get(ILanguageConfigurationService), sel, 4, Type.Toggle, true, true)
);
testLineCommentCommand(
[
'REM some text'
],
new Selection(1, 1, 1, 1),
[
'some text'
],
new Selection(1, 1, 1, 1)
);
});
function createSimpleModel(lines: string[]): ISimpleModel {
return {
getLineContent: (lineNumber: number) => {
return lines[lineNumber - 1];
}
};
}
function createBasicLinePreflightData(commentTokens: string[]): ILinePreflightData[] {
return commentTokens.map((commentString) => {
const r: ILinePreflightData = {
ignore: false,
commentStr: commentString,
commentStrOffset: 0,
commentStrLength: commentString.length
};
return r;
});
}
test('_analyzeLines', () => {
let r: IPreflightData;
r = LineCommentCommand._analyzeLines(Type.Toggle, true, createSimpleModel([
'\t\t',
' ',
' c',
'\t\td'
]), createBasicLinePreflightData(['//', 'rem', '!@#', '!@#']), 1, true, false, new TestLanguageConfigurationService());
if (!r.supported) {
throw new Error(`unexpected`);
}
assert.strictEqual(r.shouldRemoveComments, false);
// Does not change `commentStr`
assert.strictEqual(r.lines[0].commentStr, '//');
assert.strictEqual(r.lines[1].commentStr, 'rem');
assert.strictEqual(r.lines[2].commentStr, '!@#');
assert.strictEqual(r.lines[3].commentStr, '!@#');
// Fills in `isWhitespace`
assert.strictEqual(r.lines[0].ignore, true);
assert.strictEqual(r.lines[1].ignore, true);
assert.strictEqual(r.lines[2].ignore, false);
assert.strictEqual(r.lines[3].ignore, false);
// Fills in `commentStrOffset`
assert.strictEqual(r.lines[0].commentStrOffset, 2);
assert.strictEqual(r.lines[1].commentStrOffset, 4);
assert.strictEqual(r.lines[2].commentStrOffset, 4);
assert.strictEqual(r.lines[3].commentStrOffset, 2);
r = LineCommentCommand._analyzeLines(Type.Toggle, true, createSimpleModel([
'\t\t',
' rem ',
' !@# c',
'\t\t!@#d'
]), createBasicLinePreflightData(['//', 'rem', '!@#', '!@#']), 1, true, false, new TestLanguageConfigurationService());
if (!r.supported) {
throw new Error(`unexpected`);
}
assert.strictEqual(r.shouldRemoveComments, true);
// Does not change `commentStr`
assert.strictEqual(r.lines[0].commentStr, '//');
assert.strictEqual(r.lines[1].commentStr, 'rem');
assert.strictEqual(r.lines[2].commentStr, '!@#');
assert.strictEqual(r.lines[3].commentStr, '!@#');
// Fills in `isWhitespace`
assert.strictEqual(r.lines[0].ignore, true);
assert.strictEqual(r.lines[1].ignore, false);
assert.strictEqual(r.lines[2].ignore, false);
assert.strictEqual(r.lines[3].ignore, false);
// Fills in `commentStrOffset`
assert.strictEqual(r.lines[0].commentStrOffset, 2);
assert.strictEqual(r.lines[1].commentStrOffset, 4);
assert.strictEqual(r.lines[2].commentStrOffset, 4);
assert.strictEqual(r.lines[3].commentStrOffset, 2);
// Fills in `commentStrLength`
assert.strictEqual(r.lines[0].commentStrLength, 2);
assert.strictEqual(r.lines[1].commentStrLength, 4);
assert.strictEqual(r.lines[2].commentStrLength, 4);
assert.strictEqual(r.lines[3].commentStrLength, 3);
});
test('_normalizeInsertionPoint', () => {
const runTest = (mixedArr: any[], tabSize: number, expected: number[], testName: string) => {
const model = createSimpleModel(mixedArr.filter((item, idx) => idx % 2 === 0));
const offsets = mixedArr.filter((item, idx) => idx % 2 === 1).map(offset => {
return {
commentStrOffset: offset,
ignore: false
};
});
LineCommentCommand._normalizeInsertionPoint(model, offsets, 1, tabSize);
const actual = offsets.map(item => item.commentStrOffset);
assert.deepStrictEqual(actual, expected, testName);
};
// Bug 16696:[comment] comments not aligned in this case
runTest([
' XX', 2,
' YY', 4
], 4, [0, 0], 'Bug 16696');
runTest([
'\t\t\tXX', 3,
' \tYY', 5,
' ZZ', 8,
'\t\tTT', 2
], 4, [2, 5, 8, 2], 'Test1');
runTest([
'\t\t\t XX', 6,
' \t\t\t\tYY', 8,
' ZZ', 8,
'\t\t TT', 6
], 4, [2, 5, 8, 2], 'Test2');
runTest([
'\t\t', 2,
'\t\t\t', 3,
'\t\t\t\t', 4,
'\t\t\t', 3
], 4, [2, 2, 2, 2], 'Test3');
runTest([
'\t\t', 2,
'\t\t\t', 3,
'\t\t\t\t', 4,
'\t\t\t', 3,
' ', 4
], 2, [2, 2, 2, 2, 4], 'Test4');
runTest([
'\t\t', 2,
'\t\t\t', 3,
'\t\t\t\t', 4,
'\t\t\t', 3,
' ', 4
], 4, [1, 1, 1, 1, 4], 'Test5');
runTest([
' \t', 2,
' \t', 3,
' \t', 4,
' ', 4,
'\t', 1
], 4, [2, 3, 4, 4, 1], 'Test6');
runTest([
' \t\t', 3,
' \t\t', 4,
' \t\t', 5,
' \t', 5,
'\t', 1
], 4, [2, 3, 4, 4, 1], 'Test7');
runTest([
'\t', 1,
' ', 4
], 4, [1, 4], 'Test8:4');
runTest([
'\t', 1,
' ', 3
], 4, [0, 0], 'Test8:3');
runTest([
'\t', 1,
' ', 2
], 4, [0, 0], 'Test8:2');
runTest([
'\t', 1,
' ', 1
], 4, [0, 0], 'Test8:1');
runTest([
'\t', 1,
'', 0
], 4, [0, 0], 'Test8:0');
});
test('detects indentation', function () {
testLineCommentCommand(
[
'\tsome text',
'\tsome more text'
],
new Selection(2, 2, 1, 1),
[
'\t!@# some text',
'\t!@# some more text'
],
new Selection(2, 2, 1, 1)
);
});
test('detects mixed indentation', function () {
testLineCommentCommand(
[
'\tsome text',
' some more text'
],
new Selection(2, 2, 1, 1),
[
'\t!@# some text',
' !@# some more text'
],
new Selection(2, 2, 1, 1)
);
});
test('ignores whitespace lines', function () {
testLineCommentCommand(
[
'\tsome text',
'\t ',
'',
'\tsome more text'
],
new Selection(4, 2, 1, 1),
[
'\t!@# some text',
'\t ',
'',
'\t!@# some more text'
],
new Selection(4, 2, 1, 1)
);
});
test('removes its own', function () {
testLineCommentCommand(
[
'\t!@# some text',
'\t ',
'\t\t!@# some more text'
],
new Selection(3, 2, 1, 1),
[
'\tsome text',
'\t ',
'\t\tsome more text'
],
new Selection(3, 2, 1, 1)
);
});
test('works in only whitespace', function () {
testLineCommentCommand(
[
'\t ',
'\t',
'\t\tsome more text'
],
new Selection(3, 1, 1, 1),
[
'\t!@# ',
'\t!@# ',
'\t\tsome more text'
],
new Selection(3, 1, 1, 1)
);
});
test('bug 9697 - whitespace before comment token', function () {
testLineCommentCommand(
[
'\t !@#first',
'\tsecond line'
],
new Selection(1, 1, 1, 1),
[
'\t first',
'\tsecond line'
],
new Selection(1, 1, 1, 1)
);
});
test('bug 10162 - line comment before caret', function () {
testLineCommentCommand(
[
'first!@#',
'\tsecond line'
],
new Selection(1, 1, 1, 1),
[
'!@# first!@#',
'\tsecond line'
],
new Selection(1, 5, 1, 5)
);
});
test('comment single line - leading whitespace', function () {
testLineCommentCommand(
[
'first!@#',
'\tsecond line'
],
new Selection(2, 3, 2, 1),
[
'first!@#',
'\t!@# second line'
],
new Selection(2, 7, 2, 1)
);
});
test('ignores invisible selection', function () {
testLineCommentCommand(
[
'first',
'\tsecond line',
'third line',
'fourth line',
'fifth'
],
new Selection(2, 1, 1, 1),
[
'!@# first',
'\tsecond line',
'third line',
'fourth line',
'fifth'
],
new Selection(2, 1, 1, 5)
);
});
test('multiple lines', function () {
testLineCommentCommand(
[
'first',
'\tsecond line',
'third line',
'fourth line',
'fifth'
],
new Selection(2, 4, 1, 1),
[
'!@# first',
'!@# \tsecond line',
'third line',
'fourth line',
'fifth'
],
new Selection(2, 8, 1, 5)
);
});
test('multiple modes on multiple lines', function () {
testLineCommentCommand(
[
'first',
'\tsecond line',
'third line',
'fourth line',
'fifth'
],
new Selection(4, 4, 3, 1),
[
'first',
'\tsecond line',
'!@# third line',
'!@# fourth line',
'fifth'
],
new Selection(4, 8, 3, 5)
);
});
test('toggle single line', function () {
testLineCommentCommand(
[
'first',
'\tsecond line',
'third line',
'fourth line',
'fifth'
],
new Selection(1, 1, 1, 1),
[
'!@# first',
'\tsecond line',
'third line',
'fourth line',
'fifth'
],
new Selection(1, 5, 1, 5)
);
testLineCommentCommand(
[
'!@# first',
'\tsecond line',
'third line',
'fourth line',
'fifth'
],
new Selection(1, 4, 1, 4),
[
'first',
'\tsecond line',
'third line',
'fourth line',
'fifth'
],
new Selection(1, 1, 1, 1)
);
});
test('toggle multiple lines', function () {
testLineCommentCommand(
[
'first',
'\tsecond line',
'third line',
'fourth line',
'fifth'
],
new Selection(2, 4, 1, 1),
[
'!@# first',
'!@# \tsecond line',
'third line',
'fourth line',
'fifth'
],
new Selection(2, 8, 1, 5)
);
testLineCommentCommand(
[
'!@# first',
'!@# \tsecond line',
'third line',
'fourth line',
'fifth'
],
new Selection(2, 7, 1, 4),
[
'first',
'\tsecond line',
'third line',
'fourth line',
'fifth'
],
new Selection(2, 3, 1, 1)
);
});
test('issue #5964: Ctrl+/ to create comment when cursor is at the beginning of the line puts the cursor in a strange position', () => {
testLineCommentCommand(
[
'first',
'\tsecond line',
'third line',
'fourth line',
'fifth'
],
new Selection(1, 1, 1, 1),
[
'!@# first',
'\tsecond line',
'third line',
'fourth line',
'fifth'
],
new Selection(1, 5, 1, 5)
);
});
test('issue #35673: Comment hotkeys throws the cursor before the comment', () => {
testLineCommentCommand(
[
'first',
'',
'\tsecond line',
'third line',
'fourth line',
'fifth'
],
new Selection(2, 1, 2, 1),
[
'first',
'!@# ',
'\tsecond line',
'third line',
'fourth line',
'fifth'
],
new Selection(2, 5, 2, 5)
);
testLineCommentCommand(
[
'first',
'\t',
'\tsecond line',
'third line',
'fourth line',
'fifth'
],
new Selection(2, 2, 2, 2),
[
'first',
'\t!@# ',
'\tsecond line',
'third line',
'fourth line',
'fifth'
],
new Selection(2, 6, 2, 6)
);
});
test('issue #2837 "Add Line Comment" fault when blank lines involved', function () {
testAddLineCommentCommand(
[
' if displayName == "":',
' displayName = groupName',
' description = getAttr(attributes, "description")',
' mailAddress = getAttr(attributes, "mail")',
'',
' print "||Group name|%s|" % displayName',
' print "||Description|%s|" % description',
' print "||Email address|[mailto:%s]|" % mailAddress`',
],
new Selection(1, 1, 8, 56),
[
' !@# if displayName == "":',
' !@# displayName = groupName',
' !@# description = getAttr(attributes, "description")',
' !@# mailAddress = getAttr(attributes, "mail")',
'',
' !@# print "||Group name|%s|" % displayName',
' !@# print "||Description|%s|" % description',
' !@# print "||Email address|[mailto:%s]|" % mailAddress`',
],
new Selection(1, 1, 8, 60)
);
});
test('issue #47004: Toggle comments shouldn\'t move cursor', () => {
testAddLineCommentCommand(
[
' A line',
' Another line'
],
new Selection(2, 7, 1, 1),
[
' !@# A line',
' !@# Another line'
],
new Selection(2, 11, 1, 1)
);
});
test('insertSpace false', () => {
const testLineCommentCommand = createTestCommandHelper(
{ lineComment: '!@#' },
(accessor, sel) => new LineCommentCommand(accessor.get(ILanguageConfigurationService), sel, 4, Type.Toggle, false, true)
);
testLineCommentCommand(
[
'some text'
],
new Selection(1, 1, 1, 1),
[
'!@#some text'
],
new Selection(1, 4, 1, 4)
);
});
test('insertSpace false does not remove space', () => {
const testLineCommentCommand = createTestCommandHelper(
{ lineComment: '!@#' },
(accessor, sel) => new LineCommentCommand(accessor.get(ILanguageConfigurationService), sel, 4, Type.Toggle, false, true)
);
testLineCommentCommand(
[
'!@# some text'
],
new Selection(1, 1, 1, 1),
[
' some text'
],
new Selection(1, 1, 1, 1)
);
});
suite('ignoreEmptyLines false', () => {
const testLineCommentCommand = createTestCommandHelper(
{ lineComment: '!@#', blockComment: ['<!@#', '#@!>'] },
(accessor, sel) => new LineCommentCommand(accessor.get(ILanguageConfigurationService), sel, 4, Type.Toggle, true, false)
);
test('does not ignore whitespace lines', () => {
testLineCommentCommand(
[
'\tsome text',
'\t ',
'',
'\tsome more text'
],
new Selection(4, 2, 1, 1),
[
'!@# \tsome text',
'!@# \t ',
'!@# ',
'!@# \tsome more text'
],
new Selection(4, 6, 1, 5)
);
});
test('removes its own', function () {
testLineCommentCommand(
[
'\t!@# some text',
'\t ',
'\t\t!@# some more text'
],
new Selection(3, 2, 1, 1),
[
'\tsome text',
'\t ',
'\t\tsome more text'
],
new Selection(3, 2, 1, 1)
);
});
test('works in only whitespace', function () {
testLineCommentCommand(
[
'\t ',
'\t',
'\t\tsome more text'
],
new Selection(3, 1, 1, 1),
[
'\t!@# ',
'\t!@# ',
'\t\tsome more text'
],
new Selection(3, 1, 1, 1)
);
});
test('comments single line', function () {
testLineCommentCommand(
[
'some text',
'\tsome more text'
],
new Selection(1, 1, 1, 1),
[
'!@# some text',
'\tsome more text'
],
new Selection(1, 5, 1, 5)
);
});
test('detects indentation', function () {
testLineCommentCommand(
[
'\tsome text',
'\tsome more text'
],
new Selection(2, 2, 1, 1),
[
'\t!@# some text',
'\t!@# some more text'
],
new Selection(2, 2, 1, 1)
);
});
});
});
suite('Editor Contrib - Line Comment As Block Comment', () => {
const testLineCommentCommand = createTestCommandHelper(
{ lineComment: '', blockComment: ['(', ')'] },
(accessor, sel) => new LineCommentCommand(accessor.get(ILanguageConfigurationService), sel, 4, Type.Toggle, true, true)
);
test('fall back to block comment command', function () {
testLineCommentCommand(
[
'first',
'\tsecond line',
'third line',
'fourth line',
'fifth'
],
new Selection(1, 1, 1, 1),
[
'( first )',
'\tsecond line',
'third line',
'fourth line',
'fifth'
],
new Selection(1, 3, 1, 3)
);
});
test('fall back to block comment command - toggle', function () {
testLineCommentCommand(
[
'(first)',
'\tsecond line',
'third line',
'fourth line',
'fifth'
],
new Selection(1, 7, 1, 2),
[
'first',
'\tsecond line',
'third line',
'fourth line',
'fifth'
],
new Selection(1, 6, 1, 1)
);
});
test('bug 9513 - expand single line to uncomment auto block', function () {
testLineCommentCommand(
[
'first',
'\tsecond line',
'third line',
'fourth line',
'fifth'
],
new Selection(1, 1, 1, 1),
[
'( first )',
'\tsecond line',
'third line',
'fourth line',
'fifth'
],
new Selection(1, 3, 1, 3)
);
});
test('bug 9691 - always expand selection to line boundaries', function () {
testLineCommentCommand(
[
'first',
'\tsecond line',
'third line',
'fourth line',
'fifth'
],
new Selection(3, 2, 1, 3),
[
'( first',
'\tsecond line',
'third line )',
'fourth line',
'fifth'
],
new Selection(3, 2, 1, 5)
);
testLineCommentCommand(
[
'(first',
'\tsecond line',
'third line)',
'fourth line',
'fifth'
],
new Selection(3, 11, 1, 2),
[
'first',
'\tsecond line',
'third line',
'fourth line',
'fifth'
],
new Selection(3, 11, 1, 1)
);
});
});
suite('Editor Contrib - Line Comment As Block Comment 2', () => {
const testLineCommentCommand = createTestCommandHelper(
{ lineComment: null, blockComment: ['<!@#', '#@!>'] },
(accessor, sel) => new LineCommentCommand(accessor.get(ILanguageConfigurationService), sel, 4, Type.Toggle, true, true)
);
test('no selection => uses indentation', function () {
testLineCommentCommand(
[
'\t\tfirst\t ',
'\t\tsecond line',
'\tthird line',
'fourth line',
'\t\t<!@#fifth#@!>\t\t'
],
new Selection(1, 1, 1, 1),
[
'\t\t<!@# first\t #@!>',
'\t\tsecond line',
'\tthird line',
'fourth line',
'\t\t<!@#fifth#@!>\t\t'
],
new Selection(1, 1, 1, 1)
);
testLineCommentCommand(
[
'\t\t<!@#first\t #@!>',
'\t\tsecond line',
'\tthird line',
'fourth line',
'\t\t<!@#fifth#@!>\t\t'
],
new Selection(1, 1, 1, 1),
[
'\t\tfirst\t ',
'\t\tsecond line',
'\tthird line',
'fourth line',
'\t\t<!@#fifth#@!>\t\t'
],
new Selection(1, 1, 1, 1)
);
});
test('can remove', function () {
testLineCommentCommand(
[
'\t\tfirst\t ',
'\t\tsecond line',
'\tthird line',
'fourth line',
'\t\t<!@#fifth#@!>\t\t'
],
new Selection(5, 1, 5, 1),
[
'\t\tfirst\t ',
'\t\tsecond line',
'\tthird line',
'fourth line',
'\t\tfifth\t\t'
],
new Selection(5, 1, 5, 1)
);
testLineCommentCommand(
[
'\t\tfirst\t ',
'\t\tsecond line',
'\tthird line',
'fourth line',
'\t\t<!@#fifth#@!>\t\t'
],
new Selection(5, 3, 5, 3),
[
'\t\tfirst\t ',
'\t\tsecond line',
'\tthird line',
'fourth line',
'\t\tfifth\t\t'
],
new Selection(5, 3, 5, 3)
);
testLineCommentCommand(
[
'\t\tfirst\t ',
'\t\tsecond line',
'\tthird line',
'fourth line',
'\t\t<!@#fifth#@!>\t\t'
],
new Selection(5, 4, 5, 4),
[
'\t\tfirst\t ',
'\t\tsecond line',
'\tthird line',
'fourth line',
'\t\tfifth\t\t'
],
new Selection(5, 3, 5, 3)
);
testLineCommentCommand(
[
'\t\tfirst\t ',
'\t\tsecond line',
'\tthird line',
'fourth line',
'\t\t<!@#fifth#@!>\t\t'
],
new Selection(5, 16, 5, 3),
[
'\t\tfirst\t ',
'\t\tsecond line',
'\tthird line',
'fourth line',
'\t\tfifth\t\t'
],
new Selection(5, 8, 5, 3)
);
testLineCommentCommand(
[
'\t\tfirst\t ',
'\t\tsecond line',
'\tthird line',
'fourth line',
'\t\t<!@#fifth#@!>\t\t'
],
new Selection(5, 12, 5, 7),
[
'\t\tfirst\t ',
'\t\tsecond line',
'\tthird line',
'fourth line',
'\t\tfifth\t\t'
],
new Selection(5, 8, 5, 3)
);
testLineCommentCommand(
[
'\t\tfirst\t ',
'\t\tsecond line',
'\tthird line',
'fourth line',
'\t\t<!@#fifth#@!>\t\t'
],
new Selection(5, 18, 5, 18),
[
'\t\tfirst\t ',
'\t\tsecond line',
'\tthird line',
'fourth line',
'\t\tfifth\t\t'
],
new Selection(5, 10, 5, 10)
);
});
test('issue #993: Remove comment does not work consistently in HTML', () => {
testLineCommentCommand(
[
' asd qwe',
' asd qwe',
''
],
new Selection(1, 1, 3, 1),
[
' <!@# asd qwe',
' asd qwe #@!>',
''
],
new Selection(1, 1, 3, 1)
);
testLineCommentCommand(
[
' <!@#asd qwe',
' asd qwe#@!>',
''
],
new Selection(1, 1, 3, 1),
[
' asd qwe',
' asd qwe',
''
],
new Selection(1, 1, 3, 1)
);
});
});
suite('Editor Contrib - Line Comment in mixed modes', () => {
const OUTER_LANGUAGE_ID = 'outerMode';
const INNER_LANGUAGE_ID = 'innerMode';
class OuterMode extends Disposable {
private readonly languageId = OUTER_LANGUAGE_ID;
constructor(
commentsConfig: CommentRule,
@ILanguageService languageService: ILanguageService,
@ILanguageConfigurationService languageConfigurationService: ILanguageConfigurationService
) {
super();
this._register(languageService.registerLanguage({ id: this.languageId }));
this._register(languageConfigurationService.register(this.languageId, {
comments: commentsConfig
}));
this._register(TokenizationRegistry.register(this.languageId, {
getInitialState: (): IState => NullState,
tokenize: () => {
throw new Error('not implemented');
},
tokenizeEncoded: (line: string, hasEOL: boolean, state: IState): EncodedTokenizationResult => {
const languageId = (/^ /.test(line) ? INNER_LANGUAGE_ID : OUTER_LANGUAGE_ID);
const encodedLanguageId = languageService.languageIdCodec.encodeLanguageId(languageId);
const tokens = new Uint32Array(1 << 1);
tokens[(0 << 1)] = 0;
tokens[(0 << 1) + 1] = (
(ColorId.DefaultForeground << MetadataConsts.FOREGROUND_OFFSET)
| (encodedLanguageId << MetadataConsts.LANGUAGEID_OFFSET)
);
return new EncodedTokenizationResult(tokens, state);
}
}));
}
}
class InnerMode extends Disposable {
private readonly languageId = INNER_LANGUAGE_ID;
constructor(
commentsConfig: CommentRule,
@ILanguageService languageService: ILanguageService,
@ILanguageConfigurationService languageConfigurationService: ILanguageConfigurationService
) {
super();
this._register(languageService.registerLanguage({ id: this.languageId }));
this._register(languageConfigurationService.register(this.languageId, {
comments: commentsConfig
}));
}
}
function testLineCommentCommand(lines: string[], selection: Selection, expectedLines: string[], expectedSelection: Selection): void {
const setup = (accessor: ServicesAccessor, disposables: DisposableStore) => {
const instantiationService = accessor.get(IInstantiationService);
disposables.add(instantiationService.createInstance(OuterMode, { lineComment: '//', blockComment: ['/*', '*/'] }));
disposables.add(instantiationService.createInstance(InnerMode, { lineComment: null, blockComment: ['{/*', '*/}'] }));
};
testCommand(
lines,
OUTER_LANGUAGE_ID,
selection,
(accessor, sel) => new LineCommentCommand(accessor.get(ILanguageConfigurationService), sel, 4, Type.Toggle, true, true),
expectedLines,
expectedSelection,
true,
setup
);
}
test('issue #24047 (part 1): Commenting code in JSX files', () => {
testLineCommentCommand(
[
'import React from \'react\';',
'const Loader = () => (',
' <div>',
' Loading...',
' </div>',
');',
'export default Loader;'
],
new Selection(1, 1, 7, 22),
[
'// import React from \'react\';',
'// const Loader = () => (',
'// <div>',
'// Loading...',
'// </div>',
'// );',
'// export default Loader;'
],
new Selection(1, 4, 7, 25),
);
});
test('issue #24047 (part 2): Commenting code in JSX files', () => {
testLineCommentCommand(
[
'import React from \'react\';',
'const Loader = () => (',
' <div>',
' Loading...',
' </div>',
');',
'export default Loader;'
],
new Selection(3, 4, 3, 4),
[
'import React from \'react\';',
'const Loader = () => (',
' {/* <div> */}',
' Loading...',
' </div>',
');',
'export default Loader;'
],
new Selection(3, 8, 3, 8),
);
});
test('issue #36173: Commenting code in JSX tag body', () => {
testLineCommentCommand(
[
'<div>',
' {123}',
'</div>',
],
new Selection(2, 4, 2, 4),
[
'<div>',
' {/* {123} */}',
'</div>',
],
new Selection(2, 8, 2, 8),
);
});
});
| src/vs/editor/contrib/comment/test/browser/lineCommentCommand.test.ts | 0 | https://github.com/microsoft/vscode/commit/c2bf6225a12e7f7d8afada6ec39560bb38e5838a | [
0.00017712371482048184,
0.00017341788043268025,
0.00016716349637135863,
0.00017365934036206454,
0.0000018681334950088058
] |
{
"id": 4,
"code_window": [
"\t\t\t\t},\n",
"\t\t\t\tf1: false,\n",
"\t\t\t\tcategory: INTERACTIVE_SESSION_CATEGORY,\n",
"\t\t\t\ticon: Codicon.thumbsdown,\n",
"\t\t\t\tprecondition: CONTEXT_RESPONSE_VOTE.isEqualTo(''), // Should be disabled but visible when vote=down\n",
"\t\t\t\tmenu: {\n",
"\t\t\t\t\tid: MenuId.InteractiveSessionTitle,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\ttoggled: CONTEXT_RESPONSE_VOTE.isEqualTo('down'),\n"
],
"file_path": "src/vs/workbench/contrib/interactiveSession/browser/actions/interactiveSessionTitleActions.ts",
"type": "replace",
"edit_start_line_idx": 67
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Emitter } from 'vs/base/common/event';
import { Disposable, toDisposable } from 'vs/base/common/lifecycle';
import { OperatingSystem } from 'vs/base/common/platform';
import type { Terminal as XTermTerminal, IBuffer, ITerminalAddon } from 'xterm';
/**
* Provides extensions to the xterm object in a modular, testable way.
*/
export class LineDataEventAddon extends Disposable implements ITerminalAddon {
private _xterm?: XTermTerminal;
private _isOsSet = false;
private readonly _onLineData = this._register(new Emitter<string>());
readonly onLineData = this._onLineData.event;
constructor(private readonly _initializationPromise?: Promise<void>) {
super();
}
async activate(xterm: XTermTerminal) {
this._xterm = xterm;
// If there is an initialization promise, wait for it before registering the event
await this._initializationPromise;
// Fire onLineData when a line feed occurs, taking into account wrapped lines
this._register(xterm.onLineFeed(() => {
const buffer = xterm.buffer;
const newLine = buffer.active.getLine(buffer.active.baseY + buffer.active.cursorY);
if (newLine && !newLine.isWrapped) {
this._sendLineData(buffer.active, buffer.active.baseY + buffer.active.cursorY - 1);
}
}));
// Fire onLineData when disposing object to flush last line
this._register(toDisposable(() => {
const buffer = xterm.buffer;
this._sendLineData(buffer.active, buffer.active.baseY + buffer.active.cursorY);
}));
}
setOperatingSystem(os: OperatingSystem) {
if (this._isOsSet || !this._xterm) {
return;
}
this._isOsSet = true;
// Force line data to be sent when the cursor is moved, the main purpose for
// this is because ConPTY will often not do a line feed but instead move the
// cursor, in which case we still want to send the current line's data to tasks.
if (os === OperatingSystem.Windows) {
const xterm = this._xterm;
this._register(xterm.parser.registerCsiHandler({ final: 'H' }, () => {
const buffer = xterm.buffer;
this._sendLineData(buffer.active, buffer.active.baseY + buffer.active.cursorY);
return false;
}));
}
}
private _sendLineData(buffer: IBuffer, lineIndex: number): void {
let line = buffer.getLine(lineIndex);
if (!line) {
return;
}
let lineData = line.translateToString(true);
while (lineIndex > 0 && line.isWrapped) {
line = buffer.getLine(--lineIndex);
if (!line) {
break;
}
lineData = line.translateToString(false) + lineData;
}
this._onLineData.fire(lineData);
}
}
| src/vs/workbench/contrib/terminal/browser/xterm/lineDataEventAddon.ts | 0 | https://github.com/microsoft/vscode/commit/c2bf6225a12e7f7d8afada6ec39560bb38e5838a | [
0.00017573217337485403,
0.00017100200057029724,
0.0001611796033103019,
0.00017223339818883687,
0.00000425406324211508
] |
{
"id": 4,
"code_window": [
"\t\t\t\t},\n",
"\t\t\t\tf1: false,\n",
"\t\t\t\tcategory: INTERACTIVE_SESSION_CATEGORY,\n",
"\t\t\t\ticon: Codicon.thumbsdown,\n",
"\t\t\t\tprecondition: CONTEXT_RESPONSE_VOTE.isEqualTo(''), // Should be disabled but visible when vote=down\n",
"\t\t\t\tmenu: {\n",
"\t\t\t\t\tid: MenuId.InteractiveSessionTitle,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\ttoggled: CONTEXT_RESPONSE_VOTE.isEqualTo('down'),\n"
],
"file_path": "src/vs/workbench/contrib/interactiveSession/browser/actions/interactiveSessionTitleActions.ts",
"type": "replace",
"edit_start_line_idx": 67
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
.monaco-workbench > .notifications-toasts {
position: absolute;
z-index: 1000;
right: 3px;
bottom: 26px;
display: none;
overflow: hidden;
}
.monaco-workbench.nostatusbar > .notifications-toasts {
bottom: 3px;
}
.monaco-workbench > .notifications-toasts.visible {
display: flex;
flex-direction: column;
}
.monaco-workbench > .notifications-toasts .notification-toast-container {
overflow: hidden; /* this ensures that the notification toast does not shine through */
}
.monaco-workbench > .notifications-toasts .notification-toast-container > .notification-toast {
margin: 8px; /* enables separation and drop shadows around toasts */
transform: translate3d(0px, 100%, 0px); /* move the notification 50px to the bottom (to prevent bleed through) */
opacity: 0; /* fade the toast in */
transition: transform 300ms ease-out, opacity 300ms ease-out;
border-radius: 4px;
}
.monaco-workbench.reduce-motion > .notifications-toasts .notification-toast-container > .notification-toast {
transition: transform 0ms ease-out, opacity 0ms ease-out;
}
.monaco-workbench > .notifications-toasts .notification-toast-container > .notification-toast.notification-fade-in {
opacity: 1;
transform: none;
}
.monaco-workbench > .notifications-toasts .notification-toast-container > .notification-toast.notification-fade-in-done {
opacity: 1;
transform: none;
transition: none;
}
/* Icons */
.monaco-workbench > .notifications-toasts .codicon.codicon-error {
color: var(--vscode-notificationsErrorIcon-foreground) !important;
}
.monaco-workbench > .notifications-toasts .codicon.codicon-warning {
color: var(--vscode-notificationsWarningIcon-foreground) !important;
}
.monaco-workbench > .notifications-toasts .codicon.codicon-info {
color: var(--vscode-notificationsInfoIcon-foreground) !important;
}
| src/vs/workbench/browser/parts/notifications/media/notificationsToasts.css | 0 | https://github.com/microsoft/vscode/commit/c2bf6225a12e7f7d8afada6ec39560bb38e5838a | [
0.00017478532390668988,
0.00017242202011402696,
0.0001685852330410853,
0.00017305683286394924,
0.000002019825842580758
] |
{
"id": 5,
"code_window": [
"\t\t\t\tmenu: {\n",
"\t\t\t\t\tid: MenuId.InteractiveSessionTitle,\n",
"\t\t\t\t\twhen: ContextKeyExpr.and(CONTEXT_RESPONSE_HAS_PROVIDER_ID, CONTEXT_RESPONSE_VOTE.notEqualsTo('up')),\n",
"\t\t\t\t\tgroup: 'navigation',\n",
"\t\t\t\t\torder: 2\n",
"\t\t\t\t}\n",
"\t\t\t});\n",
"\t\t}\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/workbench/contrib/interactiveSession/browser/actions/interactiveSessionTitleActions.ts",
"type": "replace",
"edit_start_line_idx": 70
} | /*---------------------------------------------------------------------------------------------
* 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 { renderIcon } from 'vs/base/browser/ui/iconLabel/iconLabels';
import { IListVirtualDelegate } from 'vs/base/browser/ui/list/list';
import { IListAccessibilityProvider } from 'vs/base/browser/ui/list/listWidget';
import { ITreeNode, ITreeRenderer } from 'vs/base/browser/ui/tree/tree';
import { IntervalTimer } from 'vs/base/common/async';
import { Codicon } from 'vs/base/common/codicons';
import { Emitter, Event } from 'vs/base/common/event';
import { FuzzyScore } from 'vs/base/common/filters';
import { IMarkdownString, MarkdownString } from 'vs/base/common/htmlContent';
import { Disposable, DisposableStore, IDisposable } from 'vs/base/common/lifecycle';
import { ResourceMap } from 'vs/base/common/map';
import { FileAccess } from 'vs/base/common/network';
import { ThemeIcon } from 'vs/base/common/themables';
import { EditorExtensionsRegistry } from 'vs/editor/browser/editorExtensions';
import { CodeEditorWidget } from 'vs/editor/browser/widget/codeEditorWidget';
import { EDITOR_FONT_DEFAULTS, IEditorOptions } from 'vs/editor/common/config/editorOptions';
import { Range } from 'vs/editor/common/core/range';
import { ILanguageService } from 'vs/editor/common/languages/language';
import { ITextModel } from 'vs/editor/common/model';
import { IModelService } from 'vs/editor/common/services/model';
import { BracketMatchingController } from 'vs/editor/contrib/bracketMatching/browser/bracketMatching';
import { ContextMenuController } from 'vs/editor/contrib/contextmenu/browser/contextmenu';
import { IMarkdownRenderResult, MarkdownRenderer } from 'vs/editor/contrib/markdownRenderer/browser/markdownRenderer';
import { ViewportSemanticTokensContribution } from 'vs/editor/contrib/semanticTokens/browser/viewportSemanticTokens';
import { SmartSelectController } from 'vs/editor/contrib/smartSelect/browser/smartSelect';
import { WordHighlighterContribution } from 'vs/editor/contrib/wordHighlighter/browser/wordHighlighter';
import { localize } from 'vs/nls';
import { MenuWorkbenchToolBar } from 'vs/platform/actions/browser/toolbar';
import { MenuId } from 'vs/platform/actions/common/actions';
import { ICommandService } from 'vs/platform/commands/common/commands';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection';
import { ILogService } from 'vs/platform/log/common/log';
import { defaultButtonStyles } from 'vs/platform/theme/browser/defaultStyles';
import { MenuPreventer } from 'vs/workbench/contrib/codeEditor/browser/menuPreventer';
import { SelectionClipboardContributionID } from 'vs/workbench/contrib/codeEditor/browser/selectionClipboard';
import { getSimpleEditorOptions } from 'vs/workbench/contrib/codeEditor/browser/simpleEditorOptions';
import { IInteractiveSessionCodeBlockActionContext } from 'vs/workbench/contrib/interactiveSession/browser/actions/interactiveSessionCodeblockActions';
import { InteractiveSessionFollowups } from 'vs/workbench/contrib/interactiveSession/browser/interactiveSessionFollowups';
import { InteractiveSessionEditorOptions } from 'vs/workbench/contrib/interactiveSession/browser/interactiveSessionOptions';
import { CONTEXT_RESPONSE_HAS_PROVIDER_ID, CONTEXT_RESPONSE_VOTE } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionContextKeys';
import { IInteractiveSessionReplyFollowup, IInteractiveSessionService, IInteractiveSlashCommand, InteractiveSessionVoteDirection } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionService';
import { IInteractiveRequestViewModel, IInteractiveResponseViewModel, IInteractiveWelcomeMessageViewModel, isRequestVM, isResponseVM, isWelcomeVM } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionViewModel';
import { getNWords } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionWordCounter';
const $ = dom.$;
export type InteractiveTreeItem = IInteractiveRequestViewModel | IInteractiveResponseViewModel | IInteractiveWelcomeMessageViewModel;
interface IInteractiveListItemTemplate {
rowContainer: HTMLElement;
titleToolbar: MenuWorkbenchToolBar;
avatar: HTMLElement;
username: HTMLElement;
value: HTMLElement;
contextKeyService: IContextKeyService;
templateDisposables: IDisposable;
elementDisposables: DisposableStore;
}
interface IItemHeightChangeParams {
element: InteractiveTreeItem;
height: number;
}
const forceVerboseLayoutTracing = false;
export interface IInteractiveSessionRendererDelegate {
getListLength(): number;
getSlashCommands(): IInteractiveSlashCommand[];
}
export class InteractiveListItemRenderer extends Disposable implements ITreeRenderer<InteractiveTreeItem, FuzzyScore, IInteractiveListItemTemplate> {
static readonly cursorCharacter = '\u258c';
static readonly ID = 'item';
private readonly renderer: MarkdownRenderer;
protected readonly _onDidClickFollowup = this._register(new Emitter<IInteractiveSessionReplyFollowup>());
readonly onDidClickFollowup: Event<IInteractiveSessionReplyFollowup> = this._onDidClickFollowup.event;
protected readonly _onDidChangeItemHeight = this._register(new Emitter<IItemHeightChangeParams>());
readonly onDidChangeItemHeight: Event<IItemHeightChangeParams> = this._onDidChangeItemHeight.event;
private readonly _editorPool: EditorPool;
private _currentLayoutWidth: number = 0;
constructor(
private readonly editorOptions: InteractiveSessionEditorOptions,
private readonly delegate: IInteractiveSessionRendererDelegate,
@IInstantiationService private readonly instantiationService: IInstantiationService,
@IConfigurationService private readonly configService: IConfigurationService,
@ILogService private readonly logService: ILogService,
@ICommandService private readonly commandService: ICommandService,
@IContextKeyService private readonly contextKeyService: IContextKeyService,
@IInteractiveSessionService private readonly interactiveSessionService: IInteractiveSessionService,
) {
super();
this.renderer = this.instantiationService.createInstance(MarkdownRenderer, {});
this._editorPool = this._register(this.instantiationService.createInstance(EditorPool, this.editorOptions));
}
get templateId(): string {
return InteractiveListItemRenderer.ID;
}
private traceLayout(method: string, message: string) {
if (forceVerboseLayoutTracing) {
this.logService.info(`InteractiveListItemRenderer#${method}: ${message}`);
} else {
this.logService.trace(`InteractiveListItemRenderer#${method}: ${message}`);
}
}
private shouldRenderProgressively(element: IInteractiveResponseViewModel): boolean {
return !this.configService.getValue('interactive.experimental.disableProgressiveRendering') && element.progressiveResponseRenderingEnabled;
}
private getProgressiveRenderRate(element: IInteractiveResponseViewModel): number {
const configuredRate = this.configService.getValue('interactive.experimental.progressiveRenderingRate');
if (typeof configuredRate === 'number') {
return configuredRate;
}
if (element.isComplete) {
return 60;
}
if (element.contentUpdateTimings && element.contentUpdateTimings.impliedWordLoadRate) {
// This doesn't account for dead time after the last update. When the previous update is the final one and the model is only waiting for followupQuestions, that's good.
// When there was one quick update and then you are waiting longer for the next one, that's not good since the rate should be decreasing.
// If it's an issue, we can change this to be based on the total time from now to the beginning.
const rateBoost = 1.5;
return element.contentUpdateTimings.impliedWordLoadRate * rateBoost;
}
return 8;
}
layout(width: number): void {
this._currentLayoutWidth = width - 40; // TODO Padding
this._editorPool.inUse.forEach(editor => {
editor.layout(this._currentLayoutWidth);
});
}
renderTemplate(container: HTMLElement): IInteractiveListItemTemplate {
const templateDisposables = new DisposableStore();
const rowContainer = dom.append(container, $('.interactive-item-container'));
const header = dom.append(rowContainer, $('.header'));
const user = dom.append(header, $('.user'));
const avatar = dom.append(user, $('.avatar'));
const username = dom.append(user, $('h3.username'));
const value = dom.append(rowContainer, $('.value'));
const elementDisposables = new DisposableStore();
const contextKeyService = templateDisposables.add(this.contextKeyService.createScoped(rowContainer));
const scopedInstantiationService = this.instantiationService.createChild(new ServiceCollection([IContextKeyService, contextKeyService]));
const titleToolbar = templateDisposables.add(scopedInstantiationService.createInstance(MenuWorkbenchToolBar, header, MenuId.InteractiveSessionTitle, {
menuOptions: {
shouldForwardArgs: true
}
}));
const template: IInteractiveListItemTemplate = { avatar, username, value, rowContainer, elementDisposables, titleToolbar, templateDisposables, contextKeyService };
return template;
}
renderElement(node: ITreeNode<InteractiveTreeItem, FuzzyScore>, index: number, templateData: IInteractiveListItemTemplate): void {
const { element } = node;
const kind = isRequestVM(element) ? 'request' :
isResponseVM(element) ? 'response' :
'welcome';
this.traceLayout('renderElement', `${kind}, index=${index}`);
CONTEXT_RESPONSE_HAS_PROVIDER_ID.bindTo(templateData.contextKeyService).set(isResponseVM(element) && !!element.providerResponseId && !element.isPlaceholder);
if (isResponseVM(element)) {
CONTEXT_RESPONSE_VOTE.bindTo(templateData.contextKeyService).set(element.vote === InteractiveSessionVoteDirection.Up ? 'up' : element.vote === InteractiveSessionVoteDirection.Down ? 'down' : '');
} else {
CONTEXT_RESPONSE_VOTE.bindTo(templateData.contextKeyService).set('');
}
templateData.titleToolbar.context = element;
templateData.rowContainer.classList.toggle('interactive-request', isRequestVM(element));
templateData.rowContainer.classList.toggle('interactive-response', isResponseVM(element));
templateData.rowContainer.classList.toggle('interactive-welcome', isWelcomeVM(element));
templateData.rowContainer.classList.toggle('filtered-response', !!(isResponseVM(element) && element.errorDetails?.responseIsFiltered));
templateData.username.textContent = element.username;
if (element.avatarIconUri) {
const avatarIcon = dom.$<HTMLImageElement>('img.icon');
avatarIcon.src = FileAccess.uriToBrowserUri(element.avatarIconUri).toString(true);
templateData.avatar.replaceChildren(avatarIcon);
} else {
const defaultIcon = isRequestVM(element) ? Codicon.account : Codicon.hubot;
const avatarIcon = dom.$(ThemeIcon.asCSSSelector(defaultIcon));
templateData.avatar.replaceChildren(avatarIcon);
}
// Do a progressive render if
// - This the last response in the list
// - And the response is not complete
// - Or, we previously started a progressive rendering of this element (if the element is complete, we will finish progressive rendering with a very fast rate)
// - And, the feature is not disabled in configuration
if (isResponseVM(element) && index === this.delegate.getListLength() - 1 && (!element.isComplete || element.renderData) && this.shouldRenderProgressively(element)) {
this.traceLayout('renderElement', `start progressive render ${kind}, index=${index}`);
const progressiveRenderingDisposables = templateData.elementDisposables.add(new DisposableStore());
const timer = templateData.elementDisposables.add(new IntervalTimer());
const runProgressiveRender = (initial?: boolean) => {
try {
if (this.doNextProgressiveRender(element, index, templateData, !!initial, progressiveRenderingDisposables)) {
timer.cancel();
}
} catch (err) {
// Kill the timer if anything went wrong, avoid getting stuck in a nasty rendering loop.
timer.cancel();
throw err;
}
};
runProgressiveRender(true);
timer.cancelAndSet(runProgressiveRender, 50);
} else if (isResponseVM(element)) {
this.basicRenderElement(element.response.value, element, index, templateData);
} else if (isRequestVM(element)) {
this.basicRenderElement(element.messageText, element, index, templateData);
} else {
this.renderWelcomeMessage(element, templateData);
}
}
private basicRenderElement(markdownValue: string, element: InteractiveTreeItem, index: number, templateData: IInteractiveListItemTemplate) {
const fillInIncompleteTokens = isResponseVM(element) && (!element.isComplete || element.isCanceled || element.errorDetails?.responseIsFiltered || element.errorDetails?.responseIsIncomplete);
const result = this.renderMarkdown(new MarkdownString(markdownValue), element, templateData.elementDisposables, templateData, fillInIncompleteTokens);
dom.clearNode(templateData.value);
templateData.value.appendChild(result.element);
templateData.elementDisposables.add(result);
if (isResponseVM(element) && element.errorDetails?.message) {
const errorDetails = dom.append(templateData.value, $('.interactive-response-error-details', undefined, renderIcon(Codicon.error)));
errorDetails.appendChild($('span', undefined, element.errorDetails.message));
}
if (isResponseVM(element) && element.commandFollowups?.length) {
const followupsContainer = dom.append(templateData.value, $('.interactive-response-followups'));
templateData.elementDisposables.add(new InteractiveSessionFollowups(
followupsContainer,
element.commandFollowups,
defaultButtonStyles,
followup => {
this.interactiveSessionService.notifyUserAction({
providerId: element.providerId,
action: {
kind: 'command',
command: followup
}
});
return this.commandService.executeCommand(followup.commandId, ...(followup.args ?? []));
}));
}
}
private renderWelcomeMessage(element: IInteractiveWelcomeMessageViewModel, templateData: IInteractiveListItemTemplate) {
dom.clearNode(templateData.value);
const slashCommands = this.delegate.getSlashCommands();
for (const item of element.content) {
if (Array.isArray(item)) {
templateData.elementDisposables.add(new InteractiveSessionFollowups(
templateData.value,
item,
undefined,
followup => this._onDidClickFollowup.fire(followup)));
} else {
const result = this.renderMarkdown(item as IMarkdownString, element, templateData.elementDisposables, templateData);
for (const codeElement of result.element.querySelectorAll('code')) {
if (codeElement.textContent && slashCommands.find(command => codeElement.textContent === `/${command.command}`)) {
codeElement.classList.add('interactive-slash-command');
}
}
templateData.value.appendChild(result.element);
templateData.elementDisposables.add(result);
}
}
}
private doNextProgressiveRender(element: IInteractiveResponseViewModel, index: number, templateData: IInteractiveListItemTemplate, isInRenderElement: boolean, disposables: DisposableStore): boolean {
disposables.clear();
let isFullyRendered = false;
if (element.isCanceled) {
this.traceLayout('runProgressiveRender', `canceled, index=${index}`);
element.renderData = undefined;
this.basicRenderElement(element.response.value, element, index, templateData);
isFullyRendered = true;
} else {
// TODO- this method has the side effect of updating element.renderData
const toRender = this.getProgressiveMarkdownToRender(element);
isFullyRendered = !!element.renderData?.isFullyRendered;
if (isFullyRendered) {
// We've reached the end of the available content, so do a normal render
this.traceLayout('runProgressiveRender', `end progressive render, index=${index}`);
if (element.isComplete) {
this.traceLayout('runProgressiveRender', `and disposing renderData, response is complete, index=${index}`);
element.renderData = undefined;
} else {
this.traceLayout('runProgressiveRender', `Rendered all available words, but model is not complete.`);
}
disposables.clear();
this.basicRenderElement(element.response.value, element, index, templateData);
} else if (toRender) {
// Doing the progressive render
const plusCursor = toRender.match(/```.*$/) ? toRender + `\n${InteractiveListItemRenderer.cursorCharacter}` : toRender + ` ${InteractiveListItemRenderer.cursorCharacter}`;
const result = this.renderMarkdown(new MarkdownString(plusCursor), element, disposables, templateData, true);
dom.clearNode(templateData.value);
templateData.value.appendChild(result.element);
disposables.add(result);
} else {
// Nothing new to render, not done, keep waiting
return false;
}
}
// Some render happened - update the height
const height = templateData.rowContainer.offsetHeight;
element.currentRenderedHeight = height;
if (!isInRenderElement) {
this._onDidChangeItemHeight.fire({ element, height: templateData.rowContainer.offsetHeight });
}
return !!isFullyRendered;
}
private renderMarkdown(markdown: IMarkdownString, element: InteractiveTreeItem, disposables: DisposableStore, templateData: IInteractiveListItemTemplate, fillInIncompleteTokens = false): IMarkdownRenderResult {
const disposablesList: IDisposable[] = [];
let codeBlockIndex = 0;
// TODO if the slash commands stay completely dynamic, this isn't quite right
const slashCommands = this.delegate.getSlashCommands();
const usedSlashCommand = slashCommands.find(s => markdown.value.startsWith(`/${s.command} `));
const toRender = usedSlashCommand ? markdown.value.slice(usedSlashCommand.command.length + 2) : markdown.value;
markdown = new MarkdownString(toRender);
const result = this.renderer.render(markdown, {
fillInIncompleteTokens,
codeBlockRendererSync: (languageId, text) => {
const ref = this.renderCodeBlock({ languageId, text, codeBlockIndex: codeBlockIndex++, element, parentContextKeyService: templateData.contextKeyService }, disposables);
// Attach this after updating text/layout of the editor, so it should only be fired when the size updates later (horizontal scrollbar, wrapping)
// not during a renderElement OR a progressive render (when we will be firing this event anyway at the end of the render)
disposables.add(ref.object.onDidChangeContentHeight(() => {
ref.object.layout(this._currentLayoutWidth);
this._onDidChangeItemHeight.fire({ element, height: templateData.rowContainer.offsetHeight });
}));
disposablesList.push(ref);
return ref.object.element;
}
});
if (usedSlashCommand) {
const slashCommandElement = $('span.interactive-slash-command', { title: usedSlashCommand.detail }, `/${usedSlashCommand.command} `);
if (result.element.firstChild?.nodeName.toLowerCase() === 'p') {
result.element.firstChild.insertBefore(slashCommandElement, result.element.firstChild.firstChild);
} else {
result.element.insertBefore($('p', undefined, slashCommandElement), result.element.firstChild);
}
}
disposablesList.reverse().forEach(d => disposables.add(d));
return result;
}
private renderCodeBlock(data: IInteractiveResultCodeBlockData, disposables: DisposableStore): IDisposableReference<IInteractiveResultCodeBlockPart> {
const ref = this._editorPool.get();
const editorInfo = ref.object;
editorInfo.render(data, this._currentLayoutWidth);
return ref;
}
private getProgressiveMarkdownToRender(element: IInteractiveResponseViewModel): string | undefined {
const renderData = element.renderData ?? { renderedWordCount: 0, lastRenderTime: 0 };
const rate = this.getProgressiveRenderRate(element);
const numWordsToRender = renderData.lastRenderTime === 0 ?
1 :
renderData.renderedWordCount +
// Additional words to render beyond what's already rendered
Math.floor((Date.now() - renderData.lastRenderTime) / 1000 * rate);
if (numWordsToRender === renderData.renderedWordCount) {
return undefined;
}
const result = getNWords(element.response.value, numWordsToRender);
element.renderData = {
renderedWordCount: result.actualWordCount,
lastRenderTime: Date.now(),
isFullyRendered: result.isFullString
};
return result.value;
}
disposeElement(node: ITreeNode<InteractiveTreeItem, FuzzyScore>, index: number, templateData: IInteractiveListItemTemplate): void {
templateData.elementDisposables.clear();
}
disposeTemplate(templateData: IInteractiveListItemTemplate): void {
templateData.templateDisposables.dispose();
}
}
export class InteractiveSessionListDelegate implements IListVirtualDelegate<InteractiveTreeItem> {
constructor(
@ILogService private readonly logService: ILogService
) { }
private _traceLayout(method: string, message: string) {
if (forceVerboseLayoutTracing) {
this.logService.info(`InteractiveSessionListDelegate#${method}: ${message}`);
} else {
this.logService.trace(`InteractiveSessionListDelegate#${method}: ${message}`);
}
}
getHeight(element: InteractiveTreeItem): number {
const kind = isRequestVM(element) ? 'request' : 'response';
const height = ('currentRenderedHeight' in element ? element.currentRenderedHeight : undefined) ?? 200;
this._traceLayout('getHeight', `${kind}, height=${height}`);
return height;
}
getTemplateId(element: InteractiveTreeItem): string {
return InteractiveListItemRenderer.ID;
}
hasDynamicHeight(element: InteractiveTreeItem): boolean {
return true;
}
}
export class InteractiveSessionAccessibilityProvider implements IListAccessibilityProvider<InteractiveTreeItem> {
getWidgetAriaLabel(): string {
return localize('interactiveSession', "Interactive Session");
}
getAriaLabel(element: InteractiveTreeItem): string {
if (isRequestVM(element)) {
return localize('interactiveRequest', "Request: {0}", element.messageText);
}
if (isResponseVM(element)) {
return localize('interactiveResponse', "Response: {0}", element.response.value);
}
return '';
}
}
interface IInteractiveResultCodeBlockData {
text: string;
languageId: string;
codeBlockIndex: number;
element: InteractiveTreeItem;
parentContextKeyService: IContextKeyService;
}
interface IInteractiveResultCodeBlockPart {
readonly onDidChangeContentHeight: Event<number>;
readonly element: HTMLElement;
readonly textModel: ITextModel;
layout(width: number): void;
render(data: IInteractiveResultCodeBlockData, width: number): void;
dispose(): void;
}
export interface IInteractiveResultCodeBlockInfo {
providerId: string;
responseId: string;
codeBlockIndex: number;
}
export const codeBlockInfosByModelUri = new ResourceMap<IInteractiveResultCodeBlockInfo>();
class CodeBlockPart extends Disposable implements IInteractiveResultCodeBlockPart {
private readonly _onDidChangeContentHeight = this._register(new Emitter<number>());
public readonly onDidChangeContentHeight = this._onDidChangeContentHeight.event;
private readonly editor: CodeEditorWidget;
private readonly toolbar: MenuWorkbenchToolBar;
private readonly contextKeyService: IContextKeyService;
public readonly textModel: ITextModel;
public readonly element: HTMLElement;
constructor(
private readonly options: InteractiveSessionEditorOptions,
@IInstantiationService instantiationService: IInstantiationService,
@IContextKeyService contextKeyService: IContextKeyService,
@ILanguageService private readonly languageService: ILanguageService,
@IModelService private readonly modelService: IModelService,
) {
super();
this.element = $('.interactive-result-editor-wrapper');
this.contextKeyService = this._register(contextKeyService.createScoped(this.element));
const scopedInstantiationService = instantiationService.createChild(new ServiceCollection([IContextKeyService, this.contextKeyService]));
this.toolbar = this._register(scopedInstantiationService.createInstance(MenuWorkbenchToolBar, this.element, MenuId.InteractiveSessionCodeBlock, {
menuOptions: {
shouldForwardArgs: true
}
}));
const editorElement = dom.append(this.element, $('.interactive-result-editor'));
this.editor = this._register(scopedInstantiationService.createInstance(CodeEditorWidget, editorElement, {
...getSimpleEditorOptions(),
readOnly: true,
lineNumbers: 'off',
selectOnLineNumbers: true,
scrollBeyondLastLine: false,
lineDecorationsWidth: 8,
dragAndDrop: false,
padding: { top: 2, bottom: 2 },
mouseWheelZoom: false,
scrollbar: {
alwaysConsumeMouseWheel: false
},
...this.getEditorOptionsFromConfig()
}, {
isSimpleWidget: true,
contributions: EditorExtensionsRegistry.getSomeEditorContributions([
MenuPreventer.ID,
SelectionClipboardContributionID,
ContextMenuController.ID,
WordHighlighterContribution.ID,
ViewportSemanticTokensContribution.ID,
BracketMatchingController.ID,
SmartSelectController.ID,
])
}));
this._register(this.options.onDidChange(() => {
this.editor.updateOptions(this.getEditorOptionsFromConfig());
}));
this._register(this.editor.onDidContentSizeChange(e => {
if (e.contentHeightChanged) {
this._onDidChangeContentHeight.fire(e.contentHeight);
}
}));
this._register(this.editor.onDidBlurEditorWidget(() => {
WordHighlighterContribution.get(this.editor)?.stopHighlighting();
}));
this._register(this.editor.onDidFocusEditorWidget(() => {
WordHighlighterContribution.get(this.editor)?.restoreViewState(true);
}));
const vscodeLanguageId = this.languageService.getLanguageIdByLanguageName('javascript');
this.textModel = this._register(this.modelService.createModel('', this.languageService.createById(vscodeLanguageId), undefined));
this.editor.setModel(this.textModel);
}
private getEditorOptionsFromConfig(): IEditorOptions {
return {
wordWrap: this.options.configuration.resultEditor.wordWrap,
fontLigatures: this.options.configuration.resultEditor.fontLigatures,
bracketPairColorization: this.options.configuration.resultEditor.bracketPairColorization,
fontFamily: this.options.configuration.resultEditor.fontFamily === 'default' ?
EDITOR_FONT_DEFAULTS.fontFamily :
this.options.configuration.resultEditor.fontFamily,
fontSize: this.options.configuration.resultEditor.fontSize,
fontWeight: this.options.configuration.resultEditor.fontWeight,
lineHeight: this.options.configuration.resultEditor.lineHeight,
};
}
layout(width: number): void {
const realContentHeight = this.editor.getContentHeight();
const editorBorder = 2;
this.editor.layout({ width: width - editorBorder, height: realContentHeight });
}
render(data: IInteractiveResultCodeBlockData, width: number): void {
this.contextKeyService.updateParent(data.parentContextKeyService);
if (this.options.configuration.resultEditor.wordWrap === 'on') {
// Intialize the editor with the new proper width so that getContentHeight
// will be computed correctly in the next call to layout()
this.layout(width);
}
this.setText(data.text);
this.setLanguage(data.languageId);
this.layout(width);
if (isResponseVM(data.element) && data.element.providerResponseId) {
// For telemetry reporting
codeBlockInfosByModelUri.set(this.textModel.uri, {
providerId: data.element.providerId,
responseId: data.element.providerResponseId,
codeBlockIndex: data.codeBlockIndex
});
} else {
codeBlockInfosByModelUri.delete(this.textModel.uri);
}
this.toolbar.context = <IInteractiveSessionCodeBlockActionContext>{
code: data.text,
codeBlockIndex: data.codeBlockIndex,
element: data.element
};
}
private setText(newText: string): void {
let currentText = this.textModel.getLinesContent().join('\n');
if (newText === currentText) {
return;
}
let removedChars = 0;
if (currentText.endsWith(` ${InteractiveListItemRenderer.cursorCharacter}`)) {
removedChars = 2;
} else if (currentText.endsWith(InteractiveListItemRenderer.cursorCharacter)) {
removedChars = 1;
}
if (removedChars > 0) {
currentText = currentText.slice(0, currentText.length - removedChars);
}
if (newText.startsWith(currentText)) {
const text = newText.slice(currentText.length);
const lastLine = this.textModel.getLineCount();
const lastCol = this.textModel.getLineMaxColumn(lastLine);
const insertAtCol = lastCol - removedChars;
this.textModel.applyEdits([{ range: new Range(lastLine, insertAtCol, lastLine, lastCol), text }]);
} else {
// console.log(`Failed to optimize setText`);
this.textModel.setValue(newText);
}
}
private setLanguage(languageId: string): void {
const vscodeLanguageId = this.languageService.getLanguageIdByLanguageName(languageId);
if (vscodeLanguageId) {
this.textModel.setLanguage(vscodeLanguageId);
}
}
}
interface IDisposableReference<T> extends IDisposable {
object: T;
}
class EditorPool extends Disposable {
private _pool: ResourcePool<IInteractiveResultCodeBlockPart>;
public get inUse(): ReadonlySet<IInteractiveResultCodeBlockPart> {
return this._pool.inUse;
}
constructor(
private readonly options: InteractiveSessionEditorOptions,
@IInstantiationService private readonly instantiationService: IInstantiationService,
) {
super();
this._pool = this._register(new ResourcePool(() => this.editorFactory()));
// TODO listen to changes on options
}
private editorFactory(): IInteractiveResultCodeBlockPart {
return this.instantiationService.createInstance(CodeBlockPart, this.options);
}
get(): IDisposableReference<IInteractiveResultCodeBlockPart> {
const object = this._pool.get();
return {
object,
dispose: () => this._pool.release(object)
};
}
}
// TODO does something in lifecycle.ts cover this?
class ResourcePool<T extends IDisposable> extends Disposable {
private readonly pool: T[] = [];
private _inUse = new Set<T>;
public get inUse(): ReadonlySet<T> {
return this._inUse;
}
constructor(
private readonly _itemFactory: () => T,
) {
super();
}
get(): T {
if (this.pool.length > 0) {
const item = this.pool.pop()!;
this._inUse.add(item);
return item;
}
const item = this._register(this._itemFactory());
this._inUse.add(item);
return item;
}
release(item: T): void {
this._inUse.delete(item);
this.pool.push(item);
}
}
| src/vs/workbench/contrib/interactiveSession/browser/interactiveSessionListRenderer.ts | 1 | https://github.com/microsoft/vscode/commit/c2bf6225a12e7f7d8afada6ec39560bb38e5838a | [
0.006869778037071228,
0.0004217590903863311,
0.0001627997262403369,
0.0001703587913652882,
0.000999431242235005
] |
{
"id": 5,
"code_window": [
"\t\t\t\tmenu: {\n",
"\t\t\t\t\tid: MenuId.InteractiveSessionTitle,\n",
"\t\t\t\t\twhen: ContextKeyExpr.and(CONTEXT_RESPONSE_HAS_PROVIDER_ID, CONTEXT_RESPONSE_VOTE.notEqualsTo('up')),\n",
"\t\t\t\t\tgroup: 'navigation',\n",
"\t\t\t\t\torder: 2\n",
"\t\t\t\t}\n",
"\t\t\t});\n",
"\t\t}\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/workbench/contrib/interactiveSession/browser/actions/interactiveSessionTitleActions.ts",
"type": "replace",
"edit_start_line_idx": 70
} | /*---------------------------------------------------------------------------------------------
* 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 { Disposable, IDisposable } from 'vs/base/common/lifecycle';
import { IQuickDiffService, QuickDiff, QuickDiffProvider } from 'vs/workbench/contrib/scm/common/quickDiff';
import { isEqualOrParent } from 'vs/base/common/resources';
import { score } from 'vs/editor/common/languageSelector';
import { Emitter } from 'vs/base/common/event';
import { withNullAsUndefined } from 'vs/base/common/types';
import { IUriIdentityService } from 'vs/platform/uriIdentity/common/uriIdentity';
function createProviderComparer(uri: URI): (a: QuickDiffProvider, b: QuickDiffProvider) => number {
return (a, b) => {
if (a.rootUri && !b.rootUri) {
return -1;
} else if (!a.rootUri && b.rootUri) {
return 1;
} else if (!a.rootUri && !b.rootUri) {
return 0;
}
const aIsParent = isEqualOrParent(uri, a.rootUri!);
const bIsParent = isEqualOrParent(uri, b.rootUri!);
if (aIsParent && bIsParent) {
return a.rootUri!.fsPath.length - b.rootUri!.fsPath.length;
} else if (aIsParent) {
return -1;
} else if (bIsParent) {
return 1;
} else {
return 0;
}
};
}
export class QuickDiffService extends Disposable implements IQuickDiffService {
declare readonly _serviceBrand: undefined;
private quickDiffProviders: Set<QuickDiffProvider> = new Set();
private readonly _onDidChangeQuickDiffProviders = this._register(new Emitter<void>());
readonly onDidChangeQuickDiffProviders = this._onDidChangeQuickDiffProviders.event;
constructor(@IUriIdentityService private readonly uriIdentityService: IUriIdentityService) {
super();
}
addQuickDiffProvider(quickDiff: QuickDiffProvider): IDisposable {
this.quickDiffProviders.add(quickDiff);
this._onDidChangeQuickDiffProviders.fire();
return {
dispose: () => {
this.quickDiffProviders.delete(quickDiff);
this._onDidChangeQuickDiffProviders.fire();
}
};
}
private isQuickDiff(diff: { originalResource?: URI; label?: string; isSCM?: boolean }): diff is QuickDiff {
return !!diff.originalResource && (typeof diff.label === 'string') && (typeof diff.isSCM === 'boolean');
}
async getQuickDiffs(uri: URI, language: string = '', isSynchronized: boolean = false): Promise<QuickDiff[]> {
const providers = Array.from(this.quickDiffProviders)
.filter(provider => !provider.rootUri || this.uriIdentityService.extUri.isEqualOrParent(uri, provider.rootUri))
.sort(createProviderComparer(uri));
const diffs = await Promise.all(providers.map(async provider => {
const scoreValue = provider.selector ? score(provider.selector, uri, language, isSynchronized, undefined, undefined) : 10;
const diff: Partial<QuickDiff> = {
originalResource: scoreValue > 0 ? withNullAsUndefined(await provider.getOriginalResource(uri)) : undefined,
label: provider.label,
isSCM: provider.isSCM
};
return diff;
}));
return diffs.filter<QuickDiff>(this.isQuickDiff);
}
}
| src/vs/workbench/contrib/scm/common/quickDiffService.ts | 0 | https://github.com/microsoft/vscode/commit/c2bf6225a12e7f7d8afada6ec39560bb38e5838a | [
0.00017593821394257247,
0.00017211554222740233,
0.00016670410695951432,
0.00017306987137999386,
0.000003065186774620088
] |
{
"id": 5,
"code_window": [
"\t\t\t\tmenu: {\n",
"\t\t\t\t\tid: MenuId.InteractiveSessionTitle,\n",
"\t\t\t\t\twhen: ContextKeyExpr.and(CONTEXT_RESPONSE_HAS_PROVIDER_ID, CONTEXT_RESPONSE_VOTE.notEqualsTo('up')),\n",
"\t\t\t\t\tgroup: 'navigation',\n",
"\t\t\t\t\torder: 2\n",
"\t\t\t\t}\n",
"\t\t\t});\n",
"\t\t}\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/workbench/contrib/interactiveSession/browser/actions/interactiveSessionTitleActions.ts",
"type": "replace",
"edit_start_line_idx": 70
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { handleVetos } from 'vs/platform/lifecycle/common/lifecycle';
import { ShutdownReason, ILifecycleService, IWillShutdownEventJoiner } from 'vs/workbench/services/lifecycle/common/lifecycle';
import { IStorageService } from 'vs/platform/storage/common/storage';
import { ipcRenderer } from 'vs/base/parts/sandbox/electron-sandbox/globals';
import { ILogService } from 'vs/platform/log/common/log';
import { AbstractLifecycleService } from 'vs/workbench/services/lifecycle/common/lifecycleService';
import { InstantiationType, registerSingleton } from 'vs/platform/instantiation/common/extensions';
import { INativeHostService } from 'vs/platform/native/common/native';
import { Promises, disposableTimeout, raceCancellation } from 'vs/base/common/async';
import { toErrorMessage } from 'vs/base/common/errorMessage';
import { CancellationTokenSource } from 'vs/base/common/cancellation';
export class NativeLifecycleService extends AbstractLifecycleService {
private static readonly BEFORE_SHUTDOWN_WARNING_DELAY = 5000;
private static readonly WILL_SHUTDOWN_WARNING_DELAY = 800;
constructor(
@INativeHostService private readonly nativeHostService: INativeHostService,
@IStorageService storageService: IStorageService,
@ILogService logService: ILogService
) {
super(logService, storageService);
this.registerListeners();
}
private registerListeners(): void {
const windowId = this.nativeHostService.windowId;
// Main side indicates that window is about to unload, check for vetos
ipcRenderer.on('vscode:onBeforeUnload', async (event: unknown, reply: { okChannel: string; cancelChannel: string; reason: ShutdownReason }) => {
this.logService.trace(`[lifecycle] onBeforeUnload (reason: ${reply.reason})`);
// trigger onBeforeShutdown events and veto collecting
const veto = await this.handleBeforeShutdown(reply.reason);
// veto: cancel unload
if (veto) {
this.logService.trace('[lifecycle] onBeforeUnload prevented via veto');
// Indicate as event
this._onShutdownVeto.fire();
ipcRenderer.send(reply.cancelChannel, windowId);
}
// no veto: allow unload
else {
this.logService.trace('[lifecycle] onBeforeUnload continues without veto');
this.shutdownReason = reply.reason;
ipcRenderer.send(reply.okChannel, windowId);
}
});
// Main side indicates that we will indeed shutdown
ipcRenderer.on('vscode:onWillUnload', async (event: unknown, reply: { replyChannel: string; reason: ShutdownReason }) => {
this.logService.trace(`[lifecycle] onWillUnload (reason: ${reply.reason})`);
// trigger onWillShutdown events and joining
await this.handleWillShutdown(reply.reason);
// trigger onDidShutdown event now that we know we will quit
this._onDidShutdown.fire();
// acknowledge to main side
ipcRenderer.send(reply.replyChannel, windowId);
});
}
protected async handleBeforeShutdown(reason: ShutdownReason): Promise<boolean> {
const logService = this.logService;
const vetos: (boolean | Promise<boolean>)[] = [];
const pendingVetos = new Set<string>();
let finalVeto: (() => boolean | Promise<boolean>) | undefined = undefined;
let finalVetoId: string | undefined = undefined;
// before-shutdown event with veto support
this._onBeforeShutdown.fire({
reason,
veto(value, id) {
vetos.push(value);
// Log any veto instantly
if (value === true) {
logService.info(`[lifecycle]: Shutdown was prevented (id: ${id})`);
}
// Track promise completion
else if (value instanceof Promise) {
pendingVetos.add(id);
value.then(veto => {
if (veto === true) {
logService.info(`[lifecycle]: Shutdown was prevented (id: ${id})`);
}
}).finally(() => pendingVetos.delete(id));
}
},
finalVeto(value, id) {
if (!finalVeto) {
finalVeto = value;
finalVetoId = id;
} else {
throw new Error(`[lifecycle]: Final veto is already defined (id: ${id})`);
}
}
});
const longRunningBeforeShutdownWarning = disposableTimeout(() => {
logService.warn(`[lifecycle] onBeforeShutdown is taking a long time, pending operations: ${Array.from(pendingVetos).join(', ')}`);
}, NativeLifecycleService.BEFORE_SHUTDOWN_WARNING_DELAY);
try {
// First: run list of vetos in parallel
let veto = await handleVetos(vetos, error => this.handleBeforeShutdownError(error, reason));
if (veto) {
return veto;
}
// Second: run the final veto if defined
if (finalVeto) {
try {
pendingVetos.add(finalVetoId as unknown as string);
veto = await (finalVeto as () => Promise<boolean>)();
if (veto) {
logService.info(`[lifecycle]: Shutdown was prevented by final veto (id: ${finalVetoId})`);
}
} catch (error) {
veto = true; // treat error as veto
this.handleBeforeShutdownError(error, reason);
}
}
return veto;
} finally {
longRunningBeforeShutdownWarning.dispose();
}
}
private handleBeforeShutdownError(error: Error, reason: ShutdownReason): void {
this.logService.error(`[lifecycle]: Error during before-shutdown phase (error: ${toErrorMessage(error)})`);
this._onBeforeShutdownError.fire({ reason, error });
}
protected async handleWillShutdown(reason: ShutdownReason): Promise<void> {
const joiners: Promise<void>[] = [];
const pendingJoiners = new Set<IWillShutdownEventJoiner>();
const cts = new CancellationTokenSource();
this._onWillShutdown.fire({
reason,
token: cts.token,
joiners: () => Array.from(pendingJoiners.values()),
join(promise, joiner) {
joiners.push(promise);
// Track promise completion
pendingJoiners.add(joiner);
promise.finally(() => pendingJoiners.delete(joiner));
},
force: () => {
cts.dispose(true);
}
});
const longRunningWillShutdownWarning = disposableTimeout(() => {
this.logService.warn(`[lifecycle] onWillShutdown is taking a long time, pending operations: ${Array.from(pendingJoiners).map(joiner => joiner.id).join(', ')}`);
}, NativeLifecycleService.WILL_SHUTDOWN_WARNING_DELAY);
try {
await raceCancellation(Promises.settled(joiners), cts.token);
} catch (error) {
this.logService.error(`[lifecycle]: Error during will-shutdown phase (error: ${toErrorMessage(error)})`); // this error will not prevent the shutdown
} finally {
longRunningWillShutdownWarning.dispose();
}
}
shutdown(): Promise<void> {
return this.nativeHostService.closeWindow();
}
}
registerSingleton(ILifecycleService, NativeLifecycleService, InstantiationType.Eager);
| src/vs/workbench/services/lifecycle/electron-sandbox/lifecycleService.ts | 0 | https://github.com/microsoft/vscode/commit/c2bf6225a12e7f7d8afada6ec39560bb38e5838a | [
0.00017458012735005468,
0.0001698377018328756,
0.00016230328765232116,
0.00016991836309898645,
0.0000029303078008524608
] |
{
"id": 5,
"code_window": [
"\t\t\t\tmenu: {\n",
"\t\t\t\t\tid: MenuId.InteractiveSessionTitle,\n",
"\t\t\t\t\twhen: ContextKeyExpr.and(CONTEXT_RESPONSE_HAS_PROVIDER_ID, CONTEXT_RESPONSE_VOTE.notEqualsTo('up')),\n",
"\t\t\t\t\tgroup: 'navigation',\n",
"\t\t\t\t\torder: 2\n",
"\t\t\t\t}\n",
"\t\t\t});\n",
"\t\t}\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/workbench/contrib/interactiveSession/browser/actions/interactiveSessionTitleActions.ts",
"type": "replace",
"edit_start_line_idx": 70
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as childProcess from 'child_process';
import * as fs from 'fs';
import * as path from 'vs/base/common/path';
import { Readable } from 'stream';
import { StringDecoder } from 'string_decoder';
import * as arrays from 'vs/base/common/arrays';
import { toErrorMessage } from 'vs/base/common/errorMessage';
import * as glob from 'vs/base/common/glob';
import * as normalization from 'vs/base/common/normalization';
import { isEqualOrParent } from 'vs/base/common/extpath';
import * as platform from 'vs/base/common/platform';
import { StopWatch } from 'vs/base/common/stopwatch';
import * as strings from 'vs/base/common/strings';
import * as types from 'vs/base/common/types';
import { URI } from 'vs/base/common/uri';
import { Promises } from 'vs/base/node/pfs';
import { IFileQuery, IFolderQuery, IProgressMessage, ISearchEngineStats, IRawFileMatch, ISearchEngine, ISearchEngineSuccess, isFilePatternMatch, hasSiblingFn } from 'vs/workbench/services/search/common/search';
import { spawnRipgrepCmd } from './ripgrepFileSearch';
import { prepareQuery } from 'vs/base/common/fuzzyScorer';
interface IDirectoryEntry extends IRawFileMatch {
base: string;
basename: string;
}
interface IDirectoryTree {
rootEntries: IDirectoryEntry[];
pathToEntries: { [relativePath: string]: IDirectoryEntry[] };
}
const killCmds = new Set<() => void>();
process.on('exit', () => {
killCmds.forEach(cmd => cmd());
});
export class FileWalker {
private config: IFileQuery;
private filePattern: string;
private normalizedFilePatternLowercase: string | null = null;
private includePattern: glob.ParsedExpression | undefined;
private maxResults: number | null;
private exists: boolean;
private maxFilesize: number | null = null;
private isLimitHit: boolean;
private resultCount: number;
private isCanceled = false;
private fileWalkSW: StopWatch | null = null;
private directoriesWalked: number;
private filesWalked: number;
private errors: string[];
private cmdSW: StopWatch | null = null;
private cmdResultCount: number = 0;
private folderExcludePatterns: Map<string, AbsoluteAndRelativeParsedExpression>;
private globalExcludePattern: glob.ParsedExpression | undefined;
private walkedPaths: { [path: string]: boolean };
constructor(config: IFileQuery) {
this.config = config;
this.filePattern = config.filePattern || '';
this.includePattern = config.includePattern && glob.parse(config.includePattern);
this.maxResults = config.maxResults || null;
this.exists = !!config.exists;
this.walkedPaths = Object.create(null);
this.resultCount = 0;
this.isLimitHit = false;
this.directoriesWalked = 0;
this.filesWalked = 0;
this.errors = [];
if (this.filePattern) {
this.normalizedFilePatternLowercase = prepareQuery(this.filePattern).normalizedLowercase;
}
this.globalExcludePattern = config.excludePattern && glob.parse(config.excludePattern);
this.folderExcludePatterns = new Map<string, AbsoluteAndRelativeParsedExpression>();
config.folderQueries.forEach(folderQuery => {
const folderExcludeExpression: glob.IExpression = Object.assign({}, folderQuery.excludePattern || {}, this.config.excludePattern || {});
// Add excludes for other root folders
const fqPath = folderQuery.folder.fsPath;
config.folderQueries
.map(rootFolderQuery => rootFolderQuery.folder.fsPath)
.filter(rootFolder => rootFolder !== fqPath)
.forEach(otherRootFolder => {
// Exclude nested root folders
if (isEqualOrParent(otherRootFolder, fqPath)) {
folderExcludeExpression[path.relative(fqPath, otherRootFolder)] = true;
}
});
this.folderExcludePatterns.set(fqPath, new AbsoluteAndRelativeParsedExpression(folderExcludeExpression, fqPath));
});
}
cancel(): void {
this.isCanceled = true;
killCmds.forEach(cmd => cmd());
}
walk(folderQueries: IFolderQuery[], extraFiles: URI[], onResult: (result: IRawFileMatch) => void, onMessage: (message: IProgressMessage) => void, done: (error: Error | null, isLimitHit: boolean) => void): void {
this.fileWalkSW = StopWatch.create(false);
// Support that the file pattern is a full path to a file that exists
if (this.isCanceled) {
return done(null, this.isLimitHit);
}
// For each extra file
extraFiles.forEach(extraFilePath => {
const basename = path.basename(extraFilePath.fsPath);
if (this.globalExcludePattern && this.globalExcludePattern(extraFilePath.fsPath, basename)) {
return; // excluded
}
// File: Check for match on file pattern and include pattern
this.matchFile(onResult, { relativePath: extraFilePath.fsPath /* no workspace relative path */, searchPath: undefined });
});
this.cmdSW = StopWatch.create(false);
// For each root folder
this.parallel<IFolderQuery, void>(folderQueries, (folderQuery: IFolderQuery, rootFolderDone: (err: Error | null, result: void) => void) => {
this.call(this.cmdTraversal, this, folderQuery, onResult, onMessage, (err?: Error) => {
if (err) {
const errorMessage = toErrorMessage(err);
console.error(errorMessage);
this.errors.push(errorMessage);
rootFolderDone(err, undefined);
} else {
rootFolderDone(null, undefined);
}
});
}, (errors, _result) => {
this.fileWalkSW!.stop();
const err = errors ? arrays.coalesce(errors)[0] : null;
done(err, this.isLimitHit);
});
}
private parallel<T, E>(list: T[], fn: (item: T, callback: (err: Error | null, result: E | null) => void) => void, callback: (err: Array<Error | null> | null, result: E[]) => void): void {
const results = new Array(list.length);
const errors = new Array<Error | null>(list.length);
let didErrorOccur = false;
let doneCount = 0;
if (list.length === 0) {
return callback(null, []);
}
list.forEach((item, index) => {
fn(item, (error, result) => {
if (error) {
didErrorOccur = true;
results[index] = null;
errors[index] = error;
} else {
results[index] = result;
errors[index] = null;
}
if (++doneCount === list.length) {
return callback(didErrorOccur ? errors : null, results);
}
});
});
}
private call<F extends Function>(fun: F, that: any, ...args: any[]): void {
try {
fun.apply(that, args);
} catch (e) {
args[args.length - 1](e);
}
}
private cmdTraversal(folderQuery: IFolderQuery, onResult: (result: IRawFileMatch) => void, onMessage: (message: IProgressMessage) => void, cb: (err?: Error) => void): void {
const rootFolder = folderQuery.folder.fsPath;
const isMac = platform.isMacintosh;
const killCmd = () => cmd && cmd.kill();
killCmds.add(killCmd);
let done = (err?: Error) => {
killCmds.delete(killCmd);
done = () => { };
cb(err);
};
let leftover = '';
const tree = this.initDirectoryTree();
const ripgrep = spawnRipgrepCmd(this.config, folderQuery, this.config.includePattern, this.folderExcludePatterns.get(folderQuery.folder.fsPath)!.expression);
const cmd = ripgrep.cmd;
const noSiblingsClauses = !Object.keys(ripgrep.siblingClauses).length;
const escapedArgs = ripgrep.rgArgs.args
.map(arg => arg.match(/^-/) ? arg : `'${arg}'`)
.join(' ');
let rgCmd = `${ripgrep.rgDiskPath} ${escapedArgs}\n - cwd: ${ripgrep.cwd}`;
if (ripgrep.rgArgs.siblingClauses) {
rgCmd += `\n - Sibling clauses: ${JSON.stringify(ripgrep.rgArgs.siblingClauses)}`;
}
onMessage({ message: rgCmd });
this.cmdResultCount = 0;
this.collectStdout(cmd, 'utf8', onMessage, (err: Error | null, stdout?: string, last?: boolean) => {
if (err) {
done(err);
return;
}
if (this.isLimitHit) {
done();
return;
}
// Mac: uses NFD unicode form on disk, but we want NFC
const normalized = leftover + (isMac ? normalization.normalizeNFC(stdout || '') : stdout);
const relativeFiles = normalized.split('\n');
if (last) {
const n = relativeFiles.length;
relativeFiles[n - 1] = relativeFiles[n - 1].trim();
if (!relativeFiles[n - 1]) {
relativeFiles.pop();
}
} else {
leftover = relativeFiles.pop() || '';
}
if (relativeFiles.length && relativeFiles[0].indexOf('\n') !== -1) {
done(new Error('Splitting up files failed'));
return;
}
this.cmdResultCount += relativeFiles.length;
if (noSiblingsClauses) {
for (const relativePath of relativeFiles) {
this.matchFile(onResult, { base: rootFolder, relativePath, searchPath: this.getSearchPath(folderQuery, relativePath) });
if (this.isLimitHit) {
killCmd();
break;
}
}
if (last || this.isLimitHit) {
done();
}
return;
}
// TODO: Optimize siblings clauses with ripgrep here.
this.addDirectoryEntries(folderQuery, tree, rootFolder, relativeFiles, onResult);
if (last) {
this.matchDirectoryTree(tree, rootFolder, onResult);
done();
}
});
}
/**
* Public for testing.
*/
spawnFindCmd(folderQuery: IFolderQuery) {
const excludePattern = this.folderExcludePatterns.get(folderQuery.folder.fsPath)!;
const basenames = excludePattern.getBasenameTerms();
const pathTerms = excludePattern.getPathTerms();
const args = ['-L', '.'];
if (basenames.length || pathTerms.length) {
args.push('-not', '(', '(');
for (const basename of basenames) {
args.push('-name', basename);
args.push('-o');
}
for (const path of pathTerms) {
args.push('-path', path);
args.push('-o');
}
args.pop();
args.push(')', '-prune', ')');
}
args.push('-type', 'f');
return childProcess.spawn('find', args, { cwd: folderQuery.folder.fsPath });
}
/**
* Public for testing.
*/
readStdout(cmd: childProcess.ChildProcess, encoding: BufferEncoding, cb: (err: Error | null, stdout?: string) => void): void {
let all = '';
this.collectStdout(cmd, encoding, () => { }, (err: Error | null, stdout?: string, last?: boolean) => {
if (err) {
cb(err);
return;
}
all += stdout;
if (last) {
cb(null, all);
}
});
}
private collectStdout(cmd: childProcess.ChildProcess, encoding: BufferEncoding, onMessage: (message: IProgressMessage) => void, cb: (err: Error | null, stdout?: string, last?: boolean) => void): void {
let onData = (err: Error | null, stdout?: string, last?: boolean) => {
if (err || last) {
onData = () => { };
this.cmdSW?.stop();
}
cb(err, stdout, last);
};
let gotData = false;
if (cmd.stdout) {
// Should be non-null, but #38195
this.forwardData(cmd.stdout, encoding, onData);
cmd.stdout.once('data', () => gotData = true);
} else {
onMessage({ message: 'stdout is null' });
}
let stderr: Buffer[];
if (cmd.stderr) {
// Should be non-null, but #38195
stderr = this.collectData(cmd.stderr);
} else {
onMessage({ message: 'stderr is null' });
}
cmd.on('error', (err: Error) => {
onData(err);
});
cmd.on('close', (code: number) => {
// ripgrep returns code=1 when no results are found
let stderrText: string;
if (!gotData && (stderrText = this.decodeData(stderr, encoding)) && rgErrorMsgForDisplay(stderrText)) {
onData(new Error(`command failed with error code ${code}: ${this.decodeData(stderr, encoding)}`));
} else {
if (this.exists && code === 0) {
this.isLimitHit = true;
}
onData(null, '', true);
}
});
}
private forwardData(stream: Readable, encoding: BufferEncoding, cb: (err: Error | null, stdout?: string) => void): StringDecoder {
const decoder = new StringDecoder(encoding);
stream.on('data', (data: Buffer) => {
cb(null, decoder.write(data));
});
return decoder;
}
private collectData(stream: Readable): Buffer[] {
const buffers: Buffer[] = [];
stream.on('data', (data: Buffer) => {
buffers.push(data);
});
return buffers;
}
private decodeData(buffers: Buffer[], encoding: BufferEncoding): string {
const decoder = new StringDecoder(encoding);
return buffers.map(buffer => decoder.write(buffer)).join('');
}
private initDirectoryTree(): IDirectoryTree {
const tree: IDirectoryTree = {
rootEntries: [],
pathToEntries: Object.create(null)
};
tree.pathToEntries['.'] = tree.rootEntries;
return tree;
}
private addDirectoryEntries(folderQuery: IFolderQuery, { pathToEntries }: IDirectoryTree, base: string, relativeFiles: string[], onResult: (result: IRawFileMatch) => void) {
// Support relative paths to files from a root resource (ignores excludes)
if (relativeFiles.indexOf(this.filePattern) !== -1) {
this.matchFile(onResult, {
base,
relativePath: this.filePattern,
searchPath: this.getSearchPath(folderQuery, this.filePattern)
});
}
const add = (relativePath: string) => {
const basename = path.basename(relativePath);
const dirname = path.dirname(relativePath);
let entries = pathToEntries[dirname];
if (!entries) {
entries = pathToEntries[dirname] = [];
add(dirname);
}
entries.push({
base,
relativePath,
basename,
searchPath: this.getSearchPath(folderQuery, relativePath),
});
};
relativeFiles.forEach(add);
}
private matchDirectoryTree({ rootEntries, pathToEntries }: IDirectoryTree, rootFolder: string, onResult: (result: IRawFileMatch) => void) {
const self = this;
const excludePattern = this.folderExcludePatterns.get(rootFolder)!;
const filePattern = this.filePattern;
function matchDirectory(entries: IDirectoryEntry[]) {
self.directoriesWalked++;
const hasSibling = hasSiblingFn(() => entries.map(entry => entry.basename));
for (let i = 0, n = entries.length; i < n; i++) {
const entry = entries[i];
const { relativePath, basename } = entry;
// Check exclude pattern
// If the user searches for the exact file name, we adjust the glob matching
// to ignore filtering by siblings because the user seems to know what they
// are searching for and we want to include the result in that case anyway
if (excludePattern.test(relativePath, basename, filePattern !== basename ? hasSibling : undefined)) {
continue;
}
const sub = pathToEntries[relativePath];
if (sub) {
matchDirectory(sub);
} else {
self.filesWalked++;
if (relativePath === filePattern) {
continue; // ignore file if its path matches with the file pattern because that is already matched above
}
self.matchFile(onResult, entry);
}
if (self.isLimitHit) {
break;
}
}
}
matchDirectory(rootEntries);
}
getStats(): ISearchEngineStats {
return {
cmdTime: this.cmdSW!.elapsed(),
fileWalkTime: this.fileWalkSW!.elapsed(),
directoriesWalked: this.directoriesWalked,
filesWalked: this.filesWalked,
cmdResultCount: this.cmdResultCount
};
}
private doWalk(folderQuery: IFolderQuery, relativeParentPath: string, files: string[], onResult: (result: IRawFileMatch) => void, done: (error?: Error) => void): void {
const rootFolder = folderQuery.folder;
// Execute tasks on each file in parallel to optimize throughput
const hasSibling = hasSiblingFn(() => files);
this.parallel(files, (file: string, clb: (error: Error | null, _?: any) => void): void => {
// Check canceled
if (this.isCanceled || this.isLimitHit) {
return clb(null);
}
// Check exclude pattern
// If the user searches for the exact file name, we adjust the glob matching
// to ignore filtering by siblings because the user seems to know what they
// are searching for and we want to include the result in that case anyway
const currentRelativePath = relativeParentPath ? [relativeParentPath, file].join(path.sep) : file;
if (this.folderExcludePatterns.get(folderQuery.folder.fsPath)!.test(currentRelativePath, file, this.config.filePattern !== file ? hasSibling : undefined)) {
return clb(null);
}
// Use lstat to detect links
const currentAbsolutePath = [rootFolder.fsPath, currentRelativePath].join(path.sep);
fs.lstat(currentAbsolutePath, (error, lstat) => {
if (error || this.isCanceled || this.isLimitHit) {
return clb(null);
}
// If the path is a link, we must instead use fs.stat() to find out if the
// link is a directory or not because lstat will always return the stat of
// the link which is always a file.
this.statLinkIfNeeded(currentAbsolutePath, lstat, (error, stat) => {
if (error || this.isCanceled || this.isLimitHit) {
return clb(null);
}
// Directory: Follow directories
if (stat.isDirectory()) {
this.directoriesWalked++;
// to really prevent loops with links we need to resolve the real path of them
return this.realPathIfNeeded(currentAbsolutePath, lstat, (error, realpath) => {
if (error || this.isCanceled || this.isLimitHit) {
return clb(null);
}
realpath = realpath || '';
if (this.walkedPaths[realpath]) {
return clb(null); // escape when there are cycles (can happen with symlinks)
}
this.walkedPaths[realpath] = true; // remember as walked
// Continue walking
return Promises.readdir(currentAbsolutePath).then(children => {
if (this.isCanceled || this.isLimitHit) {
return clb(null);
}
this.doWalk(folderQuery, currentRelativePath, children, onResult, err => clb(err || null));
}, error => {
clb(null);
});
});
}
// File: Check for match on file pattern and include pattern
else {
this.filesWalked++;
if (currentRelativePath === this.filePattern) {
return clb(null, undefined); // ignore file if its path matches with the file pattern because checkFilePatternRelativeMatch() takes care of those
}
if (this.maxFilesize && types.isNumber(stat.size) && stat.size > this.maxFilesize) {
return clb(null, undefined); // ignore file if max file size is hit
}
this.matchFile(onResult, {
base: rootFolder.fsPath,
relativePath: currentRelativePath,
searchPath: this.getSearchPath(folderQuery, currentRelativePath),
});
}
// Unwind
return clb(null, undefined);
});
});
}, (error: Array<Error | null> | null): void => {
const filteredErrors = error ? arrays.coalesce(error) : error; // find any error by removing null values first
return done(filteredErrors && filteredErrors.length > 0 ? filteredErrors[0] : undefined);
});
}
private matchFile(onResult: (result: IRawFileMatch) => void, candidate: IRawFileMatch): void {
if (this.isFileMatch(candidate) && (!this.includePattern || this.includePattern(candidate.relativePath, path.basename(candidate.relativePath)))) {
this.resultCount++;
if (this.exists || (this.maxResults && this.resultCount > this.maxResults)) {
this.isLimitHit = true;
}
if (!this.isLimitHit) {
onResult(candidate);
}
}
}
private isFileMatch(candidate: IRawFileMatch): boolean {
// Check for search pattern
if (this.filePattern) {
if (this.filePattern === '*') {
return true; // support the all-matching wildcard
}
if (this.normalizedFilePatternLowercase) {
return isFilePatternMatch(candidate, this.normalizedFilePatternLowercase);
}
}
// No patterns means we match all
return true;
}
private statLinkIfNeeded(path: string, lstat: fs.Stats, clb: (error: Error | null, stat: fs.Stats) => void): void {
if (lstat.isSymbolicLink()) {
return fs.stat(path, clb); // stat the target the link points to
}
return clb(null, lstat); // not a link, so the stat is already ok for us
}
private realPathIfNeeded(path: string, lstat: fs.Stats, clb: (error: Error | null, realpath?: string) => void): void {
if (lstat.isSymbolicLink()) {
return fs.realpath(path, (error, realpath) => {
if (error) {
return clb(error);
}
return clb(null, realpath);
});
}
return clb(null, path);
}
/**
* If we're searching for files in multiple workspace folders, then better prepend the
* name of the workspace folder to the path of the file. This way we'll be able to
* better filter files that are all on the top of a workspace folder and have all the
* same name. A typical example are `package.json` or `README.md` files.
*/
private getSearchPath(folderQuery: IFolderQuery, relativePath: string): string {
if (folderQuery.folderName) {
return path.join(folderQuery.folderName, relativePath);
}
return relativePath;
}
}
export class Engine implements ISearchEngine<IRawFileMatch> {
private folderQueries: IFolderQuery[];
private extraFiles: URI[];
private walker: FileWalker;
constructor(config: IFileQuery) {
this.folderQueries = config.folderQueries;
this.extraFiles = config.extraFileResources || [];
this.walker = new FileWalker(config);
}
search(onResult: (result: IRawFileMatch) => void, onProgress: (progress: IProgressMessage) => void, done: (error: Error | null, complete: ISearchEngineSuccess) => void): void {
this.walker.walk(this.folderQueries, this.extraFiles, onResult, onProgress, (err: Error | null, isLimitHit: boolean) => {
done(err, {
limitHit: isLimitHit,
stats: this.walker.getStats(),
messages: [],
});
});
}
cancel(): void {
this.walker.cancel();
}
}
/**
* This class exists to provide one interface on top of two ParsedExpressions, one for absolute expressions and one for relative expressions.
* The absolute and relative expressions don't "have" to be kept separate, but this keeps us from having to path.join every single
* file searched, it's only used for a text search with a searchPath
*/
class AbsoluteAndRelativeParsedExpression {
private absoluteParsedExpr: glob.ParsedExpression | undefined;
private relativeParsedExpr: glob.ParsedExpression | undefined;
constructor(public expression: glob.IExpression, private root: string) {
this.init(expression);
}
/**
* Split the IExpression into its absolute and relative components, and glob.parse them separately.
*/
private init(expr: glob.IExpression): void {
let absoluteGlobExpr: glob.IExpression | undefined;
let relativeGlobExpr: glob.IExpression | undefined;
Object.keys(expr)
.filter(key => expr[key])
.forEach(key => {
if (path.isAbsolute(key)) {
absoluteGlobExpr = absoluteGlobExpr || glob.getEmptyExpression();
absoluteGlobExpr[key] = expr[key];
} else {
relativeGlobExpr = relativeGlobExpr || glob.getEmptyExpression();
relativeGlobExpr[key] = expr[key];
}
});
this.absoluteParsedExpr = absoluteGlobExpr && glob.parse(absoluteGlobExpr, { trimForExclusions: true });
this.relativeParsedExpr = relativeGlobExpr && glob.parse(relativeGlobExpr, { trimForExclusions: true });
}
test(_path: string, basename?: string, hasSibling?: (name: string) => boolean | Promise<boolean>): string | Promise<string | null> | undefined | null {
return (this.relativeParsedExpr && this.relativeParsedExpr(_path, basename, hasSibling)) ||
(this.absoluteParsedExpr && this.absoluteParsedExpr(path.join(this.root, _path), basename, hasSibling));
}
getBasenameTerms(): string[] {
const basenameTerms: string[] = [];
if (this.absoluteParsedExpr) {
basenameTerms.push(...glob.getBasenameTerms(this.absoluteParsedExpr));
}
if (this.relativeParsedExpr) {
basenameTerms.push(...glob.getBasenameTerms(this.relativeParsedExpr));
}
return basenameTerms;
}
getPathTerms(): string[] {
const pathTerms: string[] = [];
if (this.absoluteParsedExpr) {
pathTerms.push(...glob.getPathTerms(this.absoluteParsedExpr));
}
if (this.relativeParsedExpr) {
pathTerms.push(...glob.getPathTerms(this.relativeParsedExpr));
}
return pathTerms;
}
}
function rgErrorMsgForDisplay(msg: string): string | undefined {
const lines = msg.trim().split('\n');
const firstLine = lines[0].trim();
if (firstLine.startsWith('Error parsing regex')) {
return firstLine;
}
if (firstLine.startsWith('regex parse error')) {
return strings.uppercaseFirstLetter(lines[lines.length - 1].trim());
}
if (firstLine.startsWith('error parsing glob') ||
firstLine.startsWith('unsupported encoding')) {
// Uppercase first letter
return firstLine.charAt(0).toUpperCase() + firstLine.substr(1);
}
if (firstLine === `Literal '\\n' not allowed.`) {
// I won't localize this because none of the Ripgrep error messages are localized
return `Literal '\\n' currently not supported`;
}
if (firstLine.startsWith('Literal ')) {
// Other unsupported chars
return firstLine;
}
return undefined;
}
| src/vs/workbench/services/search/node/fileSearch.ts | 0 | https://github.com/microsoft/vscode/commit/c2bf6225a12e7f7d8afada6ec39560bb38e5838a | [
0.00029270091908983886,
0.00017267640214413404,
0.0001624692667974159,
0.00017184445459861308,
0.00001421624438080471
] |
{
"id": 6,
"code_window": [
" *--------------------------------------------------------------------------------------------*/\n",
"\n",
"import * as dom from 'vs/base/browser/dom';\n",
"import { renderIcon } from 'vs/base/browser/ui/iconLabel/iconLabels';\n",
"import { IListVirtualDelegate } from 'vs/base/browser/ui/list/list';\n",
"import { IListAccessibilityProvider } from 'vs/base/browser/ui/list/listWidget';\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { IActionViewItemOptions } from 'vs/base/browser/ui/actionbar/actionViewItems';\n"
],
"file_path": "src/vs/workbench/contrib/interactiveSession/browser/interactiveSessionListRenderer.ts",
"type": "add",
"edit_start_line_idx": 6
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Codicon } from 'vs/base/common/codicons';
import { ServicesAccessor } from 'vs/editor/browser/editorExtensions';
import { localize } from 'vs/nls';
import { Action2, MenuId, registerAction2 } from 'vs/platform/actions/common/actions';
import { ContextKeyExpr } from 'vs/platform/contextkey/common/contextkey';
import { INTERACTIVE_SESSION_CATEGORY } from 'vs/workbench/contrib/interactiveSession/browser/actions/interactiveSessionActions';
import { CONTEXT_RESPONSE_HAS_PROVIDER_ID, CONTEXT_RESPONSE_VOTE } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionContextKeys';
import { IInteractiveSessionService, IInteractiveSessionUserActionEvent, InteractiveSessionVoteDirection } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionService';
import { isResponseVM } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionViewModel';
export function registerInteractiveSessionTitleActions() {
registerAction2(class VoteUpAction extends Action2 {
constructor() {
super({
id: 'workbench.action.interactiveSession.voteUp',
title: {
value: localize('interactive.voteUp.label', "Vote Up"),
original: 'Vote Up'
},
f1: false,
category: INTERACTIVE_SESSION_CATEGORY,
icon: Codicon.thumbsup,
precondition: CONTEXT_RESPONSE_VOTE.isEqualTo(''), // Should be disabled but visible when vote=down
menu: {
id: MenuId.InteractiveSessionTitle,
when: ContextKeyExpr.and(CONTEXT_RESPONSE_HAS_PROVIDER_ID, CONTEXT_RESPONSE_VOTE.notEqualsTo('down')),
group: 'navigation',
order: 1
}
});
}
run(accessor: ServicesAccessor, ...args: any[]) {
const item = args[0];
if (!isResponseVM(item)) {
return;
}
const interactiveSessionService = accessor.get(IInteractiveSessionService);
interactiveSessionService.notifyUserAction(<IInteractiveSessionUserActionEvent>{
providerId: item.providerId,
action: {
kind: 'vote',
direction: InteractiveSessionVoteDirection.Up,
responseId: item.providerResponseId
}
});
item.setVote(InteractiveSessionVoteDirection.Up);
}
});
registerAction2(class VoteDownAction extends Action2 {
constructor() {
super({
id: 'workbench.action.interactiveSession.voteDown',
title: {
value: localize('interactive.voteDown.label', "Vote Down"),
original: 'Vote Down'
},
f1: false,
category: INTERACTIVE_SESSION_CATEGORY,
icon: Codicon.thumbsdown,
precondition: CONTEXT_RESPONSE_VOTE.isEqualTo(''), // Should be disabled but visible when vote=down
menu: {
id: MenuId.InteractiveSessionTitle,
when: ContextKeyExpr.and(CONTEXT_RESPONSE_HAS_PROVIDER_ID, CONTEXT_RESPONSE_VOTE.notEqualsTo('up')),
group: 'navigation',
order: 2
}
});
}
run(accessor: ServicesAccessor, ...args: any[]) {
const item = args[0];
if (!isResponseVM(item)) {
return;
}
const interactiveSessionService = accessor.get(IInteractiveSessionService);
interactiveSessionService.notifyUserAction(<IInteractiveSessionUserActionEvent>{
providerId: item.providerId,
action: {
kind: 'vote',
direction: InteractiveSessionVoteDirection.Down,
responseId: item.providerResponseId
}
});
item.setVote(InteractiveSessionVoteDirection.Down);
}
});
}
| src/vs/workbench/contrib/interactiveSession/browser/actions/interactiveSessionTitleActions.ts | 1 | https://github.com/microsoft/vscode/commit/c2bf6225a12e7f7d8afada6ec39560bb38e5838a | [
0.0001721984299365431,
0.0001688443880993873,
0.0001644987059989944,
0.00016831302491482347,
0.0000022978970264375675
] |
{
"id": 6,
"code_window": [
" *--------------------------------------------------------------------------------------------*/\n",
"\n",
"import * as dom from 'vs/base/browser/dom';\n",
"import { renderIcon } from 'vs/base/browser/ui/iconLabel/iconLabels';\n",
"import { IListVirtualDelegate } from 'vs/base/browser/ui/list/list';\n",
"import { IListAccessibilityProvider } from 'vs/base/browser/ui/list/listWidget';\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { IActionViewItemOptions } from 'vs/base/browser/ui/actionbar/actionViewItems';\n"
],
"file_path": "src/vs/workbench/contrib/interactiveSession/browser/interactiveSessionListRenderer.ts",
"type": "add",
"edit_start_line_idx": 6
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
.monaco-dialog-box {
border-radius: 6px;
}
.monaco-dialog-box .dialog-message-row .dialog-message-container .dialog-message-text {
font-size: 25px;
min-width: max-content;
}
#monaco-dialog-message-body > div > p > .codicon[class*='codicon-']::before{
padding-right: 8px;
max-width: 30px;
max-height: 30px;
position: relative;
top: auto;
color: var(--vscode-textLink-foreground);
padding-right: 20px;
font-size: 25px;
}
#monaco-dialog-message-body > .message-body > p {
display: flex;
font-size: 16px;
background: var(--vscode-welcomePage-tileHoverBackground);
border-radius: 6px;
padding: 20px;
min-height: auto;
word-wrap: break-word;
overflow-wrap:break-word;
}
#monaco-dialog-message-body > .link > p {
font-size: 16px;
}
| src/vs/workbench/contrib/welcomeDialog/browser/media/welcomeDialog.css | 0 | https://github.com/microsoft/vscode/commit/c2bf6225a12e7f7d8afada6ec39560bb38e5838a | [
0.00017289025709033012,
0.00017073319759219885,
0.00016834524285513908,
0.00017084863793570548,
0.000001902927124319831
] |
{
"id": 6,
"code_window": [
" *--------------------------------------------------------------------------------------------*/\n",
"\n",
"import * as dom from 'vs/base/browser/dom';\n",
"import { renderIcon } from 'vs/base/browser/ui/iconLabel/iconLabels';\n",
"import { IListVirtualDelegate } from 'vs/base/browser/ui/list/list';\n",
"import { IListAccessibilityProvider } from 'vs/base/browser/ui/list/listWidget';\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { IActionViewItemOptions } from 'vs/base/browser/ui/actionbar/actionViewItems';\n"
],
"file_path": "src/vs/workbench/contrib/interactiveSession/browser/interactiveSessionListRenderer.ts",
"type": "add",
"edit_start_line_idx": 6
} | /*---------------------------------------------------------------------------------------------
* 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 { getDeepestFlatNode, findNextWord, findPrevWord, getFlatNode, offsetRangeToSelection } from './util';
import { Node, CssNode, Rule, Property } from 'EmmetFlatNode';
export function nextItemStylesheet(document: vscode.TextDocument, startPosition: vscode.Position, endPosition: vscode.Position, rootNode: Node): vscode.Selection | undefined {
const startOffset = document.offsetAt(startPosition);
const endOffset = document.offsetAt(endPosition);
let currentNode: CssNode | undefined = <CssNode>getFlatNode(rootNode, endOffset, true);
if (!currentNode) {
currentNode = <CssNode>rootNode;
}
if (!currentNode) {
return;
}
// Full property is selected, so select full property value next
if (currentNode.type === 'property' &&
startOffset === currentNode.start &&
endOffset === currentNode.end) {
return getSelectionFromProperty(document, currentNode, startOffset, endOffset, true, 'next');
}
// Part or whole of propertyValue is selected, so select the next word in the propertyValue
if (currentNode.type === 'property' &&
startOffset >= (<Property>currentNode).valueToken.start &&
endOffset <= (<Property>currentNode).valueToken.end) {
const singlePropertyValue = getSelectionFromProperty(document, currentNode, startOffset, endOffset, false, 'next');
if (singlePropertyValue) {
return singlePropertyValue;
}
}
// Cursor is in the selector or in a property
if ((currentNode.type === 'rule' && endOffset < (<Rule>currentNode).selectorToken.end)
|| (currentNode.type === 'property' && endOffset < (<Property>currentNode).valueToken.end)) {
return getSelectionFromNode(document, currentNode);
}
// Get the first child of current node which is right after the cursor
let nextNode = currentNode.firstChild;
while (nextNode && endOffset >= nextNode.end) {
nextNode = nextNode.nextSibling;
}
// Get next sibling of current node or the parent
while (!nextNode && currentNode) {
nextNode = currentNode.nextSibling;
currentNode = currentNode.parent;
}
return nextNode ? getSelectionFromNode(document, nextNode) : undefined;
}
export function prevItemStylesheet(document: vscode.TextDocument, startPosition: vscode.Position, endPosition: vscode.Position, rootNode: CssNode): vscode.Selection | undefined {
const startOffset = document.offsetAt(startPosition);
const endOffset = document.offsetAt(endPosition);
let currentNode = <CssNode>getFlatNode(rootNode, startOffset, false);
if (!currentNode) {
currentNode = rootNode;
}
if (!currentNode) {
return;
}
// Full property value is selected, so select the whole property next
if (currentNode.type === 'property' &&
startOffset === (<Property>currentNode).valueToken.start &&
endOffset === (<Property>currentNode).valueToken.end) {
return getSelectionFromNode(document, currentNode);
}
// Part of propertyValue is selected, so select the prev word in the propertyValue
if (currentNode.type === 'property' &&
startOffset >= (<Property>currentNode).valueToken.start &&
endOffset <= (<Property>currentNode).valueToken.end) {
const singlePropertyValue = getSelectionFromProperty(document, currentNode, startOffset, endOffset, false, 'prev');
if (singlePropertyValue) {
return singlePropertyValue;
}
}
if (currentNode.type === 'property' || !currentNode.firstChild ||
(currentNode.type === 'rule' && startOffset <= currentNode.firstChild.start)) {
return getSelectionFromNode(document, currentNode);
}
// Select the child that appears just before the cursor
let prevNode: CssNode | undefined = currentNode.firstChild;
while (prevNode.nextSibling && startOffset >= prevNode.nextSibling.end) {
prevNode = prevNode.nextSibling;
}
prevNode = <CssNode | undefined>getDeepestFlatNode(prevNode);
return getSelectionFromProperty(document, prevNode, startOffset, endOffset, false, 'prev');
}
function getSelectionFromNode(document: vscode.TextDocument, node: Node | undefined): vscode.Selection | undefined {
if (!node) {
return;
}
const nodeToSelect = node.type === 'rule' ? (<Rule>node).selectorToken : node;
return offsetRangeToSelection(document, nodeToSelect.start, nodeToSelect.end);
}
function getSelectionFromProperty(document: vscode.TextDocument, node: Node | undefined, selectionStart: number, selectionEnd: number, selectFullValue: boolean, direction: string): vscode.Selection | undefined {
if (!node || node.type !== 'property') {
return;
}
const propertyNode = <Property>node;
const propertyValue = propertyNode.valueToken.stream.substring(propertyNode.valueToken.start, propertyNode.valueToken.end);
selectFullValue = selectFullValue ||
(direction === 'prev' && selectionStart === propertyNode.valueToken.start && selectionEnd < propertyNode.valueToken.end);
if (selectFullValue) {
return offsetRangeToSelection(document, propertyNode.valueToken.start, propertyNode.valueToken.end);
}
let pos: number = -1;
if (direction === 'prev') {
if (selectionStart === propertyNode.valueToken.start) {
return;
}
const selectionStartChar = document.positionAt(selectionStart).character;
const tokenStartChar = document.positionAt(propertyNode.valueToken.start).character;
pos = selectionStart > propertyNode.valueToken.end ? propertyValue.length :
selectionStartChar - tokenStartChar;
} else if (direction === 'next') {
if (selectionEnd === propertyNode.valueToken.end &&
(selectionStart > propertyNode.valueToken.start || !propertyValue.includes(' '))) {
return;
}
const selectionEndChar = document.positionAt(selectionEnd).character;
const tokenStartChar = document.positionAt(propertyNode.valueToken.start).character;
pos = selectionEnd === propertyNode.valueToken.end ? -1 :
selectionEndChar - tokenStartChar - 1;
}
const [newSelectionStartOffset, newSelectionEndOffset] = direction === 'prev' ? findPrevWord(propertyValue, pos) : findNextWord(propertyValue, pos);
if (!newSelectionStartOffset && !newSelectionEndOffset) {
return;
}
const tokenStart = document.positionAt(propertyNode.valueToken.start);
const newSelectionStart = tokenStart.translate(0, newSelectionStartOffset);
const newSelectionEnd = tokenStart.translate(0, newSelectionEndOffset);
return new vscode.Selection(newSelectionStart, newSelectionEnd);
}
| extensions/emmet/src/selectItemStylesheet.ts | 0 | https://github.com/microsoft/vscode/commit/c2bf6225a12e7f7d8afada6ec39560bb38e5838a | [
0.0001743335888022557,
0.00017257417493965477,
0.00016980290820356458,
0.0001728164206724614,
0.000001221679099216999
] |
{
"id": 6,
"code_window": [
" *--------------------------------------------------------------------------------------------*/\n",
"\n",
"import * as dom from 'vs/base/browser/dom';\n",
"import { renderIcon } from 'vs/base/browser/ui/iconLabel/iconLabels';\n",
"import { IListVirtualDelegate } from 'vs/base/browser/ui/list/list';\n",
"import { IListAccessibilityProvider } from 'vs/base/browser/ui/list/listWidget';\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { IActionViewItemOptions } from 'vs/base/browser/ui/actionbar/actionViewItems';\n"
],
"file_path": "src/vs/workbench/contrib/interactiveSession/browser/interactiveSessionListRenderer.ts",
"type": "add",
"edit_start_line_idx": 6
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import 'vs/css!./media/customEditor';
import { coalesce } from 'vs/base/common/arrays';
import { Emitter, Event } from 'vs/base/common/event';
import { Disposable, DisposableStore, IDisposable, toDisposable } from 'vs/base/common/lifecycle';
import { Schemas } from 'vs/base/common/network';
import { extname, isEqual } from 'vs/base/common/resources';
import { assertIsDefined } from 'vs/base/common/types';
import { URI } from 'vs/base/common/uri';
import { RedoCommand, UndoCommand } from 'vs/editor/browser/editorExtensions';
import { IContextKey, IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { IResourceEditorInput } from 'vs/platform/editor/common/editor';
import { FileOperation, IFileService } from 'vs/platform/files/common/files';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { Registry } from 'vs/platform/registry/common/platform';
import { IStorageService } from 'vs/platform/storage/common/storage';
import { IUriIdentityService } from 'vs/platform/uriIdentity/common/uriIdentity';
import { DEFAULT_EDITOR_ASSOCIATION, EditorExtensions, GroupIdentifier, IEditorFactoryRegistry, IResourceDiffEditorInput } from 'vs/workbench/common/editor';
import { DiffEditorInput } from 'vs/workbench/common/editor/diffEditorInput';
import { EditorInput } from 'vs/workbench/common/editor/editorInput';
import { CONTEXT_ACTIVE_CUSTOM_EDITOR_ID, CONTEXT_FOCUSED_CUSTOM_EDITOR_IS_EDITABLE, CustomEditorCapabilities, CustomEditorInfo, CustomEditorInfoCollection, ICustomEditorService } from 'vs/workbench/contrib/customEditor/common/customEditor';
import { CustomEditorModelManager } from 'vs/workbench/contrib/customEditor/common/customEditorModelManager';
import { IEditorGroup, IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService';
import { IEditorResolverService, IEditorType, RegisteredEditorPriority } from 'vs/workbench/services/editor/common/editorResolverService';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { ContributedCustomEditors } from '../common/contributedCustomEditors';
import { CustomEditorInput } from './customEditorInput';
export class CustomEditorService extends Disposable implements ICustomEditorService {
_serviceBrand: any;
private readonly _contributedEditors: ContributedCustomEditors;
private _untitledCounter = 0;
private readonly _editorResolverDisposables = this._register(new DisposableStore());
private readonly _editorCapabilities = new Map<string, CustomEditorCapabilities>();
private readonly _models = new CustomEditorModelManager();
private readonly _activeCustomEditorId: IContextKey<string>;
private readonly _focusedCustomEditorIsEditable: IContextKey<boolean>;
private readonly _onDidChangeEditorTypes = this._register(new Emitter<void>());
public readonly onDidChangeEditorTypes: Event<void> = this._onDidChangeEditorTypes.event;
private readonly _fileEditorFactory = Registry.as<IEditorFactoryRegistry>(EditorExtensions.EditorFactory).getFileEditorFactory();
constructor(
@IContextKeyService contextKeyService: IContextKeyService,
@IFileService fileService: IFileService,
@IStorageService storageService: IStorageService,
@IEditorService private readonly editorService: IEditorService,
@IEditorGroupsService private readonly editorGroupService: IEditorGroupsService,
@IInstantiationService private readonly instantiationService: IInstantiationService,
@IUriIdentityService private readonly uriIdentityService: IUriIdentityService,
@IEditorResolverService private readonly editorResolverService: IEditorResolverService,
) {
super();
this._activeCustomEditorId = CONTEXT_ACTIVE_CUSTOM_EDITOR_ID.bindTo(contextKeyService);
this._focusedCustomEditorIsEditable = CONTEXT_FOCUSED_CUSTOM_EDITOR_IS_EDITABLE.bindTo(contextKeyService);
this._contributedEditors = this._register(new ContributedCustomEditors(storageService));
// Register the contribution points only emitting one change from the resolver
this.editorResolverService.bufferChangeEvents(this.registerContributionPoints.bind(this));
this._register(this._contributedEditors.onChange(() => {
// Register the contribution points only emitting one change from the resolver
this.editorResolverService.bufferChangeEvents(this.registerContributionPoints.bind(this));
this.updateContexts();
this._onDidChangeEditorTypes.fire();
}));
this._register(this.editorService.onDidActiveEditorChange(() => this.updateContexts()));
this._register(fileService.onDidRunOperation(e => {
if (e.isOperation(FileOperation.MOVE)) {
this.handleMovedFileInOpenedFileEditors(e.resource, this.uriIdentityService.asCanonicalUri(e.target.resource));
}
}));
const PRIORITY = 105;
this._register(UndoCommand.addImplementation(PRIORITY, 'custom-editor', () => {
return this.withActiveCustomEditor(editor => editor.undo());
}));
this._register(RedoCommand.addImplementation(PRIORITY, 'custom-editor', () => {
return this.withActiveCustomEditor(editor => editor.redo());
}));
this.updateContexts();
}
getEditorTypes(): IEditorType[] {
return [...this._contributedEditors];
}
private withActiveCustomEditor(f: (editor: CustomEditorInput) => void | Promise<void>): boolean | Promise<void> {
const activeEditor = this.editorService.activeEditor;
if (activeEditor instanceof CustomEditorInput) {
const result = f(activeEditor);
if (result) {
return result;
}
return true;
}
return false;
}
private registerContributionPoints(): void {
// Clear all previous contributions we know
this._editorResolverDisposables.clear();
for (const contributedEditor of this._contributedEditors) {
for (const globPattern of contributedEditor.selector) {
if (!globPattern.filenamePattern) {
continue;
}
this._editorResolverDisposables.add(this.editorResolverService.registerEditor(
globPattern.filenamePattern,
{
id: contributedEditor.id,
label: contributedEditor.displayName,
detail: contributedEditor.providerDisplayName,
priority: contributedEditor.priority,
},
{
singlePerResource: () => !this.getCustomEditorCapabilities(contributedEditor.id)?.supportsMultipleEditorsPerDocument ?? true
},
{
createEditorInput: ({ resource }, group) => {
return { editor: CustomEditorInput.create(this.instantiationService, resource, contributedEditor.id, group.id) };
},
createUntitledEditorInput: ({ resource }, group) => {
return { editor: CustomEditorInput.create(this.instantiationService, resource ?? URI.from({ scheme: Schemas.untitled, authority: `Untitled-${this._untitledCounter++}` }), contributedEditor.id, group.id) };
},
createDiffEditorInput: (diffEditorInput, group) => {
return { editor: this.createDiffEditorInput(diffEditorInput, contributedEditor.id, group) };
},
}
));
}
}
}
private createDiffEditorInput(
editor: IResourceDiffEditorInput,
editorID: string,
group: IEditorGroup
): DiffEditorInput {
const modifiedOverride = CustomEditorInput.create(this.instantiationService, assertIsDefined(editor.modified.resource), editorID, group.id, { customClasses: 'modified' });
const originalOverride = CustomEditorInput.create(this.instantiationService, assertIsDefined(editor.original.resource), editorID, group.id, { customClasses: 'original' });
return this.instantiationService.createInstance(DiffEditorInput, editor.label, editor.description, originalOverride, modifiedOverride, true);
}
public get models() { return this._models; }
public getCustomEditor(viewType: string): CustomEditorInfo | undefined {
return this._contributedEditors.get(viewType);
}
public getContributedCustomEditors(resource: URI): CustomEditorInfoCollection {
return new CustomEditorInfoCollection(this._contributedEditors.getContributedEditors(resource));
}
public getUserConfiguredCustomEditors(resource: URI): CustomEditorInfoCollection {
const resourceAssocations = this.editorResolverService.getAssociationsForResource(resource);
return new CustomEditorInfoCollection(
coalesce(resourceAssocations
.map(association => this._contributedEditors.get(association.viewType))));
}
public getAllCustomEditors(resource: URI): CustomEditorInfoCollection {
return new CustomEditorInfoCollection([
...this.getUserConfiguredCustomEditors(resource).allEditors,
...this.getContributedCustomEditors(resource).allEditors,
]);
}
public registerCustomEditorCapabilities(viewType: string, options: CustomEditorCapabilities): IDisposable {
if (this._editorCapabilities.has(viewType)) {
throw new Error(`Capabilities for ${viewType} already set`);
}
this._editorCapabilities.set(viewType, options);
return toDisposable(() => {
this._editorCapabilities.delete(viewType);
});
}
public getCustomEditorCapabilities(viewType: string): CustomEditorCapabilities | undefined {
return this._editorCapabilities.get(viewType);
}
private updateContexts() {
const activeEditorPane = this.editorService.activeEditorPane;
const resource = activeEditorPane?.input?.resource;
if (!resource) {
this._activeCustomEditorId.reset();
this._focusedCustomEditorIsEditable.reset();
return;
}
this._activeCustomEditorId.set(activeEditorPane?.input instanceof CustomEditorInput ? activeEditorPane.input.viewType : '');
this._focusedCustomEditorIsEditable.set(activeEditorPane?.input instanceof CustomEditorInput);
}
private async handleMovedFileInOpenedFileEditors(oldResource: URI, newResource: URI): Promise<void> {
if (extname(oldResource).toLowerCase() === extname(newResource).toLowerCase()) {
return;
}
const possibleEditors = this.getAllCustomEditors(newResource);
// See if we have any non-optional custom editor for this resource
if (!possibleEditors.allEditors.some(editor => editor.priority !== RegisteredEditorPriority.option)) {
return;
}
// If so, check all editors to see if there are any file editors open for the new resource
const editorsToReplace = new Map<GroupIdentifier, EditorInput[]>();
for (const group of this.editorGroupService.groups) {
for (const editor of group.editors) {
if (this._fileEditorFactory.isFileEditor(editor)
&& !(editor instanceof CustomEditorInput)
&& isEqual(editor.resource, newResource)
) {
let entry = editorsToReplace.get(group.id);
if (!entry) {
entry = [];
editorsToReplace.set(group.id, entry);
}
entry.push(editor);
}
}
}
if (!editorsToReplace.size) {
return;
}
for (const [group, entries] of editorsToReplace) {
this.editorService.replaceEditors(entries.map(editor => {
let replacement: EditorInput | IResourceEditorInput;
if (possibleEditors.defaultEditor) {
const viewType = possibleEditors.defaultEditor.id;
replacement = CustomEditorInput.create(this.instantiationService, newResource, viewType!, group);
} else {
replacement = { resource: newResource, options: { override: DEFAULT_EDITOR_ASSOCIATION.id } };
}
return {
editor,
replacement,
options: {
preserveFocus: true,
}
};
}), group);
}
}
}
| src/vs/workbench/contrib/customEditor/browser/customEditors.ts | 0 | https://github.com/microsoft/vscode/commit/c2bf6225a12e7f7d8afada6ec39560bb38e5838a | [
0.00017496341024525464,
0.00017077167285606265,
0.00016537484771106392,
0.00017113152716774493,
0.0000028468323307606624
] |
{
"id": 7,
"code_window": [
"import { renderIcon } from 'vs/base/browser/ui/iconLabel/iconLabels';\n",
"import { IListVirtualDelegate } from 'vs/base/browser/ui/list/list';\n",
"import { IListAccessibilityProvider } from 'vs/base/browser/ui/list/listWidget';\n",
"import { ITreeNode, ITreeRenderer } from 'vs/base/browser/ui/tree/tree';\n",
"import { IntervalTimer } from 'vs/base/common/async';\n",
"import { Codicon } from 'vs/base/common/codicons';\n",
"import { Emitter, Event } from 'vs/base/common/event';\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { IAction } from 'vs/base/common/actions';\n"
],
"file_path": "src/vs/workbench/contrib/interactiveSession/browser/interactiveSessionListRenderer.ts",
"type": "add",
"edit_start_line_idx": 10
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Codicon } from 'vs/base/common/codicons';
import { ServicesAccessor } from 'vs/editor/browser/editorExtensions';
import { localize } from 'vs/nls';
import { Action2, MenuId, registerAction2 } from 'vs/platform/actions/common/actions';
import { ContextKeyExpr } from 'vs/platform/contextkey/common/contextkey';
import { INTERACTIVE_SESSION_CATEGORY } from 'vs/workbench/contrib/interactiveSession/browser/actions/interactiveSessionActions';
import { CONTEXT_RESPONSE_HAS_PROVIDER_ID, CONTEXT_RESPONSE_VOTE } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionContextKeys';
import { IInteractiveSessionService, IInteractiveSessionUserActionEvent, InteractiveSessionVoteDirection } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionService';
import { isResponseVM } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionViewModel';
export function registerInteractiveSessionTitleActions() {
registerAction2(class VoteUpAction extends Action2 {
constructor() {
super({
id: 'workbench.action.interactiveSession.voteUp',
title: {
value: localize('interactive.voteUp.label', "Vote Up"),
original: 'Vote Up'
},
f1: false,
category: INTERACTIVE_SESSION_CATEGORY,
icon: Codicon.thumbsup,
precondition: CONTEXT_RESPONSE_VOTE.isEqualTo(''), // Should be disabled but visible when vote=down
menu: {
id: MenuId.InteractiveSessionTitle,
when: ContextKeyExpr.and(CONTEXT_RESPONSE_HAS_PROVIDER_ID, CONTEXT_RESPONSE_VOTE.notEqualsTo('down')),
group: 'navigation',
order: 1
}
});
}
run(accessor: ServicesAccessor, ...args: any[]) {
const item = args[0];
if (!isResponseVM(item)) {
return;
}
const interactiveSessionService = accessor.get(IInteractiveSessionService);
interactiveSessionService.notifyUserAction(<IInteractiveSessionUserActionEvent>{
providerId: item.providerId,
action: {
kind: 'vote',
direction: InteractiveSessionVoteDirection.Up,
responseId: item.providerResponseId
}
});
item.setVote(InteractiveSessionVoteDirection.Up);
}
});
registerAction2(class VoteDownAction extends Action2 {
constructor() {
super({
id: 'workbench.action.interactiveSession.voteDown',
title: {
value: localize('interactive.voteDown.label', "Vote Down"),
original: 'Vote Down'
},
f1: false,
category: INTERACTIVE_SESSION_CATEGORY,
icon: Codicon.thumbsdown,
precondition: CONTEXT_RESPONSE_VOTE.isEqualTo(''), // Should be disabled but visible when vote=down
menu: {
id: MenuId.InteractiveSessionTitle,
when: ContextKeyExpr.and(CONTEXT_RESPONSE_HAS_PROVIDER_ID, CONTEXT_RESPONSE_VOTE.notEqualsTo('up')),
group: 'navigation',
order: 2
}
});
}
run(accessor: ServicesAccessor, ...args: any[]) {
const item = args[0];
if (!isResponseVM(item)) {
return;
}
const interactiveSessionService = accessor.get(IInteractiveSessionService);
interactiveSessionService.notifyUserAction(<IInteractiveSessionUserActionEvent>{
providerId: item.providerId,
action: {
kind: 'vote',
direction: InteractiveSessionVoteDirection.Down,
responseId: item.providerResponseId
}
});
item.setVote(InteractiveSessionVoteDirection.Down);
}
});
}
| src/vs/workbench/contrib/interactiveSession/browser/actions/interactiveSessionTitleActions.ts | 1 | https://github.com/microsoft/vscode/commit/c2bf6225a12e7f7d8afada6ec39560bb38e5838a | [
0.00017242664762306958,
0.00016871586558409035,
0.0001643895811866969,
0.0001685487513896078,
0.0000027085775400337297
] |
{
"id": 7,
"code_window": [
"import { renderIcon } from 'vs/base/browser/ui/iconLabel/iconLabels';\n",
"import { IListVirtualDelegate } from 'vs/base/browser/ui/list/list';\n",
"import { IListAccessibilityProvider } from 'vs/base/browser/ui/list/listWidget';\n",
"import { ITreeNode, ITreeRenderer } from 'vs/base/browser/ui/tree/tree';\n",
"import { IntervalTimer } from 'vs/base/common/async';\n",
"import { Codicon } from 'vs/base/common/codicons';\n",
"import { Emitter, Event } from 'vs/base/common/event';\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { IAction } from 'vs/base/common/actions';\n"
],
"file_path": "src/vs/workbench/contrib/interactiveSession/browser/interactiveSessionListRenderer.ts",
"type": "add",
"edit_start_line_idx": 10
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { deepStrictEqual, ok } from 'assert';
import { timeout } from 'vs/base/common/async';
import { Terminal } from 'xterm';
import { CommandDetectionCapability } from 'vs/platform/terminal/common/capabilities/commandDetectionCapability';
import { ILogService, NullLogService } from 'vs/platform/log/common/log';
import { ITerminalCommand } from 'vs/platform/terminal/common/capabilities/capabilities';
import { IContextMenuService } from 'vs/platform/contextview/browser/contextView';
import { TestInstantiationService } from 'vs/platform/instantiation/test/common/instantiationServiceMock';
import { IContextMenuDelegate } from 'vs/base/browser/contextmenu';
async function writeP(terminal: Terminal, data: string): Promise<void> {
return new Promise<void>((resolve, reject) => {
const failTimeout = timeout(2000);
failTimeout.then(() => reject('Writing to xterm is taking longer than 2 seconds'));
terminal.write(data, () => {
failTimeout.cancel();
resolve();
});
});
}
type TestTerminalCommandMatch = Pick<ITerminalCommand, 'command' | 'cwd' | 'exitCode'> & { marker: { line: number } };
class TestCommandDetectionCapability extends CommandDetectionCapability {
clearCommands() {
this._commands.length = 0;
}
}
suite('CommandDetectionCapability', () => {
let xterm: Terminal;
let capability: TestCommandDetectionCapability;
let addEvents: ITerminalCommand[];
function assertCommands(expectedCommands: TestTerminalCommandMatch[]) {
deepStrictEqual(capability.commands.map(e => e.command), expectedCommands.map(e => e.command));
deepStrictEqual(capability.commands.map(e => e.cwd), expectedCommands.map(e => e.cwd));
deepStrictEqual(capability.commands.map(e => e.exitCode), expectedCommands.map(e => e.exitCode));
deepStrictEqual(capability.commands.map(e => e.marker?.line), expectedCommands.map(e => e.marker?.line));
// Ensure timestamps are set and were captured recently
for (const command of capability.commands) {
ok(Math.abs(Date.now() - command.timestamp) < 2000);
}
deepStrictEqual(addEvents, capability.commands);
// Clear the commands to avoid re-asserting past commands
addEvents.length = 0;
capability.clearCommands();
}
async function printStandardCommand(prompt: string, command: string, output: string, cwd: string | undefined, exitCode: number) {
if (cwd !== undefined) {
capability.setCwd(cwd);
}
capability.handlePromptStart();
await writeP(xterm, `\r${prompt}`);
capability.handleCommandStart();
await writeP(xterm, command);
capability.handleCommandExecuted();
await writeP(xterm, `\r\n${output}\r\n`);
capability.handleCommandFinished(exitCode);
}
setup(() => {
xterm = new Terminal({ allowProposedApi: true, cols: 80 });
const instantiationService = new TestInstantiationService();
instantiationService.stub(IContextMenuService, { showContextMenu(delegate: IContextMenuDelegate): void { } } as Partial<IContextMenuService>);
instantiationService.stub(ILogService, new NullLogService());
capability = instantiationService.createInstance(TestCommandDetectionCapability, xterm);
addEvents = [];
capability.onCommandFinished(e => addEvents.push(e));
assertCommands([]);
});
test('should not add commands when no capability methods are triggered', async () => {
await writeP(xterm, 'foo\r\nbar\r\n');
assertCommands([]);
await writeP(xterm, 'baz\r\n');
assertCommands([]);
});
test('should add commands for expected capability method calls', async () => {
await printStandardCommand('$ ', 'echo foo', 'foo', undefined, 0);
assertCommands([{
command: 'echo foo',
exitCode: 0,
cwd: undefined,
marker: { line: 0 }
}]);
});
test('should trim the command when command executed appears on the following line', async () => {
await printStandardCommand('$ ', 'echo foo\r\n', 'foo', undefined, 0);
assertCommands([{
command: 'echo foo',
exitCode: 0,
cwd: undefined,
marker: { line: 0 }
}]);
});
suite('cwd', () => {
test('should add cwd to commands when it\'s set', async () => {
await printStandardCommand('$ ', 'echo foo', 'foo', '/home', 0);
await printStandardCommand('$ ', 'echo bar', 'bar', '/home/second', 0);
assertCommands([
{ command: 'echo foo', exitCode: 0, cwd: '/home', marker: { line: 0 } },
{ command: 'echo bar', exitCode: 0, cwd: '/home/second', marker: { line: 2 } }
]);
});
test('should add old cwd to commands if no cwd sequence is output', async () => {
await printStandardCommand('$ ', 'echo foo', 'foo', '/home', 0);
await printStandardCommand('$ ', 'echo bar', 'bar', undefined, 0);
assertCommands([
{ command: 'echo foo', exitCode: 0, cwd: '/home', marker: { line: 0 } },
{ command: 'echo bar', exitCode: 0, cwd: '/home', marker: { line: 2 } }
]);
});
test('should use an undefined cwd if it\'s not set initially', async () => {
await printStandardCommand('$ ', 'echo foo', 'foo', undefined, 0);
await printStandardCommand('$ ', 'echo bar', 'bar', '/home', 0);
assertCommands([
{ command: 'echo foo', exitCode: 0, cwd: undefined, marker: { line: 0 } },
{ command: 'echo bar', exitCode: 0, cwd: '/home', marker: { line: 2 } }
]);
});
});
});
| src/vs/workbench/contrib/terminal/test/browser/capabilities/commandDetectionCapability.test.ts | 0 | https://github.com/microsoft/vscode/commit/c2bf6225a12e7f7d8afada6ec39560bb38e5838a | [
0.00017539819236844778,
0.0001714107784209773,
0.00016522085934411734,
0.00017177117115352303,
0.0000033250171327381395
] |
{
"id": 7,
"code_window": [
"import { renderIcon } from 'vs/base/browser/ui/iconLabel/iconLabels';\n",
"import { IListVirtualDelegate } from 'vs/base/browser/ui/list/list';\n",
"import { IListAccessibilityProvider } from 'vs/base/browser/ui/list/listWidget';\n",
"import { ITreeNode, ITreeRenderer } from 'vs/base/browser/ui/tree/tree';\n",
"import { IntervalTimer } from 'vs/base/common/async';\n",
"import { Codicon } from 'vs/base/common/codicons';\n",
"import { Emitter, Event } from 'vs/base/common/event';\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { IAction } from 'vs/base/common/actions';\n"
],
"file_path": "src/vs/workbench/contrib/interactiveSession/browser/interactiveSessionListRenderer.ts",
"type": "add",
"edit_start_line_idx": 10
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { bufferToStream, streamToBuffer, VSBuffer } from 'vs/base/common/buffer';
import { CancellationToken } from 'vs/base/common/cancellation';
import { Event } from 'vs/base/common/event';
import { IChannel, IServerChannel } from 'vs/base/parts/ipc/common/ipc';
import { IHeaders, IRequestContext, IRequestOptions } from 'vs/base/parts/request/common/request';
import { IRequestService } from 'vs/platform/request/common/request';
type RequestResponse = [
{
headers: IHeaders;
statusCode?: number;
},
VSBuffer
];
export class RequestChannel implements IServerChannel {
constructor(private readonly service: IRequestService) { }
listen(context: any, event: string): Event<any> {
throw new Error('Invalid listen');
}
call(context: any, command: string, args?: any, token: CancellationToken = CancellationToken.None): Promise<any> {
switch (command) {
case 'request': return this.service.request(args[0], token)
.then(async ({ res, stream }) => {
const buffer = await streamToBuffer(stream);
return <RequestResponse>[{ statusCode: res.statusCode, headers: res.headers }, buffer];
});
case 'resolveProxy': return this.service.resolveProxy(args[0]);
}
throw new Error('Invalid call');
}
}
export class RequestChannelClient implements IRequestService {
declare readonly _serviceBrand: undefined;
constructor(private readonly channel: IChannel) { }
async request(options: IRequestOptions, token: CancellationToken): Promise<IRequestContext> {
const [res, buffer] = await this.channel.call<RequestResponse>('request', [options], token);
return { res, stream: bufferToStream(buffer) };
}
async resolveProxy(url: string): Promise<string | undefined> {
return this.channel.call<string | undefined>('resolveProxy', [url]);
}
}
| src/vs/platform/request/common/requestIpc.ts | 0 | https://github.com/microsoft/vscode/commit/c2bf6225a12e7f7d8afada6ec39560bb38e5838a | [
0.0001710476935841143,
0.00016802322352305055,
0.0001648303004913032,
0.0001686323812464252,
0.0000024303910777234705
] |
{
"id": 7,
"code_window": [
"import { renderIcon } from 'vs/base/browser/ui/iconLabel/iconLabels';\n",
"import { IListVirtualDelegate } from 'vs/base/browser/ui/list/list';\n",
"import { IListAccessibilityProvider } from 'vs/base/browser/ui/list/listWidget';\n",
"import { ITreeNode, ITreeRenderer } from 'vs/base/browser/ui/tree/tree';\n",
"import { IntervalTimer } from 'vs/base/common/async';\n",
"import { Codicon } from 'vs/base/common/codicons';\n",
"import { Emitter, Event } from 'vs/base/common/event';\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { IAction } from 'vs/base/common/actions';\n"
],
"file_path": "src/vs/workbench/contrib/interactiveSession/browser/interactiveSessionListRenderer.ts",
"type": "add",
"edit_start_line_idx": 10
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { TestConfigurationService } from 'vs/platform/configuration/test/common/testConfigurationService';
import { TestInstantiationService } from 'vs/platform/instantiation/test/common/instantiationServiceMock';
import { IProductService } from 'vs/platform/product/common/productService';
import { ITerminalSimpleLink, TerminalBuiltinLinkType } from 'vs/workbench/contrib/terminalContrib/links/browser/links';
import { TerminalWordLinkDetector } from 'vs/workbench/contrib/terminalContrib/links/browser/terminalWordLinkDetector';
import { assertLinkHelper } from 'vs/workbench/contrib/terminalContrib/links/test/browser/linkTestUtils';
import { TestProductService } from 'vs/workbench/test/common/workbenchTestServices';
import { Terminal } from 'xterm';
suite('Workbench - TerminalWordLinkDetector', () => {
let configurationService: TestConfigurationService;
let detector: TerminalWordLinkDetector;
let xterm: Terminal;
setup(async () => {
const instantiationService = new TestInstantiationService();
configurationService = new TestConfigurationService();
await configurationService.setUserConfiguration('terminal', { integrated: { wordSeparators: '' } });
instantiationService.stub(IConfigurationService, configurationService);
instantiationService.set(IProductService, TestProductService);
xterm = new Terminal({ allowProposedApi: true, cols: 80, rows: 30 });
detector = instantiationService.createInstance(TerminalWordLinkDetector, xterm);
});
async function assertLink(
text: string,
expected: (Pick<ITerminalSimpleLink, 'text'> & { range: [number, number][] })[]
) {
await assertLinkHelper(text, expected, detector, TerminalBuiltinLinkType.Search);
}
suite('should link words as defined by wordSeparators', () => {
test('" ()[]"', async () => {
await configurationService.setUserConfiguration('terminal', { integrated: { wordSeparators: ' ()[]' } });
configurationService.onDidChangeConfigurationEmitter.fire({ affectsConfiguration: () => true } as any);
await assertLink('foo', [{ range: [[1, 1], [3, 1]], text: 'foo' }]);
await assertLink(' foo ', [{ range: [[2, 1], [4, 1]], text: 'foo' }]);
await assertLink('(foo)', [{ range: [[2, 1], [4, 1]], text: 'foo' }]);
await assertLink('[foo]', [{ range: [[2, 1], [4, 1]], text: 'foo' }]);
await assertLink('{foo}', [{ range: [[1, 1], [5, 1]], text: '{foo}' }]);
});
test('" "', async () => {
await configurationService.setUserConfiguration('terminal', { integrated: { wordSeparators: ' ' } });
configurationService.onDidChangeConfigurationEmitter.fire({ affectsConfiguration: () => true } as any);
await assertLink('foo', [{ range: [[1, 1], [3, 1]], text: 'foo' }]);
await assertLink(' foo ', [{ range: [[2, 1], [4, 1]], text: 'foo' }]);
await assertLink('(foo)', [{ range: [[1, 1], [5, 1]], text: '(foo)' }]);
await assertLink('[foo]', [{ range: [[1, 1], [5, 1]], text: '[foo]' }]);
await assertLink('{foo}', [{ range: [[1, 1], [5, 1]], text: '{foo}' }]);
});
test('" []"', async () => {
await configurationService.setUserConfiguration('terminal', { integrated: { wordSeparators: ' []' } });
configurationService.onDidChangeConfigurationEmitter.fire({ affectsConfiguration: () => true } as any);
await assertLink('aabbccdd.txt ', [{ range: [[1, 1], [12, 1]], text: 'aabbccdd.txt' }]);
await assertLink(' aabbccdd.txt ', [{ range: [[2, 1], [13, 1]], text: 'aabbccdd.txt' }]);
await assertLink(' [aabbccdd.txt] ', [{ range: [[3, 1], [14, 1]], text: 'aabbccdd.txt' }]);
});
});
// These are failing - the link's start x is 1 px too far to the right bc it starts
// with a wide character, which the terminalLinkHelper currently doesn't account for
test.skip('should support wide characters', async () => {
await configurationService.setUserConfiguration('terminal', { integrated: { wordSeparators: ' []' } });
configurationService.onDidChangeConfigurationEmitter.fire({ affectsConfiguration: () => true } as any);
await assertLink('我是学生.txt ', [{ range: [[1, 1], [12, 1]], text: '我是学生.txt' }]);
await assertLink(' 我是学生.txt ', [{ range: [[2, 1], [13, 1]], text: '我是学生.txt' }]);
await assertLink(' [我是学生.txt] ', [{ range: [[3, 1], [14, 1]], text: '我是学生.txt' }]);
});
test('should support multiple link results', async () => {
await configurationService.setUserConfiguration('terminal', { integrated: { wordSeparators: ' ' } });
configurationService.onDidChangeConfigurationEmitter.fire({ affectsConfiguration: () => true } as any);
await assertLink('foo bar', [
{ range: [[1, 1], [3, 1]], text: 'foo' },
{ range: [[5, 1], [7, 1]], text: 'bar' }
]);
});
test('should remove trailing colon in the link results', async () => {
await configurationService.setUserConfiguration('terminal', { integrated: { wordSeparators: ' ' } });
configurationService.onDidChangeConfigurationEmitter.fire({ affectsConfiguration: () => true } as any);
await assertLink('foo:5:6: bar:0:32:', [
{ range: [[1, 1], [7, 1]], text: 'foo:5:6' },
{ range: [[10, 1], [17, 1]], text: 'bar:0:32' }
]);
});
test('should support wrapping', async () => {
await configurationService.setUserConfiguration('terminal', { integrated: { wordSeparators: ' ' } });
configurationService.onDidChangeConfigurationEmitter.fire({ affectsConfiguration: () => true } as any);
await assertLink('fsdjfsdkfjslkdfjskdfjsldkfjsdlkfjslkdjfskldjflskdfjskldjflskdfjsdklfjsdklfjsldkfjsdlkfjsdlkfjsdlkfjsldkfjslkdfjsdlkfjsldkfjsdlkfjskdfjsldkfjsdlkfjslkdfjsdlkfjsldkfjsldkfjsldkfjslkdfjsdlkfjslkdfjsdklfsd', [
{ range: [[1, 1], [41, 3]], text: 'fsdjfsdkfjslkdfjskdfjsldkfjsdlkfjslkdjfskldjflskdfjskldjflskdfjsdklfjsdklfjsldkfjsdlkfjsdlkfjsdlkfjsldkfjslkdfjsdlkfjsldkfjsdlkfjskdfjsldkfjsdlkfjslkdfjsdlkfjsldkfjsldkfjsldkfjslkdfjsdlkfjslkdfjsdklfsd' },
]);
});
test('should support wrapping with multiple links', async () => {
await configurationService.setUserConfiguration('terminal', { integrated: { wordSeparators: ' ' } });
configurationService.onDidChangeConfigurationEmitter.fire({ affectsConfiguration: () => true } as any);
await assertLink('fsdjfsdkfjslkdfjskdfjsldkfj sdlkfjslkdjfskldjflskdfjskldjflskdfj sdklfjsdklfjsldkfjsdlkfjsdlkfjsdlkfjsldkfjslkdfjsdlkfjsldkfjsdlkfjskdfjsldkfjsdlkfjslkdfjsdlkfjsldkfjsldkfjsldkfjslkdfjsdlkfjslkdfjsdklfsd', [
{ range: [[1, 1], [27, 1]], text: 'fsdjfsdkfjslkdfjskdfjsldkfj' },
{ range: [[29, 1], [64, 1]], text: 'sdlkfjslkdjfskldjflskdfjskldjflskdfj' },
{ range: [[66, 1], [43, 3]], text: 'sdklfjsdklfjsldkfjsdlkfjsdlkfjsdlkfjsldkfjslkdfjsdlkfjsldkfjsdlkfjskdfjsldkfjsdlkfjslkdfjsdlkfjsldkfjsldkfjsldkfjslkdfjsdlkfjslkdfjsdklfsd' }
]);
});
test('does not return any links for empty text', async () => {
await configurationService.setUserConfiguration('terminal', { integrated: { wordSeparators: ' ' } });
configurationService.onDidChangeConfigurationEmitter.fire({ affectsConfiguration: () => true } as any);
await assertLink('', []);
});
test('should support file scheme links', async () => {
await configurationService.setUserConfiguration('terminal', { integrated: { wordSeparators: ' ' } });
configurationService.onDidChangeConfigurationEmitter.fire({ affectsConfiguration: () => true } as any);
await assertLink('file:///C:/users/test/file.txt ', [{ range: [[1, 1], [30, 1]], text: 'file:///C:/users/test/file.txt' }]);
await assertLink('file:///C:/users/test/file.txt:1:10 ', [{ range: [[1, 1], [35, 1]], text: 'file:///C:/users/test/file.txt:1:10' }]);
});
});
| src/vs/workbench/contrib/terminalContrib/links/test/browser/terminalWordLinkDetector.test.ts | 0 | https://github.com/microsoft/vscode/commit/c2bf6225a12e7f7d8afada6ec39560bb38e5838a | [
0.00033554871333763003,
0.00018411136989016086,
0.00016632193000987172,
0.0001716872357064858,
0.000043759271648013964
] |
{
"id": 8,
"code_window": [
"import { ViewportSemanticTokensContribution } from 'vs/editor/contrib/semanticTokens/browser/viewportSemanticTokens';\n",
"import { SmartSelectController } from 'vs/editor/contrib/smartSelect/browser/smartSelect';\n",
"import { WordHighlighterContribution } from 'vs/editor/contrib/wordHighlighter/browser/wordHighlighter';\n",
"import { localize } from 'vs/nls';\n",
"import { MenuWorkbenchToolBar } from 'vs/platform/actions/browser/toolbar';\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep"
],
"after_edit": [
"import { IMenuEntryActionViewItemOptions, MenuEntryActionViewItem } from 'vs/platform/actions/browser/menuEntryActionViewItem';\n"
],
"file_path": "src/vs/workbench/contrib/interactiveSession/browser/interactiveSessionListRenderer.ts",
"type": "add",
"edit_start_line_idx": 33
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Codicon } from 'vs/base/common/codicons';
import { ServicesAccessor } from 'vs/editor/browser/editorExtensions';
import { localize } from 'vs/nls';
import { Action2, MenuId, registerAction2 } from 'vs/platform/actions/common/actions';
import { ContextKeyExpr } from 'vs/platform/contextkey/common/contextkey';
import { INTERACTIVE_SESSION_CATEGORY } from 'vs/workbench/contrib/interactiveSession/browser/actions/interactiveSessionActions';
import { CONTEXT_RESPONSE_HAS_PROVIDER_ID, CONTEXT_RESPONSE_VOTE } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionContextKeys';
import { IInteractiveSessionService, IInteractiveSessionUserActionEvent, InteractiveSessionVoteDirection } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionService';
import { isResponseVM } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionViewModel';
export function registerInteractiveSessionTitleActions() {
registerAction2(class VoteUpAction extends Action2 {
constructor() {
super({
id: 'workbench.action.interactiveSession.voteUp',
title: {
value: localize('interactive.voteUp.label', "Vote Up"),
original: 'Vote Up'
},
f1: false,
category: INTERACTIVE_SESSION_CATEGORY,
icon: Codicon.thumbsup,
precondition: CONTEXT_RESPONSE_VOTE.isEqualTo(''), // Should be disabled but visible when vote=down
menu: {
id: MenuId.InteractiveSessionTitle,
when: ContextKeyExpr.and(CONTEXT_RESPONSE_HAS_PROVIDER_ID, CONTEXT_RESPONSE_VOTE.notEqualsTo('down')),
group: 'navigation',
order: 1
}
});
}
run(accessor: ServicesAccessor, ...args: any[]) {
const item = args[0];
if (!isResponseVM(item)) {
return;
}
const interactiveSessionService = accessor.get(IInteractiveSessionService);
interactiveSessionService.notifyUserAction(<IInteractiveSessionUserActionEvent>{
providerId: item.providerId,
action: {
kind: 'vote',
direction: InteractiveSessionVoteDirection.Up,
responseId: item.providerResponseId
}
});
item.setVote(InteractiveSessionVoteDirection.Up);
}
});
registerAction2(class VoteDownAction extends Action2 {
constructor() {
super({
id: 'workbench.action.interactiveSession.voteDown',
title: {
value: localize('interactive.voteDown.label', "Vote Down"),
original: 'Vote Down'
},
f1: false,
category: INTERACTIVE_SESSION_CATEGORY,
icon: Codicon.thumbsdown,
precondition: CONTEXT_RESPONSE_VOTE.isEqualTo(''), // Should be disabled but visible when vote=down
menu: {
id: MenuId.InteractiveSessionTitle,
when: ContextKeyExpr.and(CONTEXT_RESPONSE_HAS_PROVIDER_ID, CONTEXT_RESPONSE_VOTE.notEqualsTo('up')),
group: 'navigation',
order: 2
}
});
}
run(accessor: ServicesAccessor, ...args: any[]) {
const item = args[0];
if (!isResponseVM(item)) {
return;
}
const interactiveSessionService = accessor.get(IInteractiveSessionService);
interactiveSessionService.notifyUserAction(<IInteractiveSessionUserActionEvent>{
providerId: item.providerId,
action: {
kind: 'vote',
direction: InteractiveSessionVoteDirection.Down,
responseId: item.providerResponseId
}
});
item.setVote(InteractiveSessionVoteDirection.Down);
}
});
}
| src/vs/workbench/contrib/interactiveSession/browser/actions/interactiveSessionTitleActions.ts | 1 | https://github.com/microsoft/vscode/commit/c2bf6225a12e7f7d8afada6ec39560bb38e5838a | [
0.0001717393024591729,
0.00016948084521573037,
0.00016451235569547862,
0.00016948128177318722,
0.000002024105242526275
] |
{
"id": 8,
"code_window": [
"import { ViewportSemanticTokensContribution } from 'vs/editor/contrib/semanticTokens/browser/viewportSemanticTokens';\n",
"import { SmartSelectController } from 'vs/editor/contrib/smartSelect/browser/smartSelect';\n",
"import { WordHighlighterContribution } from 'vs/editor/contrib/wordHighlighter/browser/wordHighlighter';\n",
"import { localize } from 'vs/nls';\n",
"import { MenuWorkbenchToolBar } from 'vs/platform/actions/browser/toolbar';\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep"
],
"after_edit": [
"import { IMenuEntryActionViewItemOptions, MenuEntryActionViewItem } from 'vs/platform/actions/browser/menuEntryActionViewItem';\n"
],
"file_path": "src/vs/workbench/contrib/interactiveSession/browser/interactiveSessionListRenderer.ts",
"type": "add",
"edit_start_line_idx": 33
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as vscode from 'vscode';
import { memoize } from './memoize';
type LogLevel = 'Trace' | 'Info' | 'Error';
export class Logger {
@memoize
private get output(): vscode.OutputChannel {
return vscode.window.createOutputChannel('TypeScript');
}
private data2String(data: any): string {
if (data instanceof Error) {
return data.stack || data.message;
}
if (data.success === false && data.message) {
return data.message;
}
return data.toString();
}
public info(message: string, data?: any): void {
this.logLevel('Info', message, data);
}
public error(message: string, data?: any): void {
// See https://github.com/microsoft/TypeScript/issues/10496
if (data && data.message === 'No content available.') {
return;
}
this.logLevel('Error', message, data);
}
public logLevel(level: LogLevel, message: string, data?: any): void {
this.output.appendLine(`[${level} - ${this.now()}] ${message}`);
if (data) {
this.output.appendLine(this.data2String(data));
}
}
private now(): string {
const now = new Date();
return padLeft(now.getUTCHours() + '', 2, '0')
+ ':' + padLeft(now.getMinutes() + '', 2, '0')
+ ':' + padLeft(now.getUTCSeconds() + '', 2, '0') + '.' + now.getMilliseconds();
}
}
function padLeft(s: string, n: number, pad = ' ') {
return pad.repeat(Math.max(0, n - s.length)) + s;
}
| extensions/typescript-language-features/src/utils/logger.ts | 0 | https://github.com/microsoft/vscode/commit/c2bf6225a12e7f7d8afada6ec39560bb38e5838a | [
0.00018597822054289281,
0.00017094520444516093,
0.00016497120668645948,
0.00016894013970158994,
0.000007034485861368012
] |
{
"id": 8,
"code_window": [
"import { ViewportSemanticTokensContribution } from 'vs/editor/contrib/semanticTokens/browser/viewportSemanticTokens';\n",
"import { SmartSelectController } from 'vs/editor/contrib/smartSelect/browser/smartSelect';\n",
"import { WordHighlighterContribution } from 'vs/editor/contrib/wordHighlighter/browser/wordHighlighter';\n",
"import { localize } from 'vs/nls';\n",
"import { MenuWorkbenchToolBar } from 'vs/platform/actions/browser/toolbar';\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep"
],
"after_edit": [
"import { IMenuEntryActionViewItemOptions, MenuEntryActionViewItem } from 'vs/platform/actions/browser/menuEntryActionViewItem';\n"
],
"file_path": "src/vs/workbench/contrib/interactiveSession/browser/interactiveSessionListRenderer.ts",
"type": "add",
"edit_start_line_idx": 33
} | <!DOCTYPE html>
<html>
<head id='headID'>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>Strada </title>
<link href="site.css" rel="stylesheet" type="text/css" />
<script src="jquery-1.4.1.js"></script>
<script src="../compiler/dtree.js" type="text/javascript"></script>
<script src="../compiler/typescript.js" type="text/javascript"></script>
<script type="text/javascript">
// Compile strada source into resulting javascript
function compile(prog, libText) {
var outfile = {
source: "",
Write: function (s) { this.source += s; },
WriteLine: function (s) { this.source += s + "\r"; },
}
var parseErrors = []
var compiler=new Tools.TypeScriptCompiler(outfile,true);
compiler.setErrorCallback(function(start,len, message) { parseErrors.push({start:start, len:len, message:message}); });
compiler.addUnit(libText,"lib.ts");
compiler.addUnit(prog,"input.ts");
compiler.typeCheck();
compiler.emit();
if(parseErrors.length > 0 ) {
//throw new Error(parseErrors);
}
while(outfile.source[0] == '/' && outfile.source[1] == '/' && outfile.source[2] == ' ') {
outfile.source = outfile.source.slice(outfile.source.indexOf('\r')+1);
}
var errorPrefix = "";
for(var i = 0;i<parseErrors.length;i++) {
errorPrefix += "// Error: (" + parseErrors[i].start + "," + parseErrors[i].len + ") " + parseErrors[i].message + "\r";
}
return errorPrefix + outfile.source;
}
</script>
<script type="text/javascript">
var libText = "";
$.get("../compiler/lib.ts", function(newLibText) {
libText = newLibText;
});
// execute the javascript in the compiledOutput pane
function execute() {
$('#compilation').text("Running...");
var txt = $('#compiledOutput').val();
var res;
try {
var ret = eval(txt);
res = "Ran successfully!";
} catch(e) {
res = "Exception thrown: " + e;
}
$('#compilation').text(String(res));
}
// recompile the stradaSrc and populate the compiledOutput pane
function srcUpdated() {
var newText = $('#stradaSrc').val();
var compiledSource;
try {
compiledSource = compile(newText, libText);
} catch (e) {
compiledSource = "//Parse error"
for(var i in e)
compiledSource += "\r// " + e[i];
}
$('#compiledOutput').val(compiledSource);
}
// Populate the stradaSrc pane with one of the built in samples
function exampleSelectionChanged() {
var examples = document.getElementById('examples');
var selectedExample = examples.options[examples.selectedIndex].value;
if (selectedExample != "") {
$.get('examples/' + selectedExample, function (srcText) {
$('#stradaSrc').val(srcText);
setTimeout(srcUpdated,100);
}, function (err) {
console.log(err);
});
}
}
</script>
</head>
<body>
<h1>TypeScript</h1>
<br />
<select id="examples" onchange='exampleSelectionChanged()'>
<option value="">Select...</option>
<option value="small.ts">Small</option>
<option value="employee.ts">Employees</option>
<option value="conway.ts">Conway Game of Life</option>
<option value="typescript.ts">TypeScript Compiler</option>
</select>
<div>
<textarea id='stradaSrc' rows='40' cols='80' onchange='srcUpdated()' onkeyup='srcUpdated()' spellcheck="false">
//Type your TypeScript here...
</textarea>
<textarea id='compiledOutput' rows='40' cols='80' spellcheck="false">
//Compiled code will show up here...
</textarea>
<br />
<button onclick='execute()'/>Run</button>
<div id='compilation'>Press 'run' to execute code...</div>
<div id='results'>...write your results into #results...</div>
</div>
<div id='bod' style='display:none'></div>
</body>
</html>
| src/vs/base/test/node/pfs/fixtures/index.html | 0 | https://github.com/microsoft/vscode/commit/c2bf6225a12e7f7d8afada6ec39560bb38e5838a | [
0.00017849904543254524,
0.00017351433052681386,
0.0001681551366345957,
0.0001737217971822247,
0.0000025453987291257363
] |
{
"id": 8,
"code_window": [
"import { ViewportSemanticTokensContribution } from 'vs/editor/contrib/semanticTokens/browser/viewportSemanticTokens';\n",
"import { SmartSelectController } from 'vs/editor/contrib/smartSelect/browser/smartSelect';\n",
"import { WordHighlighterContribution } from 'vs/editor/contrib/wordHighlighter/browser/wordHighlighter';\n",
"import { localize } from 'vs/nls';\n",
"import { MenuWorkbenchToolBar } from 'vs/platform/actions/browser/toolbar';\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep"
],
"after_edit": [
"import { IMenuEntryActionViewItemOptions, MenuEntryActionViewItem } from 'vs/platform/actions/browser/menuEntryActionViewItem';\n"
],
"file_path": "src/vs/workbench/contrib/interactiveSession/browser/interactiveSessionListRenderer.ts",
"type": "add",
"edit_start_line_idx": 33
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { localize } from 'vs/nls';
import { BaseBinaryResourceEditor } from 'vs/workbench/browser/parts/editor/binaryEditor';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { IThemeService } from 'vs/platform/theme/common/themeService';
import { EditorInput } from 'vs/workbench/common/editor/editorInput';
import { FileEditorInput } from 'vs/workbench/contrib/files/browser/editors/fileEditorInput';
import { BINARY_FILE_EDITOR_ID, BINARY_TEXT_FILE_MODE } from 'vs/workbench/contrib/files/common/files';
import { IStorageService } from 'vs/platform/storage/common/storage';
import { EditorResolution, IEditorOptions } from 'vs/platform/editor/common/editor';
import { IEditorResolverService, ResolvedStatus, ResolvedEditor } from 'vs/workbench/services/editor/common/editorResolverService';
import { isEditorInputWithOptions } from 'vs/workbench/common/editor';
import { DiffEditorInput } from 'vs/workbench/common/editor/diffEditorInput';
import { IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService';
/**
* An implementation of editor for binary files that cannot be displayed.
*/
export class BinaryFileEditor extends BaseBinaryResourceEditor {
static readonly ID = BINARY_FILE_EDITOR_ID;
constructor(
@ITelemetryService telemetryService: ITelemetryService,
@IThemeService themeService: IThemeService,
@IEditorResolverService private readonly editorResolverService: IEditorResolverService,
@IStorageService storageService: IStorageService,
@IEditorGroupsService private readonly editorGroupService: IEditorGroupsService
) {
super(
BinaryFileEditor.ID,
{
openInternal: (input, options) => this.openInternal(input, options)
},
telemetryService,
themeService,
storageService
);
}
private async openInternal(input: EditorInput, options: IEditorOptions | undefined): Promise<void> {
if (input instanceof FileEditorInput && this.group?.activeEditor) {
// We operate on the active editor here to support re-opening
// diff editors where `input` may just be one side of the
// diff editor.
// Since `openInternal` can only ever be selected from the
// active editor of the group, this is a safe assumption.
// (https://github.com/microsoft/vscode/issues/124222)
const activeEditor = this.group.activeEditor;
const untypedActiveEditor = activeEditor?.toUntyped();
if (!untypedActiveEditor) {
return; // we need untyped editor support
}
// Try to let the user pick an editor
let resolvedEditor: ResolvedEditor | undefined = await this.editorResolverService.resolveEditor({
...untypedActiveEditor,
options: {
...options,
override: EditorResolution.PICK
}
}, this.group);
if (resolvedEditor === ResolvedStatus.NONE) {
resolvedEditor = undefined;
} else if (resolvedEditor === ResolvedStatus.ABORT) {
return;
}
// If the result if a file editor, the user indicated to open
// the binary file as text. As such we adjust the input for that.
if (isEditorInputWithOptions(resolvedEditor)) {
for (const editor of resolvedEditor.editor instanceof DiffEditorInput ? [resolvedEditor.editor.original, resolvedEditor.editor.modified] : [resolvedEditor.editor]) {
if (editor instanceof FileEditorInput) {
editor.setForceOpenAsText();
editor.setPreferredLanguageId(BINARY_TEXT_FILE_MODE); // https://github.com/microsoft/vscode/issues/131076
}
}
}
// Replace the active editor with the picked one
await (this.group ?? this.editorGroupService.activeGroup).replaceEditors([{
editor: activeEditor,
replacement: resolvedEditor?.editor ?? input,
options: {
...resolvedEditor?.options ?? options
}
}]);
}
}
override getTitle(): string {
return this.input ? this.input.getName() : localize('binaryFileEditor', "Binary File Viewer");
}
}
| src/vs/workbench/contrib/files/browser/editors/binaryFileEditor.ts | 0 | https://github.com/microsoft/vscode/commit/c2bf6225a12e7f7d8afada6ec39560bb38e5838a | [
0.00017372063302900642,
0.00016901659546419978,
0.00016375580162275583,
0.000169283666764386,
0.0000030873222840455128
] |
{
"id": 9,
"code_window": [
"import { MenuWorkbenchToolBar } from 'vs/platform/actions/browser/toolbar';\n",
"import { MenuId } from 'vs/platform/actions/common/actions';\n",
"import { ICommandService } from 'vs/platform/commands/common/commands';\n",
"import { IConfigurationService } from 'vs/platform/configuration/common/configuration';\n",
"import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey';\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { MenuId, MenuItemAction } from 'vs/platform/actions/common/actions';\n"
],
"file_path": "src/vs/workbench/contrib/interactiveSession/browser/interactiveSessionListRenderer.ts",
"type": "replace",
"edit_start_line_idx": 34
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Codicon } from 'vs/base/common/codicons';
import { ServicesAccessor } from 'vs/editor/browser/editorExtensions';
import { localize } from 'vs/nls';
import { Action2, MenuId, registerAction2 } from 'vs/platform/actions/common/actions';
import { ContextKeyExpr } from 'vs/platform/contextkey/common/contextkey';
import { INTERACTIVE_SESSION_CATEGORY } from 'vs/workbench/contrib/interactiveSession/browser/actions/interactiveSessionActions';
import { CONTEXT_RESPONSE_HAS_PROVIDER_ID, CONTEXT_RESPONSE_VOTE } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionContextKeys';
import { IInteractiveSessionService, IInteractiveSessionUserActionEvent, InteractiveSessionVoteDirection } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionService';
import { isResponseVM } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionViewModel';
export function registerInteractiveSessionTitleActions() {
registerAction2(class VoteUpAction extends Action2 {
constructor() {
super({
id: 'workbench.action.interactiveSession.voteUp',
title: {
value: localize('interactive.voteUp.label', "Vote Up"),
original: 'Vote Up'
},
f1: false,
category: INTERACTIVE_SESSION_CATEGORY,
icon: Codicon.thumbsup,
precondition: CONTEXT_RESPONSE_VOTE.isEqualTo(''), // Should be disabled but visible when vote=down
menu: {
id: MenuId.InteractiveSessionTitle,
when: ContextKeyExpr.and(CONTEXT_RESPONSE_HAS_PROVIDER_ID, CONTEXT_RESPONSE_VOTE.notEqualsTo('down')),
group: 'navigation',
order: 1
}
});
}
run(accessor: ServicesAccessor, ...args: any[]) {
const item = args[0];
if (!isResponseVM(item)) {
return;
}
const interactiveSessionService = accessor.get(IInteractiveSessionService);
interactiveSessionService.notifyUserAction(<IInteractiveSessionUserActionEvent>{
providerId: item.providerId,
action: {
kind: 'vote',
direction: InteractiveSessionVoteDirection.Up,
responseId: item.providerResponseId
}
});
item.setVote(InteractiveSessionVoteDirection.Up);
}
});
registerAction2(class VoteDownAction extends Action2 {
constructor() {
super({
id: 'workbench.action.interactiveSession.voteDown',
title: {
value: localize('interactive.voteDown.label', "Vote Down"),
original: 'Vote Down'
},
f1: false,
category: INTERACTIVE_SESSION_CATEGORY,
icon: Codicon.thumbsdown,
precondition: CONTEXT_RESPONSE_VOTE.isEqualTo(''), // Should be disabled but visible when vote=down
menu: {
id: MenuId.InteractiveSessionTitle,
when: ContextKeyExpr.and(CONTEXT_RESPONSE_HAS_PROVIDER_ID, CONTEXT_RESPONSE_VOTE.notEqualsTo('up')),
group: 'navigation',
order: 2
}
});
}
run(accessor: ServicesAccessor, ...args: any[]) {
const item = args[0];
if (!isResponseVM(item)) {
return;
}
const interactiveSessionService = accessor.get(IInteractiveSessionService);
interactiveSessionService.notifyUserAction(<IInteractiveSessionUserActionEvent>{
providerId: item.providerId,
action: {
kind: 'vote',
direction: InteractiveSessionVoteDirection.Down,
responseId: item.providerResponseId
}
});
item.setVote(InteractiveSessionVoteDirection.Down);
}
});
}
| src/vs/workbench/contrib/interactiveSession/browser/actions/interactiveSessionTitleActions.ts | 1 | https://github.com/microsoft/vscode/commit/c2bf6225a12e7f7d8afada6ec39560bb38e5838a | [
0.00025106564862653613,
0.00017871070303954184,
0.0001650122576393187,
0.00016917107859626412,
0.000024938995920820162
] |
{
"id": 9,
"code_window": [
"import { MenuWorkbenchToolBar } from 'vs/platform/actions/browser/toolbar';\n",
"import { MenuId } from 'vs/platform/actions/common/actions';\n",
"import { ICommandService } from 'vs/platform/commands/common/commands';\n",
"import { IConfigurationService } from 'vs/platform/configuration/common/configuration';\n",
"import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey';\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { MenuId, MenuItemAction } from 'vs/platform/actions/common/actions';\n"
],
"file_path": "src/vs/workbench/contrib/interactiveSession/browser/interactiveSessionListRenderer.ts",
"type": "replace",
"edit_start_line_idx": 34
} | #!/usr/bin/env bash
#
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Deregister code from the alternatives system
update-alternatives --remove editor /usr/bin/@@NAME@@ | resources/linux/debian/prerm.template | 0 | https://github.com/microsoft/vscode/commit/c2bf6225a12e7f7d8afada6ec39560bb38e5838a | [
0.00017330865375697613,
0.00017330865375697613,
0.00017330865375697613,
0.00017330865375697613,
0
] |
{
"id": 9,
"code_window": [
"import { MenuWorkbenchToolBar } from 'vs/platform/actions/browser/toolbar';\n",
"import { MenuId } from 'vs/platform/actions/common/actions';\n",
"import { ICommandService } from 'vs/platform/commands/common/commands';\n",
"import { IConfigurationService } from 'vs/platform/configuration/common/configuration';\n",
"import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey';\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { MenuId, MenuItemAction } from 'vs/platform/actions/common/actions';\n"
],
"file_path": "src/vs/workbench/contrib/interactiveSession/browser/interactiveSessionListRenderer.ts",
"type": "replace",
"edit_start_line_idx": 34
} | # Setup
0. Clone, and then run `git submodule update --init --recursive`
1. Get the extensions: [rust-analyzer](https://marketplace.visualstudio.com/items?itemName=rust-lang.rust-analyzer) and [CodeLLDB](https://marketplace.visualstudio.com/items?itemName=vadimcn.vscode-lldb)
2. Ensure your workspace is set to the `launcher` folder being the root.
## Building the CLI on Windows
For the moment, we require OpenSSL on Windows, where it is not usually installed by default. To install it:
1. Install (clone) vcpkg [using their instructions](https://github.com/Microsoft/vcpkg#quick-start-windows)
1. Add the location of the `vcpkg` directory to your system or user PATH.
1. Run`vcpkg install openssl:x64-windows-static-md` (after restarting your terminal for PATH changes to apply)
1. You should be able to then `cargo build` successfully
OpenSSL is needed for the key exchange we do when forwarding Basis tunnels. When all interested Basis clients support ED25519, we would be able to solely use libsodium. At the time of writing however, there is [no active development](https://chromestatus.com/feature/4913922408710144) on this in Chromium.
# Debug
1. You can use the Debug tasks already configured to run the launcher.
| cli/CONTRIBUTING.md | 0 | https://github.com/microsoft/vscode/commit/c2bf6225a12e7f7d8afada6ec39560bb38e5838a | [
0.0001698761188890785,
0.00016582613170612603,
0.0001607463345862925,
0.00016685598529875278,
0.000003797689487328171
] |
{
"id": 9,
"code_window": [
"import { MenuWorkbenchToolBar } from 'vs/platform/actions/browser/toolbar';\n",
"import { MenuId } from 'vs/platform/actions/common/actions';\n",
"import { ICommandService } from 'vs/platform/commands/common/commands';\n",
"import { IConfigurationService } from 'vs/platform/configuration/common/configuration';\n",
"import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey';\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { MenuId, MenuItemAction } from 'vs/platform/actions/common/actions';\n"
],
"file_path": "src/vs/workbench/contrib/interactiveSession/browser/interactiveSessionListRenderer.ts",
"type": "replace",
"edit_start_line_idx": 34
} | /*---------------------------------------------------------------------------------------------
* 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 { URI } from 'vs/base/common/uri';
import { MainThreadDocumentContentProviders } from 'vs/workbench/api/browser/mainThreadDocumentContentProviders';
import { createTextModel } from 'vs/editor/test/common/testTextModel';
import { mock } from 'vs/base/test/common/mock';
import { IModelService } from 'vs/editor/common/services/model';
import { IEditorWorkerService } from 'vs/editor/common/services/editorWorker';
import { TestRPCProtocol } from 'vs/workbench/api/test/common/testRPCProtocol';
import { TextEdit } from 'vs/editor/common/languages';
suite('MainThreadDocumentContentProviders', function () {
test('events are processed properly', function () {
const uri = URI.parse('test:uri');
const model = createTextModel('1', undefined, undefined, uri);
const providers = new MainThreadDocumentContentProviders(new TestRPCProtocol(), null!, null!,
new class extends mock<IModelService>() {
override getModel(_uri: URI) {
assert.strictEqual(uri.toString(), _uri.toString());
return model;
}
},
new class extends mock<IEditorWorkerService>() {
override computeMoreMinimalEdits(_uri: URI, data: TextEdit[] | undefined) {
assert.strictEqual(model.getValue(), '1');
return Promise.resolve(data);
}
},
);
return new Promise<void>((resolve, reject) => {
let expectedEvents = 1;
model.onDidChangeContent(e => {
expectedEvents -= 1;
try {
assert.ok(expectedEvents >= 0);
} catch (err) {
reject(err);
}
if (model.getValue() === '1\n2\n3') {
model.dispose();
resolve();
}
});
providers.$onVirtualDocumentChange(uri, '1\n2');
providers.$onVirtualDocumentChange(uri, '1\n2\n3');
});
});
});
| src/vs/workbench/api/test/browser/mainThreadDocumentContentProviders.test.ts | 0 | https://github.com/microsoft/vscode/commit/c2bf6225a12e7f7d8afada6ec39560bb38e5838a | [
0.00017620129801798612,
0.00017120926349889487,
0.00016648219025228173,
0.00017128977924585342,
0.000004042452474095626
] |
{
"id": 10,
"code_window": [
"\t\tconst titleToolbar = templateDisposables.add(scopedInstantiationService.createInstance(MenuWorkbenchToolBar, header, MenuId.InteractiveSessionTitle, {\n",
"\t\t\tmenuOptions: {\n",
"\t\t\t\tshouldForwardArgs: true\n",
"\t\t\t}\n",
"\t\t}));\n",
"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t},\n",
"\t\t\tactionViewItemProvider: (action: IAction, options: IActionViewItemOptions) => {\n",
"\t\t\t\tif (action instanceof MenuItemAction) {\n",
"\t\t\t\t\treturn scopedInstantiationService.createInstance(InteractiveSessionVoteButton, action, options as IMenuEntryActionViewItemOptions);\n",
"\t\t\t\t}\n",
"\n",
"\t\t\t\treturn undefined;\n"
],
"file_path": "src/vs/workbench/contrib/interactiveSession/browser/interactiveSessionListRenderer.ts",
"type": "add",
"edit_start_line_idx": 170
} | /*---------------------------------------------------------------------------------------------
* 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 { renderIcon } from 'vs/base/browser/ui/iconLabel/iconLabels';
import { IListVirtualDelegate } from 'vs/base/browser/ui/list/list';
import { IListAccessibilityProvider } from 'vs/base/browser/ui/list/listWidget';
import { ITreeNode, ITreeRenderer } from 'vs/base/browser/ui/tree/tree';
import { IntervalTimer } from 'vs/base/common/async';
import { Codicon } from 'vs/base/common/codicons';
import { Emitter, Event } from 'vs/base/common/event';
import { FuzzyScore } from 'vs/base/common/filters';
import { IMarkdownString, MarkdownString } from 'vs/base/common/htmlContent';
import { Disposable, DisposableStore, IDisposable } from 'vs/base/common/lifecycle';
import { ResourceMap } from 'vs/base/common/map';
import { FileAccess } from 'vs/base/common/network';
import { ThemeIcon } from 'vs/base/common/themables';
import { EditorExtensionsRegistry } from 'vs/editor/browser/editorExtensions';
import { CodeEditorWidget } from 'vs/editor/browser/widget/codeEditorWidget';
import { EDITOR_FONT_DEFAULTS, IEditorOptions } from 'vs/editor/common/config/editorOptions';
import { Range } from 'vs/editor/common/core/range';
import { ILanguageService } from 'vs/editor/common/languages/language';
import { ITextModel } from 'vs/editor/common/model';
import { IModelService } from 'vs/editor/common/services/model';
import { BracketMatchingController } from 'vs/editor/contrib/bracketMatching/browser/bracketMatching';
import { ContextMenuController } from 'vs/editor/contrib/contextmenu/browser/contextmenu';
import { IMarkdownRenderResult, MarkdownRenderer } from 'vs/editor/contrib/markdownRenderer/browser/markdownRenderer';
import { ViewportSemanticTokensContribution } from 'vs/editor/contrib/semanticTokens/browser/viewportSemanticTokens';
import { SmartSelectController } from 'vs/editor/contrib/smartSelect/browser/smartSelect';
import { WordHighlighterContribution } from 'vs/editor/contrib/wordHighlighter/browser/wordHighlighter';
import { localize } from 'vs/nls';
import { MenuWorkbenchToolBar } from 'vs/platform/actions/browser/toolbar';
import { MenuId } from 'vs/platform/actions/common/actions';
import { ICommandService } from 'vs/platform/commands/common/commands';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection';
import { ILogService } from 'vs/platform/log/common/log';
import { defaultButtonStyles } from 'vs/platform/theme/browser/defaultStyles';
import { MenuPreventer } from 'vs/workbench/contrib/codeEditor/browser/menuPreventer';
import { SelectionClipboardContributionID } from 'vs/workbench/contrib/codeEditor/browser/selectionClipboard';
import { getSimpleEditorOptions } from 'vs/workbench/contrib/codeEditor/browser/simpleEditorOptions';
import { IInteractiveSessionCodeBlockActionContext } from 'vs/workbench/contrib/interactiveSession/browser/actions/interactiveSessionCodeblockActions';
import { InteractiveSessionFollowups } from 'vs/workbench/contrib/interactiveSession/browser/interactiveSessionFollowups';
import { InteractiveSessionEditorOptions } from 'vs/workbench/contrib/interactiveSession/browser/interactiveSessionOptions';
import { CONTEXT_RESPONSE_HAS_PROVIDER_ID, CONTEXT_RESPONSE_VOTE } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionContextKeys';
import { IInteractiveSessionReplyFollowup, IInteractiveSessionService, IInteractiveSlashCommand, InteractiveSessionVoteDirection } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionService';
import { IInteractiveRequestViewModel, IInteractiveResponseViewModel, IInteractiveWelcomeMessageViewModel, isRequestVM, isResponseVM, isWelcomeVM } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionViewModel';
import { getNWords } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionWordCounter';
const $ = dom.$;
export type InteractiveTreeItem = IInteractiveRequestViewModel | IInteractiveResponseViewModel | IInteractiveWelcomeMessageViewModel;
interface IInteractiveListItemTemplate {
rowContainer: HTMLElement;
titleToolbar: MenuWorkbenchToolBar;
avatar: HTMLElement;
username: HTMLElement;
value: HTMLElement;
contextKeyService: IContextKeyService;
templateDisposables: IDisposable;
elementDisposables: DisposableStore;
}
interface IItemHeightChangeParams {
element: InteractiveTreeItem;
height: number;
}
const forceVerboseLayoutTracing = false;
export interface IInteractiveSessionRendererDelegate {
getListLength(): number;
getSlashCommands(): IInteractiveSlashCommand[];
}
export class InteractiveListItemRenderer extends Disposable implements ITreeRenderer<InteractiveTreeItem, FuzzyScore, IInteractiveListItemTemplate> {
static readonly cursorCharacter = '\u258c';
static readonly ID = 'item';
private readonly renderer: MarkdownRenderer;
protected readonly _onDidClickFollowup = this._register(new Emitter<IInteractiveSessionReplyFollowup>());
readonly onDidClickFollowup: Event<IInteractiveSessionReplyFollowup> = this._onDidClickFollowup.event;
protected readonly _onDidChangeItemHeight = this._register(new Emitter<IItemHeightChangeParams>());
readonly onDidChangeItemHeight: Event<IItemHeightChangeParams> = this._onDidChangeItemHeight.event;
private readonly _editorPool: EditorPool;
private _currentLayoutWidth: number = 0;
constructor(
private readonly editorOptions: InteractiveSessionEditorOptions,
private readonly delegate: IInteractiveSessionRendererDelegate,
@IInstantiationService private readonly instantiationService: IInstantiationService,
@IConfigurationService private readonly configService: IConfigurationService,
@ILogService private readonly logService: ILogService,
@ICommandService private readonly commandService: ICommandService,
@IContextKeyService private readonly contextKeyService: IContextKeyService,
@IInteractiveSessionService private readonly interactiveSessionService: IInteractiveSessionService,
) {
super();
this.renderer = this.instantiationService.createInstance(MarkdownRenderer, {});
this._editorPool = this._register(this.instantiationService.createInstance(EditorPool, this.editorOptions));
}
get templateId(): string {
return InteractiveListItemRenderer.ID;
}
private traceLayout(method: string, message: string) {
if (forceVerboseLayoutTracing) {
this.logService.info(`InteractiveListItemRenderer#${method}: ${message}`);
} else {
this.logService.trace(`InteractiveListItemRenderer#${method}: ${message}`);
}
}
private shouldRenderProgressively(element: IInteractiveResponseViewModel): boolean {
return !this.configService.getValue('interactive.experimental.disableProgressiveRendering') && element.progressiveResponseRenderingEnabled;
}
private getProgressiveRenderRate(element: IInteractiveResponseViewModel): number {
const configuredRate = this.configService.getValue('interactive.experimental.progressiveRenderingRate');
if (typeof configuredRate === 'number') {
return configuredRate;
}
if (element.isComplete) {
return 60;
}
if (element.contentUpdateTimings && element.contentUpdateTimings.impliedWordLoadRate) {
// This doesn't account for dead time after the last update. When the previous update is the final one and the model is only waiting for followupQuestions, that's good.
// When there was one quick update and then you are waiting longer for the next one, that's not good since the rate should be decreasing.
// If it's an issue, we can change this to be based on the total time from now to the beginning.
const rateBoost = 1.5;
return element.contentUpdateTimings.impliedWordLoadRate * rateBoost;
}
return 8;
}
layout(width: number): void {
this._currentLayoutWidth = width - 40; // TODO Padding
this._editorPool.inUse.forEach(editor => {
editor.layout(this._currentLayoutWidth);
});
}
renderTemplate(container: HTMLElement): IInteractiveListItemTemplate {
const templateDisposables = new DisposableStore();
const rowContainer = dom.append(container, $('.interactive-item-container'));
const header = dom.append(rowContainer, $('.header'));
const user = dom.append(header, $('.user'));
const avatar = dom.append(user, $('.avatar'));
const username = dom.append(user, $('h3.username'));
const value = dom.append(rowContainer, $('.value'));
const elementDisposables = new DisposableStore();
const contextKeyService = templateDisposables.add(this.contextKeyService.createScoped(rowContainer));
const scopedInstantiationService = this.instantiationService.createChild(new ServiceCollection([IContextKeyService, contextKeyService]));
const titleToolbar = templateDisposables.add(scopedInstantiationService.createInstance(MenuWorkbenchToolBar, header, MenuId.InteractiveSessionTitle, {
menuOptions: {
shouldForwardArgs: true
}
}));
const template: IInteractiveListItemTemplate = { avatar, username, value, rowContainer, elementDisposables, titleToolbar, templateDisposables, contextKeyService };
return template;
}
renderElement(node: ITreeNode<InteractiveTreeItem, FuzzyScore>, index: number, templateData: IInteractiveListItemTemplate): void {
const { element } = node;
const kind = isRequestVM(element) ? 'request' :
isResponseVM(element) ? 'response' :
'welcome';
this.traceLayout('renderElement', `${kind}, index=${index}`);
CONTEXT_RESPONSE_HAS_PROVIDER_ID.bindTo(templateData.contextKeyService).set(isResponseVM(element) && !!element.providerResponseId && !element.isPlaceholder);
if (isResponseVM(element)) {
CONTEXT_RESPONSE_VOTE.bindTo(templateData.contextKeyService).set(element.vote === InteractiveSessionVoteDirection.Up ? 'up' : element.vote === InteractiveSessionVoteDirection.Down ? 'down' : '');
} else {
CONTEXT_RESPONSE_VOTE.bindTo(templateData.contextKeyService).set('');
}
templateData.titleToolbar.context = element;
templateData.rowContainer.classList.toggle('interactive-request', isRequestVM(element));
templateData.rowContainer.classList.toggle('interactive-response', isResponseVM(element));
templateData.rowContainer.classList.toggle('interactive-welcome', isWelcomeVM(element));
templateData.rowContainer.classList.toggle('filtered-response', !!(isResponseVM(element) && element.errorDetails?.responseIsFiltered));
templateData.username.textContent = element.username;
if (element.avatarIconUri) {
const avatarIcon = dom.$<HTMLImageElement>('img.icon');
avatarIcon.src = FileAccess.uriToBrowserUri(element.avatarIconUri).toString(true);
templateData.avatar.replaceChildren(avatarIcon);
} else {
const defaultIcon = isRequestVM(element) ? Codicon.account : Codicon.hubot;
const avatarIcon = dom.$(ThemeIcon.asCSSSelector(defaultIcon));
templateData.avatar.replaceChildren(avatarIcon);
}
// Do a progressive render if
// - This the last response in the list
// - And the response is not complete
// - Or, we previously started a progressive rendering of this element (if the element is complete, we will finish progressive rendering with a very fast rate)
// - And, the feature is not disabled in configuration
if (isResponseVM(element) && index === this.delegate.getListLength() - 1 && (!element.isComplete || element.renderData) && this.shouldRenderProgressively(element)) {
this.traceLayout('renderElement', `start progressive render ${kind}, index=${index}`);
const progressiveRenderingDisposables = templateData.elementDisposables.add(new DisposableStore());
const timer = templateData.elementDisposables.add(new IntervalTimer());
const runProgressiveRender = (initial?: boolean) => {
try {
if (this.doNextProgressiveRender(element, index, templateData, !!initial, progressiveRenderingDisposables)) {
timer.cancel();
}
} catch (err) {
// Kill the timer if anything went wrong, avoid getting stuck in a nasty rendering loop.
timer.cancel();
throw err;
}
};
runProgressiveRender(true);
timer.cancelAndSet(runProgressiveRender, 50);
} else if (isResponseVM(element)) {
this.basicRenderElement(element.response.value, element, index, templateData);
} else if (isRequestVM(element)) {
this.basicRenderElement(element.messageText, element, index, templateData);
} else {
this.renderWelcomeMessage(element, templateData);
}
}
private basicRenderElement(markdownValue: string, element: InteractiveTreeItem, index: number, templateData: IInteractiveListItemTemplate) {
const fillInIncompleteTokens = isResponseVM(element) && (!element.isComplete || element.isCanceled || element.errorDetails?.responseIsFiltered || element.errorDetails?.responseIsIncomplete);
const result = this.renderMarkdown(new MarkdownString(markdownValue), element, templateData.elementDisposables, templateData, fillInIncompleteTokens);
dom.clearNode(templateData.value);
templateData.value.appendChild(result.element);
templateData.elementDisposables.add(result);
if (isResponseVM(element) && element.errorDetails?.message) {
const errorDetails = dom.append(templateData.value, $('.interactive-response-error-details', undefined, renderIcon(Codicon.error)));
errorDetails.appendChild($('span', undefined, element.errorDetails.message));
}
if (isResponseVM(element) && element.commandFollowups?.length) {
const followupsContainer = dom.append(templateData.value, $('.interactive-response-followups'));
templateData.elementDisposables.add(new InteractiveSessionFollowups(
followupsContainer,
element.commandFollowups,
defaultButtonStyles,
followup => {
this.interactiveSessionService.notifyUserAction({
providerId: element.providerId,
action: {
kind: 'command',
command: followup
}
});
return this.commandService.executeCommand(followup.commandId, ...(followup.args ?? []));
}));
}
}
private renderWelcomeMessage(element: IInteractiveWelcomeMessageViewModel, templateData: IInteractiveListItemTemplate) {
dom.clearNode(templateData.value);
const slashCommands = this.delegate.getSlashCommands();
for (const item of element.content) {
if (Array.isArray(item)) {
templateData.elementDisposables.add(new InteractiveSessionFollowups(
templateData.value,
item,
undefined,
followup => this._onDidClickFollowup.fire(followup)));
} else {
const result = this.renderMarkdown(item as IMarkdownString, element, templateData.elementDisposables, templateData);
for (const codeElement of result.element.querySelectorAll('code')) {
if (codeElement.textContent && slashCommands.find(command => codeElement.textContent === `/${command.command}`)) {
codeElement.classList.add('interactive-slash-command');
}
}
templateData.value.appendChild(result.element);
templateData.elementDisposables.add(result);
}
}
}
private doNextProgressiveRender(element: IInteractiveResponseViewModel, index: number, templateData: IInteractiveListItemTemplate, isInRenderElement: boolean, disposables: DisposableStore): boolean {
disposables.clear();
let isFullyRendered = false;
if (element.isCanceled) {
this.traceLayout('runProgressiveRender', `canceled, index=${index}`);
element.renderData = undefined;
this.basicRenderElement(element.response.value, element, index, templateData);
isFullyRendered = true;
} else {
// TODO- this method has the side effect of updating element.renderData
const toRender = this.getProgressiveMarkdownToRender(element);
isFullyRendered = !!element.renderData?.isFullyRendered;
if (isFullyRendered) {
// We've reached the end of the available content, so do a normal render
this.traceLayout('runProgressiveRender', `end progressive render, index=${index}`);
if (element.isComplete) {
this.traceLayout('runProgressiveRender', `and disposing renderData, response is complete, index=${index}`);
element.renderData = undefined;
} else {
this.traceLayout('runProgressiveRender', `Rendered all available words, but model is not complete.`);
}
disposables.clear();
this.basicRenderElement(element.response.value, element, index, templateData);
} else if (toRender) {
// Doing the progressive render
const plusCursor = toRender.match(/```.*$/) ? toRender + `\n${InteractiveListItemRenderer.cursorCharacter}` : toRender + ` ${InteractiveListItemRenderer.cursorCharacter}`;
const result = this.renderMarkdown(new MarkdownString(plusCursor), element, disposables, templateData, true);
dom.clearNode(templateData.value);
templateData.value.appendChild(result.element);
disposables.add(result);
} else {
// Nothing new to render, not done, keep waiting
return false;
}
}
// Some render happened - update the height
const height = templateData.rowContainer.offsetHeight;
element.currentRenderedHeight = height;
if (!isInRenderElement) {
this._onDidChangeItemHeight.fire({ element, height: templateData.rowContainer.offsetHeight });
}
return !!isFullyRendered;
}
private renderMarkdown(markdown: IMarkdownString, element: InteractiveTreeItem, disposables: DisposableStore, templateData: IInteractiveListItemTemplate, fillInIncompleteTokens = false): IMarkdownRenderResult {
const disposablesList: IDisposable[] = [];
let codeBlockIndex = 0;
// TODO if the slash commands stay completely dynamic, this isn't quite right
const slashCommands = this.delegate.getSlashCommands();
const usedSlashCommand = slashCommands.find(s => markdown.value.startsWith(`/${s.command} `));
const toRender = usedSlashCommand ? markdown.value.slice(usedSlashCommand.command.length + 2) : markdown.value;
markdown = new MarkdownString(toRender);
const result = this.renderer.render(markdown, {
fillInIncompleteTokens,
codeBlockRendererSync: (languageId, text) => {
const ref = this.renderCodeBlock({ languageId, text, codeBlockIndex: codeBlockIndex++, element, parentContextKeyService: templateData.contextKeyService }, disposables);
// Attach this after updating text/layout of the editor, so it should only be fired when the size updates later (horizontal scrollbar, wrapping)
// not during a renderElement OR a progressive render (when we will be firing this event anyway at the end of the render)
disposables.add(ref.object.onDidChangeContentHeight(() => {
ref.object.layout(this._currentLayoutWidth);
this._onDidChangeItemHeight.fire({ element, height: templateData.rowContainer.offsetHeight });
}));
disposablesList.push(ref);
return ref.object.element;
}
});
if (usedSlashCommand) {
const slashCommandElement = $('span.interactive-slash-command', { title: usedSlashCommand.detail }, `/${usedSlashCommand.command} `);
if (result.element.firstChild?.nodeName.toLowerCase() === 'p') {
result.element.firstChild.insertBefore(slashCommandElement, result.element.firstChild.firstChild);
} else {
result.element.insertBefore($('p', undefined, slashCommandElement), result.element.firstChild);
}
}
disposablesList.reverse().forEach(d => disposables.add(d));
return result;
}
private renderCodeBlock(data: IInteractiveResultCodeBlockData, disposables: DisposableStore): IDisposableReference<IInteractiveResultCodeBlockPart> {
const ref = this._editorPool.get();
const editorInfo = ref.object;
editorInfo.render(data, this._currentLayoutWidth);
return ref;
}
private getProgressiveMarkdownToRender(element: IInteractiveResponseViewModel): string | undefined {
const renderData = element.renderData ?? { renderedWordCount: 0, lastRenderTime: 0 };
const rate = this.getProgressiveRenderRate(element);
const numWordsToRender = renderData.lastRenderTime === 0 ?
1 :
renderData.renderedWordCount +
// Additional words to render beyond what's already rendered
Math.floor((Date.now() - renderData.lastRenderTime) / 1000 * rate);
if (numWordsToRender === renderData.renderedWordCount) {
return undefined;
}
const result = getNWords(element.response.value, numWordsToRender);
element.renderData = {
renderedWordCount: result.actualWordCount,
lastRenderTime: Date.now(),
isFullyRendered: result.isFullString
};
return result.value;
}
disposeElement(node: ITreeNode<InteractiveTreeItem, FuzzyScore>, index: number, templateData: IInteractiveListItemTemplate): void {
templateData.elementDisposables.clear();
}
disposeTemplate(templateData: IInteractiveListItemTemplate): void {
templateData.templateDisposables.dispose();
}
}
export class InteractiveSessionListDelegate implements IListVirtualDelegate<InteractiveTreeItem> {
constructor(
@ILogService private readonly logService: ILogService
) { }
private _traceLayout(method: string, message: string) {
if (forceVerboseLayoutTracing) {
this.logService.info(`InteractiveSessionListDelegate#${method}: ${message}`);
} else {
this.logService.trace(`InteractiveSessionListDelegate#${method}: ${message}`);
}
}
getHeight(element: InteractiveTreeItem): number {
const kind = isRequestVM(element) ? 'request' : 'response';
const height = ('currentRenderedHeight' in element ? element.currentRenderedHeight : undefined) ?? 200;
this._traceLayout('getHeight', `${kind}, height=${height}`);
return height;
}
getTemplateId(element: InteractiveTreeItem): string {
return InteractiveListItemRenderer.ID;
}
hasDynamicHeight(element: InteractiveTreeItem): boolean {
return true;
}
}
export class InteractiveSessionAccessibilityProvider implements IListAccessibilityProvider<InteractiveTreeItem> {
getWidgetAriaLabel(): string {
return localize('interactiveSession', "Interactive Session");
}
getAriaLabel(element: InteractiveTreeItem): string {
if (isRequestVM(element)) {
return localize('interactiveRequest', "Request: {0}", element.messageText);
}
if (isResponseVM(element)) {
return localize('interactiveResponse', "Response: {0}", element.response.value);
}
return '';
}
}
interface IInteractiveResultCodeBlockData {
text: string;
languageId: string;
codeBlockIndex: number;
element: InteractiveTreeItem;
parentContextKeyService: IContextKeyService;
}
interface IInteractiveResultCodeBlockPart {
readonly onDidChangeContentHeight: Event<number>;
readonly element: HTMLElement;
readonly textModel: ITextModel;
layout(width: number): void;
render(data: IInteractiveResultCodeBlockData, width: number): void;
dispose(): void;
}
export interface IInteractiveResultCodeBlockInfo {
providerId: string;
responseId: string;
codeBlockIndex: number;
}
export const codeBlockInfosByModelUri = new ResourceMap<IInteractiveResultCodeBlockInfo>();
class CodeBlockPart extends Disposable implements IInteractiveResultCodeBlockPart {
private readonly _onDidChangeContentHeight = this._register(new Emitter<number>());
public readonly onDidChangeContentHeight = this._onDidChangeContentHeight.event;
private readonly editor: CodeEditorWidget;
private readonly toolbar: MenuWorkbenchToolBar;
private readonly contextKeyService: IContextKeyService;
public readonly textModel: ITextModel;
public readonly element: HTMLElement;
constructor(
private readonly options: InteractiveSessionEditorOptions,
@IInstantiationService instantiationService: IInstantiationService,
@IContextKeyService contextKeyService: IContextKeyService,
@ILanguageService private readonly languageService: ILanguageService,
@IModelService private readonly modelService: IModelService,
) {
super();
this.element = $('.interactive-result-editor-wrapper');
this.contextKeyService = this._register(contextKeyService.createScoped(this.element));
const scopedInstantiationService = instantiationService.createChild(new ServiceCollection([IContextKeyService, this.contextKeyService]));
this.toolbar = this._register(scopedInstantiationService.createInstance(MenuWorkbenchToolBar, this.element, MenuId.InteractiveSessionCodeBlock, {
menuOptions: {
shouldForwardArgs: true
}
}));
const editorElement = dom.append(this.element, $('.interactive-result-editor'));
this.editor = this._register(scopedInstantiationService.createInstance(CodeEditorWidget, editorElement, {
...getSimpleEditorOptions(),
readOnly: true,
lineNumbers: 'off',
selectOnLineNumbers: true,
scrollBeyondLastLine: false,
lineDecorationsWidth: 8,
dragAndDrop: false,
padding: { top: 2, bottom: 2 },
mouseWheelZoom: false,
scrollbar: {
alwaysConsumeMouseWheel: false
},
...this.getEditorOptionsFromConfig()
}, {
isSimpleWidget: true,
contributions: EditorExtensionsRegistry.getSomeEditorContributions([
MenuPreventer.ID,
SelectionClipboardContributionID,
ContextMenuController.ID,
WordHighlighterContribution.ID,
ViewportSemanticTokensContribution.ID,
BracketMatchingController.ID,
SmartSelectController.ID,
])
}));
this._register(this.options.onDidChange(() => {
this.editor.updateOptions(this.getEditorOptionsFromConfig());
}));
this._register(this.editor.onDidContentSizeChange(e => {
if (e.contentHeightChanged) {
this._onDidChangeContentHeight.fire(e.contentHeight);
}
}));
this._register(this.editor.onDidBlurEditorWidget(() => {
WordHighlighterContribution.get(this.editor)?.stopHighlighting();
}));
this._register(this.editor.onDidFocusEditorWidget(() => {
WordHighlighterContribution.get(this.editor)?.restoreViewState(true);
}));
const vscodeLanguageId = this.languageService.getLanguageIdByLanguageName('javascript');
this.textModel = this._register(this.modelService.createModel('', this.languageService.createById(vscodeLanguageId), undefined));
this.editor.setModel(this.textModel);
}
private getEditorOptionsFromConfig(): IEditorOptions {
return {
wordWrap: this.options.configuration.resultEditor.wordWrap,
fontLigatures: this.options.configuration.resultEditor.fontLigatures,
bracketPairColorization: this.options.configuration.resultEditor.bracketPairColorization,
fontFamily: this.options.configuration.resultEditor.fontFamily === 'default' ?
EDITOR_FONT_DEFAULTS.fontFamily :
this.options.configuration.resultEditor.fontFamily,
fontSize: this.options.configuration.resultEditor.fontSize,
fontWeight: this.options.configuration.resultEditor.fontWeight,
lineHeight: this.options.configuration.resultEditor.lineHeight,
};
}
layout(width: number): void {
const realContentHeight = this.editor.getContentHeight();
const editorBorder = 2;
this.editor.layout({ width: width - editorBorder, height: realContentHeight });
}
render(data: IInteractiveResultCodeBlockData, width: number): void {
this.contextKeyService.updateParent(data.parentContextKeyService);
if (this.options.configuration.resultEditor.wordWrap === 'on') {
// Intialize the editor with the new proper width so that getContentHeight
// will be computed correctly in the next call to layout()
this.layout(width);
}
this.setText(data.text);
this.setLanguage(data.languageId);
this.layout(width);
if (isResponseVM(data.element) && data.element.providerResponseId) {
// For telemetry reporting
codeBlockInfosByModelUri.set(this.textModel.uri, {
providerId: data.element.providerId,
responseId: data.element.providerResponseId,
codeBlockIndex: data.codeBlockIndex
});
} else {
codeBlockInfosByModelUri.delete(this.textModel.uri);
}
this.toolbar.context = <IInteractiveSessionCodeBlockActionContext>{
code: data.text,
codeBlockIndex: data.codeBlockIndex,
element: data.element
};
}
private setText(newText: string): void {
let currentText = this.textModel.getLinesContent().join('\n');
if (newText === currentText) {
return;
}
let removedChars = 0;
if (currentText.endsWith(` ${InteractiveListItemRenderer.cursorCharacter}`)) {
removedChars = 2;
} else if (currentText.endsWith(InteractiveListItemRenderer.cursorCharacter)) {
removedChars = 1;
}
if (removedChars > 0) {
currentText = currentText.slice(0, currentText.length - removedChars);
}
if (newText.startsWith(currentText)) {
const text = newText.slice(currentText.length);
const lastLine = this.textModel.getLineCount();
const lastCol = this.textModel.getLineMaxColumn(lastLine);
const insertAtCol = lastCol - removedChars;
this.textModel.applyEdits([{ range: new Range(lastLine, insertAtCol, lastLine, lastCol), text }]);
} else {
// console.log(`Failed to optimize setText`);
this.textModel.setValue(newText);
}
}
private setLanguage(languageId: string): void {
const vscodeLanguageId = this.languageService.getLanguageIdByLanguageName(languageId);
if (vscodeLanguageId) {
this.textModel.setLanguage(vscodeLanguageId);
}
}
}
interface IDisposableReference<T> extends IDisposable {
object: T;
}
class EditorPool extends Disposable {
private _pool: ResourcePool<IInteractiveResultCodeBlockPart>;
public get inUse(): ReadonlySet<IInteractiveResultCodeBlockPart> {
return this._pool.inUse;
}
constructor(
private readonly options: InteractiveSessionEditorOptions,
@IInstantiationService private readonly instantiationService: IInstantiationService,
) {
super();
this._pool = this._register(new ResourcePool(() => this.editorFactory()));
// TODO listen to changes on options
}
private editorFactory(): IInteractiveResultCodeBlockPart {
return this.instantiationService.createInstance(CodeBlockPart, this.options);
}
get(): IDisposableReference<IInteractiveResultCodeBlockPart> {
const object = this._pool.get();
return {
object,
dispose: () => this._pool.release(object)
};
}
}
// TODO does something in lifecycle.ts cover this?
class ResourcePool<T extends IDisposable> extends Disposable {
private readonly pool: T[] = [];
private _inUse = new Set<T>;
public get inUse(): ReadonlySet<T> {
return this._inUse;
}
constructor(
private readonly _itemFactory: () => T,
) {
super();
}
get(): T {
if (this.pool.length > 0) {
const item = this.pool.pop()!;
this._inUse.add(item);
return item;
}
const item = this._register(this._itemFactory());
this._inUse.add(item);
return item;
}
release(item: T): void {
this._inUse.delete(item);
this.pool.push(item);
}
}
| src/vs/workbench/contrib/interactiveSession/browser/interactiveSessionListRenderer.ts | 1 | https://github.com/microsoft/vscode/commit/c2bf6225a12e7f7d8afada6ec39560bb38e5838a | [
0.9965127110481262,
0.03988856449723244,
0.00016063786461018026,
0.0001727085909806192,
0.1912725269794464
] |
{
"id": 10,
"code_window": [
"\t\tconst titleToolbar = templateDisposables.add(scopedInstantiationService.createInstance(MenuWorkbenchToolBar, header, MenuId.InteractiveSessionTitle, {\n",
"\t\t\tmenuOptions: {\n",
"\t\t\t\tshouldForwardArgs: true\n",
"\t\t\t}\n",
"\t\t}));\n",
"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t},\n",
"\t\t\tactionViewItemProvider: (action: IAction, options: IActionViewItemOptions) => {\n",
"\t\t\t\tif (action instanceof MenuItemAction) {\n",
"\t\t\t\t\treturn scopedInstantiationService.createInstance(InteractiveSessionVoteButton, action, options as IMenuEntryActionViewItemOptions);\n",
"\t\t\t\t}\n",
"\n",
"\t\t\t\treturn undefined;\n"
],
"file_path": "src/vs/workbench/contrib/interactiveSession/browser/interactiveSessionListRenderer.ts",
"type": "add",
"edit_start_line_idx": 170
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { IWorkingCopyBackupService } from 'vs/workbench/services/workingCopy/common/workingCopyBackup';
import { Disposable, IDisposable, dispose, toDisposable } from 'vs/base/common/lifecycle';
import { IWorkingCopyService } from 'vs/workbench/services/workingCopy/common/workingCopyService';
import { IWorkingCopy, IWorkingCopyIdentifier, WorkingCopyCapabilities } from 'vs/workbench/services/workingCopy/common/workingCopy';
import { ILogService } from 'vs/platform/log/common/log';
import { ShutdownReason, ILifecycleService, LifecyclePhase, InternalBeforeShutdownEvent } from 'vs/workbench/services/lifecycle/common/lifecycle';
import { CancellationTokenSource } from 'vs/base/common/cancellation';
import { AutoSaveMode, IFilesConfigurationService } from 'vs/workbench/services/filesConfiguration/common/filesConfigurationService';
import { IWorkingCopyEditorHandler, IWorkingCopyEditorService } from 'vs/workbench/services/workingCopy/common/workingCopyEditorService';
import { Promises } from 'vs/base/common/async';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { EditorsOrder } from 'vs/workbench/common/editor';
import { EditorInput } from 'vs/workbench/common/editor/editorInput';
import { IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService';
/**
* The working copy backup tracker deals with:
* - restoring backups that exist
* - creating backups for dirty working copies
* - deleting backups for saved working copies
* - handling backups on shutdown
*/
export abstract class WorkingCopyBackupTracker extends Disposable {
constructor(
protected readonly workingCopyBackupService: IWorkingCopyBackupService,
protected readonly workingCopyService: IWorkingCopyService,
protected readonly logService: ILogService,
private readonly lifecycleService: ILifecycleService,
protected readonly filesConfigurationService: IFilesConfigurationService,
private readonly workingCopyEditorService: IWorkingCopyEditorService,
protected readonly editorService: IEditorService,
private readonly editorGroupService: IEditorGroupsService
) {
super();
// Fill in initial dirty working copies
for (const workingCopy of this.workingCopyService.dirtyWorkingCopies) {
this.onDidRegister(workingCopy);
}
this.registerListeners();
}
private registerListeners() {
// Working Copy events
this._register(this.workingCopyService.onDidRegister(workingCopy => this.onDidRegister(workingCopy)));
this._register(this.workingCopyService.onDidUnregister(workingCopy => this.onDidUnregister(workingCopy)));
this._register(this.workingCopyService.onDidChangeDirty(workingCopy => this.onDidChangeDirty(workingCopy)));
this._register(this.workingCopyService.onDidChangeContent(workingCopy => this.onDidChangeContent(workingCopy)));
// Lifecycle
this.lifecycleService.onBeforeShutdown(event => (event as InternalBeforeShutdownEvent).finalVeto(() => this.onFinalBeforeShutdown(event.reason), 'veto.backups'));
this.lifecycleService.onWillShutdown(() => this.onWillShutdown());
// Once a handler registers, restore backups
this._register(this.workingCopyEditorService.onDidRegisterHandler(handler => this.restoreBackups(handler)));
}
protected abstract onFinalBeforeShutdown(reason: ShutdownReason): boolean | Promise<boolean>;
private onWillShutdown(): void {
// Here we know that we will shutdown. Any backup operation that is
// already scheduled or being scheduled from this moment on runs
// at the risk of corrupting a backup because the backup operation
// might terminate at any given time now. As such, we need to disable
// this tracker from performing more backups by cancelling pending
// operations and suspending the tracker without resuming.
this.cancelBackupOperations();
this.suspendBackupOperations();
}
//#region Backup Creator
// Delay creation of backups when content changes to avoid too much
// load on the backup service when the user is typing into the editor
// Since we always schedule a backup, even when auto save is on, we
// have different scheduling delays based on auto save. This helps to
// avoid a (not critical but also not really wanted) race between saving
// (after 1s per default) and making a backup of the working copy.
private static readonly BACKUP_SCHEDULE_DELAYS = {
[AutoSaveMode.OFF]: 1000,
[AutoSaveMode.ON_FOCUS_CHANGE]: 1000,
[AutoSaveMode.ON_WINDOW_CHANGE]: 1000,
[AutoSaveMode.AFTER_SHORT_DELAY]: 2000, // explicitly higher to prevent races
[AutoSaveMode.AFTER_LONG_DELAY]: 1000
};
// A map from working copy to a version ID we compute on each content
// change. This version ID allows to e.g. ask if a backup for a specific
// content has been made before closing.
private readonly mapWorkingCopyToContentVersion = new Map<IWorkingCopy, number>();
// A map of scheduled pending backup operations for working copies
// Given https://github.com/microsoft/vscode/issues/158038, we explicitly
// do not store `IWorkingCopy` but the identifier in the map, since it
// looks like GC is not runnin for the working copy otherwise.
protected readonly pendingBackupOperations = new Map<IWorkingCopyIdentifier, IDisposable>();
private suspended = false;
private onDidRegister(workingCopy: IWorkingCopy): void {
if (this.suspended) {
this.logService.warn(`[backup tracker] suspended, ignoring register event`, workingCopy.resource.toString(), workingCopy.typeId);
return;
}
if (workingCopy.isDirty()) {
this.scheduleBackup(workingCopy);
}
}
private onDidUnregister(workingCopy: IWorkingCopy): void {
// Remove from content version map
this.mapWorkingCopyToContentVersion.delete(workingCopy);
// Check suspended
if (this.suspended) {
this.logService.warn(`[backup tracker] suspended, ignoring unregister event`, workingCopy.resource.toString(), workingCopy.typeId);
return;
}
// Discard backup
this.discardBackup(workingCopy);
}
private onDidChangeDirty(workingCopy: IWorkingCopy): void {
if (this.suspended) {
this.logService.warn(`[backup tracker] suspended, ignoring dirty change event`, workingCopy.resource.toString(), workingCopy.typeId);
return;
}
if (workingCopy.isDirty()) {
this.scheduleBackup(workingCopy);
} else {
this.discardBackup(workingCopy);
}
}
private onDidChangeContent(workingCopy: IWorkingCopy): void {
// Increment content version ID
const contentVersionId = this.getContentVersion(workingCopy);
this.mapWorkingCopyToContentVersion.set(workingCopy, contentVersionId + 1);
// Check suspended
if (this.suspended) {
this.logService.warn(`[backup tracker] suspended, ignoring content change event`, workingCopy.resource.toString(), workingCopy.typeId);
return;
}
// Schedule backup if dirty
if (workingCopy.isDirty()) {
// this listener will make sure that the backup is
// pushed out for as long as the user is still changing
// the content of the working copy.
this.scheduleBackup(workingCopy);
}
}
private scheduleBackup(workingCopy: IWorkingCopy): void {
// Clear any running backup operation
this.cancelBackupOperation(workingCopy);
this.logService.trace(`[backup tracker] scheduling backup`, workingCopy.resource.toString(), workingCopy.typeId);
// Schedule new backup
const workingCopyIdentifier = { resource: workingCopy.resource, typeId: workingCopy.typeId };
const cts = new CancellationTokenSource();
const handle = setTimeout(async () => {
if (cts.token.isCancellationRequested) {
return;
}
// Backup if dirty
if (workingCopy.isDirty()) {
this.logService.trace(`[backup tracker] creating backup`, workingCopy.resource.toString(), workingCopy.typeId);
try {
const backup = await workingCopy.backup(cts.token);
if (cts.token.isCancellationRequested) {
return;
}
if (workingCopy.isDirty()) {
this.logService.trace(`[backup tracker] storing backup`, workingCopy.resource.toString(), workingCopy.typeId);
await this.workingCopyBackupService.backup(workingCopy, backup.content, this.getContentVersion(workingCopy), backup.meta, cts.token);
}
} catch (error) {
this.logService.error(error);
}
}
// Clear disposable unless we got canceled which would
// indicate another operation has started meanwhile
if (!cts.token.isCancellationRequested) {
this.pendingBackupOperations.delete(workingCopyIdentifier);
}
}, this.getBackupScheduleDelay(workingCopy));
// Keep in map for disposal as needed
this.pendingBackupOperations.set(workingCopyIdentifier, toDisposable(() => {
this.logService.trace(`[backup tracker] clearing pending backup creation`, workingCopy.resource.toString(), workingCopy.typeId);
cts.dispose(true);
clearTimeout(handle);
}));
}
protected getBackupScheduleDelay(workingCopy: IWorkingCopy): number {
let autoSaveMode = this.filesConfigurationService.getAutoSaveMode();
if (workingCopy.capabilities & WorkingCopyCapabilities.Untitled) {
autoSaveMode = AutoSaveMode.OFF; // auto-save is never on for untitled working copies
}
return WorkingCopyBackupTracker.BACKUP_SCHEDULE_DELAYS[autoSaveMode];
}
protected getContentVersion(workingCopy: IWorkingCopy): number {
return this.mapWorkingCopyToContentVersion.get(workingCopy) || 0;
}
private discardBackup(workingCopy: IWorkingCopy): void {
// Clear any running backup operation
this.cancelBackupOperation(workingCopy);
// Schedule backup discard asap
const workingCopyIdentifier = { resource: workingCopy.resource, typeId: workingCopy.typeId };
const cts = new CancellationTokenSource();
this.doDiscardBackup(workingCopyIdentifier, cts);
// Keep in map for disposal as needed
this.pendingBackupOperations.set(workingCopyIdentifier, toDisposable(() => {
this.logService.trace(`[backup tracker] clearing pending backup discard`, workingCopy.resource.toString(), workingCopy.typeId);
cts.dispose(true);
}));
}
private async doDiscardBackup(workingCopyIdentifier: IWorkingCopyIdentifier, cts: CancellationTokenSource) {
this.logService.trace(`[backup tracker] discarding backup`, workingCopyIdentifier.resource.toString(), workingCopyIdentifier.typeId);
// Discard backup
try {
await this.workingCopyBackupService.discardBackup(workingCopyIdentifier, cts.token);
} catch (error) {
this.logService.error(error);
}
// Clear disposable unless we got canceled which would
// indicate another operation has started meanwhile
if (!cts.token.isCancellationRequested) {
this.pendingBackupOperations.delete(workingCopyIdentifier);
}
}
private cancelBackupOperation(workingCopy: IWorkingCopy): void {
// Given a working copy we want to find the matching
// identifier in our pending operations map because
// we cannot use the working copy directly, as the
// identifier might have different object identity.
let workingCopyIdentifier: IWorkingCopyIdentifier | undefined = undefined;
for (const [identifier] of this.pendingBackupOperations) {
if (identifier.resource.toString() === workingCopy.resource.toString() && identifier.typeId === workingCopy.typeId) {
workingCopyIdentifier = identifier;
break;
}
}
if (workingCopyIdentifier) {
dispose(this.pendingBackupOperations.get(workingCopyIdentifier));
this.pendingBackupOperations.delete(workingCopyIdentifier);
}
}
protected cancelBackupOperations(): void {
for (const [, disposable] of this.pendingBackupOperations) {
dispose(disposable);
}
this.pendingBackupOperations.clear();
}
protected suspendBackupOperations(): { resume: () => void } {
this.suspended = true;
return { resume: () => this.suspended = false };
}
//#endregion
//#region Backup Restorer
protected readonly unrestoredBackups = new Set<IWorkingCopyIdentifier>();
protected readonly whenReady = this.resolveBackupsToRestore();
private _isReady = false;
protected get isReady(): boolean { return this._isReady; }
private async resolveBackupsToRestore(): Promise<void> {
// Wait for resolving backups until we are restored to reduce startup pressure
await this.lifecycleService.when(LifecyclePhase.Restored);
// Remember each backup that needs to restore
for (const backup of await this.workingCopyBackupService.getBackups()) {
this.unrestoredBackups.add(backup);
}
this._isReady = true;
}
protected async restoreBackups(handler: IWorkingCopyEditorHandler): Promise<void> {
// Wait for backups to be resolved
await this.whenReady;
// Figure out already opened editors for backups vs
// non-opened.
const openedEditorsForBackups = new Set<EditorInput>();
const nonOpenedEditorsForBackups = new Set<EditorInput>();
// Ensure each backup that can be handled has an
// associated editor.
const restoredBackups = new Set<IWorkingCopyIdentifier>();
for (const unrestoredBackup of this.unrestoredBackups) {
const canHandleUnrestoredBackup = handler.handles(unrestoredBackup);
if (!canHandleUnrestoredBackup) {
continue;
}
// Collect already opened editors for backup
let hasOpenedEditorForBackup = false;
for (const { editor } of this.editorService.getEditors(EditorsOrder.MOST_RECENTLY_ACTIVE)) {
const isUnrestoredBackupOpened = handler.isOpen(unrestoredBackup, editor);
if (isUnrestoredBackupOpened) {
openedEditorsForBackups.add(editor);
hasOpenedEditorForBackup = true;
}
}
// Otherwise, make sure to create at least one editor
// for the backup to show
if (!hasOpenedEditorForBackup) {
nonOpenedEditorsForBackups.add(await handler.createEditor(unrestoredBackup));
}
// Remember as (potentially) restored
restoredBackups.add(unrestoredBackup);
}
// Ensure editors are opened for each backup without editor
// in the background without stealing focus
if (nonOpenedEditorsForBackups.size > 0) {
await this.editorGroupService.activeGroup.openEditors([...nonOpenedEditorsForBackups].map(nonOpenedEditorForBackup => ({
editor: nonOpenedEditorForBackup,
options: {
pinned: true,
preserveFocus: true,
inactive: true
}
})));
for (const nonOpenedEditorForBackup of nonOpenedEditorsForBackups) {
openedEditorsForBackups.add(nonOpenedEditorForBackup);
}
}
// Then, resolve each opened editor to make sure the working copy
// is loaded and the dirty editor appears properly
// We only do that for editors that are not active in a group
// already to prevent calling `resolve` twice!
await Promises.settled([...openedEditorsForBackups].map(async openedEditorForBackup => {
if (this.editorService.isVisible(openedEditorForBackup)) {
return;
}
return openedEditorForBackup.resolve();
}));
// Finally, remove all handled backups from the list
for (const restoredBackup of restoredBackups) {
this.unrestoredBackups.delete(restoredBackup);
}
}
//#endregion
}
| src/vs/workbench/services/workingCopy/common/workingCopyBackupTracker.ts | 0 | https://github.com/microsoft/vscode/commit/c2bf6225a12e7f7d8afada6ec39560bb38e5838a | [
0.0001745754707371816,
0.00017073018534574658,
0.00016444020729977638,
0.00017142992874141783,
0.0000024904370548028965
] |
{
"id": 10,
"code_window": [
"\t\tconst titleToolbar = templateDisposables.add(scopedInstantiationService.createInstance(MenuWorkbenchToolBar, header, MenuId.InteractiveSessionTitle, {\n",
"\t\t\tmenuOptions: {\n",
"\t\t\t\tshouldForwardArgs: true\n",
"\t\t\t}\n",
"\t\t}));\n",
"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t},\n",
"\t\t\tactionViewItemProvider: (action: IAction, options: IActionViewItemOptions) => {\n",
"\t\t\t\tif (action instanceof MenuItemAction) {\n",
"\t\t\t\t\treturn scopedInstantiationService.createInstance(InteractiveSessionVoteButton, action, options as IMenuEntryActionViewItemOptions);\n",
"\t\t\t\t}\n",
"\n",
"\t\t\t\treturn undefined;\n"
],
"file_path": "src/vs/workbench/contrib/interactiveSession/browser/interactiveSessionListRenderer.ts",
"type": "add",
"edit_start_line_idx": 170
} | # Media Preview
**Notice:** This extension is bundled with Visual Studio Code. It can be disabled but not uninstalled.
## Features
This extension provides basic preview for images, audio and video files.
### Supported image file extensions
- `.jpg`, `.jpe`, `.jpeg`
- `.png`
- `.bmp`
- `.gif`
- `.ico`
- `.webp`
- `.avif`
### Supported audio formats
- `.mp3`
- `.wav`
- `.ogg`, `.oga`
### Supported video formats
- `.mp4` (does not support `aac` audio tracks)
- `.webm` (vp8 only)
| extensions/media-preview/README.md | 0 | https://github.com/microsoft/vscode/commit/c2bf6225a12e7f7d8afada6ec39560bb38e5838a | [
0.00017211472732014954,
0.0001699148560874164,
0.00016702551511116326,
0.00017060432583093643,
0.0000021340956664062105
] |
{
"id": 10,
"code_window": [
"\t\tconst titleToolbar = templateDisposables.add(scopedInstantiationService.createInstance(MenuWorkbenchToolBar, header, MenuId.InteractiveSessionTitle, {\n",
"\t\t\tmenuOptions: {\n",
"\t\t\t\tshouldForwardArgs: true\n",
"\t\t\t}\n",
"\t\t}));\n",
"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t},\n",
"\t\t\tactionViewItemProvider: (action: IAction, options: IActionViewItemOptions) => {\n",
"\t\t\t\tif (action instanceof MenuItemAction) {\n",
"\t\t\t\t\treturn scopedInstantiationService.createInstance(InteractiveSessionVoteButton, action, options as IMenuEntryActionViewItemOptions);\n",
"\t\t\t\t}\n",
"\n",
"\t\t\t\treturn undefined;\n"
],
"file_path": "src/vs/workbench/contrib/interactiveSession/browser/interactiveSessionListRenderer.ts",
"type": "add",
"edit_start_line_idx": 170
} | /*---------------------------------------------------------------------------------------------
* 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 * as arrays from './arrays';
import { Disposable } from './dispose';
export interface TypeScriptServerPlugin {
readonly extension: vscode.Extension<unknown>;
readonly uri: vscode.Uri;
readonly name: string;
readonly enableForWorkspaceTypeScriptVersions: boolean;
readonly languages: ReadonlyArray<string>;
readonly configNamespace?: string;
}
namespace TypeScriptServerPlugin {
export function equals(a: TypeScriptServerPlugin, b: TypeScriptServerPlugin): boolean {
return a.uri.toString() === b.uri.toString()
&& a.name === b.name
&& a.enableForWorkspaceTypeScriptVersions === b.enableForWorkspaceTypeScriptVersions
&& arrays.equals(a.languages, b.languages);
}
}
export class PluginManager extends Disposable {
private readonly _pluginConfigurations = new Map<string, {}>();
private _plugins?: Map<string, ReadonlyArray<TypeScriptServerPlugin>>;
constructor() {
super();
vscode.extensions.onDidChange(() => {
if (!this._plugins) {
return;
}
const newPlugins = this.readPlugins();
if (!arrays.equals(Array.from(this._plugins.values()).flat(), Array.from(newPlugins.values()).flat(), TypeScriptServerPlugin.equals)) {
this._plugins = newPlugins;
this._onDidUpdatePlugins.fire(this);
}
}, undefined, this._disposables);
}
public get plugins(): ReadonlyArray<TypeScriptServerPlugin> {
this._plugins ??= this.readPlugins();
return Array.from(this._plugins.values()).flat();
}
private readonly _onDidUpdatePlugins = this._register(new vscode.EventEmitter<this>());
public readonly onDidChangePlugins = this._onDidUpdatePlugins.event;
private readonly _onDidUpdateConfig = this._register(new vscode.EventEmitter<{ pluginId: string; config: {} }>());
public readonly onDidUpdateConfig = this._onDidUpdateConfig.event;
public setConfiguration(pluginId: string, config: {}) {
this._pluginConfigurations.set(pluginId, config);
this._onDidUpdateConfig.fire({ pluginId, config });
}
public configurations(): IterableIterator<[string, {}]> {
return this._pluginConfigurations.entries();
}
private readPlugins() {
const pluginMap = new Map<string, ReadonlyArray<TypeScriptServerPlugin>>();
for (const extension of vscode.extensions.all) {
const pack = extension.packageJSON;
if (pack.contributes && Array.isArray(pack.contributes.typescriptServerPlugins)) {
const plugins: TypeScriptServerPlugin[] = [];
for (const plugin of pack.contributes.typescriptServerPlugins) {
plugins.push({
extension,
name: plugin.name,
enableForWorkspaceTypeScriptVersions: !!plugin.enableForWorkspaceTypeScriptVersions,
uri: extension.extensionUri,
languages: Array.isArray(plugin.languages) ? plugin.languages : [],
configNamespace: plugin.configNamespace,
});
}
if (plugins.length) {
pluginMap.set(extension.id, plugins);
}
}
}
return pluginMap;
}
}
| extensions/typescript-language-features/src/utils/plugins.ts | 0 | https://github.com/microsoft/vscode/commit/c2bf6225a12e7f7d8afada6ec39560bb38e5838a | [
0.0001765049819368869,
0.00017256458522751927,
0.00016882330237422138,
0.00017208803910762072,
0.0000024722157832002267
] |
{
"id": 11,
"code_window": [
"\t\tthis.pool.push(item);\n",
"\t}\n",
"}\n"
],
"labels": [
"keep",
"keep",
"add"
],
"after_edit": [
"\n",
"class InteractiveSessionVoteButton extends MenuEntryActionViewItem {\n",
"\toverride render(container: HTMLElement): void {\n",
"\t\tsuper.render(container);\n",
"\t\tcontainer.classList.toggle('checked', this.action.checked);\n",
"\t}\n",
"}"
],
"file_path": "src/vs/workbench/contrib/interactiveSession/browser/interactiveSessionListRenderer.ts",
"type": "add",
"edit_start_line_idx": 732
} | /*---------------------------------------------------------------------------------------------
* 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 { renderIcon } from 'vs/base/browser/ui/iconLabel/iconLabels';
import { IListVirtualDelegate } from 'vs/base/browser/ui/list/list';
import { IListAccessibilityProvider } from 'vs/base/browser/ui/list/listWidget';
import { ITreeNode, ITreeRenderer } from 'vs/base/browser/ui/tree/tree';
import { IntervalTimer } from 'vs/base/common/async';
import { Codicon } from 'vs/base/common/codicons';
import { Emitter, Event } from 'vs/base/common/event';
import { FuzzyScore } from 'vs/base/common/filters';
import { IMarkdownString, MarkdownString } from 'vs/base/common/htmlContent';
import { Disposable, DisposableStore, IDisposable } from 'vs/base/common/lifecycle';
import { ResourceMap } from 'vs/base/common/map';
import { FileAccess } from 'vs/base/common/network';
import { ThemeIcon } from 'vs/base/common/themables';
import { EditorExtensionsRegistry } from 'vs/editor/browser/editorExtensions';
import { CodeEditorWidget } from 'vs/editor/browser/widget/codeEditorWidget';
import { EDITOR_FONT_DEFAULTS, IEditorOptions } from 'vs/editor/common/config/editorOptions';
import { Range } from 'vs/editor/common/core/range';
import { ILanguageService } from 'vs/editor/common/languages/language';
import { ITextModel } from 'vs/editor/common/model';
import { IModelService } from 'vs/editor/common/services/model';
import { BracketMatchingController } from 'vs/editor/contrib/bracketMatching/browser/bracketMatching';
import { ContextMenuController } from 'vs/editor/contrib/contextmenu/browser/contextmenu';
import { IMarkdownRenderResult, MarkdownRenderer } from 'vs/editor/contrib/markdownRenderer/browser/markdownRenderer';
import { ViewportSemanticTokensContribution } from 'vs/editor/contrib/semanticTokens/browser/viewportSemanticTokens';
import { SmartSelectController } from 'vs/editor/contrib/smartSelect/browser/smartSelect';
import { WordHighlighterContribution } from 'vs/editor/contrib/wordHighlighter/browser/wordHighlighter';
import { localize } from 'vs/nls';
import { MenuWorkbenchToolBar } from 'vs/platform/actions/browser/toolbar';
import { MenuId } from 'vs/platform/actions/common/actions';
import { ICommandService } from 'vs/platform/commands/common/commands';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection';
import { ILogService } from 'vs/platform/log/common/log';
import { defaultButtonStyles } from 'vs/platform/theme/browser/defaultStyles';
import { MenuPreventer } from 'vs/workbench/contrib/codeEditor/browser/menuPreventer';
import { SelectionClipboardContributionID } from 'vs/workbench/contrib/codeEditor/browser/selectionClipboard';
import { getSimpleEditorOptions } from 'vs/workbench/contrib/codeEditor/browser/simpleEditorOptions';
import { IInteractiveSessionCodeBlockActionContext } from 'vs/workbench/contrib/interactiveSession/browser/actions/interactiveSessionCodeblockActions';
import { InteractiveSessionFollowups } from 'vs/workbench/contrib/interactiveSession/browser/interactiveSessionFollowups';
import { InteractiveSessionEditorOptions } from 'vs/workbench/contrib/interactiveSession/browser/interactiveSessionOptions';
import { CONTEXT_RESPONSE_HAS_PROVIDER_ID, CONTEXT_RESPONSE_VOTE } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionContextKeys';
import { IInteractiveSessionReplyFollowup, IInteractiveSessionService, IInteractiveSlashCommand, InteractiveSessionVoteDirection } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionService';
import { IInteractiveRequestViewModel, IInteractiveResponseViewModel, IInteractiveWelcomeMessageViewModel, isRequestVM, isResponseVM, isWelcomeVM } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionViewModel';
import { getNWords } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionWordCounter';
const $ = dom.$;
export type InteractiveTreeItem = IInteractiveRequestViewModel | IInteractiveResponseViewModel | IInteractiveWelcomeMessageViewModel;
interface IInteractiveListItemTemplate {
rowContainer: HTMLElement;
titleToolbar: MenuWorkbenchToolBar;
avatar: HTMLElement;
username: HTMLElement;
value: HTMLElement;
contextKeyService: IContextKeyService;
templateDisposables: IDisposable;
elementDisposables: DisposableStore;
}
interface IItemHeightChangeParams {
element: InteractiveTreeItem;
height: number;
}
const forceVerboseLayoutTracing = false;
export interface IInteractiveSessionRendererDelegate {
getListLength(): number;
getSlashCommands(): IInteractiveSlashCommand[];
}
export class InteractiveListItemRenderer extends Disposable implements ITreeRenderer<InteractiveTreeItem, FuzzyScore, IInteractiveListItemTemplate> {
static readonly cursorCharacter = '\u258c';
static readonly ID = 'item';
private readonly renderer: MarkdownRenderer;
protected readonly _onDidClickFollowup = this._register(new Emitter<IInteractiveSessionReplyFollowup>());
readonly onDidClickFollowup: Event<IInteractiveSessionReplyFollowup> = this._onDidClickFollowup.event;
protected readonly _onDidChangeItemHeight = this._register(new Emitter<IItemHeightChangeParams>());
readonly onDidChangeItemHeight: Event<IItemHeightChangeParams> = this._onDidChangeItemHeight.event;
private readonly _editorPool: EditorPool;
private _currentLayoutWidth: number = 0;
constructor(
private readonly editorOptions: InteractiveSessionEditorOptions,
private readonly delegate: IInteractiveSessionRendererDelegate,
@IInstantiationService private readonly instantiationService: IInstantiationService,
@IConfigurationService private readonly configService: IConfigurationService,
@ILogService private readonly logService: ILogService,
@ICommandService private readonly commandService: ICommandService,
@IContextKeyService private readonly contextKeyService: IContextKeyService,
@IInteractiveSessionService private readonly interactiveSessionService: IInteractiveSessionService,
) {
super();
this.renderer = this.instantiationService.createInstance(MarkdownRenderer, {});
this._editorPool = this._register(this.instantiationService.createInstance(EditorPool, this.editorOptions));
}
get templateId(): string {
return InteractiveListItemRenderer.ID;
}
private traceLayout(method: string, message: string) {
if (forceVerboseLayoutTracing) {
this.logService.info(`InteractiveListItemRenderer#${method}: ${message}`);
} else {
this.logService.trace(`InteractiveListItemRenderer#${method}: ${message}`);
}
}
private shouldRenderProgressively(element: IInteractiveResponseViewModel): boolean {
return !this.configService.getValue('interactive.experimental.disableProgressiveRendering') && element.progressiveResponseRenderingEnabled;
}
private getProgressiveRenderRate(element: IInteractiveResponseViewModel): number {
const configuredRate = this.configService.getValue('interactive.experimental.progressiveRenderingRate');
if (typeof configuredRate === 'number') {
return configuredRate;
}
if (element.isComplete) {
return 60;
}
if (element.contentUpdateTimings && element.contentUpdateTimings.impliedWordLoadRate) {
// This doesn't account for dead time after the last update. When the previous update is the final one and the model is only waiting for followupQuestions, that's good.
// When there was one quick update and then you are waiting longer for the next one, that's not good since the rate should be decreasing.
// If it's an issue, we can change this to be based on the total time from now to the beginning.
const rateBoost = 1.5;
return element.contentUpdateTimings.impliedWordLoadRate * rateBoost;
}
return 8;
}
layout(width: number): void {
this._currentLayoutWidth = width - 40; // TODO Padding
this._editorPool.inUse.forEach(editor => {
editor.layout(this._currentLayoutWidth);
});
}
renderTemplate(container: HTMLElement): IInteractiveListItemTemplate {
const templateDisposables = new DisposableStore();
const rowContainer = dom.append(container, $('.interactive-item-container'));
const header = dom.append(rowContainer, $('.header'));
const user = dom.append(header, $('.user'));
const avatar = dom.append(user, $('.avatar'));
const username = dom.append(user, $('h3.username'));
const value = dom.append(rowContainer, $('.value'));
const elementDisposables = new DisposableStore();
const contextKeyService = templateDisposables.add(this.contextKeyService.createScoped(rowContainer));
const scopedInstantiationService = this.instantiationService.createChild(new ServiceCollection([IContextKeyService, contextKeyService]));
const titleToolbar = templateDisposables.add(scopedInstantiationService.createInstance(MenuWorkbenchToolBar, header, MenuId.InteractiveSessionTitle, {
menuOptions: {
shouldForwardArgs: true
}
}));
const template: IInteractiveListItemTemplate = { avatar, username, value, rowContainer, elementDisposables, titleToolbar, templateDisposables, contextKeyService };
return template;
}
renderElement(node: ITreeNode<InteractiveTreeItem, FuzzyScore>, index: number, templateData: IInteractiveListItemTemplate): void {
const { element } = node;
const kind = isRequestVM(element) ? 'request' :
isResponseVM(element) ? 'response' :
'welcome';
this.traceLayout('renderElement', `${kind}, index=${index}`);
CONTEXT_RESPONSE_HAS_PROVIDER_ID.bindTo(templateData.contextKeyService).set(isResponseVM(element) && !!element.providerResponseId && !element.isPlaceholder);
if (isResponseVM(element)) {
CONTEXT_RESPONSE_VOTE.bindTo(templateData.contextKeyService).set(element.vote === InteractiveSessionVoteDirection.Up ? 'up' : element.vote === InteractiveSessionVoteDirection.Down ? 'down' : '');
} else {
CONTEXT_RESPONSE_VOTE.bindTo(templateData.contextKeyService).set('');
}
templateData.titleToolbar.context = element;
templateData.rowContainer.classList.toggle('interactive-request', isRequestVM(element));
templateData.rowContainer.classList.toggle('interactive-response', isResponseVM(element));
templateData.rowContainer.classList.toggle('interactive-welcome', isWelcomeVM(element));
templateData.rowContainer.classList.toggle('filtered-response', !!(isResponseVM(element) && element.errorDetails?.responseIsFiltered));
templateData.username.textContent = element.username;
if (element.avatarIconUri) {
const avatarIcon = dom.$<HTMLImageElement>('img.icon');
avatarIcon.src = FileAccess.uriToBrowserUri(element.avatarIconUri).toString(true);
templateData.avatar.replaceChildren(avatarIcon);
} else {
const defaultIcon = isRequestVM(element) ? Codicon.account : Codicon.hubot;
const avatarIcon = dom.$(ThemeIcon.asCSSSelector(defaultIcon));
templateData.avatar.replaceChildren(avatarIcon);
}
// Do a progressive render if
// - This the last response in the list
// - And the response is not complete
// - Or, we previously started a progressive rendering of this element (if the element is complete, we will finish progressive rendering with a very fast rate)
// - And, the feature is not disabled in configuration
if (isResponseVM(element) && index === this.delegate.getListLength() - 1 && (!element.isComplete || element.renderData) && this.shouldRenderProgressively(element)) {
this.traceLayout('renderElement', `start progressive render ${kind}, index=${index}`);
const progressiveRenderingDisposables = templateData.elementDisposables.add(new DisposableStore());
const timer = templateData.elementDisposables.add(new IntervalTimer());
const runProgressiveRender = (initial?: boolean) => {
try {
if (this.doNextProgressiveRender(element, index, templateData, !!initial, progressiveRenderingDisposables)) {
timer.cancel();
}
} catch (err) {
// Kill the timer if anything went wrong, avoid getting stuck in a nasty rendering loop.
timer.cancel();
throw err;
}
};
runProgressiveRender(true);
timer.cancelAndSet(runProgressiveRender, 50);
} else if (isResponseVM(element)) {
this.basicRenderElement(element.response.value, element, index, templateData);
} else if (isRequestVM(element)) {
this.basicRenderElement(element.messageText, element, index, templateData);
} else {
this.renderWelcomeMessage(element, templateData);
}
}
private basicRenderElement(markdownValue: string, element: InteractiveTreeItem, index: number, templateData: IInteractiveListItemTemplate) {
const fillInIncompleteTokens = isResponseVM(element) && (!element.isComplete || element.isCanceled || element.errorDetails?.responseIsFiltered || element.errorDetails?.responseIsIncomplete);
const result = this.renderMarkdown(new MarkdownString(markdownValue), element, templateData.elementDisposables, templateData, fillInIncompleteTokens);
dom.clearNode(templateData.value);
templateData.value.appendChild(result.element);
templateData.elementDisposables.add(result);
if (isResponseVM(element) && element.errorDetails?.message) {
const errorDetails = dom.append(templateData.value, $('.interactive-response-error-details', undefined, renderIcon(Codicon.error)));
errorDetails.appendChild($('span', undefined, element.errorDetails.message));
}
if (isResponseVM(element) && element.commandFollowups?.length) {
const followupsContainer = dom.append(templateData.value, $('.interactive-response-followups'));
templateData.elementDisposables.add(new InteractiveSessionFollowups(
followupsContainer,
element.commandFollowups,
defaultButtonStyles,
followup => {
this.interactiveSessionService.notifyUserAction({
providerId: element.providerId,
action: {
kind: 'command',
command: followup
}
});
return this.commandService.executeCommand(followup.commandId, ...(followup.args ?? []));
}));
}
}
private renderWelcomeMessage(element: IInteractiveWelcomeMessageViewModel, templateData: IInteractiveListItemTemplate) {
dom.clearNode(templateData.value);
const slashCommands = this.delegate.getSlashCommands();
for (const item of element.content) {
if (Array.isArray(item)) {
templateData.elementDisposables.add(new InteractiveSessionFollowups(
templateData.value,
item,
undefined,
followup => this._onDidClickFollowup.fire(followup)));
} else {
const result = this.renderMarkdown(item as IMarkdownString, element, templateData.elementDisposables, templateData);
for (const codeElement of result.element.querySelectorAll('code')) {
if (codeElement.textContent && slashCommands.find(command => codeElement.textContent === `/${command.command}`)) {
codeElement.classList.add('interactive-slash-command');
}
}
templateData.value.appendChild(result.element);
templateData.elementDisposables.add(result);
}
}
}
private doNextProgressiveRender(element: IInteractiveResponseViewModel, index: number, templateData: IInteractiveListItemTemplate, isInRenderElement: boolean, disposables: DisposableStore): boolean {
disposables.clear();
let isFullyRendered = false;
if (element.isCanceled) {
this.traceLayout('runProgressiveRender', `canceled, index=${index}`);
element.renderData = undefined;
this.basicRenderElement(element.response.value, element, index, templateData);
isFullyRendered = true;
} else {
// TODO- this method has the side effect of updating element.renderData
const toRender = this.getProgressiveMarkdownToRender(element);
isFullyRendered = !!element.renderData?.isFullyRendered;
if (isFullyRendered) {
// We've reached the end of the available content, so do a normal render
this.traceLayout('runProgressiveRender', `end progressive render, index=${index}`);
if (element.isComplete) {
this.traceLayout('runProgressiveRender', `and disposing renderData, response is complete, index=${index}`);
element.renderData = undefined;
} else {
this.traceLayout('runProgressiveRender', `Rendered all available words, but model is not complete.`);
}
disposables.clear();
this.basicRenderElement(element.response.value, element, index, templateData);
} else if (toRender) {
// Doing the progressive render
const plusCursor = toRender.match(/```.*$/) ? toRender + `\n${InteractiveListItemRenderer.cursorCharacter}` : toRender + ` ${InteractiveListItemRenderer.cursorCharacter}`;
const result = this.renderMarkdown(new MarkdownString(plusCursor), element, disposables, templateData, true);
dom.clearNode(templateData.value);
templateData.value.appendChild(result.element);
disposables.add(result);
} else {
// Nothing new to render, not done, keep waiting
return false;
}
}
// Some render happened - update the height
const height = templateData.rowContainer.offsetHeight;
element.currentRenderedHeight = height;
if (!isInRenderElement) {
this._onDidChangeItemHeight.fire({ element, height: templateData.rowContainer.offsetHeight });
}
return !!isFullyRendered;
}
private renderMarkdown(markdown: IMarkdownString, element: InteractiveTreeItem, disposables: DisposableStore, templateData: IInteractiveListItemTemplate, fillInIncompleteTokens = false): IMarkdownRenderResult {
const disposablesList: IDisposable[] = [];
let codeBlockIndex = 0;
// TODO if the slash commands stay completely dynamic, this isn't quite right
const slashCommands = this.delegate.getSlashCommands();
const usedSlashCommand = slashCommands.find(s => markdown.value.startsWith(`/${s.command} `));
const toRender = usedSlashCommand ? markdown.value.slice(usedSlashCommand.command.length + 2) : markdown.value;
markdown = new MarkdownString(toRender);
const result = this.renderer.render(markdown, {
fillInIncompleteTokens,
codeBlockRendererSync: (languageId, text) => {
const ref = this.renderCodeBlock({ languageId, text, codeBlockIndex: codeBlockIndex++, element, parentContextKeyService: templateData.contextKeyService }, disposables);
// Attach this after updating text/layout of the editor, so it should only be fired when the size updates later (horizontal scrollbar, wrapping)
// not during a renderElement OR a progressive render (when we will be firing this event anyway at the end of the render)
disposables.add(ref.object.onDidChangeContentHeight(() => {
ref.object.layout(this._currentLayoutWidth);
this._onDidChangeItemHeight.fire({ element, height: templateData.rowContainer.offsetHeight });
}));
disposablesList.push(ref);
return ref.object.element;
}
});
if (usedSlashCommand) {
const slashCommandElement = $('span.interactive-slash-command', { title: usedSlashCommand.detail }, `/${usedSlashCommand.command} `);
if (result.element.firstChild?.nodeName.toLowerCase() === 'p') {
result.element.firstChild.insertBefore(slashCommandElement, result.element.firstChild.firstChild);
} else {
result.element.insertBefore($('p', undefined, slashCommandElement), result.element.firstChild);
}
}
disposablesList.reverse().forEach(d => disposables.add(d));
return result;
}
private renderCodeBlock(data: IInteractiveResultCodeBlockData, disposables: DisposableStore): IDisposableReference<IInteractiveResultCodeBlockPart> {
const ref = this._editorPool.get();
const editorInfo = ref.object;
editorInfo.render(data, this._currentLayoutWidth);
return ref;
}
private getProgressiveMarkdownToRender(element: IInteractiveResponseViewModel): string | undefined {
const renderData = element.renderData ?? { renderedWordCount: 0, lastRenderTime: 0 };
const rate = this.getProgressiveRenderRate(element);
const numWordsToRender = renderData.lastRenderTime === 0 ?
1 :
renderData.renderedWordCount +
// Additional words to render beyond what's already rendered
Math.floor((Date.now() - renderData.lastRenderTime) / 1000 * rate);
if (numWordsToRender === renderData.renderedWordCount) {
return undefined;
}
const result = getNWords(element.response.value, numWordsToRender);
element.renderData = {
renderedWordCount: result.actualWordCount,
lastRenderTime: Date.now(),
isFullyRendered: result.isFullString
};
return result.value;
}
disposeElement(node: ITreeNode<InteractiveTreeItem, FuzzyScore>, index: number, templateData: IInteractiveListItemTemplate): void {
templateData.elementDisposables.clear();
}
disposeTemplate(templateData: IInteractiveListItemTemplate): void {
templateData.templateDisposables.dispose();
}
}
export class InteractiveSessionListDelegate implements IListVirtualDelegate<InteractiveTreeItem> {
constructor(
@ILogService private readonly logService: ILogService
) { }
private _traceLayout(method: string, message: string) {
if (forceVerboseLayoutTracing) {
this.logService.info(`InteractiveSessionListDelegate#${method}: ${message}`);
} else {
this.logService.trace(`InteractiveSessionListDelegate#${method}: ${message}`);
}
}
getHeight(element: InteractiveTreeItem): number {
const kind = isRequestVM(element) ? 'request' : 'response';
const height = ('currentRenderedHeight' in element ? element.currentRenderedHeight : undefined) ?? 200;
this._traceLayout('getHeight', `${kind}, height=${height}`);
return height;
}
getTemplateId(element: InteractiveTreeItem): string {
return InteractiveListItemRenderer.ID;
}
hasDynamicHeight(element: InteractiveTreeItem): boolean {
return true;
}
}
export class InteractiveSessionAccessibilityProvider implements IListAccessibilityProvider<InteractiveTreeItem> {
getWidgetAriaLabel(): string {
return localize('interactiveSession', "Interactive Session");
}
getAriaLabel(element: InteractiveTreeItem): string {
if (isRequestVM(element)) {
return localize('interactiveRequest', "Request: {0}", element.messageText);
}
if (isResponseVM(element)) {
return localize('interactiveResponse', "Response: {0}", element.response.value);
}
return '';
}
}
interface IInteractiveResultCodeBlockData {
text: string;
languageId: string;
codeBlockIndex: number;
element: InteractiveTreeItem;
parentContextKeyService: IContextKeyService;
}
interface IInteractiveResultCodeBlockPart {
readonly onDidChangeContentHeight: Event<number>;
readonly element: HTMLElement;
readonly textModel: ITextModel;
layout(width: number): void;
render(data: IInteractiveResultCodeBlockData, width: number): void;
dispose(): void;
}
export interface IInteractiveResultCodeBlockInfo {
providerId: string;
responseId: string;
codeBlockIndex: number;
}
export const codeBlockInfosByModelUri = new ResourceMap<IInteractiveResultCodeBlockInfo>();
class CodeBlockPart extends Disposable implements IInteractiveResultCodeBlockPart {
private readonly _onDidChangeContentHeight = this._register(new Emitter<number>());
public readonly onDidChangeContentHeight = this._onDidChangeContentHeight.event;
private readonly editor: CodeEditorWidget;
private readonly toolbar: MenuWorkbenchToolBar;
private readonly contextKeyService: IContextKeyService;
public readonly textModel: ITextModel;
public readonly element: HTMLElement;
constructor(
private readonly options: InteractiveSessionEditorOptions,
@IInstantiationService instantiationService: IInstantiationService,
@IContextKeyService contextKeyService: IContextKeyService,
@ILanguageService private readonly languageService: ILanguageService,
@IModelService private readonly modelService: IModelService,
) {
super();
this.element = $('.interactive-result-editor-wrapper');
this.contextKeyService = this._register(contextKeyService.createScoped(this.element));
const scopedInstantiationService = instantiationService.createChild(new ServiceCollection([IContextKeyService, this.contextKeyService]));
this.toolbar = this._register(scopedInstantiationService.createInstance(MenuWorkbenchToolBar, this.element, MenuId.InteractiveSessionCodeBlock, {
menuOptions: {
shouldForwardArgs: true
}
}));
const editorElement = dom.append(this.element, $('.interactive-result-editor'));
this.editor = this._register(scopedInstantiationService.createInstance(CodeEditorWidget, editorElement, {
...getSimpleEditorOptions(),
readOnly: true,
lineNumbers: 'off',
selectOnLineNumbers: true,
scrollBeyondLastLine: false,
lineDecorationsWidth: 8,
dragAndDrop: false,
padding: { top: 2, bottom: 2 },
mouseWheelZoom: false,
scrollbar: {
alwaysConsumeMouseWheel: false
},
...this.getEditorOptionsFromConfig()
}, {
isSimpleWidget: true,
contributions: EditorExtensionsRegistry.getSomeEditorContributions([
MenuPreventer.ID,
SelectionClipboardContributionID,
ContextMenuController.ID,
WordHighlighterContribution.ID,
ViewportSemanticTokensContribution.ID,
BracketMatchingController.ID,
SmartSelectController.ID,
])
}));
this._register(this.options.onDidChange(() => {
this.editor.updateOptions(this.getEditorOptionsFromConfig());
}));
this._register(this.editor.onDidContentSizeChange(e => {
if (e.contentHeightChanged) {
this._onDidChangeContentHeight.fire(e.contentHeight);
}
}));
this._register(this.editor.onDidBlurEditorWidget(() => {
WordHighlighterContribution.get(this.editor)?.stopHighlighting();
}));
this._register(this.editor.onDidFocusEditorWidget(() => {
WordHighlighterContribution.get(this.editor)?.restoreViewState(true);
}));
const vscodeLanguageId = this.languageService.getLanguageIdByLanguageName('javascript');
this.textModel = this._register(this.modelService.createModel('', this.languageService.createById(vscodeLanguageId), undefined));
this.editor.setModel(this.textModel);
}
private getEditorOptionsFromConfig(): IEditorOptions {
return {
wordWrap: this.options.configuration.resultEditor.wordWrap,
fontLigatures: this.options.configuration.resultEditor.fontLigatures,
bracketPairColorization: this.options.configuration.resultEditor.bracketPairColorization,
fontFamily: this.options.configuration.resultEditor.fontFamily === 'default' ?
EDITOR_FONT_DEFAULTS.fontFamily :
this.options.configuration.resultEditor.fontFamily,
fontSize: this.options.configuration.resultEditor.fontSize,
fontWeight: this.options.configuration.resultEditor.fontWeight,
lineHeight: this.options.configuration.resultEditor.lineHeight,
};
}
layout(width: number): void {
const realContentHeight = this.editor.getContentHeight();
const editorBorder = 2;
this.editor.layout({ width: width - editorBorder, height: realContentHeight });
}
render(data: IInteractiveResultCodeBlockData, width: number): void {
this.contextKeyService.updateParent(data.parentContextKeyService);
if (this.options.configuration.resultEditor.wordWrap === 'on') {
// Intialize the editor with the new proper width so that getContentHeight
// will be computed correctly in the next call to layout()
this.layout(width);
}
this.setText(data.text);
this.setLanguage(data.languageId);
this.layout(width);
if (isResponseVM(data.element) && data.element.providerResponseId) {
// For telemetry reporting
codeBlockInfosByModelUri.set(this.textModel.uri, {
providerId: data.element.providerId,
responseId: data.element.providerResponseId,
codeBlockIndex: data.codeBlockIndex
});
} else {
codeBlockInfosByModelUri.delete(this.textModel.uri);
}
this.toolbar.context = <IInteractiveSessionCodeBlockActionContext>{
code: data.text,
codeBlockIndex: data.codeBlockIndex,
element: data.element
};
}
private setText(newText: string): void {
let currentText = this.textModel.getLinesContent().join('\n');
if (newText === currentText) {
return;
}
let removedChars = 0;
if (currentText.endsWith(` ${InteractiveListItemRenderer.cursorCharacter}`)) {
removedChars = 2;
} else if (currentText.endsWith(InteractiveListItemRenderer.cursorCharacter)) {
removedChars = 1;
}
if (removedChars > 0) {
currentText = currentText.slice(0, currentText.length - removedChars);
}
if (newText.startsWith(currentText)) {
const text = newText.slice(currentText.length);
const lastLine = this.textModel.getLineCount();
const lastCol = this.textModel.getLineMaxColumn(lastLine);
const insertAtCol = lastCol - removedChars;
this.textModel.applyEdits([{ range: new Range(lastLine, insertAtCol, lastLine, lastCol), text }]);
} else {
// console.log(`Failed to optimize setText`);
this.textModel.setValue(newText);
}
}
private setLanguage(languageId: string): void {
const vscodeLanguageId = this.languageService.getLanguageIdByLanguageName(languageId);
if (vscodeLanguageId) {
this.textModel.setLanguage(vscodeLanguageId);
}
}
}
interface IDisposableReference<T> extends IDisposable {
object: T;
}
class EditorPool extends Disposable {
private _pool: ResourcePool<IInteractiveResultCodeBlockPart>;
public get inUse(): ReadonlySet<IInteractiveResultCodeBlockPart> {
return this._pool.inUse;
}
constructor(
private readonly options: InteractiveSessionEditorOptions,
@IInstantiationService private readonly instantiationService: IInstantiationService,
) {
super();
this._pool = this._register(new ResourcePool(() => this.editorFactory()));
// TODO listen to changes on options
}
private editorFactory(): IInteractiveResultCodeBlockPart {
return this.instantiationService.createInstance(CodeBlockPart, this.options);
}
get(): IDisposableReference<IInteractiveResultCodeBlockPart> {
const object = this._pool.get();
return {
object,
dispose: () => this._pool.release(object)
};
}
}
// TODO does something in lifecycle.ts cover this?
class ResourcePool<T extends IDisposable> extends Disposable {
private readonly pool: T[] = [];
private _inUse = new Set<T>;
public get inUse(): ReadonlySet<T> {
return this._inUse;
}
constructor(
private readonly _itemFactory: () => T,
) {
super();
}
get(): T {
if (this.pool.length > 0) {
const item = this.pool.pop()!;
this._inUse.add(item);
return item;
}
const item = this._register(this._itemFactory());
this._inUse.add(item);
return item;
}
release(item: T): void {
this._inUse.delete(item);
this.pool.push(item);
}
}
| src/vs/workbench/contrib/interactiveSession/browser/interactiveSessionListRenderer.ts | 1 | https://github.com/microsoft/vscode/commit/c2bf6225a12e7f7d8afada6ec39560bb38e5838a | [
0.7544252276420593,
0.017069194465875626,
0.00016392170800827444,
0.000169248174643144,
0.10006219893693924
] |
{
"id": 11,
"code_window": [
"\t\tthis.pool.push(item);\n",
"\t}\n",
"}\n"
],
"labels": [
"keep",
"keep",
"add"
],
"after_edit": [
"\n",
"class InteractiveSessionVoteButton extends MenuEntryActionViewItem {\n",
"\toverride render(container: HTMLElement): void {\n",
"\t\tsuper.render(container);\n",
"\t\tcontainer.classList.toggle('checked', this.action.checked);\n",
"\t}\n",
"}"
],
"file_path": "src/vs/workbench/contrib/interactiveSession/browser/interactiveSessionListRenderer.ts",
"type": "add",
"edit_start_line_idx": 732
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { CancelablePromise, createCancelablePromise } from 'vs/base/common/async';
import { VSBuffer } from 'vs/base/common/buffer';
import { CancellationToken, CancellationTokenSource } from 'vs/base/common/cancellation';
import { isCancellationError, onUnexpectedError } from 'vs/base/common/errors';
import { Emitter } from 'vs/base/common/event';
import { Disposable, DisposableStore, IDisposable, toDisposable } from 'vs/base/common/lifecycle';
import * as performance from 'vs/base/common/performance';
import { StopWatch } from 'vs/base/common/stopwatch';
import { generateUuid } from 'vs/base/common/uuid';
import { IIPCLogger } from 'vs/base/parts/ipc/common/ipc';
import { Client, ConnectionHealth, ISocket, PersistentProtocol, ProtocolConstants, SocketCloseEventType } from 'vs/base/parts/ipc/common/ipc.net';
import { ILogService } from 'vs/platform/log/common/log';
import { RemoteAgentConnectionContext } from 'vs/platform/remote/common/remoteAgentEnvironment';
import { RemoteAuthorityResolverError } from 'vs/platform/remote/common/remoteAuthorityResolver';
import { getRemoteServerRootPath } from 'vs/platform/remote/common/remoteHosts';
import { ISignService } from 'vs/platform/sign/common/sign';
const RECONNECT_TIMEOUT = 30 * 1000 /* 30s */;
export const enum ConnectionType {
Management = 1,
ExtensionHost = 2,
Tunnel = 3,
}
function connectionTypeToString(connectionType: ConnectionType): string {
switch (connectionType) {
case ConnectionType.Management:
return 'Management';
case ConnectionType.ExtensionHost:
return 'ExtensionHost';
case ConnectionType.Tunnel:
return 'Tunnel';
}
}
export interface AuthRequest {
type: 'auth';
auth: string;
data: string;
}
export interface SignRequest {
type: 'sign';
data: string;
signedData: string;
}
export interface ConnectionTypeRequest {
type: 'connectionType';
commit?: string;
signedData: string;
desiredConnectionType?: ConnectionType;
args?: any;
}
export interface ErrorMessage {
type: 'error';
reason: string;
}
export interface OKMessage {
type: 'ok';
}
export type HandshakeMessage = AuthRequest | SignRequest | ConnectionTypeRequest | ErrorMessage | OKMessage;
interface ISimpleConnectionOptions {
commit: string | undefined;
quality: string | undefined;
host: string;
port: number;
connectionToken: string | undefined;
reconnectionToken: string;
reconnectionProtocol: PersistentProtocol | null;
socketFactory: ISocketFactory;
signService: ISignService;
logService: ILogService;
}
export interface IConnectCallback {
(err: any | undefined, socket: ISocket | undefined): void;
}
export interface ISocketFactory {
connect(host: string, port: number, path: string, query: string, debugLabel: string, callback: IConnectCallback): void;
}
function createTimeoutCancellation(millis: number): CancellationToken {
const source = new CancellationTokenSource();
setTimeout(() => source.cancel(), millis);
return source.token;
}
function combineTimeoutCancellation(a: CancellationToken, b: CancellationToken): CancellationToken {
if (a.isCancellationRequested || b.isCancellationRequested) {
return CancellationToken.Cancelled;
}
const source = new CancellationTokenSource();
a.onCancellationRequested(() => source.cancel());
b.onCancellationRequested(() => source.cancel());
return source.token;
}
class PromiseWithTimeout<T> {
private _state: 'pending' | 'resolved' | 'rejected' | 'timedout';
private readonly _disposables: DisposableStore;
public readonly promise: Promise<T>;
private _resolvePromise!: (value: T) => void;
private _rejectPromise!: (err: any) => void;
public get didTimeout(): boolean {
return (this._state === 'timedout');
}
constructor(timeoutCancellationToken: CancellationToken) {
this._state = 'pending';
this._disposables = new DisposableStore();
this.promise = new Promise<T>((resolve, reject) => {
this._resolvePromise = resolve;
this._rejectPromise = reject;
});
if (timeoutCancellationToken.isCancellationRequested) {
this._timeout();
} else {
this._disposables.add(timeoutCancellationToken.onCancellationRequested(() => this._timeout()));
}
}
public registerDisposable(disposable: IDisposable): void {
if (this._state === 'pending') {
this._disposables.add(disposable);
} else {
disposable.dispose();
}
}
private _timeout(): void {
if (this._state !== 'pending') {
return;
}
this._disposables.dispose();
this._state = 'timedout';
this._rejectPromise(this._createTimeoutError());
}
private _createTimeoutError(): Error {
const err: any = new Error('Time limit reached');
err.code = 'ETIMEDOUT';
err.syscall = 'connect';
return err;
}
public resolve(value: T): void {
if (this._state !== 'pending') {
return;
}
this._disposables.dispose();
this._state = 'resolved';
this._resolvePromise(value);
}
public reject(err: any): void {
if (this._state !== 'pending') {
return;
}
this._disposables.dispose();
this._state = 'rejected';
this._rejectPromise(err);
}
}
function readOneControlMessage<T>(protocol: PersistentProtocol, timeoutCancellationToken: CancellationToken): Promise<T> {
const result = new PromiseWithTimeout<T>(timeoutCancellationToken);
result.registerDisposable(protocol.onControlMessage(raw => {
const msg: T = JSON.parse(raw.toString());
const error = getErrorFromMessage(msg);
if (error) {
result.reject(error);
} else {
result.resolve(msg);
}
}));
return result.promise;
}
function createSocket(logService: ILogService, socketFactory: ISocketFactory, host: string, port: number, path: string, query: string, debugConnectionType: string, debugLabel: string, timeoutCancellationToken: CancellationToken): Promise<ISocket> {
const result = new PromiseWithTimeout<ISocket>(timeoutCancellationToken);
const sw = StopWatch.create(false);
logService.info(`Creating a socket (${debugLabel})...`);
performance.mark(`code/willCreateSocket/${debugConnectionType}`);
socketFactory.connect(host, port, path, query, debugLabel, (err: any, socket: ISocket | undefined) => {
if (result.didTimeout) {
performance.mark(`code/didCreateSocketError/${debugConnectionType}`);
logService.info(`Creating a socket (${debugLabel}) finished after ${sw.elapsed()} ms, but this is too late and has timed out already.`);
if (err) {
logService.error(err);
}
socket?.dispose();
} else {
if (err || !socket) {
performance.mark(`code/didCreateSocketError/${debugConnectionType}`);
logService.info(`Creating a socket (${debugLabel}) returned an error after ${sw.elapsed()} ms.`);
result.reject(err);
} else {
performance.mark(`code/didCreateSocketOK/${debugConnectionType}`);
logService.info(`Creating a socket (${debugLabel}) was successful after ${sw.elapsed()} ms.`);
result.resolve(socket);
}
}
});
return result.promise;
}
function raceWithTimeoutCancellation<T>(promise: Promise<T>, timeoutCancellationToken: CancellationToken): Promise<T> {
const result = new PromiseWithTimeout<T>(timeoutCancellationToken);
promise.then(
(res) => {
if (!result.didTimeout) {
result.resolve(res);
}
},
(err) => {
if (!result.didTimeout) {
result.reject(err);
}
}
);
return result.promise;
}
async function connectToRemoteExtensionHostAgent(options: ISimpleConnectionOptions, connectionType: ConnectionType, args: any | undefined, timeoutCancellationToken: CancellationToken): Promise<{ protocol: PersistentProtocol; ownsProtocol: boolean }> {
const logPrefix = connectLogPrefix(options, connectionType);
options.logService.trace(`${logPrefix} 1/6. invoking socketFactory.connect().`);
let socket: ISocket;
try {
socket = await createSocket(options.logService, options.socketFactory, options.host, options.port, getRemoteServerRootPath(options), `reconnectionToken=${options.reconnectionToken}&reconnection=${options.reconnectionProtocol ? 'true' : 'false'}`, connectionTypeToString(connectionType), `renderer-${connectionTypeToString(connectionType)}-${options.reconnectionToken}`, timeoutCancellationToken);
} catch (error) {
options.logService.error(`${logPrefix} socketFactory.connect() failed or timed out. Error:`);
options.logService.error(error);
throw error;
}
options.logService.trace(`${logPrefix} 2/6. socketFactory.connect() was successful.`);
let protocol: PersistentProtocol;
let ownsProtocol: boolean;
if (options.reconnectionProtocol) {
options.reconnectionProtocol.beginAcceptReconnection(socket, null);
protocol = options.reconnectionProtocol;
ownsProtocol = false;
} else {
protocol = new PersistentProtocol({ socket, measureRoundTripTime: true });
ownsProtocol = true;
}
options.logService.trace(`${logPrefix} 3/6. sending AuthRequest control message.`);
const message = await raceWithTimeoutCancellation(options.signService.createNewMessage(generateUuid()), timeoutCancellationToken);
const authRequest: AuthRequest = {
type: 'auth',
auth: options.connectionToken || '00000000000000000000',
data: message.data
};
protocol.sendControl(VSBuffer.fromString(JSON.stringify(authRequest)));
try {
const msg = await readOneControlMessage<HandshakeMessage>(protocol, combineTimeoutCancellation(timeoutCancellationToken, createTimeoutCancellation(10000)));
if (msg.type !== 'sign' || typeof msg.data !== 'string') {
const error: any = new Error('Unexpected handshake message');
error.code = 'VSCODE_CONNECTION_ERROR';
throw error;
}
options.logService.trace(`${logPrefix} 4/6. received SignRequest control message.`);
const isValid = await raceWithTimeoutCancellation(options.signService.validate(message, msg.signedData), timeoutCancellationToken);
if (!isValid) {
const error: any = new Error('Refused to connect to unsupported server');
error.code = 'VSCODE_CONNECTION_ERROR';
throw error;
}
const signed = await raceWithTimeoutCancellation(options.signService.sign(msg.data), timeoutCancellationToken);
const connTypeRequest: ConnectionTypeRequest = {
type: 'connectionType',
commit: options.commit,
signedData: signed,
desiredConnectionType: connectionType
};
if (args) {
connTypeRequest.args = args;
}
options.logService.trace(`${logPrefix} 5/6. sending ConnectionTypeRequest control message.`);
protocol.sendControl(VSBuffer.fromString(JSON.stringify(connTypeRequest)));
return { protocol, ownsProtocol };
} catch (error) {
if (error && error.code === 'ETIMEDOUT') {
options.logService.error(`${logPrefix} the handshake timed out. Error:`);
options.logService.error(error);
}
if (error && error.code === 'VSCODE_CONNECTION_ERROR') {
options.logService.error(`${logPrefix} received error control message when negotiating connection. Error:`);
options.logService.error(error);
}
if (ownsProtocol) {
safeDisposeProtocolAndSocket(protocol);
}
throw error;
}
}
interface IManagementConnectionResult {
protocol: PersistentProtocol;
}
async function connectToRemoteExtensionHostAgentAndReadOneMessage<T>(options: ISimpleConnectionOptions, connectionType: ConnectionType, args: any | undefined, timeoutCancellationToken: CancellationToken): Promise<{ protocol: PersistentProtocol; firstMessage: T }> {
const startTime = Date.now();
const logPrefix = connectLogPrefix(options, connectionType);
const { protocol, ownsProtocol } = await connectToRemoteExtensionHostAgent(options, connectionType, args, timeoutCancellationToken);
const result = new PromiseWithTimeout<{ protocol: PersistentProtocol; firstMessage: T }>(timeoutCancellationToken);
result.registerDisposable(protocol.onControlMessage(raw => {
const msg: T = JSON.parse(raw.toString());
const error = getErrorFromMessage(msg);
if (error) {
options.logService.error(`${logPrefix} received error control message when negotiating connection. Error:`);
options.logService.error(error);
if (ownsProtocol) {
safeDisposeProtocolAndSocket(protocol);
}
result.reject(error);
} else {
options.reconnectionProtocol?.endAcceptReconnection();
options.logService.trace(`${logPrefix} 6/6. handshake finished, connection is up and running after ${logElapsed(startTime)}!`);
result.resolve({ protocol, firstMessage: msg });
}
}));
return result.promise;
}
async function doConnectRemoteAgentManagement(options: ISimpleConnectionOptions, timeoutCancellationToken: CancellationToken): Promise<IManagementConnectionResult> {
const { protocol } = await connectToRemoteExtensionHostAgentAndReadOneMessage(options, ConnectionType.Management, undefined, timeoutCancellationToken);
return { protocol };
}
export interface IRemoteExtensionHostStartParams {
language: string;
debugId?: string;
break?: boolean;
port?: number | null;
env?: { [key: string]: string | null };
}
interface IExtensionHostConnectionResult {
protocol: PersistentProtocol;
debugPort?: number;
}
async function doConnectRemoteAgentExtensionHost(options: ISimpleConnectionOptions, startArguments: IRemoteExtensionHostStartParams, timeoutCancellationToken: CancellationToken): Promise<IExtensionHostConnectionResult> {
const { protocol, firstMessage } = await connectToRemoteExtensionHostAgentAndReadOneMessage<{ debugPort?: number }>(options, ConnectionType.ExtensionHost, startArguments, timeoutCancellationToken);
const debugPort = firstMessage && firstMessage.debugPort;
return { protocol, debugPort };
}
export interface ITunnelConnectionStartParams {
host: string;
port: number;
}
async function doConnectRemoteAgentTunnel(options: ISimpleConnectionOptions, startParams: ITunnelConnectionStartParams, timeoutCancellationToken: CancellationToken): Promise<PersistentProtocol> {
const startTime = Date.now();
const logPrefix = connectLogPrefix(options, ConnectionType.Tunnel);
const { protocol } = await connectToRemoteExtensionHostAgent(options, ConnectionType.Tunnel, startParams, timeoutCancellationToken);
options.logService.trace(`${logPrefix} 6/6. handshake finished, connection is up and running after ${logElapsed(startTime)}!`);
return protocol;
}
export interface IConnectionOptions {
commit: string | undefined;
quality: string | undefined;
socketFactory: ISocketFactory;
addressProvider: IAddressProvider;
signService: ISignService;
logService: ILogService;
ipcLogger: IIPCLogger | null;
}
async function resolveConnectionOptions(options: IConnectionOptions, reconnectionToken: string, reconnectionProtocol: PersistentProtocol | null): Promise<ISimpleConnectionOptions> {
const { host, port, connectionToken } = await options.addressProvider.getAddress();
return {
commit: options.commit,
quality: options.quality,
host: host,
port: port,
connectionToken: connectionToken,
reconnectionToken: reconnectionToken,
reconnectionProtocol: reconnectionProtocol,
socketFactory: options.socketFactory,
signService: options.signService,
logService: options.logService
};
}
export interface IAddress {
host: string;
port: number;
connectionToken: string | undefined;
}
export interface IAddressProvider {
getAddress(): Promise<IAddress>;
}
export async function connectRemoteAgentManagement(options: IConnectionOptions, remoteAuthority: string, clientId: string): Promise<ManagementPersistentConnection> {
return createInitialConnection(
options,
async (simpleOptions) => {
const { protocol } = await doConnectRemoteAgentManagement(simpleOptions, CancellationToken.None);
return new ManagementPersistentConnection(options, remoteAuthority, clientId, simpleOptions.reconnectionToken, protocol);
}
);
}
export async function connectRemoteAgentExtensionHost(options: IConnectionOptions, startArguments: IRemoteExtensionHostStartParams): Promise<ExtensionHostPersistentConnection> {
return createInitialConnection(
options,
async (simpleOptions) => {
const { protocol, debugPort } = await doConnectRemoteAgentExtensionHost(simpleOptions, startArguments, CancellationToken.None);
return new ExtensionHostPersistentConnection(options, startArguments, simpleOptions.reconnectionToken, protocol, debugPort);
}
);
}
/**
* Will attempt to connect 5 times. If it fails 5 consecutive times, it will give up.
*/
async function createInitialConnection<T extends PersistentConnection>(options: IConnectionOptions, connectionFactory: (simpleOptions: ISimpleConnectionOptions) => Promise<T>): Promise<T> {
const MAX_ATTEMPTS = 5;
for (let attempt = 1; ; attempt++) {
try {
const reconnectionToken = generateUuid();
const simpleOptions = await resolveConnectionOptions(options, reconnectionToken, null);
const result = await connectionFactory(simpleOptions);
return result;
} catch (err) {
if (attempt < MAX_ATTEMPTS) {
options.logService.error(`[remote-connection][attempt ${attempt}] An error occurred in initial connection! Will retry... Error:`);
options.logService.error(err);
} else {
options.logService.error(`[remote-connection][attempt ${attempt}] An error occurred in initial connection! It will be treated as a permanent error. Error:`);
options.logService.error(err);
PersistentConnection.triggerPermanentFailure(0, 0, RemoteAuthorityResolverError.isHandled(err));
throw err;
}
}
}
}
export async function connectRemoteAgentTunnel(options: IConnectionOptions, tunnelRemoteHost: string, tunnelRemotePort: number): Promise<PersistentProtocol> {
const simpleOptions = await resolveConnectionOptions(options, generateUuid(), null);
const protocol = await doConnectRemoteAgentTunnel(simpleOptions, { host: tunnelRemoteHost, port: tunnelRemotePort }, CancellationToken.None);
return protocol;
}
function sleep(seconds: number): CancelablePromise<void> {
return createCancelablePromise(token => {
return new Promise((resolve, reject) => {
const timeout = setTimeout(resolve, seconds * 1000);
token.onCancellationRequested(() => {
clearTimeout(timeout);
resolve();
});
});
});
}
export const enum PersistentConnectionEventType {
ConnectionLost,
ReconnectionWait,
ReconnectionRunning,
ReconnectionPermanentFailure,
ConnectionGain,
ConnectionHealthChanged
}
export class ConnectionLostEvent {
public readonly type = PersistentConnectionEventType.ConnectionLost;
constructor(
public readonly reconnectionToken: string,
public readonly millisSinceLastIncomingData: number
) { }
}
export class ReconnectionWaitEvent {
public readonly type = PersistentConnectionEventType.ReconnectionWait;
constructor(
public readonly reconnectionToken: string,
public readonly millisSinceLastIncomingData: number,
public readonly durationSeconds: number,
private readonly cancellableTimer: CancelablePromise<void>
) { }
public skipWait(): void {
this.cancellableTimer.cancel();
}
}
export class ReconnectionRunningEvent {
public readonly type = PersistentConnectionEventType.ReconnectionRunning;
constructor(
public readonly reconnectionToken: string,
public readonly millisSinceLastIncomingData: number,
public readonly attempt: number
) { }
}
export class ConnectionGainEvent {
public readonly type = PersistentConnectionEventType.ConnectionGain;
constructor(
public readonly reconnectionToken: string,
public readonly millisSinceLastIncomingData: number,
public readonly attempt: number
) { }
}
export class ConnectionHealthChangedEvent {
public readonly type = PersistentConnectionEventType.ConnectionHealthChanged;
constructor(
public readonly reconnectionToken: string,
public readonly connectionHealth: ConnectionHealth
) { }
}
export class ReconnectionPermanentFailureEvent {
public readonly type = PersistentConnectionEventType.ReconnectionPermanentFailure;
constructor(
public readonly reconnectionToken: string,
public readonly millisSinceLastIncomingData: number,
public readonly attempt: number,
public readonly handled: boolean
) { }
}
export type PersistentConnectionEvent = ConnectionGainEvent | ConnectionHealthChangedEvent | ConnectionLostEvent | ReconnectionWaitEvent | ReconnectionRunningEvent | ReconnectionPermanentFailureEvent;
export abstract class PersistentConnection extends Disposable {
public static triggerPermanentFailure(millisSinceLastIncomingData: number, attempt: number, handled: boolean): void {
this._permanentFailure = true;
this._permanentFailureMillisSinceLastIncomingData = millisSinceLastIncomingData;
this._permanentFailureAttempt = attempt;
this._permanentFailureHandled = handled;
this._instances.forEach(instance => instance._gotoPermanentFailure(this._permanentFailureMillisSinceLastIncomingData, this._permanentFailureAttempt, this._permanentFailureHandled));
}
public static debugTriggerReconnection() {
this._instances.forEach(instance => instance._beginReconnecting());
}
public static debugPauseSocketWriting() {
this._instances.forEach(instance => instance._pauseSocketWriting());
}
private static _permanentFailure: boolean = false;
private static _permanentFailureMillisSinceLastIncomingData: number = 0;
private static _permanentFailureAttempt: number = 0;
private static _permanentFailureHandled: boolean = false;
private static _instances: PersistentConnection[] = [];
private readonly _onDidStateChange = this._register(new Emitter<PersistentConnectionEvent>());
public readonly onDidStateChange = this._onDidStateChange.event;
private _permanentFailure: boolean = false;
private get _isPermanentFailure(): boolean {
return this._permanentFailure || PersistentConnection._permanentFailure;
}
private _isReconnecting: boolean = false;
private _isDisposed: boolean = false;
constructor(
private readonly _connectionType: ConnectionType,
protected readonly _options: IConnectionOptions,
public readonly reconnectionToken: string,
public readonly protocol: PersistentProtocol,
private readonly _reconnectionFailureIsFatal: boolean
) {
super();
this._onDidStateChange.fire(new ConnectionGainEvent(this.reconnectionToken, 0, 0));
this._register(protocol.onSocketClose((e) => {
const logPrefix = commonLogPrefix(this._connectionType, this.reconnectionToken, true);
if (!e) {
this._options.logService.info(`${logPrefix} received socket close event.`);
} else if (e.type === SocketCloseEventType.NodeSocketCloseEvent) {
this._options.logService.info(`${logPrefix} received socket close event (hadError: ${e.hadError}).`);
if (e.error) {
this._options.logService.error(e.error);
}
} else {
this._options.logService.info(`${logPrefix} received socket close event (wasClean: ${e.wasClean}, code: ${e.code}, reason: ${e.reason}).`);
if (e.event) {
this._options.logService.error(e.event);
}
}
this._beginReconnecting();
}));
this._register(protocol.onSocketTimeout((e) => {
const logPrefix = commonLogPrefix(this._connectionType, this.reconnectionToken, true);
this._options.logService.info(`${logPrefix} received socket timeout event (unacknowledgedMsgCount: ${e.unacknowledgedMsgCount}, timeSinceOldestUnacknowledgedMsg: ${e.timeSinceOldestUnacknowledgedMsg}, timeSinceLastReceivedSomeData: ${e.timeSinceLastReceivedSomeData}).`);
this._beginReconnecting();
}));
this._register(protocol.onHighRoundTripTime((e) => {
const logPrefix = _commonLogPrefix(this._connectionType, this.reconnectionToken);
this._options.logService.info(`${logPrefix} high roundtrip time: ${e.roundTripTime}ms (${e.recentHighRoundTripCount} of ${ProtocolConstants.LatencySampleCount} recent samples)`);
}));
this._register(protocol.onDidChangeConnectionHealth((connectionHealth) => {
this._onDidStateChange.fire(new ConnectionHealthChangedEvent(this.reconnectionToken, connectionHealth));
}));
PersistentConnection._instances.push(this);
this._register(toDisposable(() => {
const myIndex = PersistentConnection._instances.indexOf(this);
if (myIndex >= 0) {
PersistentConnection._instances.splice(myIndex, 1);
}
}));
if (this._isPermanentFailure) {
this._gotoPermanentFailure(PersistentConnection._permanentFailureMillisSinceLastIncomingData, PersistentConnection._permanentFailureAttempt, PersistentConnection._permanentFailureHandled);
}
}
public override dispose(): void {
super.dispose();
this._isDisposed = true;
}
private async _beginReconnecting(): Promise<void> {
// Only have one reconnection loop active at a time.
if (this._isReconnecting) {
return;
}
try {
this._isReconnecting = true;
await this._runReconnectingLoop();
} finally {
this._isReconnecting = false;
}
}
private async _runReconnectingLoop(): Promise<void> {
if (this._isPermanentFailure || this._isDisposed) {
// no more attempts!
return;
}
const logPrefix = commonLogPrefix(this._connectionType, this.reconnectionToken, true);
this._options.logService.info(`${logPrefix} starting reconnecting loop. You can get more information with the trace log level.`);
this._onDidStateChange.fire(new ConnectionLostEvent(this.reconnectionToken, this.protocol.getMillisSinceLastIncomingData()));
const TIMES = [0, 5, 5, 10, 10, 10, 10, 10, 30];
let attempt = -1;
do {
attempt++;
const waitTime = (attempt < TIMES.length ? TIMES[attempt] : TIMES[TIMES.length - 1]);
try {
if (waitTime > 0) {
const sleepPromise = sleep(waitTime);
this._onDidStateChange.fire(new ReconnectionWaitEvent(this.reconnectionToken, this.protocol.getMillisSinceLastIncomingData(), waitTime, sleepPromise));
this._options.logService.info(`${logPrefix} waiting for ${waitTime} seconds before reconnecting...`);
try {
await sleepPromise;
} catch { } // User canceled timer
}
if (this._isPermanentFailure) {
this._options.logService.error(`${logPrefix} permanent failure occurred while running the reconnecting loop.`);
break;
}
// connection was lost, let's try to re-establish it
this._onDidStateChange.fire(new ReconnectionRunningEvent(this.reconnectionToken, this.protocol.getMillisSinceLastIncomingData(), attempt + 1));
this._options.logService.info(`${logPrefix} resolving connection...`);
const simpleOptions = await resolveConnectionOptions(this._options, this.reconnectionToken, this.protocol);
this._options.logService.info(`${logPrefix} connecting to ${simpleOptions.host}:${simpleOptions.port}...`);
await this._reconnect(simpleOptions, createTimeoutCancellation(RECONNECT_TIMEOUT));
this._options.logService.info(`${logPrefix} reconnected!`);
this._onDidStateChange.fire(new ConnectionGainEvent(this.reconnectionToken, this.protocol.getMillisSinceLastIncomingData(), attempt + 1));
break;
} catch (err) {
if (err.code === 'VSCODE_CONNECTION_ERROR') {
this._options.logService.error(`${logPrefix} A permanent error occurred in the reconnecting loop! Will give up now! Error:`);
this._options.logService.error(err);
this._onReconnectionPermanentFailure(this.protocol.getMillisSinceLastIncomingData(), attempt + 1, false);
break;
}
if (attempt > 360) {
// ReconnectionGraceTime is 3hrs, with 30s between attempts that yields a maximum of 360 attempts
this._options.logService.error(`${logPrefix} An error occurred while reconnecting, but it will be treated as a permanent error because the reconnection grace time has expired! Will give up now! Error:`);
this._options.logService.error(err);
this._onReconnectionPermanentFailure(this.protocol.getMillisSinceLastIncomingData(), attempt + 1, false);
break;
}
if (RemoteAuthorityResolverError.isTemporarilyNotAvailable(err)) {
this._options.logService.info(`${logPrefix} A temporarily not available error occurred while trying to reconnect, will try again...`);
this._options.logService.trace(err);
// try again!
continue;
}
if ((err.code === 'ETIMEDOUT' || err.code === 'ENETUNREACH' || err.code === 'ECONNREFUSED' || err.code === 'ECONNRESET') && err.syscall === 'connect') {
this._options.logService.info(`${logPrefix} A network error occurred while trying to reconnect, will try again...`);
this._options.logService.trace(err);
// try again!
continue;
}
if (isCancellationError(err)) {
this._options.logService.info(`${logPrefix} A promise cancelation error occurred while trying to reconnect, will try again...`);
this._options.logService.trace(err);
// try again!
continue;
}
if (err instanceof RemoteAuthorityResolverError) {
this._options.logService.error(`${logPrefix} A RemoteAuthorityResolverError occurred while trying to reconnect. Will give up now! Error:`);
this._options.logService.error(err);
this._onReconnectionPermanentFailure(this.protocol.getMillisSinceLastIncomingData(), attempt + 1, RemoteAuthorityResolverError.isHandled(err));
break;
}
this._options.logService.error(`${logPrefix} An unknown error occurred while trying to reconnect, since this is an unknown case, it will be treated as a permanent error! Will give up now! Error:`);
this._options.logService.error(err);
this._onReconnectionPermanentFailure(this.protocol.getMillisSinceLastIncomingData(), attempt + 1, false);
break;
}
} while (!this._isPermanentFailure && !this._isDisposed);
}
private _onReconnectionPermanentFailure(millisSinceLastIncomingData: number, attempt: number, handled: boolean): void {
if (this._reconnectionFailureIsFatal) {
PersistentConnection.triggerPermanentFailure(millisSinceLastIncomingData, attempt, handled);
} else {
this._gotoPermanentFailure(millisSinceLastIncomingData, attempt, handled);
}
}
private _gotoPermanentFailure(millisSinceLastIncomingData: number, attempt: number, handled: boolean): void {
this._onDidStateChange.fire(new ReconnectionPermanentFailureEvent(this.reconnectionToken, millisSinceLastIncomingData, attempt, handled));
safeDisposeProtocolAndSocket(this.protocol);
}
private _pauseSocketWriting(): void {
this.protocol.pauseSocketWriting();
}
protected abstract _reconnect(options: ISimpleConnectionOptions, timeoutCancellationToken: CancellationToken): Promise<void>;
}
export class ManagementPersistentConnection extends PersistentConnection {
public readonly client: Client<RemoteAgentConnectionContext>;
constructor(options: IConnectionOptions, remoteAuthority: string, clientId: string, reconnectionToken: string, protocol: PersistentProtocol) {
super(ConnectionType.Management, options, reconnectionToken, protocol, /*reconnectionFailureIsFatal*/true);
this.client = this._register(new Client<RemoteAgentConnectionContext>(protocol, {
remoteAuthority: remoteAuthority,
clientId: clientId
}, options.ipcLogger));
}
protected async _reconnect(options: ISimpleConnectionOptions, timeoutCancellationToken: CancellationToken): Promise<void> {
await doConnectRemoteAgentManagement(options, timeoutCancellationToken);
}
}
export class ExtensionHostPersistentConnection extends PersistentConnection {
private readonly _startArguments: IRemoteExtensionHostStartParams;
public readonly debugPort: number | undefined;
constructor(options: IConnectionOptions, startArguments: IRemoteExtensionHostStartParams, reconnectionToken: string, protocol: PersistentProtocol, debugPort: number | undefined) {
super(ConnectionType.ExtensionHost, options, reconnectionToken, protocol, /*reconnectionFailureIsFatal*/false);
this._startArguments = startArguments;
this.debugPort = debugPort;
}
protected async _reconnect(options: ISimpleConnectionOptions, timeoutCancellationToken: CancellationToken): Promise<void> {
await doConnectRemoteAgentExtensionHost(options, this._startArguments, timeoutCancellationToken);
}
}
function safeDisposeProtocolAndSocket(protocol: PersistentProtocol): void {
try {
protocol.acceptDisconnect();
const socket = protocol.getSocket();
protocol.dispose();
socket.dispose();
} catch (err) {
onUnexpectedError(err);
}
}
function getErrorFromMessage(msg: any): Error | null {
if (msg && msg.type === 'error') {
const error = new Error(`Connection error: ${msg.reason}`);
(<any>error).code = 'VSCODE_CONNECTION_ERROR';
return error;
}
return null;
}
function stringRightPad(str: string, len: number): string {
while (str.length < len) {
str += ' ';
}
return str;
}
function _commonLogPrefix(connectionType: ConnectionType, reconnectionToken: string): string {
return `[remote-connection][${stringRightPad(connectionTypeToString(connectionType), 13)}][${reconnectionToken.substr(0, 5)}…]`;
}
function commonLogPrefix(connectionType: ConnectionType, reconnectionToken: string, isReconnect: boolean): string {
return `${_commonLogPrefix(connectionType, reconnectionToken)}[${isReconnect ? 'reconnect' : 'initial'}]`;
}
function connectLogPrefix(options: ISimpleConnectionOptions, connectionType: ConnectionType): string {
return `${commonLogPrefix(connectionType, options.reconnectionToken, !!options.reconnectionProtocol)}[${options.host}:${options.port}]`;
}
function logElapsed(startTime: number): string {
return `${Date.now() - startTime} ms`;
}
| src/vs/platform/remote/common/remoteAgentConnection.ts | 0 | https://github.com/microsoft/vscode/commit/c2bf6225a12e7f7d8afada6ec39560bb38e5838a | [
0.002274188445881009,
0.00023123488062992692,
0.00016510432760696858,
0.00017046058201231062,
0.0002867449657060206
] |
{
"id": 11,
"code_window": [
"\t\tthis.pool.push(item);\n",
"\t}\n",
"}\n"
],
"labels": [
"keep",
"keep",
"add"
],
"after_edit": [
"\n",
"class InteractiveSessionVoteButton extends MenuEntryActionViewItem {\n",
"\toverride render(container: HTMLElement): void {\n",
"\t\tsuper.render(container);\n",
"\t\tcontainer.classList.toggle('checked', this.action.checked);\n",
"\t}\n",
"}"
],
"file_path": "src/vs/workbench/contrib/interactiveSession/browser/interactiveSessionListRenderer.ts",
"type": "add",
"edit_start_line_idx": 732
} | # THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.
# yarn lockfile v1
| extensions/log/yarn.lock | 0 | https://github.com/microsoft/vscode/commit/c2bf6225a12e7f7d8afada6ec39560bb38e5838a | [
0.00017009249131660908,
0.00017009249131660908,
0.00017009249131660908,
0.00017009249131660908,
0
] |
{
"id": 11,
"code_window": [
"\t\tthis.pool.push(item);\n",
"\t}\n",
"}\n"
],
"labels": [
"keep",
"keep",
"add"
],
"after_edit": [
"\n",
"class InteractiveSessionVoteButton extends MenuEntryActionViewItem {\n",
"\toverride render(container: HTMLElement): void {\n",
"\t\tsuper.render(container);\n",
"\t\tcontainer.classList.toggle('checked', this.action.checked);\n",
"\t}\n",
"}"
],
"file_path": "src/vs/workbench/contrib/interactiveSession/browser/interactiveSessionListRenderer.ts",
"type": "add",
"edit_start_line_idx": 732
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
interface ILimitedTaskFactory<T> {
factory: ITask<Promise<T>>;
c: (value: T | Promise<T>) => void;
e: (error?: unknown) => void;
}
interface ITask<T> {
(): T;
}
/**
* A helper to queue N promises and run them all with a max degree of parallelism. The helper
* ensures that at any time no more than M promises are running at the same time.
*
* Taken from 'src/vs/base/common/async.ts'
*/
export class Limiter<T> {
private _size = 0;
private runningPromises: number;
private readonly maxDegreeOfParalellism: number;
private readonly outstandingPromises: ILimitedTaskFactory<T>[];
constructor(maxDegreeOfParalellism: number) {
this.maxDegreeOfParalellism = maxDegreeOfParalellism;
this.outstandingPromises = [];
this.runningPromises = 0;
}
get size(): number {
return this._size;
}
queue(factory: ITask<Promise<T>>): Promise<T> {
this._size++;
return new Promise<T>((c, e) => {
this.outstandingPromises.push({ factory, c, e });
this.consume();
});
}
private consume(): void {
while (this.outstandingPromises.length && this.runningPromises < this.maxDegreeOfParalellism) {
const iLimitedTask = this.outstandingPromises.shift()!;
this.runningPromises++;
const promise = iLimitedTask.factory();
promise.then(iLimitedTask.c, iLimitedTask.e);
promise.then(() => this.consumed(), () => this.consumed());
}
}
private consumed(): void {
this._size--;
this.runningPromises--;
if (this.outstandingPromises.length > 0) {
this.consume();
}
}
}
| extensions/markdown-language-features/server/src/util/limiter.ts | 0 | https://github.com/microsoft/vscode/commit/c2bf6225a12e7f7d8afada6ec39560bb38e5838a | [
0.00020786782260984182,
0.0001769671362126246,
0.00016760287689976394,
0.00016987464914564043,
0.000013782631867798045
] |
{
"id": 12,
"code_window": [
"\n",
".interactive-list .interactive-item-container.interactive-response:hover .header .monaco-toolbar {\n",
"\tdisplay: initial;\n",
"}\n",
"\n",
".interactive-list .interactive-item-container .value {\n",
"\twidth: 100%;\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
".interactive-list .interactive-item-container .header .monaco-toolbar .action-label {\n",
"\tborder: 1px solid transparent;\n",
"\tpadding: 2px;\n",
"}\n",
"\n",
".interactive-list .interactive-item-container .header .monaco-toolbar .checked .action-label,\n",
".interactive-list .interactive-item-container .header .monaco-toolbar .checked .action-label:hover {\n",
"\tcolor: var(--vscode-inputOption-activeForeground) !important;\n",
"\tborder-color: var(--vscode-inputOption-activeBorder);\n",
"\tbackground-color: var(--vscode-inputOption-activeBackground);\n",
"}\n",
"\n"
],
"file_path": "src/vs/workbench/contrib/interactiveSession/browser/media/interactiveSession.css",
"type": "add",
"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.
*--------------------------------------------------------------------------------------------*/
import { Codicon } from 'vs/base/common/codicons';
import { ServicesAccessor } from 'vs/editor/browser/editorExtensions';
import { localize } from 'vs/nls';
import { Action2, MenuId, registerAction2 } from 'vs/platform/actions/common/actions';
import { ContextKeyExpr } from 'vs/platform/contextkey/common/contextkey';
import { INTERACTIVE_SESSION_CATEGORY } from 'vs/workbench/contrib/interactiveSession/browser/actions/interactiveSessionActions';
import { CONTEXT_RESPONSE_HAS_PROVIDER_ID, CONTEXT_RESPONSE_VOTE } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionContextKeys';
import { IInteractiveSessionService, IInteractiveSessionUserActionEvent, InteractiveSessionVoteDirection } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionService';
import { isResponseVM } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionViewModel';
export function registerInteractiveSessionTitleActions() {
registerAction2(class VoteUpAction extends Action2 {
constructor() {
super({
id: 'workbench.action.interactiveSession.voteUp',
title: {
value: localize('interactive.voteUp.label', "Vote Up"),
original: 'Vote Up'
},
f1: false,
category: INTERACTIVE_SESSION_CATEGORY,
icon: Codicon.thumbsup,
precondition: CONTEXT_RESPONSE_VOTE.isEqualTo(''), // Should be disabled but visible when vote=down
menu: {
id: MenuId.InteractiveSessionTitle,
when: ContextKeyExpr.and(CONTEXT_RESPONSE_HAS_PROVIDER_ID, CONTEXT_RESPONSE_VOTE.notEqualsTo('down')),
group: 'navigation',
order: 1
}
});
}
run(accessor: ServicesAccessor, ...args: any[]) {
const item = args[0];
if (!isResponseVM(item)) {
return;
}
const interactiveSessionService = accessor.get(IInteractiveSessionService);
interactiveSessionService.notifyUserAction(<IInteractiveSessionUserActionEvent>{
providerId: item.providerId,
action: {
kind: 'vote',
direction: InteractiveSessionVoteDirection.Up,
responseId: item.providerResponseId
}
});
item.setVote(InteractiveSessionVoteDirection.Up);
}
});
registerAction2(class VoteDownAction extends Action2 {
constructor() {
super({
id: 'workbench.action.interactiveSession.voteDown',
title: {
value: localize('interactive.voteDown.label', "Vote Down"),
original: 'Vote Down'
},
f1: false,
category: INTERACTIVE_SESSION_CATEGORY,
icon: Codicon.thumbsdown,
precondition: CONTEXT_RESPONSE_VOTE.isEqualTo(''), // Should be disabled but visible when vote=down
menu: {
id: MenuId.InteractiveSessionTitle,
when: ContextKeyExpr.and(CONTEXT_RESPONSE_HAS_PROVIDER_ID, CONTEXT_RESPONSE_VOTE.notEqualsTo('up')),
group: 'navigation',
order: 2
}
});
}
run(accessor: ServicesAccessor, ...args: any[]) {
const item = args[0];
if (!isResponseVM(item)) {
return;
}
const interactiveSessionService = accessor.get(IInteractiveSessionService);
interactiveSessionService.notifyUserAction(<IInteractiveSessionUserActionEvent>{
providerId: item.providerId,
action: {
kind: 'vote',
direction: InteractiveSessionVoteDirection.Down,
responseId: item.providerResponseId
}
});
item.setVote(InteractiveSessionVoteDirection.Down);
}
});
}
| src/vs/workbench/contrib/interactiveSession/browser/actions/interactiveSessionTitleActions.ts | 1 | https://github.com/microsoft/vscode/commit/c2bf6225a12e7f7d8afada6ec39560bb38e5838a | [
0.0002504707663320005,
0.00018673090380616486,
0.00016732868971303105,
0.00017273139383178204,
0.000030940725991968066
] |
{
"id": 12,
"code_window": [
"\n",
".interactive-list .interactive-item-container.interactive-response:hover .header .monaco-toolbar {\n",
"\tdisplay: initial;\n",
"}\n",
"\n",
".interactive-list .interactive-item-container .value {\n",
"\twidth: 100%;\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
".interactive-list .interactive-item-container .header .monaco-toolbar .action-label {\n",
"\tborder: 1px solid transparent;\n",
"\tpadding: 2px;\n",
"}\n",
"\n",
".interactive-list .interactive-item-container .header .monaco-toolbar .checked .action-label,\n",
".interactive-list .interactive-item-container .header .monaco-toolbar .checked .action-label:hover {\n",
"\tcolor: var(--vscode-inputOption-activeForeground) !important;\n",
"\tborder-color: var(--vscode-inputOption-activeBorder);\n",
"\tbackground-color: var(--vscode-inputOption-activeBackground);\n",
"}\n",
"\n"
],
"file_path": "src/vs/workbench/contrib/interactiveSession/browser/media/interactiveSession.css",
"type": "add",
"edit_start_line_idx": 73
} | swagger: '2.0'
info:
description: 'The API Management Service API defines an updated and refined version
of the concepts currently known as Developer, APP, and API Product in Edge. Of
note is the introduction of the API concept, missing previously from Edge
'
title: API Management Service API
version: initial | extensions/vscode-colorize-tests/test/colorize-fixtures/issue-6303.yaml | 0 | https://github.com/microsoft/vscode/commit/c2bf6225a12e7f7d8afada6ec39560bb38e5838a | [
0.0003790666232816875,
0.0003790666232816875,
0.0003790666232816875,
0.0003790666232816875,
0
] |
{
"id": 12,
"code_window": [
"\n",
".interactive-list .interactive-item-container.interactive-response:hover .header .monaco-toolbar {\n",
"\tdisplay: initial;\n",
"}\n",
"\n",
".interactive-list .interactive-item-container .value {\n",
"\twidth: 100%;\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
".interactive-list .interactive-item-container .header .monaco-toolbar .action-label {\n",
"\tborder: 1px solid transparent;\n",
"\tpadding: 2px;\n",
"}\n",
"\n",
".interactive-list .interactive-item-container .header .monaco-toolbar .checked .action-label,\n",
".interactive-list .interactive-item-container .header .monaco-toolbar .checked .action-label:hover {\n",
"\tcolor: var(--vscode-inputOption-activeForeground) !important;\n",
"\tborder-color: var(--vscode-inputOption-activeBorder);\n",
"\tbackground-color: var(--vscode-inputOption-activeBackground);\n",
"}\n",
"\n"
],
"file_path": "src/vs/workbench/contrib/interactiveSession/browser/media/interactiveSession.css",
"type": "add",
"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.
*--------------------------------------------------------------------------------------------*/
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { ICommandService, ICommandEvent, CommandsRegistry } from 'vs/platform/commands/common/commands';
import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions';
import { Event, Emitter } from 'vs/base/common/event';
import { Disposable } from 'vs/base/common/lifecycle';
import { ILogService } from 'vs/platform/log/common/log';
import { InstantiationType, registerSingleton } from 'vs/platform/instantiation/common/extensions';
import { timeout } from 'vs/base/common/async';
export class CommandService extends Disposable implements ICommandService {
declare readonly _serviceBrand: undefined;
private _extensionHostIsReady: boolean = false;
private _starActivation: Promise<void> | null;
private readonly _onWillExecuteCommand: Emitter<ICommandEvent> = this._register(new Emitter<ICommandEvent>());
public readonly onWillExecuteCommand: Event<ICommandEvent> = this._onWillExecuteCommand.event;
private readonly _onDidExecuteCommand: Emitter<ICommandEvent> = new Emitter<ICommandEvent>();
public readonly onDidExecuteCommand: Event<ICommandEvent> = this._onDidExecuteCommand.event;
constructor(
@IInstantiationService private readonly _instantiationService: IInstantiationService,
@IExtensionService private readonly _extensionService: IExtensionService,
@ILogService private readonly _logService: ILogService
) {
super();
this._extensionService.whenInstalledExtensionsRegistered().then(value => this._extensionHostIsReady = value);
this._starActivation = null;
}
private _activateStar(): Promise<void> {
if (!this._starActivation) {
// wait for * activation, limited to at most 30s
this._starActivation = Promise.race<any>([
this._extensionService.activateByEvent(`*`),
timeout(30000)
]);
}
return this._starActivation;
}
async executeCommand<T>(id: string, ...args: any[]): Promise<T> {
this._logService.trace('CommandService#executeCommand', id);
const activationEvent = `onCommand:${id}`;
const commandIsRegistered = !!CommandsRegistry.getCommand(id);
if (commandIsRegistered) {
// if the activation event has already resolved (i.e. subsequent call),
// we will execute the registered command immediately
if (this._extensionService.activationEventIsDone(activationEvent)) {
return this._tryExecuteCommand(id, args);
}
// if the extension host didn't start yet, we will execute the registered
// command immediately and send an activation event, but not wait for it
if (!this._extensionHostIsReady) {
this._extensionService.activateByEvent(activationEvent); // intentionally not awaited
return this._tryExecuteCommand(id, args);
}
// we will wait for a simple activation event (e.g. in case an extension wants to overwrite it)
await this._extensionService.activateByEvent(activationEvent);
return this._tryExecuteCommand(id, args);
}
// finally, if the command is not registered we will send a simple activation event
// as well as a * activation event raced against registration and against 30s
await Promise.all([
this._extensionService.activateByEvent(activationEvent),
Promise.race<any>([
// race * activation against command registration
this._activateStar(),
Event.toPromise(Event.filter(CommandsRegistry.onDidRegisterCommand, e => e === id))
]),
]);
return this._tryExecuteCommand(id, args);
}
private _tryExecuteCommand(id: string, args: any[]): Promise<any> {
const command = CommandsRegistry.getCommand(id);
if (!command) {
return Promise.reject(new Error(`command '${id}' not found`));
}
try {
this._onWillExecuteCommand.fire({ commandId: id, args });
const result = this._instantiationService.invokeFunction(command.handler, ...args);
this._onDidExecuteCommand.fire({ commandId: id, args });
return Promise.resolve(result);
} catch (err) {
return Promise.reject(err);
}
}
}
registerSingleton(ICommandService, CommandService, InstantiationType.Delayed);
| src/vs/workbench/services/commands/common/commandService.ts | 0 | https://github.com/microsoft/vscode/commit/c2bf6225a12e7f7d8afada6ec39560bb38e5838a | [
0.00017487684090156108,
0.0001717681880109012,
0.00016786229389254004,
0.00017176666005980223,
0.000002119560349456151
] |
{
"id": 12,
"code_window": [
"\n",
".interactive-list .interactive-item-container.interactive-response:hover .header .monaco-toolbar {\n",
"\tdisplay: initial;\n",
"}\n",
"\n",
".interactive-list .interactive-item-container .value {\n",
"\twidth: 100%;\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
".interactive-list .interactive-item-container .header .monaco-toolbar .action-label {\n",
"\tborder: 1px solid transparent;\n",
"\tpadding: 2px;\n",
"}\n",
"\n",
".interactive-list .interactive-item-container .header .monaco-toolbar .checked .action-label,\n",
".interactive-list .interactive-item-container .header .monaco-toolbar .checked .action-label:hover {\n",
"\tcolor: var(--vscode-inputOption-activeForeground) !important;\n",
"\tborder-color: var(--vscode-inputOption-activeBorder);\n",
"\tbackground-color: var(--vscode-inputOption-activeBackground);\n",
"}\n",
"\n"
],
"file_path": "src/vs/workbench/contrib/interactiveSession/browser/media/interactiveSession.css",
"type": "add",
"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.
*--------------------------------------------------------------------------------------------*/
import { handleANSIOutput } from './ansi';
export const scrollableClass = 'scrollable';
function generateViewMoreElement(outputId: string) {
const container = document.createElement('div');
const first = document.createElement('span');
first.textContent = 'Output exceeds the ';
const second = document.createElement('a');
second.textContent = 'size limit';
second.href = `command:workbench.action.openSettings?%5B%22notebook.output.textLineLimit%22%5D`;
container.appendChild(first);
container.appendChild(second);
const third = document.createElement('span');
third.textContent = '. Open the full output data ';
const forth = document.createElement('a');
forth.textContent = 'in a text editor';
forth.href = `command:workbench.action.openLargeOutput?${outputId}`;
container.appendChild(third);
container.appendChild(forth);
const refreshSpan = document.createElement('span');
refreshSpan.classList.add('scroll-refresh');
const fifth = document.createElement('span');
fifth.textContent = '. Refresh to view ';
const sixth = document.createElement('a');
sixth.textContent = 'scrollable element';
sixth.href = `command:cellOutput.enableScrolling?${outputId}`;
refreshSpan.appendChild(fifth);
refreshSpan.appendChild(sixth);
container.appendChild(refreshSpan);
return container;
}
function generateNestedViewAllElement(outputId: string) {
const container = document.createElement('div');
const link = document.createElement('a');
link.textContent = '...';
link.href = `command:workbench.action.openLargeOutput?${outputId}`;
link.ariaLabel = 'Open full output in text editor';
link.title = 'Open full output in text editor';
link.style.setProperty('text-decoration', 'none');
container.appendChild(link);
return container;
}
function truncatedArrayOfString(id: string, buffer: string[], linesLimit: number, trustHtml: boolean) {
const container = document.createElement('div');
const lineCount = buffer.length;
if (lineCount <= linesLimit) {
const spanElement = handleANSIOutput(buffer.join('\n'), trustHtml);
container.appendChild(spanElement);
return container;
}
container.appendChild(generateViewMoreElement(id));
container.appendChild(handleANSIOutput(buffer.slice(0, linesLimit - 5).join('\n'), trustHtml));
// truncated piece
const elipses = document.createElement('div');
elipses.innerText = '...';
container.appendChild(elipses);
container.appendChild(handleANSIOutput(buffer.slice(lineCount - 5).join('\n'), trustHtml));
return container;
}
function scrollableArrayOfString(id: string, buffer: string[], trustHtml: boolean) {
const element = document.createElement('div');
if (buffer.length > 5000) {
element.appendChild(generateNestedViewAllElement(id));
}
element.appendChild(handleANSIOutput(buffer.slice(-5000).join('\n'), trustHtml));
return element;
}
export function createOutputContent(id: string, outputs: string[], linesLimit: number, scrollable: boolean, trustHtml: boolean): HTMLElement {
const buffer = outputs.join('\n').split(/\r\n|\r|\n/g);
if (scrollable) {
return scrollableArrayOfString(id, buffer, trustHtml);
} else {
return truncatedArrayOfString(id, buffer, linesLimit, trustHtml);
}
}
| extensions/notebook-renderers/src/textHelper.ts | 0 | https://github.com/microsoft/vscode/commit/c2bf6225a12e7f7d8afada6ec39560bb38e5838a | [
0.00023784836230333894,
0.0001765947527019307,
0.00016640506510157138,
0.00017030622984748334,
0.000019565088223316707
] |
{
"id": 13,
"code_window": [
"}\n",
"\n",
".interactive-list .interactive-item-container .monaco-toolbar .codicon {\n",
"\t/* Very aggressive list styles try to apply focus colors to every codicon in a list row. */\n",
"\tcolor: var(--vscode-foreground) !important;\n",
"}\n",
"\n",
".interactive-session .interactive-item-container.filtered-response .value .rendered-markdown {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tcolor: var(--vscode-icon-foreground) !important;\n"
],
"file_path": "src/vs/workbench/contrib/interactiveSession/browser/media/interactiveSession.css",
"type": "replace",
"edit_start_line_idx": 326
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
.interactive-list .monaco-list-row:not(:first-of-type) .interactive-item-container {
border-top: 1px solid var(--vscode-interactive-responseBorder);
}
.interactive-list .monaco-list-row .monaco-tl-twistie {
/* Hide twisties */
display: none !important;
}
.interactive-list .interactive-item-container {
padding: 16px 20px 0px 20px;
display: flex;
flex-direction: column;
gap: 6px;
cursor: default;
user-select: text;
-webkit-user-select: text;
}
.interactive-list .interactive-item-container .header {
display: flex;
align-items: center;
justify-content: space-between;
}
.interactive-list .interactive-item-container .header .user {
display: flex;
align-items: center;
gap: 6px;
}
.interactive-list .interactive-item-container .header .username {
margin: 0;
font-size: 12px;
font-weight: 600;
}
.interactive-list .interactive-item-container .header .avatar {
display: flex;
align-items: center;
justify-content: center;
width: 24px;
height: 24px;
border-radius: 50%;
background: var(--vscode-badge-background);
pointer-events: none;
user-select: none;
}
.interactive-list .interactive-item-container .header .avatar .icon {
width: 24px;
height: 24px;
border-radius: 50%;
}
.interactive-list .interactive-item-container .header .avatar .codicon {
color: var(--vscode-badge-foreground) !important;
}
.interactive-list .interactive-item-container .header .monaco-toolbar {
display: none;
}
.interactive-list .interactive-item-container.interactive-response:hover .header .monaco-toolbar {
display: initial;
}
.interactive-list .interactive-item-container .value {
width: 100%;
}
.interactive-list .interactive-item-container .value table {
width: 100%;
text-align: left;
margin-bottom: 16px;
}
.interactive-list .interactive-item-container .value table,
.interactive-list .interactive-item-container .value table td,
.interactive-list .interactive-item-container .value table th {
border: 1px solid var(--vscode-interactive-responseBorder);
border-collapse: collapse;
padding: 4px 6px;
}
.interactive-list .interactive-item-container .value a {
color: var(--vscode-textLink-foreground);
}
.interactive-list .interactive-item-container .value a:hover,
.interactive-list .interactive-item-container .value a:active {
color: var(--vscode-textLink-activeForeground);
}
.interactive-list {
overflow: hidden;
}
.interactive-list .monaco-list-row .interactive-response,
.interactive-list .monaco-list-row .interactive-welcome {
background-color: var(--vscode-interactive-responseBackground);
}
.interactive-list .monaco-list-row .value {
white-space: normal;
min-height: 36px;
}
.interactive-list .monaco-list-row .value > :last-child:not(.rendered-markdown) {
/* The container has padding on all sides except the bottom. The last element needs to provide this margin. rendered-markdown has its own margin.
TODO Another approach could be removing the margin on the very last element inside the markdown container? */
margin-bottom: 16px;
}
.interactive-list .monaco-list-row .value > .interactive-response-error-details:not(:last-child) {
margin-bottom: 8px;
}
.interactive-list .monaco-list-row .value h1 {
font-size: 20px;
font-weight: 600;
margin: 16px 0;
}
.interactive-list .monaco-list-row .value h2 {
font-size: 16px;
font-weight: 600;
margin: 16px 0;
}
.interactive-list .monaco-list-row .value h3 {
font-size: 14px;
font-weight: 600;
margin: 16px 0;
}
.interactive-list .monaco-list-row .value p {
margin: 0 0 16px 0;
line-height: 1.6em;
}
.interactive-list .monaco-list-row .monaco-tokenized-source,
.interactive-list .monaco-list-row code {
font-family: var(--monaco-monospace-font);
word-break: break-all;
word-wrap: break-word;
}
.interactive-session .interactive-input-and-toolbar {
display: flex;
box-sizing: border-box;
cursor: text;
margin: 0px 12px;
background-color: var(--vscode-input-background);
border: 1px solid var(--vscode-input-border, transparent);
border-radius: 4px;
position: relative;
padding-left: 8px;
}
.interactive-session .interactive-input-and-toolbar.focused {
border-color: var(--vscode-focusBorder);
}
.interactive-session .interactive-input-and-toolbar .monaco-editor,
.interactive-session .interactive-input-and-toolbar .monaco-editor .monaco-editor-background {
background-color: var(--vscode-input-background) !important;
}
.interactive-session .interactive-input-and-toolbar .monaco-editor .cursors-layer {
padding-left: 4px;
}
.interactive-session .interactive-input-part .interactive-execute-toolbar {
position: absolute;
height: 22px;
right: 3px;
bottom: 6px;
}
.interactive-session .interactive-input-part .interactive-execute-toolbar .codicon-debug-stop {
color: var(--vscode-icon-foreground) !important;
}
.interactive-session .monaco-inputbox {
width: 100%;
}
.interactive-session .interactive-result-editor-wrapper {
position: relative;
}
.interactive-session .interactive-result-editor-wrapper .monaco-toolbar {
display: none;
position: absolute;
top: -13px;
right: 10px;
height: 26px;
background-color: var(--vscode-interactive-result-editor-background-color);
border: 1px solid var(--vscode-interactive-responseBorder);
z-index: 100;
}
.interactive-session .interactive-result-editor-wrapper .monaco-toolbar .action-item {
height: 24px;
width: 24px;
margin: 1px 2px;
}
.interactive-session .interactive-result-editor-wrapper .monaco-toolbar .action-item .codicon {
margin: 1px;
}
.interactive-session .interactive-result-editor-wrapper:hover .monaco-toolbar {
display: initial;
}
.interactive-session .interactive-result-editor-wrapper .interactive-result-editor {
border: 1px solid var(--vscode-input-border, transparent);
}
.interactive-session .interactive-response .monaco-editor .margin,
.interactive-session .interactive-response .monaco-editor .monaco-editor-background {
background-color: var(--vscode-interactive-result-editor-background-color);
}
.interactive-result-editor-wrapper {
margin: 16px 0;
}
.interactive-session .interactive-session-welcome-view {
box-sizing: border-box;
display: flex;
flex-direction: column;
justify-content: start;
padding: 20px;
gap: 16px;
}
.interactive-session .interactive-session-welcome-view .monaco-button {
max-width: 400px;
margin: 0;
}
.interactive-session .interactive-response .interactive-response-error-details {
display: flex;
align-items: start;
gap: 6px;
}
.interactive-session .interactive-response .interactive-response-error-details .codicon {
margin-top: 1px;
color: var(--vscode-errorForeground) !important; /* Have to override default styles which apply to all lists */
}
.interactive-session .interactive-item-container .value .interactive-slash-command {
color: var(--vscode-textLink-foreground);
}
.interactive-session .interactive-input-part {
padding: 12px 0px;
display: flex;
flex-direction: column;
border-top: solid 1px var(--vscode-interactive-responseBorder);
}
.interactive-session .interactive-session-followups {
display: flex;
flex-direction: column;
gap: 5px;
align-items: start;
}
.interactive-session .interactive-session-followups .monaco-button {
text-align: left;
width: initial;
}
.interactive-session .interactive-session-followups .monaco-button .codicon {
margin-left: 0;
margin-top: 1px;
}
.interactive-session .interactive-response-followups .monaco-button {
padding: 4px 8px;
}
.interactive-session .interactive-input-part .interactive-input-followups {
margin: 0px 20px;
}
.interactive-session .interactive-input-part .interactive-input-followups .interactive-session-followups {
margin-bottom: 8px;
}
.interactive-session .interactive-input-part .interactive-input-followups .interactive-session-followups .monaco-button {
display: block;
color: var(--vscode-textLink-foreground);
}
.interactive-session .interactive-input-part .interactive-input-followups .interactive-session-followups .monaco-button .codicon-sparkle {
float: left;
}
.interactive-session .interactive-session-followups .monaco-button.interactive-followup-reply {
padding: 0px;
font-size: 11px;
font-weight: 600;
border: none;
}
.interactive-session .interactive-welcome .value .interactive-session-followups {
margin-bottom: 10px;
}
.interactive-list .interactive-item-container .monaco-toolbar .codicon {
/* Very aggressive list styles try to apply focus colors to every codicon in a list row. */
color: var(--vscode-foreground) !important;
}
.interactive-session .interactive-item-container.filtered-response .value .rendered-markdown {
-webkit-mask-image: linear-gradient(rgba(0, 0, 0, 0.85), rgba(0, 0, 0, 0.05));
mask-image: linear-gradient(rgba(0, 0, 0, 0.85), rgba(0, 0, 0, 0.05));
}
| src/vs/workbench/contrib/interactiveSession/browser/media/interactiveSession.css | 1 | https://github.com/microsoft/vscode/commit/c2bf6225a12e7f7d8afada6ec39560bb38e5838a | [
0.9918121099472046,
0.03202931210398674,
0.00016812756075523794,
0.001831097062677145,
0.16713020205497742
] |
{
"id": 13,
"code_window": [
"}\n",
"\n",
".interactive-list .interactive-item-container .monaco-toolbar .codicon {\n",
"\t/* Very aggressive list styles try to apply focus colors to every codicon in a list row. */\n",
"\tcolor: var(--vscode-foreground) !important;\n",
"}\n",
"\n",
".interactive-session .interactive-item-container.filtered-response .value .rendered-markdown {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tcolor: var(--vscode-icon-foreground) !important;\n"
],
"file_path": "src/vs/workbench/contrib/interactiveSession/browser/media/interactiveSession.css",
"type": "replace",
"edit_start_line_idx": 326
} | /*---------------------------------------------------------------------------------------------
* 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 { toUint32 } from 'vs/base/common/uint';
import { PrefixSumComputer, PrefixSumIndexOfResult } from 'vs/editor/common/model/prefixSumComputer';
function toUint32Array(arr: number[]): Uint32Array {
const len = arr.length;
const r = new Uint32Array(len);
for (let i = 0; i < len; i++) {
r[i] = toUint32(arr[i]);
}
return r;
}
suite('Editor ViewModel - PrefixSumComputer', () => {
test('PrefixSumComputer', () => {
let indexOfResult: PrefixSumIndexOfResult;
const psc = new PrefixSumComputer(toUint32Array([1, 1, 2, 1, 3]));
assert.strictEqual(psc.getTotalSum(), 8);
assert.strictEqual(psc.getPrefixSum(-1), 0);
assert.strictEqual(psc.getPrefixSum(0), 1);
assert.strictEqual(psc.getPrefixSum(1), 2);
assert.strictEqual(psc.getPrefixSum(2), 4);
assert.strictEqual(psc.getPrefixSum(3), 5);
assert.strictEqual(psc.getPrefixSum(4), 8);
indexOfResult = psc.getIndexOf(0);
assert.strictEqual(indexOfResult.index, 0);
assert.strictEqual(indexOfResult.remainder, 0);
indexOfResult = psc.getIndexOf(1);
assert.strictEqual(indexOfResult.index, 1);
assert.strictEqual(indexOfResult.remainder, 0);
indexOfResult = psc.getIndexOf(2);
assert.strictEqual(indexOfResult.index, 2);
assert.strictEqual(indexOfResult.remainder, 0);
indexOfResult = psc.getIndexOf(3);
assert.strictEqual(indexOfResult.index, 2);
assert.strictEqual(indexOfResult.remainder, 1);
indexOfResult = psc.getIndexOf(4);
assert.strictEqual(indexOfResult.index, 3);
assert.strictEqual(indexOfResult.remainder, 0);
indexOfResult = psc.getIndexOf(5);
assert.strictEqual(indexOfResult.index, 4);
assert.strictEqual(indexOfResult.remainder, 0);
indexOfResult = psc.getIndexOf(6);
assert.strictEqual(indexOfResult.index, 4);
assert.strictEqual(indexOfResult.remainder, 1);
indexOfResult = psc.getIndexOf(7);
assert.strictEqual(indexOfResult.index, 4);
assert.strictEqual(indexOfResult.remainder, 2);
indexOfResult = psc.getIndexOf(8);
assert.strictEqual(indexOfResult.index, 4);
assert.strictEqual(indexOfResult.remainder, 3);
// [1, 2, 2, 1, 3]
psc.setValue(1, 2);
assert.strictEqual(psc.getTotalSum(), 9);
assert.strictEqual(psc.getPrefixSum(0), 1);
assert.strictEqual(psc.getPrefixSum(1), 3);
assert.strictEqual(psc.getPrefixSum(2), 5);
assert.strictEqual(psc.getPrefixSum(3), 6);
assert.strictEqual(psc.getPrefixSum(4), 9);
// [1, 0, 2, 1, 3]
psc.setValue(1, 0);
assert.strictEqual(psc.getTotalSum(), 7);
assert.strictEqual(psc.getPrefixSum(0), 1);
assert.strictEqual(psc.getPrefixSum(1), 1);
assert.strictEqual(psc.getPrefixSum(2), 3);
assert.strictEqual(psc.getPrefixSum(3), 4);
assert.strictEqual(psc.getPrefixSum(4), 7);
indexOfResult = psc.getIndexOf(0);
assert.strictEqual(indexOfResult.index, 0);
assert.strictEqual(indexOfResult.remainder, 0);
indexOfResult = psc.getIndexOf(1);
assert.strictEqual(indexOfResult.index, 2);
assert.strictEqual(indexOfResult.remainder, 0);
indexOfResult = psc.getIndexOf(2);
assert.strictEqual(indexOfResult.index, 2);
assert.strictEqual(indexOfResult.remainder, 1);
indexOfResult = psc.getIndexOf(3);
assert.strictEqual(indexOfResult.index, 3);
assert.strictEqual(indexOfResult.remainder, 0);
indexOfResult = psc.getIndexOf(4);
assert.strictEqual(indexOfResult.index, 4);
assert.strictEqual(indexOfResult.remainder, 0);
indexOfResult = psc.getIndexOf(5);
assert.strictEqual(indexOfResult.index, 4);
assert.strictEqual(indexOfResult.remainder, 1);
indexOfResult = psc.getIndexOf(6);
assert.strictEqual(indexOfResult.index, 4);
assert.strictEqual(indexOfResult.remainder, 2);
indexOfResult = psc.getIndexOf(7);
assert.strictEqual(indexOfResult.index, 4);
assert.strictEqual(indexOfResult.remainder, 3);
// [1, 0, 0, 1, 3]
psc.setValue(2, 0);
assert.strictEqual(psc.getTotalSum(), 5);
assert.strictEqual(psc.getPrefixSum(0), 1);
assert.strictEqual(psc.getPrefixSum(1), 1);
assert.strictEqual(psc.getPrefixSum(2), 1);
assert.strictEqual(psc.getPrefixSum(3), 2);
assert.strictEqual(psc.getPrefixSum(4), 5);
indexOfResult = psc.getIndexOf(0);
assert.strictEqual(indexOfResult.index, 0);
assert.strictEqual(indexOfResult.remainder, 0);
indexOfResult = psc.getIndexOf(1);
assert.strictEqual(indexOfResult.index, 3);
assert.strictEqual(indexOfResult.remainder, 0);
indexOfResult = psc.getIndexOf(2);
assert.strictEqual(indexOfResult.index, 4);
assert.strictEqual(indexOfResult.remainder, 0);
indexOfResult = psc.getIndexOf(3);
assert.strictEqual(indexOfResult.index, 4);
assert.strictEqual(indexOfResult.remainder, 1);
indexOfResult = psc.getIndexOf(4);
assert.strictEqual(indexOfResult.index, 4);
assert.strictEqual(indexOfResult.remainder, 2);
indexOfResult = psc.getIndexOf(5);
assert.strictEqual(indexOfResult.index, 4);
assert.strictEqual(indexOfResult.remainder, 3);
// [1, 0, 0, 0, 3]
psc.setValue(3, 0);
assert.strictEqual(psc.getTotalSum(), 4);
assert.strictEqual(psc.getPrefixSum(0), 1);
assert.strictEqual(psc.getPrefixSum(1), 1);
assert.strictEqual(psc.getPrefixSum(2), 1);
assert.strictEqual(psc.getPrefixSum(3), 1);
assert.strictEqual(psc.getPrefixSum(4), 4);
indexOfResult = psc.getIndexOf(0);
assert.strictEqual(indexOfResult.index, 0);
assert.strictEqual(indexOfResult.remainder, 0);
indexOfResult = psc.getIndexOf(1);
assert.strictEqual(indexOfResult.index, 4);
assert.strictEqual(indexOfResult.remainder, 0);
indexOfResult = psc.getIndexOf(2);
assert.strictEqual(indexOfResult.index, 4);
assert.strictEqual(indexOfResult.remainder, 1);
indexOfResult = psc.getIndexOf(3);
assert.strictEqual(indexOfResult.index, 4);
assert.strictEqual(indexOfResult.remainder, 2);
indexOfResult = psc.getIndexOf(4);
assert.strictEqual(indexOfResult.index, 4);
assert.strictEqual(indexOfResult.remainder, 3);
// [1, 1, 0, 1, 1]
psc.setValue(1, 1);
psc.setValue(3, 1);
psc.setValue(4, 1);
assert.strictEqual(psc.getTotalSum(), 4);
assert.strictEqual(psc.getPrefixSum(0), 1);
assert.strictEqual(psc.getPrefixSum(1), 2);
assert.strictEqual(psc.getPrefixSum(2), 2);
assert.strictEqual(psc.getPrefixSum(3), 3);
assert.strictEqual(psc.getPrefixSum(4), 4);
indexOfResult = psc.getIndexOf(0);
assert.strictEqual(indexOfResult.index, 0);
assert.strictEqual(indexOfResult.remainder, 0);
indexOfResult = psc.getIndexOf(1);
assert.strictEqual(indexOfResult.index, 1);
assert.strictEqual(indexOfResult.remainder, 0);
indexOfResult = psc.getIndexOf(2);
assert.strictEqual(indexOfResult.index, 3);
assert.strictEqual(indexOfResult.remainder, 0);
indexOfResult = psc.getIndexOf(3);
assert.strictEqual(indexOfResult.index, 4);
assert.strictEqual(indexOfResult.remainder, 0);
indexOfResult = psc.getIndexOf(4);
assert.strictEqual(indexOfResult.index, 4);
assert.strictEqual(indexOfResult.remainder, 1);
});
});
| src/vs/editor/test/common/viewModel/prefixSumComputer.test.ts | 0 | https://github.com/microsoft/vscode/commit/c2bf6225a12e7f7d8afada6ec39560bb38e5838a | [
0.00017402932280674577,
0.00017130911874119192,
0.00016822006728034467,
0.0001716859987936914,
0.0000016576142343183164
] |
{
"id": 13,
"code_window": [
"}\n",
"\n",
".interactive-list .interactive-item-container .monaco-toolbar .codicon {\n",
"\t/* Very aggressive list styles try to apply focus colors to every codicon in a list row. */\n",
"\tcolor: var(--vscode-foreground) !important;\n",
"}\n",
"\n",
".interactive-session .interactive-item-container.filtered-response .value .rendered-markdown {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tcolor: var(--vscode-icon-foreground) !important;\n"
],
"file_path": "src/vs/workbench/contrib/interactiveSession/browser/media/interactiveSession.css",
"type": "replace",
"edit_start_line_idx": 326
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { exec } from 'child_process';
import { FileAccess } from 'vs/base/common/network';
import { ProcessItem } from 'vs/base/common/processes';
export function listProcesses(rootPid: number): Promise<ProcessItem> {
return new Promise((resolve, reject) => {
let rootItem: ProcessItem | undefined;
const map = new Map<number, ProcessItem>();
function addToTree(pid: number, ppid: number, cmd: string, load: number, mem: number) {
const parent = map.get(ppid);
if (pid === rootPid || parent) {
const item: ProcessItem = {
name: findName(cmd),
cmd,
pid,
ppid,
load,
mem
};
map.set(pid, item);
if (pid === rootPid) {
rootItem = item;
}
if (parent) {
if (!parent.children) {
parent.children = [];
}
parent.children.push(item);
if (parent.children.length > 1) {
parent.children = parent.children.sort((a, b) => a.pid - b.pid);
}
}
}
}
function findName(cmd: string): string {
const UTILITY_NETWORK_HINT = /--utility-sub-type=network/i;
const NODEJS_PROCESS_HINT = /--ms-enable-electron-run-as-node/i;
const WINDOWS_CRASH_REPORTER = /--crashes-directory/i;
const WINDOWS_PTY = /\\pipe\\winpty-control/i;
const WINDOWS_CONSOLE_HOST = /conhost\.exe/i;
const TYPE = /--type=([a-zA-Z-]+)/;
// find windows crash reporter
if (WINDOWS_CRASH_REPORTER.exec(cmd)) {
return 'electron-crash-reporter';
}
// find windows pty process
if (WINDOWS_PTY.exec(cmd)) {
return 'winpty-process';
}
// find windows console host process
if (WINDOWS_CONSOLE_HOST.exec(cmd)) {
return 'console-window-host (Windows internal process)';
}
// find "--type=xxxx"
let matches = TYPE.exec(cmd);
if (matches && matches.length === 2) {
if (matches[1] === 'renderer') {
return `window`;
} else if (matches[1] === 'utility') {
if (UTILITY_NETWORK_HINT.exec(cmd)) {
return 'utility-network-service';
}
return 'utility-process';
} else if (matches[1] === 'extensionHost') {
return 'extension-host'; // normalize remote extension host type
}
return matches[1];
}
// find all xxxx.js
const JS = /[a-zA-Z-]+\.js/g;
let result = '';
do {
matches = JS.exec(cmd);
if (matches) {
result += matches + ' ';
}
} while (matches);
if (result) {
if (cmd.indexOf('node ') < 0 && cmd.indexOf('node.exe') < 0) {
return `electron-nodejs (${result})`;
}
}
// find Electron node.js processes
if (NODEJS_PROCESS_HINT.exec(cmd)) {
return `electron-nodejs (${cmd})`;
}
return cmd;
}
if (process.platform === 'win32') {
const cleanUNCPrefix = (value: string): string => {
if (value.indexOf('\\\\?\\') === 0) {
return value.substr(4);
} else if (value.indexOf('\\??\\') === 0) {
return value.substr(4);
} else if (value.indexOf('"\\\\?\\') === 0) {
return '"' + value.substr(5);
} else if (value.indexOf('"\\??\\') === 0) {
return '"' + value.substr(5);
} else {
return value;
}
};
(import('windows-process-tree')).then(windowsProcessTree => {
windowsProcessTree.getProcessList(rootPid, (processList) => {
if (!processList) {
reject(new Error(`Root process ${rootPid} not found`));
return;
}
windowsProcessTree.getProcessCpuUsage(processList, (completeProcessList) => {
const processItems: Map<number, ProcessItem> = new Map();
completeProcessList.forEach(process => {
const commandLine = cleanUNCPrefix(process.commandLine || '');
processItems.set(process.pid, {
name: findName(commandLine),
cmd: commandLine,
pid: process.pid,
ppid: process.ppid,
load: process.cpu || 0,
mem: process.memory || 0
});
});
rootItem = processItems.get(rootPid);
if (rootItem) {
processItems.forEach(item => {
const parent = processItems.get(item.ppid);
if (parent) {
if (!parent.children) {
parent.children = [];
}
parent.children.push(item);
}
});
processItems.forEach(item => {
if (item.children) {
item.children = item.children.sort((a, b) => a.pid - b.pid);
}
});
resolve(rootItem);
} else {
reject(new Error(`Root process ${rootPid} not found`));
}
});
}, windowsProcessTree.ProcessDataFlag.CommandLine | windowsProcessTree.ProcessDataFlag.Memory);
});
} else { // OS X & Linux
function calculateLinuxCpuUsage() {
// Flatten rootItem to get a list of all VSCode processes
let processes = [rootItem];
const pids: number[] = [];
while (processes.length) {
const process = processes.shift();
if (process) {
pids.push(process.pid);
if (process.children) {
processes = processes.concat(process.children);
}
}
}
// The cpu usage value reported on Linux is the average over the process lifetime,
// recalculate the usage over a one second interval
// JSON.stringify is needed to escape spaces, https://github.com/nodejs/node/issues/6803
let cmd = JSON.stringify(FileAccess.asFileUri('vs/base/node/cpuUsage.sh').fsPath);
cmd += ' ' + pids.join(' ');
exec(cmd, {}, (err, stdout, stderr) => {
if (err || stderr) {
reject(err || new Error(stderr.toString()));
} else {
const cpuUsage = stdout.toString().split('\n');
for (let i = 0; i < pids.length; i++) {
const processInfo = map.get(pids[i])!;
processInfo.load = parseFloat(cpuUsage[i]);
}
if (!rootItem) {
reject(new Error(`Root process ${rootPid} not found`));
return;
}
resolve(rootItem);
}
});
}
exec('which ps', {}, (err, stdout, stderr) => {
if (err || stderr) {
if (process.platform !== 'linux') {
reject(err || new Error(stderr.toString()));
} else {
const cmd = JSON.stringify(FileAccess.asFileUri('vs/base/node/ps.sh').fsPath);
exec(cmd, {}, (err, stdout, stderr) => {
if (err || stderr) {
reject(err || new Error(stderr.toString()));
} else {
parsePsOutput(stdout, addToTree);
calculateLinuxCpuUsage();
}
});
}
} else {
const ps = stdout.toString().trim();
const args = '-ax -o pid=,ppid=,pcpu=,pmem=,command=';
// Set numeric locale to ensure '.' is used as the decimal separator
exec(`${ps} ${args}`, { maxBuffer: 1000 * 1024, env: { LC_NUMERIC: 'en_US.UTF-8' } }, (err, stdout, stderr) => {
// Silently ignoring the screen size is bogus error. See https://github.com/microsoft/vscode/issues/98590
if (err || (stderr && !stderr.includes('screen size is bogus'))) {
reject(err || new Error(stderr.toString()));
} else {
parsePsOutput(stdout, addToTree);
if (process.platform === 'linux') {
calculateLinuxCpuUsage();
} else {
if (!rootItem) {
reject(new Error(`Root process ${rootPid} not found`));
} else {
resolve(rootItem);
}
}
}
});
}
});
}
});
}
function parsePsOutput(stdout: string, addToTree: (pid: number, ppid: number, cmd: string, load: number, mem: number) => void): void {
const PID_CMD = /^\s*([0-9]+)\s+([0-9]+)\s+([0-9]+\.[0-9]+)\s+([0-9]+\.[0-9]+)\s+(.+)$/;
const lines = stdout.toString().split('\n');
for (const line of lines) {
const matches = PID_CMD.exec(line.trim());
if (matches && matches.length === 6) {
addToTree(parseInt(matches[1]), parseInt(matches[2]), matches[5], parseFloat(matches[3]), parseFloat(matches[4]));
}
}
}
| src/vs/base/node/ps.ts | 0 | https://github.com/microsoft/vscode/commit/c2bf6225a12e7f7d8afada6ec39560bb38e5838a | [
0.000594955519773066,
0.00018915630062110722,
0.00016503193182870746,
0.00016928899276535958,
0.00008037344377953559
] |
{
"id": 13,
"code_window": [
"}\n",
"\n",
".interactive-list .interactive-item-container .monaco-toolbar .codicon {\n",
"\t/* Very aggressive list styles try to apply focus colors to every codicon in a list row. */\n",
"\tcolor: var(--vscode-foreground) !important;\n",
"}\n",
"\n",
".interactive-session .interactive-item-container.filtered-response .value .rendered-markdown {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tcolor: var(--vscode-icon-foreground) !important;\n"
],
"file_path": "src/vs/workbench/contrib/interactiveSession/browser/media/interactiveSession.css",
"type": "replace",
"edit_start_line_idx": 326
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
.quick-input-widget {
font-size: 13px;
}
.quick-input-widget .monaco-highlighted-label .highlight,
.quick-input-widget .monaco-highlighted-label .highlight {
color: #0066BF;
}
.vs .quick-input-widget .monaco-list-row.focused .monaco-highlighted-label .highlight,
.vs .quick-input-widget .monaco-list-row.focused .monaco-highlighted-label .highlight {
color: #9DDDFF;
}
.vs-dark .quick-input-widget .monaco-highlighted-label .highlight,
.vs-dark .quick-input-widget .monaco-highlighted-label .highlight {
color: #0097fb;
}
.hc-black .quick-input-widget .monaco-highlighted-label .highlight,
.hc-black .quick-input-widget .monaco-highlighted-label .highlight {
color: #F38518;
}
.hc-light .quick-input-widget .monaco-highlighted-label .highlight,
.hc-light .quick-input-widget .monaco-highlighted-label .highlight {
color: #0F4A85;
}
.monaco-keybinding > .monaco-keybinding-key {
background-color: rgba(221, 221, 221, 0.4);
border: solid 1px rgba(204, 204, 204, 0.4);
border-bottom-color: rgba(187, 187, 187, 0.4);
box-shadow: inset 0 -1px 0 rgba(187, 187, 187, 0.4);
color: #555;
}
.hc-black .monaco-keybinding > .monaco-keybinding-key {
background-color: transparent;
border: solid 1px rgb(111, 195, 223);
box-shadow: none;
color: #fff;
}
.hc-light .monaco-keybinding > .monaco-keybinding-key {
background-color: transparent;
border: solid 1px #0F4A85;
box-shadow: none;
color: #292929;
}
.vs-dark .monaco-keybinding > .monaco-keybinding-key {
background-color: rgba(128, 128, 128, 0.17);
border: solid 1px rgba(51, 51, 51, 0.6);
border-bottom-color: rgba(68, 68, 68, 0.6);
box-shadow: inset 0 -1px 0 rgba(68, 68, 68, 0.6);
color: #ccc;
}
| src/vs/editor/standalone/browser/quickInput/standaloneQuickInput.css | 0 | https://github.com/microsoft/vscode/commit/c2bf6225a12e7f7d8afada6ec39560bb38e5838a | [
0.00041497484198771417,
0.00023641050211153924,
0.000164927463629283,
0.0002303358050994575,
0.0000779297188273631
] |
{
"id": 1,
"code_window": [
" });\n",
" }));\n",
"\n",
" it('should support template directives via `template` attribute.',\n",
" inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => {\n",
" tcb.overrideView(\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" it('should use a comment while stamping out `<template>` elements.',\n",
" inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => {\n",
" tcb.overrideView(MyComp, new ViewMetadata({template: '<template></template>'}))\n",
"\n",
" .createAsync(MyComp)\n",
" .then((fixture) => {\n",
" var childNodesOfWrapper = DOM.childNodes(fixture.debugElement.nativeElement);\n",
" expect(childNodesOfWrapper.length).toBe(1);\n",
" expect(DOM.isCommentNode(childNodesOfWrapper[0])).toBe(true);\n",
" async.done();\n",
" });\n",
" }));\n",
"\n"
],
"file_path": "modules/angular2/test/core/linker/integration_spec.ts",
"type": "add",
"edit_start_line_idx": 478
} | import {CONST_EXPR, isPresent, NumberWrapper, StringWrapper} from 'angular2/src/facade/lang';
import {MapWrapper, Map, ListWrapper} from 'angular2/src/facade/collection';
import {Injectable, provide, Provider} from 'angular2/src/core/di';
import {AppViewListener} from 'angular2/src/core/linker/view_listener';
import {AppView} from 'angular2/src/core/linker/view';
import {DOM} from 'angular2/src/platform/dom/dom_adapter';
import {Renderer} from 'angular2/src/core/render/api';
import {DebugElement, DebugElement_} from 'angular2/src/core/debug/debug_element';
const NG_ID_PROPERTY = 'ngid';
const INSPECT_GLOBAL_NAME = 'ng.probe';
const NG_ID_SEPARATOR = '#';
// Need to keep the views in a global Map so that multiple angular apps are supported
var _allIdsByView = new Map<AppView, number>();
var _allViewsById = new Map<number, AppView>();
var _nextId = 0;
function _setElementId(element, indices: number[]) {
if (isPresent(element)) {
DOM.setData(element, NG_ID_PROPERTY, indices.join(NG_ID_SEPARATOR));
}
}
function _getElementId(element): number[] {
var elId = DOM.getData(element, NG_ID_PROPERTY);
if (isPresent(elId)) {
return elId.split(NG_ID_SEPARATOR).map(partStr => NumberWrapper.parseInt(partStr, 10));
} else {
return null;
}
}
export function inspectNativeElement(element): DebugElement {
var elId = _getElementId(element);
if (isPresent(elId)) {
var view = _allViewsById.get(elId[0]);
if (isPresent(view)) {
return new DebugElement_(view, elId[1]);
}
}
return null;
}
@Injectable()
export class DebugElementViewListener implements AppViewListener {
constructor(private _renderer: Renderer) {
DOM.setGlobalVar(INSPECT_GLOBAL_NAME, inspectNativeElement);
}
onViewCreated(view: AppView) {
var viewId = _nextId++;
_allViewsById.set(viewId, view);
_allIdsByView.set(view, viewId);
for (var i = 0; i < view.elementRefs.length; i++) {
var el = view.elementRefs[i];
_setElementId(this._renderer.getNativeElementSync(el), [viewId, i]);
}
}
onViewDestroyed(view: AppView) {
var viewId = _allIdsByView.get(view);
_allIdsByView.delete(view);
_allViewsById.delete(viewId);
}
}
export const ELEMENT_PROBE_PROVIDERS: any[] = CONST_EXPR([
DebugElementViewListener,
CONST_EXPR(new Provider(AppViewListener, {useExisting: DebugElementViewListener})),
]);
export const ELEMENT_PROBE_BINDINGS = ELEMENT_PROBE_PROVIDERS;
| modules/angular2/src/platform/dom/debug/debug_element_view_listener.ts | 1 | https://github.com/angular/angular/commit/194dc7da78c4cb564054f47a2dbcd8479a302b63 | [
0.00022619162336923182,
0.00018311158055439591,
0.00016330268408637494,
0.00016852676344569772,
0.00002523570401535835
] |
{
"id": 1,
"code_window": [
" });\n",
" }));\n",
"\n",
" it('should support template directives via `template` attribute.',\n",
" inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => {\n",
" tcb.overrideView(\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" it('should use a comment while stamping out `<template>` elements.',\n",
" inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => {\n",
" tcb.overrideView(MyComp, new ViewMetadata({template: '<template></template>'}))\n",
"\n",
" .createAsync(MyComp)\n",
" .then((fixture) => {\n",
" var childNodesOfWrapper = DOM.childNodes(fixture.debugElement.nativeElement);\n",
" expect(childNodesOfWrapper.length).toBe(1);\n",
" expect(DOM.isCommentNode(childNodesOfWrapper[0])).toBe(true);\n",
" async.done();\n",
" });\n",
" }));\n",
"\n"
],
"file_path": "modules/angular2/test/core/linker/integration_spec.ts",
"type": "add",
"edit_start_line_idx": 478
} | /**
* Dart version of browser APIs. This library depends on 'dart:html' and
* therefore can only run in the browser.
*/
library angular2.src.facade.browser;
import 'dart:js' show context;
import 'dart:html' show Location, window;
export 'dart:html'
show
document,
window,
Element,
Node,
MouseEvent,
KeyboardEvent,
Event,
EventTarget,
History,
Location,
EventListener;
Location get location => window.location;
final _gc = context['gc'];
void gc() {
if (_gc != null) {
_gc.apply(const []);
}
}
| modules/angular2/src/facade/browser.dart | 0 | https://github.com/angular/angular/commit/194dc7da78c4cb564054f47a2dbcd8479a302b63 | [
0.00017353438306599855,
0.00017154637316707522,
0.00016617118672002107,
0.00017323996871709824,
0.0000031092079098016256
] |
{
"id": 1,
"code_window": [
" });\n",
" }));\n",
"\n",
" it('should support template directives via `template` attribute.',\n",
" inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => {\n",
" tcb.overrideView(\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" it('should use a comment while stamping out `<template>` elements.',\n",
" inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => {\n",
" tcb.overrideView(MyComp, new ViewMetadata({template: '<template></template>'}))\n",
"\n",
" .createAsync(MyComp)\n",
" .then((fixture) => {\n",
" var childNodesOfWrapper = DOM.childNodes(fixture.debugElement.nativeElement);\n",
" expect(childNodesOfWrapper.length).toBe(1);\n",
" expect(DOM.isCommentNode(childNodesOfWrapper[0])).toBe(true);\n",
" async.done();\n",
" });\n",
" }));\n",
"\n"
],
"file_path": "modules/angular2/test/core/linker/integration_spec.ts",
"type": "add",
"edit_start_line_idx": 478
} | import {Router, RouterOutlet, Location, PlatformLocation} from 'angular2/router';
import {SpyObject, proxy} from 'angular2/testing_internal';
export class SpyRouter extends SpyObject {
constructor() { super(Router); }
}
export class SpyRouterOutlet extends SpyObject {
constructor() { super(RouterOutlet); }
}
export class SpyLocation extends SpyObject {
constructor() { super(Location); }
}
export class SpyPlatformLocation extends SpyObject {
pathname: string = null;
constructor() { super(SpyPlatformLocation); }
}
| modules/angular2/test/router/spies.ts | 0 | https://github.com/angular/angular/commit/194dc7da78c4cb564054f47a2dbcd8479a302b63 | [
0.00016878530732356012,
0.0001680771092651412,
0.00016736891120672226,
0.0001680771092651412,
7.081980584189296e-7
] |
{
"id": 1,
"code_window": [
" });\n",
" }));\n",
"\n",
" it('should support template directives via `template` attribute.',\n",
" inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => {\n",
" tcb.overrideView(\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" it('should use a comment while stamping out `<template>` elements.',\n",
" inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => {\n",
" tcb.overrideView(MyComp, new ViewMetadata({template: '<template></template>'}))\n",
"\n",
" .createAsync(MyComp)\n",
" .then((fixture) => {\n",
" var childNodesOfWrapper = DOM.childNodes(fixture.debugElement.nativeElement);\n",
" expect(childNodesOfWrapper.length).toBe(1);\n",
" expect(DOM.isCommentNode(childNodesOfWrapper[0])).toBe(true);\n",
" async.done();\n",
" });\n",
" }));\n",
"\n"
],
"file_path": "modules/angular2/test/core/linker/integration_spec.ts",
"type": "add",
"edit_start_line_idx": 478
} | /**
* Public Test Library for unit testing Angular2 Applications. Uses the
* Jasmine framework.
*/
import {global} from 'angular2/src/facade/lang';
import {ListWrapper} from 'angular2/src/facade/collection';
import {bind} from 'angular2/src/core/di';
import {
createTestInjectorWithRuntimeCompiler,
FunctionWithParamTokens,
inject,
injectAsync
} from './test_injector';
export {inject, injectAsync} from './test_injector';
export {expect, NgMatchers} from './matchers';
var _global: jasmine.GlobalPolluter = <any>(typeof window === 'undefined' ? global : window);
/**
* See http://jasmine.github.io/
*/
export var afterEach: Function = _global.afterEach;
/**
* See http://jasmine.github.io/
*/
export var describe: Function = _global.describe;
/**
* See http://jasmine.github.io/
*/
export var ddescribe: Function = _global.fdescribe;
/**
* See http://jasmine.github.io/
*/
export var fdescribe: Function = _global.fdescribe;
/**
* See http://jasmine.github.io/
*/
export var xdescribe: Function = _global.xdescribe;
export type SyncTestFn = () => void;
export type AsyncTestFn = (done: () => void) => void;
export type AnyTestFn = SyncTestFn | AsyncTestFn;
var jsmBeforeEach = _global.beforeEach;
var jsmIt = _global.it;
var jsmIIt = _global.fit;
var jsmXIt = _global.xit;
var testProviders;
var injector;
// Reset the test providers before each test.
jsmBeforeEach(() => {
testProviders = [];
injector = null;
});
/**
* Allows overriding default providers of the test injector,
* which are defined in test_injector.js.
*
* The given function must return a list of DI providers.
*
* Example:
*
* ```
* beforeEachProviders(() => [
* bind(Compiler).toClass(MockCompiler),
* bind(SomeToken).toValue(myValue),
* ]);
* ```
*/
export function beforeEachProviders(fn): void {
jsmBeforeEach(() => {
var providers = fn();
if (!providers) return;
testProviders = [...testProviders, ...providers];
if (injector !== null) {
throw new Error('beforeEachProviders was called after the injector had ' +
'been used in a beforeEach or it block. This invalidates the ' +
'test injector');
}
});
}
function _isPromiseLike(input): boolean {
return input && !!(input.then);
}
function runInTestZone(fnToExecute, finishCallback, failCallback): any {
var pendingMicrotasks = 0;
var pendingTimeouts = [];
var ngTestZone = (<Zone>global.zone)
.fork({
onError: function(e) { failCallback(e); },
'$run': function(parentRun) {
return function() {
try {
return parentRun.apply(this, arguments);
} finally {
if (pendingMicrotasks == 0 && pendingTimeouts.length == 0) {
finishCallback();
}
}
};
},
'$scheduleMicrotask': function(parentScheduleMicrotask) {
return function(fn) {
pendingMicrotasks++;
var microtask = function() {
try {
fn();
} finally {
pendingMicrotasks--;
}
};
parentScheduleMicrotask.call(this, microtask);
};
},
'$setTimeout': function(parentSetTimeout) {
return function(fn: Function, delay: number, ...args) {
var id;
var cb = function() {
fn();
ListWrapper.remove(pendingTimeouts, id);
};
id = parentSetTimeout(cb, delay, args);
pendingTimeouts.push(id);
return id;
};
},
'$clearTimeout': function(parentClearTimeout) {
return function(id: number) {
parentClearTimeout(id);
ListWrapper.remove(pendingTimeouts, id);
};
},
});
return ngTestZone.run(fnToExecute);
}
function _it(jsmFn: Function, name: string, testFn: FunctionWithParamTokens | AnyTestFn,
testTimeOut: number): void {
var timeOut = testTimeOut;
if (testFn instanceof FunctionWithParamTokens) {
jsmFn(name, (done) => {
if (!injector) {
injector = createTestInjectorWithRuntimeCompiler(testProviders);
}
var returnedTestValue = runInTestZone(() => testFn.execute(injector), done, done.fail);
if (_isPromiseLike(returnedTestValue)) {
(<Promise<any>>returnedTestValue).then(null, (err) => { done.fail(err); });
}
}, timeOut);
} else {
// The test case doesn't use inject(). ie `it('test', (done) => { ... }));`
jsmFn(name, testFn, timeOut);
}
}
/**
* Wrapper around Jasmine beforeEach function.
* See http://jasmine.github.io/
*
* beforeEach may be used with the `inject` function to fetch dependencies.
* The test will automatically wait for any asynchronous calls inside the
* injected test function to complete.
*/
export function beforeEach(fn: FunctionWithParamTokens | AnyTestFn): void {
if (fn instanceof FunctionWithParamTokens) {
// The test case uses inject(). ie `beforeEach(inject([ClassA], (a) => { ...
// }));`
jsmBeforeEach((done) => {
if (!injector) {
injector = createTestInjectorWithRuntimeCompiler(testProviders);
}
runInTestZone(() => fn.execute(injector), done, done.fail);
});
} else {
// The test case doesn't use inject(). ie `beforeEach((done) => { ... }));`
if ((<any>fn).length === 0) {
jsmBeforeEach(() => { (<SyncTestFn>fn)(); });
} else {
jsmBeforeEach((done) => { (<AsyncTestFn>fn)(done); });
}
}
}
/**
* Wrapper around Jasmine it function.
* See http://jasmine.github.io/
*
* it may be used with the `inject` function to fetch dependencies.
* The test will automatically wait for any asynchronous calls inside the
* injected test function to complete.
*/
export function it(name: string, fn: FunctionWithParamTokens | AnyTestFn,
timeOut: number = null): void {
return _it(jsmIt, name, fn, timeOut);
}
/**
* Wrapper around Jasmine xit (skipped it) function.
* See http://jasmine.github.io/
*
* it may be used with the `inject` function to fetch dependencies.
* The test will automatically wait for any asynchronous calls inside the
* injected test function to complete.
*/
export function xit(name: string, fn: FunctionWithParamTokens | AnyTestFn,
timeOut: number = null): void {
return _it(jsmXIt, name, fn, timeOut);
}
/**
* Wrapper around Jasmine iit (focused it) function.
* See http://jasmine.github.io/
*
* it may be used with the `inject` function to fetch dependencies.
* The test will automatically wait for any asynchronous calls inside the
* injected test function to complete.
*/
export function iit(name: string, fn: FunctionWithParamTokens | AnyTestFn,
timeOut: number = null): void {
return _it(jsmIIt, name, fn, timeOut);
}
/**
* Wrapper around Jasmine fit (focused it) function.
* See http://jasmine.github.io/
*
* it may be used with the `inject` function to fetch dependencies.
* The test will automatically wait for any asynchronous calls inside the
* injected test function to complete.
*/
export function fit(name: string, fn: FunctionWithParamTokens | AnyTestFn,
timeOut: number = null): void {
return _it(jsmIIt, name, fn, timeOut);
}
| modules/angular2/src/testing/testing.ts | 0 | https://github.com/angular/angular/commit/194dc7da78c4cb564054f47a2dbcd8479a302b63 | [
0.010212129913270473,
0.0007508277194574475,
0.00016426407091785222,
0.00017305865185335279,
0.0019529246492311358
] |
{
"id": 2,
"code_window": [
"\n",
" it('should not throw errors', function() {\n",
" browser.get(URL);\n",
" var expectedRowCount = 18;\n",
" var expectedCellsPerRow = 28;\n",
" var allScrollItems = 'scroll-app #testArea scroll-item';\n",
" var cells = `${ allScrollItems } .row *`;\n",
" var stageButtons = `${ allScrollItems } .row stage-buttons button`;\n",
"\n",
" var count = function(selector) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" var expectedCellsPerRow = 27;\n"
],
"file_path": "modules/benchmarks/e2e_test/naive_infinite_scroll_spec.ts",
"type": "replace",
"edit_start_line_idx": 11
} | import {CONST_EXPR, isPresent, NumberWrapper, StringWrapper} from 'angular2/src/facade/lang';
import {MapWrapper, Map, ListWrapper} from 'angular2/src/facade/collection';
import {Injectable, provide, Provider} from 'angular2/src/core/di';
import {AppViewListener} from 'angular2/src/core/linker/view_listener';
import {AppView} from 'angular2/src/core/linker/view';
import {DOM} from 'angular2/src/platform/dom/dom_adapter';
import {Renderer} from 'angular2/src/core/render/api';
import {DebugElement, DebugElement_} from 'angular2/src/core/debug/debug_element';
const NG_ID_PROPERTY = 'ngid';
const INSPECT_GLOBAL_NAME = 'ng.probe';
const NG_ID_SEPARATOR = '#';
// Need to keep the views in a global Map so that multiple angular apps are supported
var _allIdsByView = new Map<AppView, number>();
var _allViewsById = new Map<number, AppView>();
var _nextId = 0;
function _setElementId(element, indices: number[]) {
if (isPresent(element)) {
DOM.setData(element, NG_ID_PROPERTY, indices.join(NG_ID_SEPARATOR));
}
}
function _getElementId(element): number[] {
var elId = DOM.getData(element, NG_ID_PROPERTY);
if (isPresent(elId)) {
return elId.split(NG_ID_SEPARATOR).map(partStr => NumberWrapper.parseInt(partStr, 10));
} else {
return null;
}
}
export function inspectNativeElement(element): DebugElement {
var elId = _getElementId(element);
if (isPresent(elId)) {
var view = _allViewsById.get(elId[0]);
if (isPresent(view)) {
return new DebugElement_(view, elId[1]);
}
}
return null;
}
@Injectable()
export class DebugElementViewListener implements AppViewListener {
constructor(private _renderer: Renderer) {
DOM.setGlobalVar(INSPECT_GLOBAL_NAME, inspectNativeElement);
}
onViewCreated(view: AppView) {
var viewId = _nextId++;
_allViewsById.set(viewId, view);
_allIdsByView.set(view, viewId);
for (var i = 0; i < view.elementRefs.length; i++) {
var el = view.elementRefs[i];
_setElementId(this._renderer.getNativeElementSync(el), [viewId, i]);
}
}
onViewDestroyed(view: AppView) {
var viewId = _allIdsByView.get(view);
_allIdsByView.delete(view);
_allViewsById.delete(viewId);
}
}
export const ELEMENT_PROBE_PROVIDERS: any[] = CONST_EXPR([
DebugElementViewListener,
CONST_EXPR(new Provider(AppViewListener, {useExisting: DebugElementViewListener})),
]);
export const ELEMENT_PROBE_BINDINGS = ELEMENT_PROBE_PROVIDERS;
| modules/angular2/src/platform/dom/debug/debug_element_view_listener.ts | 1 | https://github.com/angular/angular/commit/194dc7da78c4cb564054f47a2dbcd8479a302b63 | [
0.00017503215349279344,
0.00017075057257898152,
0.00016692918143235147,
0.00017097368254326284,
0.0000027457188025437063
] |
{
"id": 2,
"code_window": [
"\n",
" it('should not throw errors', function() {\n",
" browser.get(URL);\n",
" var expectedRowCount = 18;\n",
" var expectedCellsPerRow = 28;\n",
" var allScrollItems = 'scroll-app #testArea scroll-item';\n",
" var cells = `${ allScrollItems } .row *`;\n",
" var stageButtons = `${ allScrollItems } .row stage-buttons button`;\n",
"\n",
" var count = function(selector) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" var expectedCellsPerRow = 27;\n"
],
"file_path": "modules/benchmarks/e2e_test/naive_infinite_scroll_spec.ts",
"type": "replace",
"edit_start_line_idx": 11
} | function file2moduleName(filePath) {
return filePath.replace(/\\/g, '/')
// module name should be relative to `modules` and `tools` folder
.replace(/.*\/modules\//, '')
// and 'dist' folder
.replace(/.*\/dist\/js\/dev\/es5\//, '')
// module name should not include `lib`, `web` folders
// as they are wrapper packages for dart
.replace(/\/web\//, '/')
.replace(/\/lib\//, '/')
// module name should not have a suffix
.replace(/\.\w*$/, '');
}
if (typeof module !== 'undefined') {
module.exports = file2moduleName;
}
| tools/build/file2modulename.js | 0 | https://github.com/angular/angular/commit/194dc7da78c4cb564054f47a2dbcd8479a302b63 | [
0.00017538700194563717,
0.00017483154078945518,
0.00017427607963327318,
0.00017483154078945518,
5.554611561819911e-7
] |
{
"id": 2,
"code_window": [
"\n",
" it('should not throw errors', function() {\n",
" browser.get(URL);\n",
" var expectedRowCount = 18;\n",
" var expectedCellsPerRow = 28;\n",
" var allScrollItems = 'scroll-app #testArea scroll-item';\n",
" var cells = `${ allScrollItems } .row *`;\n",
" var stageButtons = `${ allScrollItems } .row stage-buttons button`;\n",
"\n",
" var count = function(selector) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" var expectedCellsPerRow = 27;\n"
],
"file_path": "modules/benchmarks/e2e_test/naive_infinite_scroll_spec.ts",
"type": "replace",
"edit_start_line_idx": 11
} | /**
* See {@link bootstrap} for more information.
* @deprecated
*/
export {bootstrapStatic} from 'angular2/platform/browser_static';
export {AngularEntrypoint} from 'angular2/src/core/angular_entrypoint';
| modules/angular2/bootstrap_static.ts | 0 | https://github.com/angular/angular/commit/194dc7da78c4cb564054f47a2dbcd8479a302b63 | [
0.00017039102385751903,
0.00017039102385751903,
0.00017039102385751903,
0.00017039102385751903,
0
] |
{
"id": 2,
"code_window": [
"\n",
" it('should not throw errors', function() {\n",
" browser.get(URL);\n",
" var expectedRowCount = 18;\n",
" var expectedCellsPerRow = 28;\n",
" var allScrollItems = 'scroll-app #testArea scroll-item';\n",
" var cells = `${ allScrollItems } .row *`;\n",
" var stageButtons = `${ allScrollItems } .row stage-buttons button`;\n",
"\n",
" var count = function(selector) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" var expectedCellsPerRow = 27;\n"
],
"file_path": "modules/benchmarks/e2e_test/naive_infinite_scroll_spec.ts",
"type": "replace",
"edit_start_line_idx": 11
} | import {isPresent} from 'angular2/src/facade/lang';
import {unimplemented} from 'angular2/src/facade/exceptions';
import * as viewModule from './view';
import {ChangeDetectorRef} from '../change_detection/change_detector_ref';
import {RenderViewRef, RenderFragmentRef} from 'angular2/src/core/render/api';
// This is a workaround for privacy in Dart as we don't have library parts
export function internalView(viewRef: ViewRef): viewModule.AppView {
return (<ViewRef_>viewRef)._view;
}
// This is a workaround for privacy in Dart as we don't have library parts
export function internalProtoView(protoViewRef: ProtoViewRef): viewModule.AppProtoView {
return isPresent(protoViewRef) ? (<ProtoViewRef_>protoViewRef)._protoView : null;
}
/**
* Represents a View containing a single Element that is the Host Element of a {@link Component}
* instance.
*
* A Host View is created for every dynamically created Component that was compiled on its own (as
* opposed to as a part of another Component's Template) via {@link Compiler#compileInHost} or one
* of the higher-level APIs: {@link AppViewManager#createRootHostView},
* {@link AppViewManager#createHostViewInContainer}, {@link ViewContainerRef#createHostView}.
*/
export interface HostViewRef {
/**
* @internal
*/
changeDetectorRef: ChangeDetectorRef;
}
/**
* Represents an Angular View.
*
* <!-- TODO: move the next two paragraphs to the dev guide -->
* A View is a fundamental building block of the application UI. It is the smallest grouping of
* Elements which are created and destroyed together.
*
* Properties of elements in a View can change, but the structure (number and order) of elements in
* a View cannot. Changing the structure of Elements can only be done by inserting, moving or
* removing nested Views via a {@link ViewContainer}. Each View can contain many View Containers.
* <!-- /TODO -->
*
* ### Example
*
* Given this template...
*
* ```
* Count: {{items.length}}
* <ul>
* <li *ngFor="var item of items">{{item}}</li>
* </ul>
* ```
*
* ... we have two {@link ProtoViewRef}s:
*
* Outer {@link ProtoViewRef}:
* ```
* Count: {{items.length}}
* <ul>
* <template ngFor var-item [ngForOf]="items"></template>
* </ul>
* ```
*
* Inner {@link ProtoViewRef}:
* ```
* <li>{{item}}</li>
* ```
*
* Notice that the original template is broken down into two separate {@link ProtoViewRef}s.
*
* The outer/inner {@link ProtoViewRef}s are then assembled into views like so:
*
* ```
* <!-- ViewRef: outer-0 -->
* Count: 2
* <ul>
* <template view-container-ref></template>
* <!-- ViewRef: inner-1 --><li>first</li><!-- /ViewRef: inner-1 -->
* <!-- ViewRef: inner-2 --><li>second</li><!-- /ViewRef: inner-2 -->
* </ul>
* <!-- /ViewRef: outer-0 -->
* ```
*/
export abstract class ViewRef implements HostViewRef {
/**
* Sets `value` of local variable called `variableName` in this View.
*/
abstract setLocal(variableName: string, value: any): void;
get changeDetectorRef(): ChangeDetectorRef { return unimplemented(); }
set changeDetectorRef(value: ChangeDetectorRef) {
unimplemented(); // TODO: https://github.com/Microsoft/TypeScript/issues/12
}
}
export class ViewRef_ extends ViewRef {
private _changeDetectorRef: ChangeDetectorRef = null;
/** @internal */
public _view: viewModule.AppView;
constructor(_view: viewModule.AppView) {
super();
this._view = _view;
}
/**
* Return `RenderViewRef`
*/
get render(): RenderViewRef { return this._view.render; }
/**
* Return `RenderFragmentRef`
*/
get renderFragment(): RenderFragmentRef { return this._view.renderFragment; }
/**
* Return `ChangeDetectorRef`
*/
get changeDetectorRef(): ChangeDetectorRef {
if (this._changeDetectorRef === null) {
this._changeDetectorRef = this._view.changeDetector.ref;
}
return this._changeDetectorRef;
}
setLocal(variableName: string, value: any): void { this._view.setLocal(variableName, value); }
}
/**
* Represents an Angular ProtoView.
*
* A ProtoView is a prototypical {@link ViewRef View} that is the result of Template compilation and
* is used by Angular to efficiently create an instance of this View based on the compiled Template.
*
* Most ProtoViews are created and used internally by Angular and you don't need to know about them,
* except in advanced use-cases where you compile components yourself via the low-level
* {@link Compiler#compileInHost} API.
*
*
* ### Example
*
* Given this template:
*
* ```
* Count: {{items.length}}
* <ul>
* <li *ngFor="var item of items">{{item}}</li>
* </ul>
* ```
*
* Angular desugars and compiles the template into two ProtoViews:
*
* Outer ProtoView:
* ```
* Count: {{items.length}}
* <ul>
* <template ngFor var-item [ngForOf]="items"></template>
* </ul>
* ```
*
* Inner ProtoView:
* ```
* <li>{{item}}</li>
* ```
*
* Notice that the original template is broken down into two separate ProtoViews.
*/
export abstract class ProtoViewRef {}
export class ProtoViewRef_ extends ProtoViewRef {
/** @internal */
public _protoView: viewModule.AppProtoView;
constructor(_protoView: viewModule.AppProtoView) {
super();
this._protoView = _protoView;
}
}
| modules/angular2/src/core/linker/view_ref.ts | 0 | https://github.com/angular/angular/commit/194dc7da78c4cb564054f47a2dbcd8479a302b63 | [
0.0001772903196979314,
0.0001695995160844177,
0.00016100818174891174,
0.00016888586105778813,
0.000004313127192290267
] |
{
"id": 0,
"code_window": [
"\t\texpression.available = !!(response && response.body);\n",
"\t\tif (response.body) {\n",
"\t\t\texpression.value = response.body.result;\n",
"\t\t\texpression.reference = response.body.variablesReference;\n",
"\t\t\texpression.childrenCount = response.body.indexedVariables;\n",
"\t\t\texpression.type = response.body.type;\n",
"\t\t}\n",
"\n",
"\t\treturn expression;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\texpression.indexedVariables = response.body.indexedVariables;\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debugModel.ts",
"type": "replace",
"edit_start_line_idx": 41
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { TPromise } from 'vs/base/common/winjs.base';
import nls = require('vs/nls');
import lifecycle = require('vs/base/common/lifecycle');
import Event, { Emitter } from 'vs/base/common/event';
import uuid = require('vs/base/common/uuid');
import objects = require('vs/base/common/objects');
import severity from 'vs/base/common/severity';
import types = require('vs/base/common/types');
import arrays = require('vs/base/common/arrays');
import debug = require('vs/workbench/parts/debug/common/debug');
import { Source } from 'vs/workbench/parts/debug/common/debugSource';
const MAX_REPL_LENGTH = 10000;
const UNKNOWN_SOURCE_LABEL = nls.localize('unknownSource', "Unknown Source");
function massageValue(value: string): string {
return value ? value.replace(/\n/g, '\\n').replace(/\r/g, '\\r').replace(/\t/g, '\\t') : value;
}
export function evaluateExpression(session: debug.IRawDebugSession, stackFrame: debug.IStackFrame, expression: Expression, context: string): TPromise<Expression> {
if (!session) {
expression.value = context === 'repl' ? nls.localize('startDebugFirst', "Please start a debug session to evaluate") : Expression.DEFAULT_VALUE;
expression.available = false;
expression.reference = 0;
return TPromise.as(expression);
}
return session.evaluate({
expression: expression.name,
frameId: stackFrame ? stackFrame.frameId : undefined,
context
}).then(response => {
expression.available = !!(response && response.body);
if (response.body) {
expression.value = response.body.result;
expression.reference = response.body.variablesReference;
expression.childrenCount = response.body.indexedVariables;
expression.type = response.body.type;
}
return expression;
}, err => {
expression.value = err.message;
expression.available = false;
expression.reference = 0;
return expression;
});
}
const notPropertySyntax = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
const arrayElementSyntax = /\[.*\]$/;
export function getFullExpressionName(expression: debug.IExpression, sessionType: string): string {
let names = [expression.name];
if (expression instanceof Variable) {
let v = (<Variable> expression).parent;
while (v instanceof Variable || v instanceof Expression) {
names.push((<Variable> v).name);
v = (<Variable> v).parent;
}
}
names = names.reverse();
let result = null;
names.forEach(name => {
if (!result) {
result = name;
} else if (arrayElementSyntax.test(name) || (sessionType === 'node' && !notPropertySyntax.test(name))) {
// use safe way to access node properties a['property_name']. Also handles array elements.
result = name && name.indexOf('[') === 0 ? `${ result }${ name }` : `${ result }['${ name }']`;
} else {
result = `${ result }.${ name }`;
}
});
return result;
}
export class Thread implements debug.IThread {
private promisedCallStack: TPromise<debug.IStackFrame[]>;
private cachedCallStack: debug.IStackFrame[];
public stoppedDetails: debug.IRawStoppedDetails;
public stopped: boolean;
constructor(public name: string, public threadId: number) {
this.promisedCallStack = undefined;
this.stoppedDetails = undefined;
this.cachedCallStack = undefined;
this.stopped = false;
}
public getId(): string {
return `thread:${ this.name }:${ this.threadId }`;
}
public clearCallStack(): void {
this.promisedCallStack = undefined;
this.cachedCallStack = undefined;
}
public getCachedCallStack(): debug.IStackFrame[] {
return this.cachedCallStack;
}
public getCallStack(debugService: debug.IDebugService, getAdditionalStackFrames = false): TPromise<debug.IStackFrame[]> {
if (!this.stopped) {
return TPromise.as([]);
}
if (!this.promisedCallStack) {
this.promisedCallStack = this.getCallStackImpl(debugService, 0).then(callStack => {
this.cachedCallStack = callStack;
return callStack;
});
} else if (getAdditionalStackFrames) {
this.promisedCallStack = this.promisedCallStack.then(callStackFirstPart => this.getCallStackImpl(debugService, callStackFirstPart.length).then(callStackSecondPart => {
this.cachedCallStack = callStackFirstPart.concat(callStackSecondPart);
return this.cachedCallStack;
}));
}
return this.promisedCallStack;
}
private getCallStackImpl(debugService: debug.IDebugService, startFrame: number): TPromise<debug.IStackFrame[]> {
let session = debugService.getActiveSession();
return session.stackTrace({ threadId: this.threadId, startFrame, levels: 20 }).then(response => {
this.stoppedDetails.totalFrames = response.body.totalFrames;
return response.body.stackFrames.map((rsf, level) => {
if (!rsf) {
return new StackFrame(this.threadId, 0, new Source({ name: UNKNOWN_SOURCE_LABEL }, false), nls.localize('unknownStack', "Unknown stack location"), undefined, undefined);
}
return new StackFrame(this.threadId, rsf.id, rsf.source ? new Source(rsf.source) : new Source({ name: UNKNOWN_SOURCE_LABEL }, false), rsf.name, rsf.line, rsf.column);
});
}, (err: Error) => {
this.stoppedDetails.framesErrorMessage = err.message;
return [];
});
}
}
export class OutputElement implements debug.ITreeElement {
private static ID_COUNTER = 0;
constructor(private id = OutputElement.ID_COUNTER++) {
// noop
}
public getId(): string {
return `outputelement:${ this.id }`;
}
}
export class ValueOutputElement extends OutputElement {
constructor(
public value: string,
public severity: severity,
public category?: string,
public counter: number = 1
) {
super();
}
}
export class KeyValueOutputElement extends OutputElement {
private static MAX_CHILDREN = 1000; // upper bound of children per value
private children: debug.ITreeElement[];
private _valueName: string;
constructor(public key: string, public valueObj: any, public annotation?: string) {
super();
this._valueName = null;
}
public get value(): string {
if (this._valueName === null) {
if (this.valueObj === null) {
this._valueName = 'null';
} else if (Array.isArray(this.valueObj)) {
this._valueName = `Array[${this.valueObj.length}]`;
} else if (types.isObject(this.valueObj)) {
this._valueName = 'Object';
} else if (types.isString(this.valueObj)) {
this._valueName = `"${massageValue(this.valueObj)}"`;
} else {
this._valueName = String(this.valueObj);
}
if (!this._valueName) {
this._valueName = '';
}
}
return this._valueName;
}
public getChildren(): debug.ITreeElement[] {
if (!this.children) {
if (Array.isArray(this.valueObj)) {
this.children = (<any[]>this.valueObj).slice(0, KeyValueOutputElement.MAX_CHILDREN).map((v, index) => new KeyValueOutputElement(String(index), v, null));
} else if (types.isObject(this.valueObj)) {
this.children = Object.getOwnPropertyNames(this.valueObj).slice(0, KeyValueOutputElement.MAX_CHILDREN).map(key => new KeyValueOutputElement(key, this.valueObj[key], null));
} else {
this.children = [];
}
}
return this.children;
}
}
export abstract class ExpressionContainer implements debug.IExpressionContainer {
public static allValues: { [id: string]: string } = {};
// Use chunks to support variable paging #9537
private static CHUNK_SIZE = 100;
public valueChanged: boolean;
private children: TPromise<debug.IExpression[]>;
private _value: string;
constructor(
public reference: number,
private id: string,
private cacheChildren: boolean,
public childrenCount: number,
private chunkIndex = 0
) {
// noop
}
public getChildren(debugService: debug.IDebugService): TPromise<debug.IExpression[]> {
if (!this.cacheChildren || !this.children) {
const session = debugService.getActiveSession();
// only variables with reference > 0 have children.
if (!session || this.reference <= 0) {
this.children = TPromise.as([]);
} else {
if (this.childrenCount > ExpressionContainer.CHUNK_SIZE) {
// There are a lot of children, create fake intermediate values that represent chunks #9537
const chunks = [];
const numberOfChunks = this.childrenCount / ExpressionContainer.CHUNK_SIZE;
for (let i = 0; i < numberOfChunks; i++) {
const chunkSize = (i < numberOfChunks - 1) ? ExpressionContainer.CHUNK_SIZE : this.childrenCount % ExpressionContainer.CHUNK_SIZE;
const chunkName = `${i * ExpressionContainer.CHUNK_SIZE}..${i * ExpressionContainer.CHUNK_SIZE + chunkSize - 1}`;
chunks.push(new Variable(this, this.reference, chunkName, '', chunkSize, null, true, i));
}
this.children = TPromise.as(chunks);
} else {
const start = this.getChildrenInChunks ? this.chunkIndex * ExpressionContainer.CHUNK_SIZE : undefined;
const count = this.getChildrenInChunks ? this.childrenCount : undefined;
this.children = session.variables({
variablesReference: this.reference,
start,
count
}).then(response => {
return arrays.distinct(response.body.variables.filter(v => !!v), v => v.name).map(
v => new Variable(this, v.variablesReference, v.name, v.value, v.indexedVariables, v.type)
);
}, (e: Error) => [new Variable(this, 0, null, e.message, 0, null, false)]);
}
}
}
return this.children;
}
public getId(): string {
return this.id;
}
public get value(): string {
return this._value;
}
// The adapter explicitly sents the children count of an expression only if there are lots of children which should be chunked.
private get getChildrenInChunks(): boolean {
return !!this.childrenCount;
}
public set value(value: string) {
this._value = massageValue(value);
this.valueChanged = ExpressionContainer.allValues[this.getId()] &&
ExpressionContainer.allValues[this.getId()] !== Expression.DEFAULT_VALUE && ExpressionContainer.allValues[this.getId()] !== value;
ExpressionContainer.allValues[this.getId()] = value;
}
}
export class Expression extends ExpressionContainer implements debug.IExpression {
static DEFAULT_VALUE = 'not available';
public available: boolean;
public type: string;
constructor(public name: string, cacheChildren: boolean, id = uuid.generateUuid()) {
super(0, id, cacheChildren, 0);
this.value = Expression.DEFAULT_VALUE;
this.available = false;
}
}
export class Variable extends ExpressionContainer implements debug.IExpression {
// Used to show the error message coming from the adapter when setting the value #7807
public errorMessage: string;
constructor(
public parent: debug.IExpressionContainer,
reference: number,
public name: string,
value: string,
childrenCount: number,
public type: string = null,
public available = true,
chunkIndex = 0
) {
super(reference, `variable:${ parent.getId() }:${ name }`, true, childrenCount, chunkIndex);
this.value = massageValue(value);
}
}
export class Scope extends ExpressionContainer implements debug.IScope {
constructor(
private threadId: number,
public name: string,
reference: number,
public expensive: boolean,
childrenCount: number
) {
super(reference, `scope:${threadId}:${name}:${reference}`, true, childrenCount);
}
}
export class StackFrame implements debug.IStackFrame {
private scopes: TPromise<Scope[]>;
constructor(
public threadId: number,
public frameId: number,
public source: Source,
public name: string,
public lineNumber: number,
public column: number
) {
this.scopes = null;
}
public getId(): string {
return `stackframe:${ this.threadId }:${ this.frameId }`;
}
public getScopes(debugService: debug.IDebugService): TPromise<debug.IScope[]> {
if (!this.scopes) {
this.scopes = debugService.getActiveSession().scopes({ frameId: this.frameId }).then(response => {
return response.body.scopes.map(rs => new Scope(this.threadId, rs.name, rs.variablesReference, rs.expensive, rs.indexedVariables));
}, err => []);
}
return this.scopes;
}
}
export class Breakpoint implements debug.IBreakpoint {
public lineNumber: number;
public verified: boolean;
public idFromAdapter: number;
public message: string;
private id: string;
constructor(
public source: Source,
public desiredLineNumber: number,
public enabled: boolean,
public condition: string
) {
if (enabled === undefined) {
this.enabled = true;
}
this.lineNumber = this.desiredLineNumber;
this.verified = false;
this.id = uuid.generateUuid();
}
public getId(): string {
return this.id;
}
}
export class FunctionBreakpoint implements debug.IFunctionBreakpoint {
private id: string;
public verified: boolean;
public idFromAdapter: number;
constructor(public name: string, public enabled: boolean) {
this.verified = false;
this.id = uuid.generateUuid();
}
public getId(): string {
return this.id;
}
}
export class ExceptionBreakpoint implements debug.IExceptionBreakpoint {
private id: string;
constructor(public filter: string, public label: string, public enabled: boolean) {
this.id = uuid.generateUuid();
}
public getId(): string {
return this.id;
}
}
export class Model implements debug.IModel {
private threads: { [reference: number]: debug.IThread; };
private toDispose: lifecycle.IDisposable[];
private replElements: debug.ITreeElement[];
private _onDidChangeBreakpoints: Emitter<void>;
private _onDidChangeCallStack: Emitter<void>;
private _onDidChangeWatchExpressions: Emitter<debug.IExpression>;
private _onDidChangeREPLElements: Emitter<void>;
constructor(
private breakpoints: debug.IBreakpoint[],
private breakpointsActivated: boolean,
private functionBreakpoints: debug.IFunctionBreakpoint[],
private exceptionBreakpoints: debug.IExceptionBreakpoint[],
private watchExpressions: Expression[]
) {
this.threads = {};
this.replElements = [];
this.toDispose = [];
this._onDidChangeBreakpoints = new Emitter<void>();
this._onDidChangeCallStack = new Emitter<void>();
this._onDidChangeWatchExpressions = new Emitter<debug.IExpression>();
this._onDidChangeREPLElements = new Emitter<void>();
}
public getId(): string {
return 'root';
}
public get onDidChangeBreakpoints(): Event<void> {
return this._onDidChangeBreakpoints.event;
}
public get onDidChangeCallStack(): Event<void> {
return this._onDidChangeCallStack.event;
}
public get onDidChangeWatchExpressions(): Event<debug.IExpression> {
return this._onDidChangeWatchExpressions.event;
}
public get onDidChangeReplElements(): Event<void> {
return this._onDidChangeREPLElements.event;
}
public getThreads(): { [reference: number]: debug.IThread; } {
return this.threads;
}
public clearThreads(removeThreads: boolean, reference: number = undefined): void {
if (reference) {
if (this.threads[reference]) {
this.threads[reference].clearCallStack();
this.threads[reference].stoppedDetails = undefined;
this.threads[reference].stopped = false;
if (removeThreads) {
delete this.threads[reference];
}
}
} else {
Object.keys(this.threads).forEach(ref => {
this.threads[ref].clearCallStack();
this.threads[ref].stoppedDetails = undefined;
this.threads[ref].stopped = false;
});
if (removeThreads) {
this.threads = {};
ExpressionContainer.allValues = {};
}
}
this._onDidChangeCallStack.fire();
}
public getBreakpoints(): debug.IBreakpoint[] {
return this.breakpoints;
}
public getFunctionBreakpoints(): debug.IFunctionBreakpoint[] {
return this.functionBreakpoints;
}
public getExceptionBreakpoints(): debug.IExceptionBreakpoint[] {
return this.exceptionBreakpoints;
}
public setExceptionBreakpoints(data: DebugProtocol.ExceptionBreakpointsFilter[]): void {
if (data) {
this.exceptionBreakpoints = data.map(d => {
const ebp = this.exceptionBreakpoints.filter(ebp => ebp.filter === d.filter).pop();
return new ExceptionBreakpoint(d.filter, d.label, ebp ? ebp.enabled : d.default);
});
}
}
public areBreakpointsActivated(): boolean {
return this.breakpointsActivated;
}
public setBreakpointsActivated(activated: boolean): void {
this.breakpointsActivated = activated;
this._onDidChangeBreakpoints.fire();
}
public addBreakpoints(rawData: debug.IRawBreakpoint[]): void {
this.breakpoints = this.breakpoints.concat(rawData.map(rawBp =>
new Breakpoint(new Source(Source.toRawSource(rawBp.uri, this)), rawBp.lineNumber, rawBp.enabled, rawBp.condition)));
this.breakpointsActivated = true;
this._onDidChangeBreakpoints.fire();
}
public removeBreakpoints(toRemove: debug.IBreakpoint[]): void {
this.breakpoints = this.breakpoints.filter(bp => !toRemove.some(toRemove => toRemove.getId() === bp.getId()));
this._onDidChangeBreakpoints.fire();
}
public updateBreakpoints(data: { [id: string]: DebugProtocol.Breakpoint }): void {
this.breakpoints.forEach(bp => {
const bpData = data[bp.getId()];
if (bpData) {
bp.lineNumber = bpData.line ? bpData.line : bp.lineNumber;
bp.verified = bpData.verified;
bp.idFromAdapter = bpData.id;
bp.message = bpData.message;
}
});
this._onDidChangeBreakpoints.fire();
}
public setEnablement(element: debug.IEnablement, enable: boolean): void {
element.enabled = enable;
if (element instanceof Breakpoint && !element.enabled) {
var breakpoint = <Breakpoint> element;
breakpoint.lineNumber = breakpoint.desiredLineNumber;
breakpoint.verified = false;
}
this._onDidChangeBreakpoints.fire();
}
public enableOrDisableAllBreakpoints(enable: boolean): void {
this.breakpoints.forEach(bp => {
bp.enabled = enable;
if (!enable) {
bp.lineNumber = bp.desiredLineNumber;
bp.verified = false;
}
});
this.exceptionBreakpoints.forEach(ebp => ebp.enabled = enable);
this.functionBreakpoints.forEach(fbp => fbp.enabled = enable);
this._onDidChangeBreakpoints.fire();
}
public addFunctionBreakpoint(functionName: string): void {
this.functionBreakpoints.push(new FunctionBreakpoint(functionName, true));
this._onDidChangeBreakpoints.fire();
}
public updateFunctionBreakpoints(data: { [id: string]: { name?: string, verified?: boolean; id?: number } }): void {
this.functionBreakpoints.forEach(fbp => {
const fbpData = data[fbp.getId()];
if (fbpData) {
fbp.name = fbpData.name || fbp.name;
fbp.verified = fbpData.verified;
fbp.idFromAdapter = fbpData.id;
}
});
this._onDidChangeBreakpoints.fire();
}
public removeFunctionBreakpoints(id?: string): void {
this.functionBreakpoints = id ? this.functionBreakpoints.filter(fbp => fbp.getId() !== id) : [];
this._onDidChangeBreakpoints.fire();
}
public getReplElements(): debug.ITreeElement[] {
return this.replElements;
}
public addReplExpression(session: debug.IRawDebugSession, stackFrame: debug.IStackFrame, name: string): TPromise<void> {
const expression = new Expression(name, true);
this.addReplElements([expression]);
return evaluateExpression(session, stackFrame, expression, 'repl')
.then(() => this._onDidChangeREPLElements.fire());
}
public logToRepl(value: string | { [key: string]: any }, severity?: severity): void {
let elements:OutputElement[] = [];
let previousOutput = this.replElements.length && (<ValueOutputElement>this.replElements[this.replElements.length - 1]);
// string message
if (typeof value === 'string') {
if (value && value.trim() && previousOutput && previousOutput.value === value && previousOutput.severity === severity) {
previousOutput.counter++; // we got the same output (but not an empty string when trimmed) so we just increment the counter
} else {
let lines = value.trim().split('\n');
lines.forEach((line, index) => {
elements.push(new ValueOutputElement(line, severity));
});
}
}
// key-value output
else {
elements.push(new KeyValueOutputElement((<any>value).prototype, value, nls.localize('snapshotObj', "Only primitive values are shown for this object.")));
}
if (elements.length) {
this.addReplElements(elements);
}
this._onDidChangeREPLElements.fire();
}
public appendReplOutput(value: string, severity?: severity): void {
const elements: OutputElement[] = [];
let previousOutput = this.replElements.length && (<ValueOutputElement>this.replElements[this.replElements.length - 1]);
let lines = value.split('\n');
let groupTogether = !!previousOutput && (previousOutput.category === 'output' && severity === previousOutput.severity);
if (groupTogether) {
// append to previous line if same group
previousOutput.value += lines.shift();
} else if (previousOutput && previousOutput.value === '') {
// remove potential empty lines between different output types
this.replElements.pop();
}
// fill in lines as output value elements
lines.forEach((line, index) => {
elements.push(new ValueOutputElement(line, severity, 'output'));
});
this.addReplElements(elements);
this._onDidChangeREPLElements.fire();
}
private addReplElements(newElements: debug.ITreeElement[]): void {
this.replElements.push(...newElements);
if (this.replElements.length > MAX_REPL_LENGTH) {
this.replElements.splice(0, this.replElements.length - MAX_REPL_LENGTH);
}
}
public removeReplExpressions(): void {
if (this.replElements.length > 0) {
this.replElements = [];
this._onDidChangeREPLElements.fire();
}
}
public getWatchExpressions(): Expression[] {
return this.watchExpressions;
}
public addWatchExpression(session: debug.IRawDebugSession, stackFrame: debug.IStackFrame, name: string): TPromise<void> {
const we = new Expression(name, false);
this.watchExpressions.push(we);
if (!name) {
this._onDidChangeWatchExpressions.fire(we);
return TPromise.as(null);
}
return this.evaluateWatchExpressions(session, stackFrame, we.getId());
}
public renameWatchExpression(session: debug.IRawDebugSession, stackFrame: debug.IStackFrame, id: string, newName: string): TPromise<void> {
const filtered = this.watchExpressions.filter(we => we.getId() === id);
if (filtered.length === 1) {
filtered[0].name = newName;
return evaluateExpression(session, stackFrame, filtered[0], 'watch').then(() => {
this._onDidChangeWatchExpressions.fire(filtered[0]);
});
}
return TPromise.as(null);
}
public evaluateWatchExpressions(session: debug.IRawDebugSession, stackFrame: debug.IStackFrame, id: string = null): TPromise<void> {
if (id) {
const filtered = this.watchExpressions.filter(we => we.getId() === id);
if (filtered.length !== 1) {
return TPromise.as(null);
}
return evaluateExpression(session, stackFrame, filtered[0], 'watch').then(() => {
this._onDidChangeWatchExpressions.fire(filtered[0]);
});
}
return TPromise.join(this.watchExpressions.map(we => evaluateExpression(session, stackFrame, we, 'watch'))).then(() => {
this._onDidChangeWatchExpressions.fire();
});
}
public clearWatchExpressionValues(): void {
this.watchExpressions.forEach(we => {
we.value = Expression.DEFAULT_VALUE;
we.available = false;
we.reference = 0;
});
this._onDidChangeWatchExpressions.fire();
}
public removeWatchExpressions(id: string = null): void {
this.watchExpressions = id ? this.watchExpressions.filter(we => we.getId() !== id) : [];
this._onDidChangeWatchExpressions.fire();
}
public sourceIsUnavailable(source: Source): void {
Object.keys(this.threads).forEach(key => {
if (this.threads[key].getCachedCallStack()) {
this.threads[key].getCachedCallStack().forEach(stackFrame => {
if (stackFrame.source.uri.toString() === source.uri.toString()) {
stackFrame.source.available = false;
}
});
}
});
this._onDidChangeCallStack.fire();
}
public rawUpdate(data: debug.IRawModelUpdate): void {
if (data.thread && !this.threads[data.threadId]) {
// A new thread came in, initialize it.
this.threads[data.threadId] = new Thread(data.thread.name, data.thread.id);
}
if (data.stoppedDetails) {
// Set the availability of the threads' callstacks depending on
// whether the thread is stopped or not
if (data.allThreadsStopped) {
Object.keys(this.threads).forEach(ref => {
// Only update the details if all the threads are stopped
// because we don't want to overwrite the details of other
// threads that have stopped for a different reason
this.threads[ref].stoppedDetails = objects.clone(data.stoppedDetails);
this.threads[ref].stopped = true;
this.threads[ref].clearCallStack();
});
} else {
// One thread is stopped, only update that thread.
this.threads[data.threadId].stoppedDetails = data.stoppedDetails;
this.threads[data.threadId].clearCallStack();
this.threads[data.threadId].stopped = true;
}
}
this._onDidChangeCallStack.fire();
}
public dispose(): void {
this.threads = null;
this.breakpoints = null;
this.exceptionBreakpoints = null;
this.functionBreakpoints = null;
this.watchExpressions = null;
this.replElements = null;
this.toDispose = lifecycle.dispose(this.toDispose);
}
}
| src/vs/workbench/parts/debug/common/debugModel.ts | 1 | https://github.com/microsoft/vscode/commit/3978edfa64c9a7b8a8ba823e3ab30767457dc5c6 | [
0.992921769618988,
0.025153974071145058,
0.0001620561524759978,
0.00017243833281099796,
0.15451189875602722
] |
{
"id": 0,
"code_window": [
"\t\texpression.available = !!(response && response.body);\n",
"\t\tif (response.body) {\n",
"\t\t\texpression.value = response.body.result;\n",
"\t\t\texpression.reference = response.body.variablesReference;\n",
"\t\t\texpression.childrenCount = response.body.indexedVariables;\n",
"\t\t\texpression.type = response.body.type;\n",
"\t\t}\n",
"\n",
"\t\treturn expression;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\texpression.indexedVariables = response.body.indexedVariables;\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debugModel.ts",
"type": "replace",
"edit_start_line_idx": 41
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Do not edit this file. It is machine generated.
{
"workingFilesViewerAriaLabel": "{0}, 작업 파일"
} | i18n/kor/src/vs/workbench/parts/files/browser/views/workingFilesViewer.i18n.json | 0 | https://github.com/microsoft/vscode/commit/3978edfa64c9a7b8a8ba823e3ab30767457dc5c6 | [
0.000175082401256077,
0.000175082401256077,
0.000175082401256077,
0.000175082401256077,
0
] |
{
"id": 0,
"code_window": [
"\t\texpression.available = !!(response && response.body);\n",
"\t\tif (response.body) {\n",
"\t\t\texpression.value = response.body.result;\n",
"\t\t\texpression.reference = response.body.variablesReference;\n",
"\t\t\texpression.childrenCount = response.body.indexedVariables;\n",
"\t\t\texpression.type = response.body.type;\n",
"\t\t}\n",
"\n",
"\t\treturn expression;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\texpression.indexedVariables = response.body.indexedVariables;\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debugModel.ts",
"type": "replace",
"edit_start_line_idx": 41
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Do not edit this file. It is machine generated.
{
"globalConsoleActionMacLinux": "開啟新的終端機",
"globalConsoleActionWin": "開啟新的命令提示字元",
"scopedConsoleActionMacLinux": "在終端機中開啟",
"scopedConsoleActionWin": "在命令提示字元中開啟",
"terminal.external.linuxExec": "自訂要在 Linux 上執行的終端機。",
"terminal.external.osxExec": "自訂要在 OS X 上執行的終端機應用程式。",
"terminal.external.windowsExec": "自訂要在 Windows 上執行的終端機。",
"terminalConfigurationTitle": "外部終端機組態"
} | i18n/cht/src/vs/workbench/parts/execution/electron-browser/terminal.contribution.i18n.json | 0 | https://github.com/microsoft/vscode/commit/3978edfa64c9a7b8a8ba823e3ab30767457dc5c6 | [
0.00017011909221764654,
0.0001687514886725694,
0.00016738389967940748,
0.0001687514886725694,
0.000001367596269119531
] |
{
"id": 0,
"code_window": [
"\t\texpression.available = !!(response && response.body);\n",
"\t\tif (response.body) {\n",
"\t\t\texpression.value = response.body.result;\n",
"\t\t\texpression.reference = response.body.variablesReference;\n",
"\t\t\texpression.childrenCount = response.body.indexedVariables;\n",
"\t\t\texpression.type = response.body.type;\n",
"\t\t}\n",
"\n",
"\t\treturn expression;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\texpression.indexedVariables = response.body.indexedVariables;\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debugModel.ts",
"type": "replace",
"edit_start_line_idx": 41
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Do not edit this file. It is machine generated.
{
"installNet": "下载 .NET Framework 4.5",
"netVersionError": "需要 Microsoft .NET Framework 4.5。请访问链接安装它。",
"trashFailed": "未能将“{0}”移动到垃圾桶"
} | i18n/chs/src/vs/workbench/services/files/electron-browser/fileService.i18n.json | 0 | https://github.com/microsoft/vscode/commit/3978edfa64c9a7b8a8ba823e3ab30767457dc5c6 | [
0.0001717180130071938,
0.00017095060320571065,
0.0001701831934042275,
0.00017095060320571065,
7.674098014831543e-7
] |
{
"id": 1,
"code_window": [
"\n",
"\tconstructor(\n",
"\t\tpublic reference: number,\n",
"\t\tprivate id: string,\n",
"\t\tprivate cacheChildren: boolean,\n",
"\t\tpublic childrenCount: number,\n",
"\t\tprivate chunkIndex = 0\n",
"\t) {\n",
"\t\t// noop\n",
"\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tpublic namedVariables: number,\n",
"\t\tpublic indexedVariables: number,\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debugModel.ts",
"type": "replace",
"edit_start_line_idx": 236
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { TPromise } from 'vs/base/common/winjs.base';
import nls = require('vs/nls');
import lifecycle = require('vs/base/common/lifecycle');
import Event, { Emitter } from 'vs/base/common/event';
import uuid = require('vs/base/common/uuid');
import objects = require('vs/base/common/objects');
import severity from 'vs/base/common/severity';
import types = require('vs/base/common/types');
import arrays = require('vs/base/common/arrays');
import debug = require('vs/workbench/parts/debug/common/debug');
import { Source } from 'vs/workbench/parts/debug/common/debugSource';
const MAX_REPL_LENGTH = 10000;
const UNKNOWN_SOURCE_LABEL = nls.localize('unknownSource', "Unknown Source");
function massageValue(value: string): string {
return value ? value.replace(/\n/g, '\\n').replace(/\r/g, '\\r').replace(/\t/g, '\\t') : value;
}
export function evaluateExpression(session: debug.IRawDebugSession, stackFrame: debug.IStackFrame, expression: Expression, context: string): TPromise<Expression> {
if (!session) {
expression.value = context === 'repl' ? nls.localize('startDebugFirst', "Please start a debug session to evaluate") : Expression.DEFAULT_VALUE;
expression.available = false;
expression.reference = 0;
return TPromise.as(expression);
}
return session.evaluate({
expression: expression.name,
frameId: stackFrame ? stackFrame.frameId : undefined,
context
}).then(response => {
expression.available = !!(response && response.body);
if (response.body) {
expression.value = response.body.result;
expression.reference = response.body.variablesReference;
expression.childrenCount = response.body.indexedVariables;
expression.type = response.body.type;
}
return expression;
}, err => {
expression.value = err.message;
expression.available = false;
expression.reference = 0;
return expression;
});
}
const notPropertySyntax = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
const arrayElementSyntax = /\[.*\]$/;
export function getFullExpressionName(expression: debug.IExpression, sessionType: string): string {
let names = [expression.name];
if (expression instanceof Variable) {
let v = (<Variable> expression).parent;
while (v instanceof Variable || v instanceof Expression) {
names.push((<Variable> v).name);
v = (<Variable> v).parent;
}
}
names = names.reverse();
let result = null;
names.forEach(name => {
if (!result) {
result = name;
} else if (arrayElementSyntax.test(name) || (sessionType === 'node' && !notPropertySyntax.test(name))) {
// use safe way to access node properties a['property_name']. Also handles array elements.
result = name && name.indexOf('[') === 0 ? `${ result }${ name }` : `${ result }['${ name }']`;
} else {
result = `${ result }.${ name }`;
}
});
return result;
}
export class Thread implements debug.IThread {
private promisedCallStack: TPromise<debug.IStackFrame[]>;
private cachedCallStack: debug.IStackFrame[];
public stoppedDetails: debug.IRawStoppedDetails;
public stopped: boolean;
constructor(public name: string, public threadId: number) {
this.promisedCallStack = undefined;
this.stoppedDetails = undefined;
this.cachedCallStack = undefined;
this.stopped = false;
}
public getId(): string {
return `thread:${ this.name }:${ this.threadId }`;
}
public clearCallStack(): void {
this.promisedCallStack = undefined;
this.cachedCallStack = undefined;
}
public getCachedCallStack(): debug.IStackFrame[] {
return this.cachedCallStack;
}
public getCallStack(debugService: debug.IDebugService, getAdditionalStackFrames = false): TPromise<debug.IStackFrame[]> {
if (!this.stopped) {
return TPromise.as([]);
}
if (!this.promisedCallStack) {
this.promisedCallStack = this.getCallStackImpl(debugService, 0).then(callStack => {
this.cachedCallStack = callStack;
return callStack;
});
} else if (getAdditionalStackFrames) {
this.promisedCallStack = this.promisedCallStack.then(callStackFirstPart => this.getCallStackImpl(debugService, callStackFirstPart.length).then(callStackSecondPart => {
this.cachedCallStack = callStackFirstPart.concat(callStackSecondPart);
return this.cachedCallStack;
}));
}
return this.promisedCallStack;
}
private getCallStackImpl(debugService: debug.IDebugService, startFrame: number): TPromise<debug.IStackFrame[]> {
let session = debugService.getActiveSession();
return session.stackTrace({ threadId: this.threadId, startFrame, levels: 20 }).then(response => {
this.stoppedDetails.totalFrames = response.body.totalFrames;
return response.body.stackFrames.map((rsf, level) => {
if (!rsf) {
return new StackFrame(this.threadId, 0, new Source({ name: UNKNOWN_SOURCE_LABEL }, false), nls.localize('unknownStack', "Unknown stack location"), undefined, undefined);
}
return new StackFrame(this.threadId, rsf.id, rsf.source ? new Source(rsf.source) : new Source({ name: UNKNOWN_SOURCE_LABEL }, false), rsf.name, rsf.line, rsf.column);
});
}, (err: Error) => {
this.stoppedDetails.framesErrorMessage = err.message;
return [];
});
}
}
export class OutputElement implements debug.ITreeElement {
private static ID_COUNTER = 0;
constructor(private id = OutputElement.ID_COUNTER++) {
// noop
}
public getId(): string {
return `outputelement:${ this.id }`;
}
}
export class ValueOutputElement extends OutputElement {
constructor(
public value: string,
public severity: severity,
public category?: string,
public counter: number = 1
) {
super();
}
}
export class KeyValueOutputElement extends OutputElement {
private static MAX_CHILDREN = 1000; // upper bound of children per value
private children: debug.ITreeElement[];
private _valueName: string;
constructor(public key: string, public valueObj: any, public annotation?: string) {
super();
this._valueName = null;
}
public get value(): string {
if (this._valueName === null) {
if (this.valueObj === null) {
this._valueName = 'null';
} else if (Array.isArray(this.valueObj)) {
this._valueName = `Array[${this.valueObj.length}]`;
} else if (types.isObject(this.valueObj)) {
this._valueName = 'Object';
} else if (types.isString(this.valueObj)) {
this._valueName = `"${massageValue(this.valueObj)}"`;
} else {
this._valueName = String(this.valueObj);
}
if (!this._valueName) {
this._valueName = '';
}
}
return this._valueName;
}
public getChildren(): debug.ITreeElement[] {
if (!this.children) {
if (Array.isArray(this.valueObj)) {
this.children = (<any[]>this.valueObj).slice(0, KeyValueOutputElement.MAX_CHILDREN).map((v, index) => new KeyValueOutputElement(String(index), v, null));
} else if (types.isObject(this.valueObj)) {
this.children = Object.getOwnPropertyNames(this.valueObj).slice(0, KeyValueOutputElement.MAX_CHILDREN).map(key => new KeyValueOutputElement(key, this.valueObj[key], null));
} else {
this.children = [];
}
}
return this.children;
}
}
export abstract class ExpressionContainer implements debug.IExpressionContainer {
public static allValues: { [id: string]: string } = {};
// Use chunks to support variable paging #9537
private static CHUNK_SIZE = 100;
public valueChanged: boolean;
private children: TPromise<debug.IExpression[]>;
private _value: string;
constructor(
public reference: number,
private id: string,
private cacheChildren: boolean,
public childrenCount: number,
private chunkIndex = 0
) {
// noop
}
public getChildren(debugService: debug.IDebugService): TPromise<debug.IExpression[]> {
if (!this.cacheChildren || !this.children) {
const session = debugService.getActiveSession();
// only variables with reference > 0 have children.
if (!session || this.reference <= 0) {
this.children = TPromise.as([]);
} else {
if (this.childrenCount > ExpressionContainer.CHUNK_SIZE) {
// There are a lot of children, create fake intermediate values that represent chunks #9537
const chunks = [];
const numberOfChunks = this.childrenCount / ExpressionContainer.CHUNK_SIZE;
for (let i = 0; i < numberOfChunks; i++) {
const chunkSize = (i < numberOfChunks - 1) ? ExpressionContainer.CHUNK_SIZE : this.childrenCount % ExpressionContainer.CHUNK_SIZE;
const chunkName = `${i * ExpressionContainer.CHUNK_SIZE}..${i * ExpressionContainer.CHUNK_SIZE + chunkSize - 1}`;
chunks.push(new Variable(this, this.reference, chunkName, '', chunkSize, null, true, i));
}
this.children = TPromise.as(chunks);
} else {
const start = this.getChildrenInChunks ? this.chunkIndex * ExpressionContainer.CHUNK_SIZE : undefined;
const count = this.getChildrenInChunks ? this.childrenCount : undefined;
this.children = session.variables({
variablesReference: this.reference,
start,
count
}).then(response => {
return arrays.distinct(response.body.variables.filter(v => !!v), v => v.name).map(
v => new Variable(this, v.variablesReference, v.name, v.value, v.indexedVariables, v.type)
);
}, (e: Error) => [new Variable(this, 0, null, e.message, 0, null, false)]);
}
}
}
return this.children;
}
public getId(): string {
return this.id;
}
public get value(): string {
return this._value;
}
// The adapter explicitly sents the children count of an expression only if there are lots of children which should be chunked.
private get getChildrenInChunks(): boolean {
return !!this.childrenCount;
}
public set value(value: string) {
this._value = massageValue(value);
this.valueChanged = ExpressionContainer.allValues[this.getId()] &&
ExpressionContainer.allValues[this.getId()] !== Expression.DEFAULT_VALUE && ExpressionContainer.allValues[this.getId()] !== value;
ExpressionContainer.allValues[this.getId()] = value;
}
}
export class Expression extends ExpressionContainer implements debug.IExpression {
static DEFAULT_VALUE = 'not available';
public available: boolean;
public type: string;
constructor(public name: string, cacheChildren: boolean, id = uuid.generateUuid()) {
super(0, id, cacheChildren, 0);
this.value = Expression.DEFAULT_VALUE;
this.available = false;
}
}
export class Variable extends ExpressionContainer implements debug.IExpression {
// Used to show the error message coming from the adapter when setting the value #7807
public errorMessage: string;
constructor(
public parent: debug.IExpressionContainer,
reference: number,
public name: string,
value: string,
childrenCount: number,
public type: string = null,
public available = true,
chunkIndex = 0
) {
super(reference, `variable:${ parent.getId() }:${ name }`, true, childrenCount, chunkIndex);
this.value = massageValue(value);
}
}
export class Scope extends ExpressionContainer implements debug.IScope {
constructor(
private threadId: number,
public name: string,
reference: number,
public expensive: boolean,
childrenCount: number
) {
super(reference, `scope:${threadId}:${name}:${reference}`, true, childrenCount);
}
}
export class StackFrame implements debug.IStackFrame {
private scopes: TPromise<Scope[]>;
constructor(
public threadId: number,
public frameId: number,
public source: Source,
public name: string,
public lineNumber: number,
public column: number
) {
this.scopes = null;
}
public getId(): string {
return `stackframe:${ this.threadId }:${ this.frameId }`;
}
public getScopes(debugService: debug.IDebugService): TPromise<debug.IScope[]> {
if (!this.scopes) {
this.scopes = debugService.getActiveSession().scopes({ frameId: this.frameId }).then(response => {
return response.body.scopes.map(rs => new Scope(this.threadId, rs.name, rs.variablesReference, rs.expensive, rs.indexedVariables));
}, err => []);
}
return this.scopes;
}
}
export class Breakpoint implements debug.IBreakpoint {
public lineNumber: number;
public verified: boolean;
public idFromAdapter: number;
public message: string;
private id: string;
constructor(
public source: Source,
public desiredLineNumber: number,
public enabled: boolean,
public condition: string
) {
if (enabled === undefined) {
this.enabled = true;
}
this.lineNumber = this.desiredLineNumber;
this.verified = false;
this.id = uuid.generateUuid();
}
public getId(): string {
return this.id;
}
}
export class FunctionBreakpoint implements debug.IFunctionBreakpoint {
private id: string;
public verified: boolean;
public idFromAdapter: number;
constructor(public name: string, public enabled: boolean) {
this.verified = false;
this.id = uuid.generateUuid();
}
public getId(): string {
return this.id;
}
}
export class ExceptionBreakpoint implements debug.IExceptionBreakpoint {
private id: string;
constructor(public filter: string, public label: string, public enabled: boolean) {
this.id = uuid.generateUuid();
}
public getId(): string {
return this.id;
}
}
export class Model implements debug.IModel {
private threads: { [reference: number]: debug.IThread; };
private toDispose: lifecycle.IDisposable[];
private replElements: debug.ITreeElement[];
private _onDidChangeBreakpoints: Emitter<void>;
private _onDidChangeCallStack: Emitter<void>;
private _onDidChangeWatchExpressions: Emitter<debug.IExpression>;
private _onDidChangeREPLElements: Emitter<void>;
constructor(
private breakpoints: debug.IBreakpoint[],
private breakpointsActivated: boolean,
private functionBreakpoints: debug.IFunctionBreakpoint[],
private exceptionBreakpoints: debug.IExceptionBreakpoint[],
private watchExpressions: Expression[]
) {
this.threads = {};
this.replElements = [];
this.toDispose = [];
this._onDidChangeBreakpoints = new Emitter<void>();
this._onDidChangeCallStack = new Emitter<void>();
this._onDidChangeWatchExpressions = new Emitter<debug.IExpression>();
this._onDidChangeREPLElements = new Emitter<void>();
}
public getId(): string {
return 'root';
}
public get onDidChangeBreakpoints(): Event<void> {
return this._onDidChangeBreakpoints.event;
}
public get onDidChangeCallStack(): Event<void> {
return this._onDidChangeCallStack.event;
}
public get onDidChangeWatchExpressions(): Event<debug.IExpression> {
return this._onDidChangeWatchExpressions.event;
}
public get onDidChangeReplElements(): Event<void> {
return this._onDidChangeREPLElements.event;
}
public getThreads(): { [reference: number]: debug.IThread; } {
return this.threads;
}
public clearThreads(removeThreads: boolean, reference: number = undefined): void {
if (reference) {
if (this.threads[reference]) {
this.threads[reference].clearCallStack();
this.threads[reference].stoppedDetails = undefined;
this.threads[reference].stopped = false;
if (removeThreads) {
delete this.threads[reference];
}
}
} else {
Object.keys(this.threads).forEach(ref => {
this.threads[ref].clearCallStack();
this.threads[ref].stoppedDetails = undefined;
this.threads[ref].stopped = false;
});
if (removeThreads) {
this.threads = {};
ExpressionContainer.allValues = {};
}
}
this._onDidChangeCallStack.fire();
}
public getBreakpoints(): debug.IBreakpoint[] {
return this.breakpoints;
}
public getFunctionBreakpoints(): debug.IFunctionBreakpoint[] {
return this.functionBreakpoints;
}
public getExceptionBreakpoints(): debug.IExceptionBreakpoint[] {
return this.exceptionBreakpoints;
}
public setExceptionBreakpoints(data: DebugProtocol.ExceptionBreakpointsFilter[]): void {
if (data) {
this.exceptionBreakpoints = data.map(d => {
const ebp = this.exceptionBreakpoints.filter(ebp => ebp.filter === d.filter).pop();
return new ExceptionBreakpoint(d.filter, d.label, ebp ? ebp.enabled : d.default);
});
}
}
public areBreakpointsActivated(): boolean {
return this.breakpointsActivated;
}
public setBreakpointsActivated(activated: boolean): void {
this.breakpointsActivated = activated;
this._onDidChangeBreakpoints.fire();
}
public addBreakpoints(rawData: debug.IRawBreakpoint[]): void {
this.breakpoints = this.breakpoints.concat(rawData.map(rawBp =>
new Breakpoint(new Source(Source.toRawSource(rawBp.uri, this)), rawBp.lineNumber, rawBp.enabled, rawBp.condition)));
this.breakpointsActivated = true;
this._onDidChangeBreakpoints.fire();
}
public removeBreakpoints(toRemove: debug.IBreakpoint[]): void {
this.breakpoints = this.breakpoints.filter(bp => !toRemove.some(toRemove => toRemove.getId() === bp.getId()));
this._onDidChangeBreakpoints.fire();
}
public updateBreakpoints(data: { [id: string]: DebugProtocol.Breakpoint }): void {
this.breakpoints.forEach(bp => {
const bpData = data[bp.getId()];
if (bpData) {
bp.lineNumber = bpData.line ? bpData.line : bp.lineNumber;
bp.verified = bpData.verified;
bp.idFromAdapter = bpData.id;
bp.message = bpData.message;
}
});
this._onDidChangeBreakpoints.fire();
}
public setEnablement(element: debug.IEnablement, enable: boolean): void {
element.enabled = enable;
if (element instanceof Breakpoint && !element.enabled) {
var breakpoint = <Breakpoint> element;
breakpoint.lineNumber = breakpoint.desiredLineNumber;
breakpoint.verified = false;
}
this._onDidChangeBreakpoints.fire();
}
public enableOrDisableAllBreakpoints(enable: boolean): void {
this.breakpoints.forEach(bp => {
bp.enabled = enable;
if (!enable) {
bp.lineNumber = bp.desiredLineNumber;
bp.verified = false;
}
});
this.exceptionBreakpoints.forEach(ebp => ebp.enabled = enable);
this.functionBreakpoints.forEach(fbp => fbp.enabled = enable);
this._onDidChangeBreakpoints.fire();
}
public addFunctionBreakpoint(functionName: string): void {
this.functionBreakpoints.push(new FunctionBreakpoint(functionName, true));
this._onDidChangeBreakpoints.fire();
}
public updateFunctionBreakpoints(data: { [id: string]: { name?: string, verified?: boolean; id?: number } }): void {
this.functionBreakpoints.forEach(fbp => {
const fbpData = data[fbp.getId()];
if (fbpData) {
fbp.name = fbpData.name || fbp.name;
fbp.verified = fbpData.verified;
fbp.idFromAdapter = fbpData.id;
}
});
this._onDidChangeBreakpoints.fire();
}
public removeFunctionBreakpoints(id?: string): void {
this.functionBreakpoints = id ? this.functionBreakpoints.filter(fbp => fbp.getId() !== id) : [];
this._onDidChangeBreakpoints.fire();
}
public getReplElements(): debug.ITreeElement[] {
return this.replElements;
}
public addReplExpression(session: debug.IRawDebugSession, stackFrame: debug.IStackFrame, name: string): TPromise<void> {
const expression = new Expression(name, true);
this.addReplElements([expression]);
return evaluateExpression(session, stackFrame, expression, 'repl')
.then(() => this._onDidChangeREPLElements.fire());
}
public logToRepl(value: string | { [key: string]: any }, severity?: severity): void {
let elements:OutputElement[] = [];
let previousOutput = this.replElements.length && (<ValueOutputElement>this.replElements[this.replElements.length - 1]);
// string message
if (typeof value === 'string') {
if (value && value.trim() && previousOutput && previousOutput.value === value && previousOutput.severity === severity) {
previousOutput.counter++; // we got the same output (but not an empty string when trimmed) so we just increment the counter
} else {
let lines = value.trim().split('\n');
lines.forEach((line, index) => {
elements.push(new ValueOutputElement(line, severity));
});
}
}
// key-value output
else {
elements.push(new KeyValueOutputElement((<any>value).prototype, value, nls.localize('snapshotObj', "Only primitive values are shown for this object.")));
}
if (elements.length) {
this.addReplElements(elements);
}
this._onDidChangeREPLElements.fire();
}
public appendReplOutput(value: string, severity?: severity): void {
const elements: OutputElement[] = [];
let previousOutput = this.replElements.length && (<ValueOutputElement>this.replElements[this.replElements.length - 1]);
let lines = value.split('\n');
let groupTogether = !!previousOutput && (previousOutput.category === 'output' && severity === previousOutput.severity);
if (groupTogether) {
// append to previous line if same group
previousOutput.value += lines.shift();
} else if (previousOutput && previousOutput.value === '') {
// remove potential empty lines between different output types
this.replElements.pop();
}
// fill in lines as output value elements
lines.forEach((line, index) => {
elements.push(new ValueOutputElement(line, severity, 'output'));
});
this.addReplElements(elements);
this._onDidChangeREPLElements.fire();
}
private addReplElements(newElements: debug.ITreeElement[]): void {
this.replElements.push(...newElements);
if (this.replElements.length > MAX_REPL_LENGTH) {
this.replElements.splice(0, this.replElements.length - MAX_REPL_LENGTH);
}
}
public removeReplExpressions(): void {
if (this.replElements.length > 0) {
this.replElements = [];
this._onDidChangeREPLElements.fire();
}
}
public getWatchExpressions(): Expression[] {
return this.watchExpressions;
}
public addWatchExpression(session: debug.IRawDebugSession, stackFrame: debug.IStackFrame, name: string): TPromise<void> {
const we = new Expression(name, false);
this.watchExpressions.push(we);
if (!name) {
this._onDidChangeWatchExpressions.fire(we);
return TPromise.as(null);
}
return this.evaluateWatchExpressions(session, stackFrame, we.getId());
}
public renameWatchExpression(session: debug.IRawDebugSession, stackFrame: debug.IStackFrame, id: string, newName: string): TPromise<void> {
const filtered = this.watchExpressions.filter(we => we.getId() === id);
if (filtered.length === 1) {
filtered[0].name = newName;
return evaluateExpression(session, stackFrame, filtered[0], 'watch').then(() => {
this._onDidChangeWatchExpressions.fire(filtered[0]);
});
}
return TPromise.as(null);
}
public evaluateWatchExpressions(session: debug.IRawDebugSession, stackFrame: debug.IStackFrame, id: string = null): TPromise<void> {
if (id) {
const filtered = this.watchExpressions.filter(we => we.getId() === id);
if (filtered.length !== 1) {
return TPromise.as(null);
}
return evaluateExpression(session, stackFrame, filtered[0], 'watch').then(() => {
this._onDidChangeWatchExpressions.fire(filtered[0]);
});
}
return TPromise.join(this.watchExpressions.map(we => evaluateExpression(session, stackFrame, we, 'watch'))).then(() => {
this._onDidChangeWatchExpressions.fire();
});
}
public clearWatchExpressionValues(): void {
this.watchExpressions.forEach(we => {
we.value = Expression.DEFAULT_VALUE;
we.available = false;
we.reference = 0;
});
this._onDidChangeWatchExpressions.fire();
}
public removeWatchExpressions(id: string = null): void {
this.watchExpressions = id ? this.watchExpressions.filter(we => we.getId() !== id) : [];
this._onDidChangeWatchExpressions.fire();
}
public sourceIsUnavailable(source: Source): void {
Object.keys(this.threads).forEach(key => {
if (this.threads[key].getCachedCallStack()) {
this.threads[key].getCachedCallStack().forEach(stackFrame => {
if (stackFrame.source.uri.toString() === source.uri.toString()) {
stackFrame.source.available = false;
}
});
}
});
this._onDidChangeCallStack.fire();
}
public rawUpdate(data: debug.IRawModelUpdate): void {
if (data.thread && !this.threads[data.threadId]) {
// A new thread came in, initialize it.
this.threads[data.threadId] = new Thread(data.thread.name, data.thread.id);
}
if (data.stoppedDetails) {
// Set the availability of the threads' callstacks depending on
// whether the thread is stopped or not
if (data.allThreadsStopped) {
Object.keys(this.threads).forEach(ref => {
// Only update the details if all the threads are stopped
// because we don't want to overwrite the details of other
// threads that have stopped for a different reason
this.threads[ref].stoppedDetails = objects.clone(data.stoppedDetails);
this.threads[ref].stopped = true;
this.threads[ref].clearCallStack();
});
} else {
// One thread is stopped, only update that thread.
this.threads[data.threadId].stoppedDetails = data.stoppedDetails;
this.threads[data.threadId].clearCallStack();
this.threads[data.threadId].stopped = true;
}
}
this._onDidChangeCallStack.fire();
}
public dispose(): void {
this.threads = null;
this.breakpoints = null;
this.exceptionBreakpoints = null;
this.functionBreakpoints = null;
this.watchExpressions = null;
this.replElements = null;
this.toDispose = lifecycle.dispose(this.toDispose);
}
}
| src/vs/workbench/parts/debug/common/debugModel.ts | 1 | https://github.com/microsoft/vscode/commit/3978edfa64c9a7b8a8ba823e3ab30767457dc5c6 | [
0.9956216216087341,
0.03818821907043457,
0.00016210685134865344,
0.00017161924915853888,
0.18777133524417877
] |
{
"id": 1,
"code_window": [
"\n",
"\tconstructor(\n",
"\t\tpublic reference: number,\n",
"\t\tprivate id: string,\n",
"\t\tprivate cacheChildren: boolean,\n",
"\t\tpublic childrenCount: number,\n",
"\t\tprivate chunkIndex = 0\n",
"\t) {\n",
"\t\t// noop\n",
"\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tpublic namedVariables: number,\n",
"\t\tpublic indexedVariables: number,\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debugModel.ts",
"type": "replace",
"edit_start_line_idx": 236
} | // ATTENTION - THIS DIRECTORY CONTAINS THIRD PARTY OPEN SOURCE MATERIALS:
[{
"name": "ionide/ionide-fsharp",
"version": "0.0.0",
"license": "MIT",
"repositoryURL": "https://github.com/ionide/ionide-fsharp",
"description": "The file syntaxes/fsharp.json was included from https://github.com/ionide/ionide-fsharp/blob/develop/release/grammars/fsharp.json."
}]
| extensions/fsharp/OSSREADME.json | 0 | https://github.com/microsoft/vscode/commit/3978edfa64c9a7b8a8ba823e3ab30767457dc5c6 | [
0.00016851031978148967,
0.00016851031978148967,
0.00016851031978148967,
0.00016851031978148967,
0
] |
{
"id": 1,
"code_window": [
"\n",
"\tconstructor(\n",
"\t\tpublic reference: number,\n",
"\t\tprivate id: string,\n",
"\t\tprivate cacheChildren: boolean,\n",
"\t\tpublic childrenCount: number,\n",
"\t\tprivate chunkIndex = 0\n",
"\t) {\n",
"\t\t// noop\n",
"\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tpublic namedVariables: number,\n",
"\t\tpublic indexedVariables: number,\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debugModel.ts",
"type": "replace",
"edit_start_line_idx": 236
} | /*---------------------------------------------------------------------------------------------
* 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.
{
"collapseExplorerFolders": "エクスプローラーのフォルダーを折りたたむ",
"compareFiles": "ファイルの比較",
"compareSource": "比較対象の選択",
"compareWith": "'{0}' と比較",
"confirmDeleteMessageFile": "'{0}' を完全に削除してもよろしいですか?",
"confirmDeleteMessageFolder": "'{0}' とその内容を完全に削除してもよろしいですか?",
"confirmMoveTrashMessageFile": "'{0}' を削除しますか?",
"confirmMoveTrashMessageFolder": "'{0}' とその内容を削除しますか?",
"confirmOverwrite": "保存先のフォルダーに同じ名前のファイルまたはフォルダーが既に存在します。置き換えてもよろしいですか?",
"copyFile": "コピー",
"createNewFile": "新しいファイル",
"createNewFolder": "新しいフォルダー",
"delete": "削除",
"deleteButtonLabel": "削除(&&D)",
"deleteButtonLabelRecycleBin": "ごみ箱に移動(&&M)",
"deleteButtonLabelTrash": "ゴミ箱に移動(&&M)",
"duplicateFile": "重複",
"emptyFileNameError": "ファイルまたはフォルダーの名前を指定する必要があります。",
"fileNameExistsError": "**{0}** というファイルまたはフォルダーはこの場所に既に存在します。別の名前を指定してください。",
"filePathTooLongError": "名前 **{0}** のパスが長すぎます。名前を短くしてください。",
"focusFilesExplorer": "ファイル エクスプローラーにフォーカスを置く",
"focusOpenEditors": "開いているエディターのビューにフォーカスする",
"globalCompareFile": "アクティブ ファイルを比較しています...",
"importFiles": "ファイルのインポート",
"invalidFileNameError": "名前 **{0}** がファイル名またはフォルダー名として無効です。別の名前を指定してください。",
"irreversible": "このアクションは元に戻すことができません。",
"newFile": "新しいファイル",
"newFolder": "新しいフォルダー",
"newUntitledFile": "無題の新規ファイル",
"openFileToCompare": "まずファイルを開いてから別のファイルと比較してください",
"openFileToShow": "エクスプローラーでファイルを表示するには、ファイルをまず開く必要があります",
"openFolderFirst": "フォルダー内にファイルやフォルダーを作成するには、フォルダーをまず開く必要があります。",
"openToSide": "横に並べて開く",
"pasteFile": "貼り付け",
"permDelete": "完全に削除",
"refresh": "最新の情報に更新",
"refreshExplorer": "エクスプローラーを最新表示する",
"rename": "名前変更",
"replaceButtonLabel": "置換(&&R)",
"retry": "再試行",
"revert": "ファイルを元に戻す",
"save": "保存",
"saveAll": "すべて保存",
"saveAllInGroup": "グループ内のすべてを保存する",
"saveAs": "名前を付けて保存...",
"saveFiles": "ダーティ ファイルを保存",
"showInExplorer": "アクティブ ファイルをエクスプローラーで表示",
"unableToFileToCompare": "選択されたファイルを '{0}' と比較できません。",
"undoBin": "ごみ箱から復元できます。",
"undoTrash": "ゴミ箱から復元できます。",
"warningFileDirty": "ファイル '{0}' は現在保存中です。後でもう一度お試しください。"
} | i18n/jpn/src/vs/workbench/parts/files/browser/fileActions.i18n.json | 0 | https://github.com/microsoft/vscode/commit/3978edfa64c9a7b8a8ba823e3ab30767457dc5c6 | [
0.0001739143772283569,
0.00016804703045636415,
0.00016410845273640007,
0.00016664410941302776,
0.0000032614436804578872
] |
{
"id": 1,
"code_window": [
"\n",
"\tconstructor(\n",
"\t\tpublic reference: number,\n",
"\t\tprivate id: string,\n",
"\t\tprivate cacheChildren: boolean,\n",
"\t\tpublic childrenCount: number,\n",
"\t\tprivate chunkIndex = 0\n",
"\t) {\n",
"\t\t// noop\n",
"\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tpublic namedVariables: number,\n",
"\t\tpublic indexedVariables: number,\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debugModel.ts",
"type": "replace",
"edit_start_line_idx": 236
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var ts = require('typescript');
var Lint = require('tslint/lib/lint');
/**
* Implementation of the no-unexternalized-strings rule.
*/
var Rule = (function (_super) {
__extends(Rule, _super);
function Rule() {
_super.apply(this, arguments);
}
Rule.prototype.apply = function (sourceFile) {
return this.applyWithWalker(new NoUnexternalizedStringsRuleWalker(sourceFile, this.getOptions()));
};
return Rule;
}(Lint.Rules.AbstractRule));
exports.Rule = Rule;
function isStringLiteral(node) {
return node && node.kind === ts.SyntaxKind.StringLiteral;
}
function isObjectLiteral(node) {
return node && node.kind === ts.SyntaxKind.ObjectLiteralExpression;
}
function isPropertyAssignment(node) {
return node && node.kind === ts.SyntaxKind.PropertyAssignment;
}
var NoUnexternalizedStringsRuleWalker = (function (_super) {
__extends(NoUnexternalizedStringsRuleWalker, _super);
function NoUnexternalizedStringsRuleWalker(file, opts) {
var _this = this;
_super.call(this, file, opts);
this.signatures = Object.create(null);
this.ignores = Object.create(null);
this.messageIndex = undefined;
this.keyIndex = undefined;
this.usedKeys = Object.create(null);
var options = this.getOptions();
var first = options && options.length > 0 ? options[0] : null;
if (first) {
if (Array.isArray(first.signatures)) {
first.signatures.forEach(function (signature) { return _this.signatures[signature] = true; });
}
if (Array.isArray(first.ignores)) {
first.ignores.forEach(function (ignore) { return _this.ignores[ignore] = true; });
}
if (typeof first.messageIndex !== 'undefined') {
this.messageIndex = first.messageIndex;
}
if (typeof first.keyIndex !== 'undefined') {
this.keyIndex = first.keyIndex;
}
}
}
NoUnexternalizedStringsRuleWalker.prototype.visitSourceFile = function (node) {
var _this = this;
_super.prototype.visitSourceFile.call(this, node);
Object.keys(this.usedKeys).forEach(function (key) {
var occurences = _this.usedKeys[key];
if (occurences.length > 1) {
occurences.forEach(function (occurence) {
_this.addFailure((_this.createFailure(occurence.key.getStart(), occurence.key.getWidth(), "Duplicate key " + occurence.key.getText() + " with different message value.")));
});
}
});
};
NoUnexternalizedStringsRuleWalker.prototype.visitStringLiteral = function (node) {
this.checkStringLiteral(node);
_super.prototype.visitStringLiteral.call(this, node);
};
NoUnexternalizedStringsRuleWalker.prototype.checkStringLiteral = function (node) {
var text = node.getText();
var doubleQuoted = text.length >= 2 && text[0] === NoUnexternalizedStringsRuleWalker.DOUBLE_QUOTE && text[text.length - 1] === NoUnexternalizedStringsRuleWalker.DOUBLE_QUOTE;
var info = this.findDescribingParent(node);
// Ignore strings in import and export nodes.
if (info && info.ignoreUsage) {
return;
}
var callInfo = info ? info.callInfo : null;
var functionName = callInfo ? callInfo.callExpression.expression.getText() : null;
if (functionName && this.ignores[functionName]) {
return;
}
if (doubleQuoted && (!callInfo || callInfo.argIndex === -1 || !this.signatures[functionName])) {
this.addFailure(this.createFailure(node.getStart(), node.getWidth(), "Unexternalized string found: " + node.getText()));
return;
}
// We have a single quoted string outside a localize function name.
if (!doubleQuoted && !this.signatures[functionName]) {
return;
}
// We have a string that is a direct argument into the localize call.
var keyArg = callInfo.argIndex === this.keyIndex
? callInfo.callExpression.arguments[this.keyIndex]
: null;
if (keyArg) {
if (isStringLiteral(keyArg)) {
this.recordKey(keyArg, this.messageIndex ? callInfo.callExpression.arguments[this.messageIndex] : undefined);
}
else if (isObjectLiteral(keyArg)) {
for (var i = 0; i < keyArg.properties.length; i++) {
var property = keyArg.properties[i];
if (isPropertyAssignment(property)) {
var name_1 = property.name.getText();
if (name_1 === 'key') {
var initializer = property.initializer;
if (isStringLiteral(initializer)) {
this.recordKey(initializer, this.messageIndex ? callInfo.callExpression.arguments[this.messageIndex] : undefined);
}
break;
}
}
}
}
}
var messageArg = callInfo.argIndex === this.messageIndex
? callInfo.callExpression.arguments[this.messageIndex]
: null;
if (messageArg && messageArg !== node) {
this.addFailure(this.createFailure(messageArg.getStart(), messageArg.getWidth(), "Message argument to '" + callInfo.callExpression.expression.getText() + "' must be a string literal."));
return;
}
};
NoUnexternalizedStringsRuleWalker.prototype.recordKey = function (keyNode, messageNode) {
var text = keyNode.getText();
var occurences = this.usedKeys[text];
if (!occurences) {
occurences = [];
this.usedKeys[text] = occurences;
}
if (messageNode) {
if (occurences.some(function (pair) { return pair.message ? pair.message.getText() === messageNode.getText() : false; })) {
return;
}
}
occurences.push({ key: keyNode, message: messageNode });
};
NoUnexternalizedStringsRuleWalker.prototype.findDescribingParent = function (node) {
var parent;
while ((parent = node.parent)) {
var kind = parent.kind;
if (kind === ts.SyntaxKind.CallExpression) {
var callExpression = parent;
return { callInfo: { callExpression: callExpression, argIndex: callExpression.arguments.indexOf(node) } };
}
else if (kind === ts.SyntaxKind.ImportEqualsDeclaration || kind === ts.SyntaxKind.ImportDeclaration || kind === ts.SyntaxKind.ExportDeclaration) {
return { ignoreUsage: true };
}
else if (kind === ts.SyntaxKind.VariableDeclaration || kind === ts.SyntaxKind.FunctionDeclaration || kind === ts.SyntaxKind.PropertyDeclaration
|| kind === ts.SyntaxKind.MethodDeclaration || kind === ts.SyntaxKind.VariableDeclarationList || kind === ts.SyntaxKind.InterfaceDeclaration
|| kind === ts.SyntaxKind.ClassDeclaration || kind === ts.SyntaxKind.EnumDeclaration || kind === ts.SyntaxKind.ModuleDeclaration
|| kind === ts.SyntaxKind.TypeAliasDeclaration || kind === ts.SyntaxKind.SourceFile) {
return null;
}
node = parent;
}
};
NoUnexternalizedStringsRuleWalker.DOUBLE_QUOTE = '"';
return NoUnexternalizedStringsRuleWalker;
}(Lint.RuleWalker));
| build/lib/tslint/noUnexternalizedStringsRule.js | 0 | https://github.com/microsoft/vscode/commit/3978edfa64c9a7b8a8ba823e3ab30767457dc5c6 | [
0.00017349251720588654,
0.00017005030531436205,
0.00016619733651168644,
0.00017036146891769022,
0.0000020422330635483377
] |
{
"id": 2,
"code_window": [
"\t\t\tif (!session || this.reference <= 0) {\n",
"\t\t\t\tthis.children = TPromise.as([]);\n",
"\t\t\t} else {\n",
"\t\t\t\tif (this.childrenCount > ExpressionContainer.CHUNK_SIZE) {\n",
"\t\t\t\t\t// There are a lot of children, create fake intermediate values that represent chunks #9537\n",
"\t\t\t\t\tconst chunks = [];\n",
"\t\t\t\t\tconst numberOfChunks = this.childrenCount / ExpressionContainer.CHUNK_SIZE;\n",
"\t\t\t\t\tfor (let i = 0; i < numberOfChunks; i++) {\n",
"\t\t\t\t\t\tconst chunkSize = (i < numberOfChunks - 1) ? ExpressionContainer.CHUNK_SIZE : this.childrenCount % ExpressionContainer.CHUNK_SIZE;\n",
"\t\t\t\t\t\tconst chunkName = `${i * ExpressionContainer.CHUNK_SIZE}..${i * ExpressionContainer.CHUNK_SIZE + chunkSize - 1}`;\n",
"\t\t\t\t\t\tchunks.push(new Variable(this, this.reference, chunkName, '', chunkSize, null, true, i));\n",
"\t\t\t\t\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [
"\n",
"\t\t\t\t// Check if object has named variables, fetch them independent from indexed variables #9670\n",
"\t\t\t\tthis.children = (!!this.namedVariables ? this.fetchVariables(session, undefined, undefined, 'named') : TPromise.as([])).then(childrenArray => {\n",
"\t\t\t\t\tif (this.indexedVariables > ExpressionContainer.CHUNK_SIZE) {\n",
"\t\t\t\t\t\t// There are a lot of children, create fake intermediate values that represent chunks #9537\n",
"\t\t\t\t\t\tconst numberOfChunks = this.indexedVariables / ExpressionContainer.CHUNK_SIZE;\n",
"\t\t\t\t\t\tfor (let i = 0; i < numberOfChunks; i++) {\n",
"\t\t\t\t\t\t\tconst chunkSize = (i < numberOfChunks - 1) ? ExpressionContainer.CHUNK_SIZE : this.indexedVariables % ExpressionContainer.CHUNK_SIZE;\n",
"\t\t\t\t\t\t\tconst chunkName = `${i * ExpressionContainer.CHUNK_SIZE}..${i * ExpressionContainer.CHUNK_SIZE + chunkSize - 1}`;\n",
"\t\t\t\t\t\t\tchildrenArray.push(new Variable(this, this.reference, chunkName, '', null, chunkSize, null, true, i));\n",
"\t\t\t\t\t\t}\n",
"\n",
"\t\t\t\t\t\treturn childrenArray;\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debugModel.ts",
"type": "replace",
"edit_start_line_idx": 249
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { TPromise } from 'vs/base/common/winjs.base';
import nls = require('vs/nls');
import lifecycle = require('vs/base/common/lifecycle');
import Event, { Emitter } from 'vs/base/common/event';
import uuid = require('vs/base/common/uuid');
import objects = require('vs/base/common/objects');
import severity from 'vs/base/common/severity';
import types = require('vs/base/common/types');
import arrays = require('vs/base/common/arrays');
import debug = require('vs/workbench/parts/debug/common/debug');
import { Source } from 'vs/workbench/parts/debug/common/debugSource';
const MAX_REPL_LENGTH = 10000;
const UNKNOWN_SOURCE_LABEL = nls.localize('unknownSource', "Unknown Source");
function massageValue(value: string): string {
return value ? value.replace(/\n/g, '\\n').replace(/\r/g, '\\r').replace(/\t/g, '\\t') : value;
}
export function evaluateExpression(session: debug.IRawDebugSession, stackFrame: debug.IStackFrame, expression: Expression, context: string): TPromise<Expression> {
if (!session) {
expression.value = context === 'repl' ? nls.localize('startDebugFirst', "Please start a debug session to evaluate") : Expression.DEFAULT_VALUE;
expression.available = false;
expression.reference = 0;
return TPromise.as(expression);
}
return session.evaluate({
expression: expression.name,
frameId: stackFrame ? stackFrame.frameId : undefined,
context
}).then(response => {
expression.available = !!(response && response.body);
if (response.body) {
expression.value = response.body.result;
expression.reference = response.body.variablesReference;
expression.childrenCount = response.body.indexedVariables;
expression.type = response.body.type;
}
return expression;
}, err => {
expression.value = err.message;
expression.available = false;
expression.reference = 0;
return expression;
});
}
const notPropertySyntax = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
const arrayElementSyntax = /\[.*\]$/;
export function getFullExpressionName(expression: debug.IExpression, sessionType: string): string {
let names = [expression.name];
if (expression instanceof Variable) {
let v = (<Variable> expression).parent;
while (v instanceof Variable || v instanceof Expression) {
names.push((<Variable> v).name);
v = (<Variable> v).parent;
}
}
names = names.reverse();
let result = null;
names.forEach(name => {
if (!result) {
result = name;
} else if (arrayElementSyntax.test(name) || (sessionType === 'node' && !notPropertySyntax.test(name))) {
// use safe way to access node properties a['property_name']. Also handles array elements.
result = name && name.indexOf('[') === 0 ? `${ result }${ name }` : `${ result }['${ name }']`;
} else {
result = `${ result }.${ name }`;
}
});
return result;
}
export class Thread implements debug.IThread {
private promisedCallStack: TPromise<debug.IStackFrame[]>;
private cachedCallStack: debug.IStackFrame[];
public stoppedDetails: debug.IRawStoppedDetails;
public stopped: boolean;
constructor(public name: string, public threadId: number) {
this.promisedCallStack = undefined;
this.stoppedDetails = undefined;
this.cachedCallStack = undefined;
this.stopped = false;
}
public getId(): string {
return `thread:${ this.name }:${ this.threadId }`;
}
public clearCallStack(): void {
this.promisedCallStack = undefined;
this.cachedCallStack = undefined;
}
public getCachedCallStack(): debug.IStackFrame[] {
return this.cachedCallStack;
}
public getCallStack(debugService: debug.IDebugService, getAdditionalStackFrames = false): TPromise<debug.IStackFrame[]> {
if (!this.stopped) {
return TPromise.as([]);
}
if (!this.promisedCallStack) {
this.promisedCallStack = this.getCallStackImpl(debugService, 0).then(callStack => {
this.cachedCallStack = callStack;
return callStack;
});
} else if (getAdditionalStackFrames) {
this.promisedCallStack = this.promisedCallStack.then(callStackFirstPart => this.getCallStackImpl(debugService, callStackFirstPart.length).then(callStackSecondPart => {
this.cachedCallStack = callStackFirstPart.concat(callStackSecondPart);
return this.cachedCallStack;
}));
}
return this.promisedCallStack;
}
private getCallStackImpl(debugService: debug.IDebugService, startFrame: number): TPromise<debug.IStackFrame[]> {
let session = debugService.getActiveSession();
return session.stackTrace({ threadId: this.threadId, startFrame, levels: 20 }).then(response => {
this.stoppedDetails.totalFrames = response.body.totalFrames;
return response.body.stackFrames.map((rsf, level) => {
if (!rsf) {
return new StackFrame(this.threadId, 0, new Source({ name: UNKNOWN_SOURCE_LABEL }, false), nls.localize('unknownStack', "Unknown stack location"), undefined, undefined);
}
return new StackFrame(this.threadId, rsf.id, rsf.source ? new Source(rsf.source) : new Source({ name: UNKNOWN_SOURCE_LABEL }, false), rsf.name, rsf.line, rsf.column);
});
}, (err: Error) => {
this.stoppedDetails.framesErrorMessage = err.message;
return [];
});
}
}
export class OutputElement implements debug.ITreeElement {
private static ID_COUNTER = 0;
constructor(private id = OutputElement.ID_COUNTER++) {
// noop
}
public getId(): string {
return `outputelement:${ this.id }`;
}
}
export class ValueOutputElement extends OutputElement {
constructor(
public value: string,
public severity: severity,
public category?: string,
public counter: number = 1
) {
super();
}
}
export class KeyValueOutputElement extends OutputElement {
private static MAX_CHILDREN = 1000; // upper bound of children per value
private children: debug.ITreeElement[];
private _valueName: string;
constructor(public key: string, public valueObj: any, public annotation?: string) {
super();
this._valueName = null;
}
public get value(): string {
if (this._valueName === null) {
if (this.valueObj === null) {
this._valueName = 'null';
} else if (Array.isArray(this.valueObj)) {
this._valueName = `Array[${this.valueObj.length}]`;
} else if (types.isObject(this.valueObj)) {
this._valueName = 'Object';
} else if (types.isString(this.valueObj)) {
this._valueName = `"${massageValue(this.valueObj)}"`;
} else {
this._valueName = String(this.valueObj);
}
if (!this._valueName) {
this._valueName = '';
}
}
return this._valueName;
}
public getChildren(): debug.ITreeElement[] {
if (!this.children) {
if (Array.isArray(this.valueObj)) {
this.children = (<any[]>this.valueObj).slice(0, KeyValueOutputElement.MAX_CHILDREN).map((v, index) => new KeyValueOutputElement(String(index), v, null));
} else if (types.isObject(this.valueObj)) {
this.children = Object.getOwnPropertyNames(this.valueObj).slice(0, KeyValueOutputElement.MAX_CHILDREN).map(key => new KeyValueOutputElement(key, this.valueObj[key], null));
} else {
this.children = [];
}
}
return this.children;
}
}
export abstract class ExpressionContainer implements debug.IExpressionContainer {
public static allValues: { [id: string]: string } = {};
// Use chunks to support variable paging #9537
private static CHUNK_SIZE = 100;
public valueChanged: boolean;
private children: TPromise<debug.IExpression[]>;
private _value: string;
constructor(
public reference: number,
private id: string,
private cacheChildren: boolean,
public childrenCount: number,
private chunkIndex = 0
) {
// noop
}
public getChildren(debugService: debug.IDebugService): TPromise<debug.IExpression[]> {
if (!this.cacheChildren || !this.children) {
const session = debugService.getActiveSession();
// only variables with reference > 0 have children.
if (!session || this.reference <= 0) {
this.children = TPromise.as([]);
} else {
if (this.childrenCount > ExpressionContainer.CHUNK_SIZE) {
// There are a lot of children, create fake intermediate values that represent chunks #9537
const chunks = [];
const numberOfChunks = this.childrenCount / ExpressionContainer.CHUNK_SIZE;
for (let i = 0; i < numberOfChunks; i++) {
const chunkSize = (i < numberOfChunks - 1) ? ExpressionContainer.CHUNK_SIZE : this.childrenCount % ExpressionContainer.CHUNK_SIZE;
const chunkName = `${i * ExpressionContainer.CHUNK_SIZE}..${i * ExpressionContainer.CHUNK_SIZE + chunkSize - 1}`;
chunks.push(new Variable(this, this.reference, chunkName, '', chunkSize, null, true, i));
}
this.children = TPromise.as(chunks);
} else {
const start = this.getChildrenInChunks ? this.chunkIndex * ExpressionContainer.CHUNK_SIZE : undefined;
const count = this.getChildrenInChunks ? this.childrenCount : undefined;
this.children = session.variables({
variablesReference: this.reference,
start,
count
}).then(response => {
return arrays.distinct(response.body.variables.filter(v => !!v), v => v.name).map(
v => new Variable(this, v.variablesReference, v.name, v.value, v.indexedVariables, v.type)
);
}, (e: Error) => [new Variable(this, 0, null, e.message, 0, null, false)]);
}
}
}
return this.children;
}
public getId(): string {
return this.id;
}
public get value(): string {
return this._value;
}
// The adapter explicitly sents the children count of an expression only if there are lots of children which should be chunked.
private get getChildrenInChunks(): boolean {
return !!this.childrenCount;
}
public set value(value: string) {
this._value = massageValue(value);
this.valueChanged = ExpressionContainer.allValues[this.getId()] &&
ExpressionContainer.allValues[this.getId()] !== Expression.DEFAULT_VALUE && ExpressionContainer.allValues[this.getId()] !== value;
ExpressionContainer.allValues[this.getId()] = value;
}
}
export class Expression extends ExpressionContainer implements debug.IExpression {
static DEFAULT_VALUE = 'not available';
public available: boolean;
public type: string;
constructor(public name: string, cacheChildren: boolean, id = uuid.generateUuid()) {
super(0, id, cacheChildren, 0);
this.value = Expression.DEFAULT_VALUE;
this.available = false;
}
}
export class Variable extends ExpressionContainer implements debug.IExpression {
// Used to show the error message coming from the adapter when setting the value #7807
public errorMessage: string;
constructor(
public parent: debug.IExpressionContainer,
reference: number,
public name: string,
value: string,
childrenCount: number,
public type: string = null,
public available = true,
chunkIndex = 0
) {
super(reference, `variable:${ parent.getId() }:${ name }`, true, childrenCount, chunkIndex);
this.value = massageValue(value);
}
}
export class Scope extends ExpressionContainer implements debug.IScope {
constructor(
private threadId: number,
public name: string,
reference: number,
public expensive: boolean,
childrenCount: number
) {
super(reference, `scope:${threadId}:${name}:${reference}`, true, childrenCount);
}
}
export class StackFrame implements debug.IStackFrame {
private scopes: TPromise<Scope[]>;
constructor(
public threadId: number,
public frameId: number,
public source: Source,
public name: string,
public lineNumber: number,
public column: number
) {
this.scopes = null;
}
public getId(): string {
return `stackframe:${ this.threadId }:${ this.frameId }`;
}
public getScopes(debugService: debug.IDebugService): TPromise<debug.IScope[]> {
if (!this.scopes) {
this.scopes = debugService.getActiveSession().scopes({ frameId: this.frameId }).then(response => {
return response.body.scopes.map(rs => new Scope(this.threadId, rs.name, rs.variablesReference, rs.expensive, rs.indexedVariables));
}, err => []);
}
return this.scopes;
}
}
export class Breakpoint implements debug.IBreakpoint {
public lineNumber: number;
public verified: boolean;
public idFromAdapter: number;
public message: string;
private id: string;
constructor(
public source: Source,
public desiredLineNumber: number,
public enabled: boolean,
public condition: string
) {
if (enabled === undefined) {
this.enabled = true;
}
this.lineNumber = this.desiredLineNumber;
this.verified = false;
this.id = uuid.generateUuid();
}
public getId(): string {
return this.id;
}
}
export class FunctionBreakpoint implements debug.IFunctionBreakpoint {
private id: string;
public verified: boolean;
public idFromAdapter: number;
constructor(public name: string, public enabled: boolean) {
this.verified = false;
this.id = uuid.generateUuid();
}
public getId(): string {
return this.id;
}
}
export class ExceptionBreakpoint implements debug.IExceptionBreakpoint {
private id: string;
constructor(public filter: string, public label: string, public enabled: boolean) {
this.id = uuid.generateUuid();
}
public getId(): string {
return this.id;
}
}
export class Model implements debug.IModel {
private threads: { [reference: number]: debug.IThread; };
private toDispose: lifecycle.IDisposable[];
private replElements: debug.ITreeElement[];
private _onDidChangeBreakpoints: Emitter<void>;
private _onDidChangeCallStack: Emitter<void>;
private _onDidChangeWatchExpressions: Emitter<debug.IExpression>;
private _onDidChangeREPLElements: Emitter<void>;
constructor(
private breakpoints: debug.IBreakpoint[],
private breakpointsActivated: boolean,
private functionBreakpoints: debug.IFunctionBreakpoint[],
private exceptionBreakpoints: debug.IExceptionBreakpoint[],
private watchExpressions: Expression[]
) {
this.threads = {};
this.replElements = [];
this.toDispose = [];
this._onDidChangeBreakpoints = new Emitter<void>();
this._onDidChangeCallStack = new Emitter<void>();
this._onDidChangeWatchExpressions = new Emitter<debug.IExpression>();
this._onDidChangeREPLElements = new Emitter<void>();
}
public getId(): string {
return 'root';
}
public get onDidChangeBreakpoints(): Event<void> {
return this._onDidChangeBreakpoints.event;
}
public get onDidChangeCallStack(): Event<void> {
return this._onDidChangeCallStack.event;
}
public get onDidChangeWatchExpressions(): Event<debug.IExpression> {
return this._onDidChangeWatchExpressions.event;
}
public get onDidChangeReplElements(): Event<void> {
return this._onDidChangeREPLElements.event;
}
public getThreads(): { [reference: number]: debug.IThread; } {
return this.threads;
}
public clearThreads(removeThreads: boolean, reference: number = undefined): void {
if (reference) {
if (this.threads[reference]) {
this.threads[reference].clearCallStack();
this.threads[reference].stoppedDetails = undefined;
this.threads[reference].stopped = false;
if (removeThreads) {
delete this.threads[reference];
}
}
} else {
Object.keys(this.threads).forEach(ref => {
this.threads[ref].clearCallStack();
this.threads[ref].stoppedDetails = undefined;
this.threads[ref].stopped = false;
});
if (removeThreads) {
this.threads = {};
ExpressionContainer.allValues = {};
}
}
this._onDidChangeCallStack.fire();
}
public getBreakpoints(): debug.IBreakpoint[] {
return this.breakpoints;
}
public getFunctionBreakpoints(): debug.IFunctionBreakpoint[] {
return this.functionBreakpoints;
}
public getExceptionBreakpoints(): debug.IExceptionBreakpoint[] {
return this.exceptionBreakpoints;
}
public setExceptionBreakpoints(data: DebugProtocol.ExceptionBreakpointsFilter[]): void {
if (data) {
this.exceptionBreakpoints = data.map(d => {
const ebp = this.exceptionBreakpoints.filter(ebp => ebp.filter === d.filter).pop();
return new ExceptionBreakpoint(d.filter, d.label, ebp ? ebp.enabled : d.default);
});
}
}
public areBreakpointsActivated(): boolean {
return this.breakpointsActivated;
}
public setBreakpointsActivated(activated: boolean): void {
this.breakpointsActivated = activated;
this._onDidChangeBreakpoints.fire();
}
public addBreakpoints(rawData: debug.IRawBreakpoint[]): void {
this.breakpoints = this.breakpoints.concat(rawData.map(rawBp =>
new Breakpoint(new Source(Source.toRawSource(rawBp.uri, this)), rawBp.lineNumber, rawBp.enabled, rawBp.condition)));
this.breakpointsActivated = true;
this._onDidChangeBreakpoints.fire();
}
public removeBreakpoints(toRemove: debug.IBreakpoint[]): void {
this.breakpoints = this.breakpoints.filter(bp => !toRemove.some(toRemove => toRemove.getId() === bp.getId()));
this._onDidChangeBreakpoints.fire();
}
public updateBreakpoints(data: { [id: string]: DebugProtocol.Breakpoint }): void {
this.breakpoints.forEach(bp => {
const bpData = data[bp.getId()];
if (bpData) {
bp.lineNumber = bpData.line ? bpData.line : bp.lineNumber;
bp.verified = bpData.verified;
bp.idFromAdapter = bpData.id;
bp.message = bpData.message;
}
});
this._onDidChangeBreakpoints.fire();
}
public setEnablement(element: debug.IEnablement, enable: boolean): void {
element.enabled = enable;
if (element instanceof Breakpoint && !element.enabled) {
var breakpoint = <Breakpoint> element;
breakpoint.lineNumber = breakpoint.desiredLineNumber;
breakpoint.verified = false;
}
this._onDidChangeBreakpoints.fire();
}
public enableOrDisableAllBreakpoints(enable: boolean): void {
this.breakpoints.forEach(bp => {
bp.enabled = enable;
if (!enable) {
bp.lineNumber = bp.desiredLineNumber;
bp.verified = false;
}
});
this.exceptionBreakpoints.forEach(ebp => ebp.enabled = enable);
this.functionBreakpoints.forEach(fbp => fbp.enabled = enable);
this._onDidChangeBreakpoints.fire();
}
public addFunctionBreakpoint(functionName: string): void {
this.functionBreakpoints.push(new FunctionBreakpoint(functionName, true));
this._onDidChangeBreakpoints.fire();
}
public updateFunctionBreakpoints(data: { [id: string]: { name?: string, verified?: boolean; id?: number } }): void {
this.functionBreakpoints.forEach(fbp => {
const fbpData = data[fbp.getId()];
if (fbpData) {
fbp.name = fbpData.name || fbp.name;
fbp.verified = fbpData.verified;
fbp.idFromAdapter = fbpData.id;
}
});
this._onDidChangeBreakpoints.fire();
}
public removeFunctionBreakpoints(id?: string): void {
this.functionBreakpoints = id ? this.functionBreakpoints.filter(fbp => fbp.getId() !== id) : [];
this._onDidChangeBreakpoints.fire();
}
public getReplElements(): debug.ITreeElement[] {
return this.replElements;
}
public addReplExpression(session: debug.IRawDebugSession, stackFrame: debug.IStackFrame, name: string): TPromise<void> {
const expression = new Expression(name, true);
this.addReplElements([expression]);
return evaluateExpression(session, stackFrame, expression, 'repl')
.then(() => this._onDidChangeREPLElements.fire());
}
public logToRepl(value: string | { [key: string]: any }, severity?: severity): void {
let elements:OutputElement[] = [];
let previousOutput = this.replElements.length && (<ValueOutputElement>this.replElements[this.replElements.length - 1]);
// string message
if (typeof value === 'string') {
if (value && value.trim() && previousOutput && previousOutput.value === value && previousOutput.severity === severity) {
previousOutput.counter++; // we got the same output (but not an empty string when trimmed) so we just increment the counter
} else {
let lines = value.trim().split('\n');
lines.forEach((line, index) => {
elements.push(new ValueOutputElement(line, severity));
});
}
}
// key-value output
else {
elements.push(new KeyValueOutputElement((<any>value).prototype, value, nls.localize('snapshotObj', "Only primitive values are shown for this object.")));
}
if (elements.length) {
this.addReplElements(elements);
}
this._onDidChangeREPLElements.fire();
}
public appendReplOutput(value: string, severity?: severity): void {
const elements: OutputElement[] = [];
let previousOutput = this.replElements.length && (<ValueOutputElement>this.replElements[this.replElements.length - 1]);
let lines = value.split('\n');
let groupTogether = !!previousOutput && (previousOutput.category === 'output' && severity === previousOutput.severity);
if (groupTogether) {
// append to previous line if same group
previousOutput.value += lines.shift();
} else if (previousOutput && previousOutput.value === '') {
// remove potential empty lines between different output types
this.replElements.pop();
}
// fill in lines as output value elements
lines.forEach((line, index) => {
elements.push(new ValueOutputElement(line, severity, 'output'));
});
this.addReplElements(elements);
this._onDidChangeREPLElements.fire();
}
private addReplElements(newElements: debug.ITreeElement[]): void {
this.replElements.push(...newElements);
if (this.replElements.length > MAX_REPL_LENGTH) {
this.replElements.splice(0, this.replElements.length - MAX_REPL_LENGTH);
}
}
public removeReplExpressions(): void {
if (this.replElements.length > 0) {
this.replElements = [];
this._onDidChangeREPLElements.fire();
}
}
public getWatchExpressions(): Expression[] {
return this.watchExpressions;
}
public addWatchExpression(session: debug.IRawDebugSession, stackFrame: debug.IStackFrame, name: string): TPromise<void> {
const we = new Expression(name, false);
this.watchExpressions.push(we);
if (!name) {
this._onDidChangeWatchExpressions.fire(we);
return TPromise.as(null);
}
return this.evaluateWatchExpressions(session, stackFrame, we.getId());
}
public renameWatchExpression(session: debug.IRawDebugSession, stackFrame: debug.IStackFrame, id: string, newName: string): TPromise<void> {
const filtered = this.watchExpressions.filter(we => we.getId() === id);
if (filtered.length === 1) {
filtered[0].name = newName;
return evaluateExpression(session, stackFrame, filtered[0], 'watch').then(() => {
this._onDidChangeWatchExpressions.fire(filtered[0]);
});
}
return TPromise.as(null);
}
public evaluateWatchExpressions(session: debug.IRawDebugSession, stackFrame: debug.IStackFrame, id: string = null): TPromise<void> {
if (id) {
const filtered = this.watchExpressions.filter(we => we.getId() === id);
if (filtered.length !== 1) {
return TPromise.as(null);
}
return evaluateExpression(session, stackFrame, filtered[0], 'watch').then(() => {
this._onDidChangeWatchExpressions.fire(filtered[0]);
});
}
return TPromise.join(this.watchExpressions.map(we => evaluateExpression(session, stackFrame, we, 'watch'))).then(() => {
this._onDidChangeWatchExpressions.fire();
});
}
public clearWatchExpressionValues(): void {
this.watchExpressions.forEach(we => {
we.value = Expression.DEFAULT_VALUE;
we.available = false;
we.reference = 0;
});
this._onDidChangeWatchExpressions.fire();
}
public removeWatchExpressions(id: string = null): void {
this.watchExpressions = id ? this.watchExpressions.filter(we => we.getId() !== id) : [];
this._onDidChangeWatchExpressions.fire();
}
public sourceIsUnavailable(source: Source): void {
Object.keys(this.threads).forEach(key => {
if (this.threads[key].getCachedCallStack()) {
this.threads[key].getCachedCallStack().forEach(stackFrame => {
if (stackFrame.source.uri.toString() === source.uri.toString()) {
stackFrame.source.available = false;
}
});
}
});
this._onDidChangeCallStack.fire();
}
public rawUpdate(data: debug.IRawModelUpdate): void {
if (data.thread && !this.threads[data.threadId]) {
// A new thread came in, initialize it.
this.threads[data.threadId] = new Thread(data.thread.name, data.thread.id);
}
if (data.stoppedDetails) {
// Set the availability of the threads' callstacks depending on
// whether the thread is stopped or not
if (data.allThreadsStopped) {
Object.keys(this.threads).forEach(ref => {
// Only update the details if all the threads are stopped
// because we don't want to overwrite the details of other
// threads that have stopped for a different reason
this.threads[ref].stoppedDetails = objects.clone(data.stoppedDetails);
this.threads[ref].stopped = true;
this.threads[ref].clearCallStack();
});
} else {
// One thread is stopped, only update that thread.
this.threads[data.threadId].stoppedDetails = data.stoppedDetails;
this.threads[data.threadId].clearCallStack();
this.threads[data.threadId].stopped = true;
}
}
this._onDidChangeCallStack.fire();
}
public dispose(): void {
this.threads = null;
this.breakpoints = null;
this.exceptionBreakpoints = null;
this.functionBreakpoints = null;
this.watchExpressions = null;
this.replElements = null;
this.toDispose = lifecycle.dispose(this.toDispose);
}
}
| src/vs/workbench/parts/debug/common/debugModel.ts | 1 | https://github.com/microsoft/vscode/commit/3978edfa64c9a7b8a8ba823e3ab30767457dc5c6 | [
0.9984040856361389,
0.02481503039598465,
0.00016137983766384423,
0.00016971635341178626,
0.15265677869319916
] |
{
"id": 2,
"code_window": [
"\t\t\tif (!session || this.reference <= 0) {\n",
"\t\t\t\tthis.children = TPromise.as([]);\n",
"\t\t\t} else {\n",
"\t\t\t\tif (this.childrenCount > ExpressionContainer.CHUNK_SIZE) {\n",
"\t\t\t\t\t// There are a lot of children, create fake intermediate values that represent chunks #9537\n",
"\t\t\t\t\tconst chunks = [];\n",
"\t\t\t\t\tconst numberOfChunks = this.childrenCount / ExpressionContainer.CHUNK_SIZE;\n",
"\t\t\t\t\tfor (let i = 0; i < numberOfChunks; i++) {\n",
"\t\t\t\t\t\tconst chunkSize = (i < numberOfChunks - 1) ? ExpressionContainer.CHUNK_SIZE : this.childrenCount % ExpressionContainer.CHUNK_SIZE;\n",
"\t\t\t\t\t\tconst chunkName = `${i * ExpressionContainer.CHUNK_SIZE}..${i * ExpressionContainer.CHUNK_SIZE + chunkSize - 1}`;\n",
"\t\t\t\t\t\tchunks.push(new Variable(this, this.reference, chunkName, '', chunkSize, null, true, i));\n",
"\t\t\t\t\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [
"\n",
"\t\t\t\t// Check if object has named variables, fetch them independent from indexed variables #9670\n",
"\t\t\t\tthis.children = (!!this.namedVariables ? this.fetchVariables(session, undefined, undefined, 'named') : TPromise.as([])).then(childrenArray => {\n",
"\t\t\t\t\tif (this.indexedVariables > ExpressionContainer.CHUNK_SIZE) {\n",
"\t\t\t\t\t\t// There are a lot of children, create fake intermediate values that represent chunks #9537\n",
"\t\t\t\t\t\tconst numberOfChunks = this.indexedVariables / ExpressionContainer.CHUNK_SIZE;\n",
"\t\t\t\t\t\tfor (let i = 0; i < numberOfChunks; i++) {\n",
"\t\t\t\t\t\t\tconst chunkSize = (i < numberOfChunks - 1) ? ExpressionContainer.CHUNK_SIZE : this.indexedVariables % ExpressionContainer.CHUNK_SIZE;\n",
"\t\t\t\t\t\t\tconst chunkName = `${i * ExpressionContainer.CHUNK_SIZE}..${i * ExpressionContainer.CHUNK_SIZE + chunkSize - 1}`;\n",
"\t\t\t\t\t\t\tchildrenArray.push(new Variable(this, this.reference, chunkName, '', null, chunkSize, null, true, i));\n",
"\t\t\t\t\t\t}\n",
"\n",
"\t\t\t\t\t\treturn childrenArray;\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debugModel.ts",
"type": "replace",
"edit_start_line_idx": 249
} | /*---------------------------------------------------------------------------------------------
* 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.
{
"alertErrorMessage": "错误: {0}",
"alertInfoMessage": "信息: {0}",
"alertWarningMessage": "警告: {0}"
} | i18n/chs/src/vs/base/browser/ui/inputbox/inputBox.i18n.json | 0 | https://github.com/microsoft/vscode/commit/3978edfa64c9a7b8a8ba823e3ab30767457dc5c6 | [
0.00017276221478823572,
0.000169139209901914,
0.00016551620501559228,
0.000169139209901914,
0.0000036230048863217235
] |
{
"id": 2,
"code_window": [
"\t\t\tif (!session || this.reference <= 0) {\n",
"\t\t\t\tthis.children = TPromise.as([]);\n",
"\t\t\t} else {\n",
"\t\t\t\tif (this.childrenCount > ExpressionContainer.CHUNK_SIZE) {\n",
"\t\t\t\t\t// There are a lot of children, create fake intermediate values that represent chunks #9537\n",
"\t\t\t\t\tconst chunks = [];\n",
"\t\t\t\t\tconst numberOfChunks = this.childrenCount / ExpressionContainer.CHUNK_SIZE;\n",
"\t\t\t\t\tfor (let i = 0; i < numberOfChunks; i++) {\n",
"\t\t\t\t\t\tconst chunkSize = (i < numberOfChunks - 1) ? ExpressionContainer.CHUNK_SIZE : this.childrenCount % ExpressionContainer.CHUNK_SIZE;\n",
"\t\t\t\t\t\tconst chunkName = `${i * ExpressionContainer.CHUNK_SIZE}..${i * ExpressionContainer.CHUNK_SIZE + chunkSize - 1}`;\n",
"\t\t\t\t\t\tchunks.push(new Variable(this, this.reference, chunkName, '', chunkSize, null, true, i));\n",
"\t\t\t\t\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [
"\n",
"\t\t\t\t// Check if object has named variables, fetch them independent from indexed variables #9670\n",
"\t\t\t\tthis.children = (!!this.namedVariables ? this.fetchVariables(session, undefined, undefined, 'named') : TPromise.as([])).then(childrenArray => {\n",
"\t\t\t\t\tif (this.indexedVariables > ExpressionContainer.CHUNK_SIZE) {\n",
"\t\t\t\t\t\t// There are a lot of children, create fake intermediate values that represent chunks #9537\n",
"\t\t\t\t\t\tconst numberOfChunks = this.indexedVariables / ExpressionContainer.CHUNK_SIZE;\n",
"\t\t\t\t\t\tfor (let i = 0; i < numberOfChunks; i++) {\n",
"\t\t\t\t\t\t\tconst chunkSize = (i < numberOfChunks - 1) ? ExpressionContainer.CHUNK_SIZE : this.indexedVariables % ExpressionContainer.CHUNK_SIZE;\n",
"\t\t\t\t\t\t\tconst chunkName = `${i * ExpressionContainer.CHUNK_SIZE}..${i * ExpressionContainer.CHUNK_SIZE + chunkSize - 1}`;\n",
"\t\t\t\t\t\t\tchildrenArray.push(new Variable(this, this.reference, chunkName, '', null, chunkSize, null, true, i));\n",
"\t\t\t\t\t\t}\n",
"\n",
"\t\t\t\t\t\treturn childrenArray;\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debugModel.ts",
"type": "replace",
"edit_start_line_idx": 249
} | /*---------------------------------------------------------------------------------------------
* 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.
{
"AbstractTaskAction.noWorkspace": "Las tareas solo están disponibles en una carpeta del área de trabajo.",
"BuildAction.label": "Ejecutar tarea de compilación",
"CleanAction.label": "Ejecutar tarea de limpieza",
"CloseMessageAction.label": "Cerrar",
"ConfigureTaskRunnerAction.autoDetect": "Error de detección automática del sistema de tareas. Se usa la plantilla predeterminada. Consulte el resultado de la tarea para obtener más detalles",
"ConfigureTaskRunnerAction.autoDetecting": "Detectando tareas automáticamente para {0}",
"ConfigureTaskRunnerAction.failed": "No se puede crear el archivo \"tasks.json\" dentro de la carpeta \".vscode\". Consulte el resultado de la tarea para obtener más detalles.",
"ConfigureTaskRunnerAction.label": "Configurar ejecutor de tareas",
"ConfigureTaskRunnerAction.noWorkspace": "Las tareas solo están disponibles en una carpeta del área de trabajo.",
"ConfigureTaskRunnerAction.quickPick.template": "Seleccionar un ejecutador de tareas",
"JsonSchema.args": "Argumentos adicionales que se pasan al comando.",
"JsonSchema.command": "El comando que se va a ejecutar. Puede ser un programa externo o un comando shell.",
"JsonSchema.echoCommand": "Controla si el comando ejecutado se muestra en la salida. El valor predeterminado es false.",
"JsonSchema.linux": "Configuración de compilación específica de Linux.",
"JsonSchema.mac": "Configuración de compilación específica de Mac.",
"JsonSchema.matchers": "Buscadores de coincidencias de problemas que se van a usar. Puede ser una definición de cadena o de buscador de coincidencias de problemas, o bien una matriz de cadenas y de buscadores de coincidencias de problemas.",
"JsonSchema.options": "Opciones de comando adicionales",
"JsonSchema.options.cwd": "Directorio de trabajo actual del script o el programa ejecutado. Si se omite, se usa la raíz del área de trabajo actual de Code.",
"JsonSchema.options.env": "Entorno del shell o el programa ejecutado. Si se omite, se usa el entorno del proceso primario.",
"JsonSchema.pattern.code": "Índice de grupo de coincidencias del código del problema. Valor predeterminado como no definido.",
"JsonSchema.pattern.column": "Índice de grupo de coincidencias de la columna del problema. Valor predeterminado: 3.",
"JsonSchema.pattern.endColumn": "Índice de grupo de coincidencias de la columna final del problema. Valor predeterminado como no definido.",
"JsonSchema.pattern.endLine": "Índice de grupo de coincidencias de la línea final del problema. Valor predeterminado como no definido.",
"JsonSchema.pattern.file": "Índice de grupo de coincidencias del nombre de archivo. Si se omite, se usa 1.",
"JsonSchema.pattern.line": "Índice de grupo de coincidencias de la línea del problema. Valor predeterminado: 2.",
"JsonSchema.pattern.location": "Índice de grupo de coincidencias de la ubicación del problema. Los patrones de ubicación válidos son: (line), (line,column) y (startLine,startColumn,endLine,endColumn). Si se omite, se asume el uso de \"line\" y \"column\".",
"JsonSchema.pattern.loop": "En un bucle de buscador de coincidencias multilínea, indica si este patrón se ejecuta en un bucle siempre que haya coincidencias. Solo puede especificarse en el último patrón de un patrón multilínea.",
"JsonSchema.pattern.message": "Índice de grupo de coincidencias del mensaje. Si se omite, el valor predeterminado es 4 en caso de definirse la ubicación. De lo contrario, el valor predeterminado es 5.",
"JsonSchema.pattern.regexp": "Expresión regular para encontrar un error, una advertencia o información en la salida.",
"JsonSchema.pattern.severity": "Índice de grupo de coincidencias de la gravedad del problema. Valor predeterminado como no definido.",
"JsonSchema.problemMatcher.applyTo": "Controla si un problema notificado en un documento de texto se aplica solamente a los documentos abiertos, cerrados o a todos los documentos.",
"JsonSchema.problemMatcher.base": "Nombre de un buscador de coincidencias de problemas base que se va a usar.",
"JsonSchema.problemMatcher.fileLocation": "Define cómo deben interpretarse los nombres de archivo notificados en un patrón de problema.",
"JsonSchema.problemMatcher.owner": "Propietario del problema dentro de Code. Se puede omitir si se especifica \"base\". Si se omite y no se especifica \"base\", el valor predeterminado es \"external\".",
"JsonSchema.problemMatcher.pattern": "Patrón de problema o nombre de un patrón de problema predefinido. Se puede omitir si se especifica \"base\".",
"JsonSchema.problemMatcher.severity": "Gravedad predeterminada para los problemas de capturas. Se usa si el patrón no define un grupo de coincidencias para \"severity\".",
"JsonSchema.problemMatcher.watchedBegin": "Expresión regular que señala que una tarea inspeccionada comienza a ejecutarse desencadenada a través de la inspección de archivos.",
"JsonSchema.problemMatcher.watchedEnd": "Expresión regular que señala que una tarea inspeccionada termina de ejecutarse.",
"JsonSchema.problemMatcher.watching.activeOnStart": "Si se establece en true, el monitor está en modo activo cuando la tarea empieza. Esto es equivalente a emitir una línea que coincide con beginPattern",
"JsonSchema.problemMatcher.watching.beginsPattern": "Si se encuentran coincidencias en la salida, se señala el inicio de una tarea de inspección.",
"JsonSchema.problemMatcher.watching.endsPattern": "Si se encuentran coincidencias en la salida, se señala el fin de una tarea de inspección",
"JsonSchema.promptOnClose": "Indica si se pregunta al usuario cuando VS Code se cierra con una tarea en ejecución en segundo plano.",
"JsonSchema.shell": "Especifica si el comando es un comando shell o un programa externo. Si se omite, el valor predeterminado es false.",
"JsonSchema.showOutput": "Controla si la salida de la tarea en ejecución se muestra o no. Si se omite, se usa \"always\".",
"JsonSchema.suppressTaskName": "Controla si el nombre de la tarea se agrega como argumento al comando. El valor predeterminado es false.",
"JsonSchema.taskSelector": "Prefijo para indicar que un argumento es una tarea.",
"JsonSchema.tasks": "Configuraciones de tarea. Suele enriquecerse una tarea ya definida en el ejecutor de tareas externo.",
"JsonSchema.tasks.args": "Argumentos adicionales que se pasan al comando cuando se invoca esta tarea.",
"JsonSchema.tasks.build": "Asigna esta tarea al comando de compilación predeterminado de Code.",
"JsonSchema.tasks.matchers": "Buscadores de coincidencias de problemas que se van a usar. Puede ser una definición de cadena o de buscador de coincidencias de problemas, o bien una matriz de cadenas y de buscadores de coincidencias de problemas.",
"JsonSchema.tasks.showOutput": "Controla si la salida de la tarea en ejecución se muestra o no. Si se omite, se usa el valor definido globalmente.",
"JsonSchema.tasks.suppressTaskName": "Controla si el nombre de la tarea se agrega como argumento al comando. Si se omite, se usa el valor definido globalmente.",
"JsonSchema.tasks.taskName": "Nombre de la tarea",
"JsonSchema.tasks.test": "Asigna esta tarea al comando de prueba predeterminado de Code.",
"JsonSchema.tasks.watching": "Indica si la tarea ejecutada se mantiene activa e inspecciona el sistema de archivos.",
"JsonSchema.version": "Número de versión de la configuración",
"JsonSchema.watching": "Indica si la tarea ejecutada se mantiene activa e inspecciona el sistema de archivos.",
"JsonSchema.watchingPattern.file": "Índice de grupo de coincidencias del nombre de archivo. Se puede omitir.",
"JsonSchema.watchingPattern.regexp": "Expresión regular para detectar el principio o el final de una tarea de inspección.",
"JsonSchema.windows": "Configuración de compilación específica de Windows.",
"RebuildAction.label": "Ejecutar tarea de recompilación",
"RunTaskAction.label": "Ejecutar tarea",
"ShowLogAction.label": "Mostrar registro de tareas",
"TaskSystem.active": "Hay una tarea en ejecución activa en este momento. Finalícela antes de ejecutar otra tarea.",
"TaskSystem.invalidTaskJson": "Error: El contenido del archivo tasks.json tiene errores de sintaxis. Corríjalos antes de ejecutar una tarea.\n",
"TaskSystem.noBuildType": "No se ha configurado un ejecutador de tareas válido. Los ejecutadores de tareas compatibles son \"service\" y \"program\".",
"TaskSystem.noConfiguration": "No se ha configurado un ejecutador de tareas.",
"TaskSystem.runningTask": "Hay una tarea en ejecución. ¿Quiere finalizarla?",
"TaskSystem.terminateTask": "&&Finalizar tarea",
"TaskSystem.unknownError": "Error durante la ejecución de una tarea. Consulte el registro de tareas para obtener más detalles.",
"TerminateAction.failed": "No se pudo finalizar la tarea en ejecución",
"TerminateAction.label": "Finalizar tarea en ejecución",
"TestAction.label": "Ejecutar tarea de prueba",
"manyMarkers": "Más de 99",
"taskCommands": "Ejecutar tarea",
"tasks": "Tareas",
"tasksCategory": "Tareas"
} | i18n/esn/src/vs/workbench/parts/tasks/electron-browser/task.contribution.i18n.json | 0 | https://github.com/microsoft/vscode/commit/3978edfa64c9a7b8a8ba823e3ab30767457dc5c6 | [
0.00017409688734915107,
0.00017150711209978908,
0.00016845153004396707,
0.0001718865823931992,
0.000001580888124408375
] |
{
"id": 2,
"code_window": [
"\t\t\tif (!session || this.reference <= 0) {\n",
"\t\t\t\tthis.children = TPromise.as([]);\n",
"\t\t\t} else {\n",
"\t\t\t\tif (this.childrenCount > ExpressionContainer.CHUNK_SIZE) {\n",
"\t\t\t\t\t// There are a lot of children, create fake intermediate values that represent chunks #9537\n",
"\t\t\t\t\tconst chunks = [];\n",
"\t\t\t\t\tconst numberOfChunks = this.childrenCount / ExpressionContainer.CHUNK_SIZE;\n",
"\t\t\t\t\tfor (let i = 0; i < numberOfChunks; i++) {\n",
"\t\t\t\t\t\tconst chunkSize = (i < numberOfChunks - 1) ? ExpressionContainer.CHUNK_SIZE : this.childrenCount % ExpressionContainer.CHUNK_SIZE;\n",
"\t\t\t\t\t\tconst chunkName = `${i * ExpressionContainer.CHUNK_SIZE}..${i * ExpressionContainer.CHUNK_SIZE + chunkSize - 1}`;\n",
"\t\t\t\t\t\tchunks.push(new Variable(this, this.reference, chunkName, '', chunkSize, null, true, i));\n",
"\t\t\t\t\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [
"\n",
"\t\t\t\t// Check if object has named variables, fetch them independent from indexed variables #9670\n",
"\t\t\t\tthis.children = (!!this.namedVariables ? this.fetchVariables(session, undefined, undefined, 'named') : TPromise.as([])).then(childrenArray => {\n",
"\t\t\t\t\tif (this.indexedVariables > ExpressionContainer.CHUNK_SIZE) {\n",
"\t\t\t\t\t\t// There are a lot of children, create fake intermediate values that represent chunks #9537\n",
"\t\t\t\t\t\tconst numberOfChunks = this.indexedVariables / ExpressionContainer.CHUNK_SIZE;\n",
"\t\t\t\t\t\tfor (let i = 0; i < numberOfChunks; i++) {\n",
"\t\t\t\t\t\t\tconst chunkSize = (i < numberOfChunks - 1) ? ExpressionContainer.CHUNK_SIZE : this.indexedVariables % ExpressionContainer.CHUNK_SIZE;\n",
"\t\t\t\t\t\t\tconst chunkName = `${i * ExpressionContainer.CHUNK_SIZE}..${i * ExpressionContainer.CHUNK_SIZE + chunkSize - 1}`;\n",
"\t\t\t\t\t\t\tchildrenArray.push(new Variable(this, this.reference, chunkName, '', null, chunkSize, null, true, i));\n",
"\t\t\t\t\t\t}\n",
"\n",
"\t\t\t\t\t\treturn childrenArray;\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debugModel.ts",
"type": "replace",
"edit_start_line_idx": 249
} | /*---------------------------------------------------------------------------------------------
* 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 uuid = require('vs/base/common/uuid');
suite('UUID', () => {
test('generation', () => {
var asHex = uuid.v4().asHex();
assert.equal(asHex.length, 36);
assert.equal(asHex[14], '4');
assert(asHex[19] === '8' || asHex[19] === '9' || asHex[19] === 'a' || asHex[19] === 'b');
});
test('parse', () => {
var id = uuid.v4();
var asHext = id.asHex();
var id2 = uuid.parse(asHext);
assert(id.equals(id2));
assert(id2.equals(id));
});
}); | src/vs/base/test/common/uuid.test.ts | 0 | https://github.com/microsoft/vscode/commit/3978edfa64c9a7b8a8ba823e3ab30767457dc5c6 | [
0.0001744541514199227,
0.0001726084592519328,
0.00017105290316976607,
0.00017231833771802485,
0.0000014036268112249672
] |
{
"id": 3,
"code_window": [
"\t\t\t\t\t}\n",
"\t\t\t\t\tthis.children = TPromise.as(chunks);\n",
"\t\t\t\t} else {\n",
"\t\t\t\t\tconst start = this.getChildrenInChunks ? this.chunkIndex * ExpressionContainer.CHUNK_SIZE : undefined;\n"
],
"labels": [
"keep",
"replace",
"replace",
"keep"
],
"after_edit": [
"\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debugModel.ts",
"type": "replace",
"edit_start_line_idx": 258
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { TPromise } from 'vs/base/common/winjs.base';
import nls = require('vs/nls');
import lifecycle = require('vs/base/common/lifecycle');
import Event, { Emitter } from 'vs/base/common/event';
import uuid = require('vs/base/common/uuid');
import objects = require('vs/base/common/objects');
import severity from 'vs/base/common/severity';
import types = require('vs/base/common/types');
import arrays = require('vs/base/common/arrays');
import debug = require('vs/workbench/parts/debug/common/debug');
import { Source } from 'vs/workbench/parts/debug/common/debugSource';
const MAX_REPL_LENGTH = 10000;
const UNKNOWN_SOURCE_LABEL = nls.localize('unknownSource', "Unknown Source");
function massageValue(value: string): string {
return value ? value.replace(/\n/g, '\\n').replace(/\r/g, '\\r').replace(/\t/g, '\\t') : value;
}
export function evaluateExpression(session: debug.IRawDebugSession, stackFrame: debug.IStackFrame, expression: Expression, context: string): TPromise<Expression> {
if (!session) {
expression.value = context === 'repl' ? nls.localize('startDebugFirst', "Please start a debug session to evaluate") : Expression.DEFAULT_VALUE;
expression.available = false;
expression.reference = 0;
return TPromise.as(expression);
}
return session.evaluate({
expression: expression.name,
frameId: stackFrame ? stackFrame.frameId : undefined,
context
}).then(response => {
expression.available = !!(response && response.body);
if (response.body) {
expression.value = response.body.result;
expression.reference = response.body.variablesReference;
expression.childrenCount = response.body.indexedVariables;
expression.type = response.body.type;
}
return expression;
}, err => {
expression.value = err.message;
expression.available = false;
expression.reference = 0;
return expression;
});
}
const notPropertySyntax = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
const arrayElementSyntax = /\[.*\]$/;
export function getFullExpressionName(expression: debug.IExpression, sessionType: string): string {
let names = [expression.name];
if (expression instanceof Variable) {
let v = (<Variable> expression).parent;
while (v instanceof Variable || v instanceof Expression) {
names.push((<Variable> v).name);
v = (<Variable> v).parent;
}
}
names = names.reverse();
let result = null;
names.forEach(name => {
if (!result) {
result = name;
} else if (arrayElementSyntax.test(name) || (sessionType === 'node' && !notPropertySyntax.test(name))) {
// use safe way to access node properties a['property_name']. Also handles array elements.
result = name && name.indexOf('[') === 0 ? `${ result }${ name }` : `${ result }['${ name }']`;
} else {
result = `${ result }.${ name }`;
}
});
return result;
}
export class Thread implements debug.IThread {
private promisedCallStack: TPromise<debug.IStackFrame[]>;
private cachedCallStack: debug.IStackFrame[];
public stoppedDetails: debug.IRawStoppedDetails;
public stopped: boolean;
constructor(public name: string, public threadId: number) {
this.promisedCallStack = undefined;
this.stoppedDetails = undefined;
this.cachedCallStack = undefined;
this.stopped = false;
}
public getId(): string {
return `thread:${ this.name }:${ this.threadId }`;
}
public clearCallStack(): void {
this.promisedCallStack = undefined;
this.cachedCallStack = undefined;
}
public getCachedCallStack(): debug.IStackFrame[] {
return this.cachedCallStack;
}
public getCallStack(debugService: debug.IDebugService, getAdditionalStackFrames = false): TPromise<debug.IStackFrame[]> {
if (!this.stopped) {
return TPromise.as([]);
}
if (!this.promisedCallStack) {
this.promisedCallStack = this.getCallStackImpl(debugService, 0).then(callStack => {
this.cachedCallStack = callStack;
return callStack;
});
} else if (getAdditionalStackFrames) {
this.promisedCallStack = this.promisedCallStack.then(callStackFirstPart => this.getCallStackImpl(debugService, callStackFirstPart.length).then(callStackSecondPart => {
this.cachedCallStack = callStackFirstPart.concat(callStackSecondPart);
return this.cachedCallStack;
}));
}
return this.promisedCallStack;
}
private getCallStackImpl(debugService: debug.IDebugService, startFrame: number): TPromise<debug.IStackFrame[]> {
let session = debugService.getActiveSession();
return session.stackTrace({ threadId: this.threadId, startFrame, levels: 20 }).then(response => {
this.stoppedDetails.totalFrames = response.body.totalFrames;
return response.body.stackFrames.map((rsf, level) => {
if (!rsf) {
return new StackFrame(this.threadId, 0, new Source({ name: UNKNOWN_SOURCE_LABEL }, false), nls.localize('unknownStack', "Unknown stack location"), undefined, undefined);
}
return new StackFrame(this.threadId, rsf.id, rsf.source ? new Source(rsf.source) : new Source({ name: UNKNOWN_SOURCE_LABEL }, false), rsf.name, rsf.line, rsf.column);
});
}, (err: Error) => {
this.stoppedDetails.framesErrorMessage = err.message;
return [];
});
}
}
export class OutputElement implements debug.ITreeElement {
private static ID_COUNTER = 0;
constructor(private id = OutputElement.ID_COUNTER++) {
// noop
}
public getId(): string {
return `outputelement:${ this.id }`;
}
}
export class ValueOutputElement extends OutputElement {
constructor(
public value: string,
public severity: severity,
public category?: string,
public counter: number = 1
) {
super();
}
}
export class KeyValueOutputElement extends OutputElement {
private static MAX_CHILDREN = 1000; // upper bound of children per value
private children: debug.ITreeElement[];
private _valueName: string;
constructor(public key: string, public valueObj: any, public annotation?: string) {
super();
this._valueName = null;
}
public get value(): string {
if (this._valueName === null) {
if (this.valueObj === null) {
this._valueName = 'null';
} else if (Array.isArray(this.valueObj)) {
this._valueName = `Array[${this.valueObj.length}]`;
} else if (types.isObject(this.valueObj)) {
this._valueName = 'Object';
} else if (types.isString(this.valueObj)) {
this._valueName = `"${massageValue(this.valueObj)}"`;
} else {
this._valueName = String(this.valueObj);
}
if (!this._valueName) {
this._valueName = '';
}
}
return this._valueName;
}
public getChildren(): debug.ITreeElement[] {
if (!this.children) {
if (Array.isArray(this.valueObj)) {
this.children = (<any[]>this.valueObj).slice(0, KeyValueOutputElement.MAX_CHILDREN).map((v, index) => new KeyValueOutputElement(String(index), v, null));
} else if (types.isObject(this.valueObj)) {
this.children = Object.getOwnPropertyNames(this.valueObj).slice(0, KeyValueOutputElement.MAX_CHILDREN).map(key => new KeyValueOutputElement(key, this.valueObj[key], null));
} else {
this.children = [];
}
}
return this.children;
}
}
export abstract class ExpressionContainer implements debug.IExpressionContainer {
public static allValues: { [id: string]: string } = {};
// Use chunks to support variable paging #9537
private static CHUNK_SIZE = 100;
public valueChanged: boolean;
private children: TPromise<debug.IExpression[]>;
private _value: string;
constructor(
public reference: number,
private id: string,
private cacheChildren: boolean,
public childrenCount: number,
private chunkIndex = 0
) {
// noop
}
public getChildren(debugService: debug.IDebugService): TPromise<debug.IExpression[]> {
if (!this.cacheChildren || !this.children) {
const session = debugService.getActiveSession();
// only variables with reference > 0 have children.
if (!session || this.reference <= 0) {
this.children = TPromise.as([]);
} else {
if (this.childrenCount > ExpressionContainer.CHUNK_SIZE) {
// There are a lot of children, create fake intermediate values that represent chunks #9537
const chunks = [];
const numberOfChunks = this.childrenCount / ExpressionContainer.CHUNK_SIZE;
for (let i = 0; i < numberOfChunks; i++) {
const chunkSize = (i < numberOfChunks - 1) ? ExpressionContainer.CHUNK_SIZE : this.childrenCount % ExpressionContainer.CHUNK_SIZE;
const chunkName = `${i * ExpressionContainer.CHUNK_SIZE}..${i * ExpressionContainer.CHUNK_SIZE + chunkSize - 1}`;
chunks.push(new Variable(this, this.reference, chunkName, '', chunkSize, null, true, i));
}
this.children = TPromise.as(chunks);
} else {
const start = this.getChildrenInChunks ? this.chunkIndex * ExpressionContainer.CHUNK_SIZE : undefined;
const count = this.getChildrenInChunks ? this.childrenCount : undefined;
this.children = session.variables({
variablesReference: this.reference,
start,
count
}).then(response => {
return arrays.distinct(response.body.variables.filter(v => !!v), v => v.name).map(
v => new Variable(this, v.variablesReference, v.name, v.value, v.indexedVariables, v.type)
);
}, (e: Error) => [new Variable(this, 0, null, e.message, 0, null, false)]);
}
}
}
return this.children;
}
public getId(): string {
return this.id;
}
public get value(): string {
return this._value;
}
// The adapter explicitly sents the children count of an expression only if there are lots of children which should be chunked.
private get getChildrenInChunks(): boolean {
return !!this.childrenCount;
}
public set value(value: string) {
this._value = massageValue(value);
this.valueChanged = ExpressionContainer.allValues[this.getId()] &&
ExpressionContainer.allValues[this.getId()] !== Expression.DEFAULT_VALUE && ExpressionContainer.allValues[this.getId()] !== value;
ExpressionContainer.allValues[this.getId()] = value;
}
}
export class Expression extends ExpressionContainer implements debug.IExpression {
static DEFAULT_VALUE = 'not available';
public available: boolean;
public type: string;
constructor(public name: string, cacheChildren: boolean, id = uuid.generateUuid()) {
super(0, id, cacheChildren, 0);
this.value = Expression.DEFAULT_VALUE;
this.available = false;
}
}
export class Variable extends ExpressionContainer implements debug.IExpression {
// Used to show the error message coming from the adapter when setting the value #7807
public errorMessage: string;
constructor(
public parent: debug.IExpressionContainer,
reference: number,
public name: string,
value: string,
childrenCount: number,
public type: string = null,
public available = true,
chunkIndex = 0
) {
super(reference, `variable:${ parent.getId() }:${ name }`, true, childrenCount, chunkIndex);
this.value = massageValue(value);
}
}
export class Scope extends ExpressionContainer implements debug.IScope {
constructor(
private threadId: number,
public name: string,
reference: number,
public expensive: boolean,
childrenCount: number
) {
super(reference, `scope:${threadId}:${name}:${reference}`, true, childrenCount);
}
}
export class StackFrame implements debug.IStackFrame {
private scopes: TPromise<Scope[]>;
constructor(
public threadId: number,
public frameId: number,
public source: Source,
public name: string,
public lineNumber: number,
public column: number
) {
this.scopes = null;
}
public getId(): string {
return `stackframe:${ this.threadId }:${ this.frameId }`;
}
public getScopes(debugService: debug.IDebugService): TPromise<debug.IScope[]> {
if (!this.scopes) {
this.scopes = debugService.getActiveSession().scopes({ frameId: this.frameId }).then(response => {
return response.body.scopes.map(rs => new Scope(this.threadId, rs.name, rs.variablesReference, rs.expensive, rs.indexedVariables));
}, err => []);
}
return this.scopes;
}
}
export class Breakpoint implements debug.IBreakpoint {
public lineNumber: number;
public verified: boolean;
public idFromAdapter: number;
public message: string;
private id: string;
constructor(
public source: Source,
public desiredLineNumber: number,
public enabled: boolean,
public condition: string
) {
if (enabled === undefined) {
this.enabled = true;
}
this.lineNumber = this.desiredLineNumber;
this.verified = false;
this.id = uuid.generateUuid();
}
public getId(): string {
return this.id;
}
}
export class FunctionBreakpoint implements debug.IFunctionBreakpoint {
private id: string;
public verified: boolean;
public idFromAdapter: number;
constructor(public name: string, public enabled: boolean) {
this.verified = false;
this.id = uuid.generateUuid();
}
public getId(): string {
return this.id;
}
}
export class ExceptionBreakpoint implements debug.IExceptionBreakpoint {
private id: string;
constructor(public filter: string, public label: string, public enabled: boolean) {
this.id = uuid.generateUuid();
}
public getId(): string {
return this.id;
}
}
export class Model implements debug.IModel {
private threads: { [reference: number]: debug.IThread; };
private toDispose: lifecycle.IDisposable[];
private replElements: debug.ITreeElement[];
private _onDidChangeBreakpoints: Emitter<void>;
private _onDidChangeCallStack: Emitter<void>;
private _onDidChangeWatchExpressions: Emitter<debug.IExpression>;
private _onDidChangeREPLElements: Emitter<void>;
constructor(
private breakpoints: debug.IBreakpoint[],
private breakpointsActivated: boolean,
private functionBreakpoints: debug.IFunctionBreakpoint[],
private exceptionBreakpoints: debug.IExceptionBreakpoint[],
private watchExpressions: Expression[]
) {
this.threads = {};
this.replElements = [];
this.toDispose = [];
this._onDidChangeBreakpoints = new Emitter<void>();
this._onDidChangeCallStack = new Emitter<void>();
this._onDidChangeWatchExpressions = new Emitter<debug.IExpression>();
this._onDidChangeREPLElements = new Emitter<void>();
}
public getId(): string {
return 'root';
}
public get onDidChangeBreakpoints(): Event<void> {
return this._onDidChangeBreakpoints.event;
}
public get onDidChangeCallStack(): Event<void> {
return this._onDidChangeCallStack.event;
}
public get onDidChangeWatchExpressions(): Event<debug.IExpression> {
return this._onDidChangeWatchExpressions.event;
}
public get onDidChangeReplElements(): Event<void> {
return this._onDidChangeREPLElements.event;
}
public getThreads(): { [reference: number]: debug.IThread; } {
return this.threads;
}
public clearThreads(removeThreads: boolean, reference: number = undefined): void {
if (reference) {
if (this.threads[reference]) {
this.threads[reference].clearCallStack();
this.threads[reference].stoppedDetails = undefined;
this.threads[reference].stopped = false;
if (removeThreads) {
delete this.threads[reference];
}
}
} else {
Object.keys(this.threads).forEach(ref => {
this.threads[ref].clearCallStack();
this.threads[ref].stoppedDetails = undefined;
this.threads[ref].stopped = false;
});
if (removeThreads) {
this.threads = {};
ExpressionContainer.allValues = {};
}
}
this._onDidChangeCallStack.fire();
}
public getBreakpoints(): debug.IBreakpoint[] {
return this.breakpoints;
}
public getFunctionBreakpoints(): debug.IFunctionBreakpoint[] {
return this.functionBreakpoints;
}
public getExceptionBreakpoints(): debug.IExceptionBreakpoint[] {
return this.exceptionBreakpoints;
}
public setExceptionBreakpoints(data: DebugProtocol.ExceptionBreakpointsFilter[]): void {
if (data) {
this.exceptionBreakpoints = data.map(d => {
const ebp = this.exceptionBreakpoints.filter(ebp => ebp.filter === d.filter).pop();
return new ExceptionBreakpoint(d.filter, d.label, ebp ? ebp.enabled : d.default);
});
}
}
public areBreakpointsActivated(): boolean {
return this.breakpointsActivated;
}
public setBreakpointsActivated(activated: boolean): void {
this.breakpointsActivated = activated;
this._onDidChangeBreakpoints.fire();
}
public addBreakpoints(rawData: debug.IRawBreakpoint[]): void {
this.breakpoints = this.breakpoints.concat(rawData.map(rawBp =>
new Breakpoint(new Source(Source.toRawSource(rawBp.uri, this)), rawBp.lineNumber, rawBp.enabled, rawBp.condition)));
this.breakpointsActivated = true;
this._onDidChangeBreakpoints.fire();
}
public removeBreakpoints(toRemove: debug.IBreakpoint[]): void {
this.breakpoints = this.breakpoints.filter(bp => !toRemove.some(toRemove => toRemove.getId() === bp.getId()));
this._onDidChangeBreakpoints.fire();
}
public updateBreakpoints(data: { [id: string]: DebugProtocol.Breakpoint }): void {
this.breakpoints.forEach(bp => {
const bpData = data[bp.getId()];
if (bpData) {
bp.lineNumber = bpData.line ? bpData.line : bp.lineNumber;
bp.verified = bpData.verified;
bp.idFromAdapter = bpData.id;
bp.message = bpData.message;
}
});
this._onDidChangeBreakpoints.fire();
}
public setEnablement(element: debug.IEnablement, enable: boolean): void {
element.enabled = enable;
if (element instanceof Breakpoint && !element.enabled) {
var breakpoint = <Breakpoint> element;
breakpoint.lineNumber = breakpoint.desiredLineNumber;
breakpoint.verified = false;
}
this._onDidChangeBreakpoints.fire();
}
public enableOrDisableAllBreakpoints(enable: boolean): void {
this.breakpoints.forEach(bp => {
bp.enabled = enable;
if (!enable) {
bp.lineNumber = bp.desiredLineNumber;
bp.verified = false;
}
});
this.exceptionBreakpoints.forEach(ebp => ebp.enabled = enable);
this.functionBreakpoints.forEach(fbp => fbp.enabled = enable);
this._onDidChangeBreakpoints.fire();
}
public addFunctionBreakpoint(functionName: string): void {
this.functionBreakpoints.push(new FunctionBreakpoint(functionName, true));
this._onDidChangeBreakpoints.fire();
}
public updateFunctionBreakpoints(data: { [id: string]: { name?: string, verified?: boolean; id?: number } }): void {
this.functionBreakpoints.forEach(fbp => {
const fbpData = data[fbp.getId()];
if (fbpData) {
fbp.name = fbpData.name || fbp.name;
fbp.verified = fbpData.verified;
fbp.idFromAdapter = fbpData.id;
}
});
this._onDidChangeBreakpoints.fire();
}
public removeFunctionBreakpoints(id?: string): void {
this.functionBreakpoints = id ? this.functionBreakpoints.filter(fbp => fbp.getId() !== id) : [];
this._onDidChangeBreakpoints.fire();
}
public getReplElements(): debug.ITreeElement[] {
return this.replElements;
}
public addReplExpression(session: debug.IRawDebugSession, stackFrame: debug.IStackFrame, name: string): TPromise<void> {
const expression = new Expression(name, true);
this.addReplElements([expression]);
return evaluateExpression(session, stackFrame, expression, 'repl')
.then(() => this._onDidChangeREPLElements.fire());
}
public logToRepl(value: string | { [key: string]: any }, severity?: severity): void {
let elements:OutputElement[] = [];
let previousOutput = this.replElements.length && (<ValueOutputElement>this.replElements[this.replElements.length - 1]);
// string message
if (typeof value === 'string') {
if (value && value.trim() && previousOutput && previousOutput.value === value && previousOutput.severity === severity) {
previousOutput.counter++; // we got the same output (but not an empty string when trimmed) so we just increment the counter
} else {
let lines = value.trim().split('\n');
lines.forEach((line, index) => {
elements.push(new ValueOutputElement(line, severity));
});
}
}
// key-value output
else {
elements.push(new KeyValueOutputElement((<any>value).prototype, value, nls.localize('snapshotObj', "Only primitive values are shown for this object.")));
}
if (elements.length) {
this.addReplElements(elements);
}
this._onDidChangeREPLElements.fire();
}
public appendReplOutput(value: string, severity?: severity): void {
const elements: OutputElement[] = [];
let previousOutput = this.replElements.length && (<ValueOutputElement>this.replElements[this.replElements.length - 1]);
let lines = value.split('\n');
let groupTogether = !!previousOutput && (previousOutput.category === 'output' && severity === previousOutput.severity);
if (groupTogether) {
// append to previous line if same group
previousOutput.value += lines.shift();
} else if (previousOutput && previousOutput.value === '') {
// remove potential empty lines between different output types
this.replElements.pop();
}
// fill in lines as output value elements
lines.forEach((line, index) => {
elements.push(new ValueOutputElement(line, severity, 'output'));
});
this.addReplElements(elements);
this._onDidChangeREPLElements.fire();
}
private addReplElements(newElements: debug.ITreeElement[]): void {
this.replElements.push(...newElements);
if (this.replElements.length > MAX_REPL_LENGTH) {
this.replElements.splice(0, this.replElements.length - MAX_REPL_LENGTH);
}
}
public removeReplExpressions(): void {
if (this.replElements.length > 0) {
this.replElements = [];
this._onDidChangeREPLElements.fire();
}
}
public getWatchExpressions(): Expression[] {
return this.watchExpressions;
}
public addWatchExpression(session: debug.IRawDebugSession, stackFrame: debug.IStackFrame, name: string): TPromise<void> {
const we = new Expression(name, false);
this.watchExpressions.push(we);
if (!name) {
this._onDidChangeWatchExpressions.fire(we);
return TPromise.as(null);
}
return this.evaluateWatchExpressions(session, stackFrame, we.getId());
}
public renameWatchExpression(session: debug.IRawDebugSession, stackFrame: debug.IStackFrame, id: string, newName: string): TPromise<void> {
const filtered = this.watchExpressions.filter(we => we.getId() === id);
if (filtered.length === 1) {
filtered[0].name = newName;
return evaluateExpression(session, stackFrame, filtered[0], 'watch').then(() => {
this._onDidChangeWatchExpressions.fire(filtered[0]);
});
}
return TPromise.as(null);
}
public evaluateWatchExpressions(session: debug.IRawDebugSession, stackFrame: debug.IStackFrame, id: string = null): TPromise<void> {
if (id) {
const filtered = this.watchExpressions.filter(we => we.getId() === id);
if (filtered.length !== 1) {
return TPromise.as(null);
}
return evaluateExpression(session, stackFrame, filtered[0], 'watch').then(() => {
this._onDidChangeWatchExpressions.fire(filtered[0]);
});
}
return TPromise.join(this.watchExpressions.map(we => evaluateExpression(session, stackFrame, we, 'watch'))).then(() => {
this._onDidChangeWatchExpressions.fire();
});
}
public clearWatchExpressionValues(): void {
this.watchExpressions.forEach(we => {
we.value = Expression.DEFAULT_VALUE;
we.available = false;
we.reference = 0;
});
this._onDidChangeWatchExpressions.fire();
}
public removeWatchExpressions(id: string = null): void {
this.watchExpressions = id ? this.watchExpressions.filter(we => we.getId() !== id) : [];
this._onDidChangeWatchExpressions.fire();
}
public sourceIsUnavailable(source: Source): void {
Object.keys(this.threads).forEach(key => {
if (this.threads[key].getCachedCallStack()) {
this.threads[key].getCachedCallStack().forEach(stackFrame => {
if (stackFrame.source.uri.toString() === source.uri.toString()) {
stackFrame.source.available = false;
}
});
}
});
this._onDidChangeCallStack.fire();
}
public rawUpdate(data: debug.IRawModelUpdate): void {
if (data.thread && !this.threads[data.threadId]) {
// A new thread came in, initialize it.
this.threads[data.threadId] = new Thread(data.thread.name, data.thread.id);
}
if (data.stoppedDetails) {
// Set the availability of the threads' callstacks depending on
// whether the thread is stopped or not
if (data.allThreadsStopped) {
Object.keys(this.threads).forEach(ref => {
// Only update the details if all the threads are stopped
// because we don't want to overwrite the details of other
// threads that have stopped for a different reason
this.threads[ref].stoppedDetails = objects.clone(data.stoppedDetails);
this.threads[ref].stopped = true;
this.threads[ref].clearCallStack();
});
} else {
// One thread is stopped, only update that thread.
this.threads[data.threadId].stoppedDetails = data.stoppedDetails;
this.threads[data.threadId].clearCallStack();
this.threads[data.threadId].stopped = true;
}
}
this._onDidChangeCallStack.fire();
}
public dispose(): void {
this.threads = null;
this.breakpoints = null;
this.exceptionBreakpoints = null;
this.functionBreakpoints = null;
this.watchExpressions = null;
this.replElements = null;
this.toDispose = lifecycle.dispose(this.toDispose);
}
}
| src/vs/workbench/parts/debug/common/debugModel.ts | 1 | https://github.com/microsoft/vscode/commit/3978edfa64c9a7b8a8ba823e3ab30767457dc5c6 | [
0.9971264004707336,
0.024554291740059853,
0.0001619415415916592,
0.00017157677211798728,
0.15140709280967712
] |
{
"id": 3,
"code_window": [
"\t\t\t\t\t}\n",
"\t\t\t\t\tthis.children = TPromise.as(chunks);\n",
"\t\t\t\t} else {\n",
"\t\t\t\t\tconst start = this.getChildrenInChunks ? this.chunkIndex * ExpressionContainer.CHUNK_SIZE : undefined;\n"
],
"labels": [
"keep",
"replace",
"replace",
"keep"
],
"after_edit": [
"\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debugModel.ts",
"type": "replace",
"edit_start_line_idx": 258
} | /*---------------------------------------------------------------------------------------------
* 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.
{
"downloadNow": "Scarica ora",
"later": "In seguito",
"noUpdatesAvailable": "Al momento non sono disponibili aggiornamenti.",
"releaseNotes": "Note sulla versione",
"thereIsUpdateAvailable": "È disponibile un aggiornamento.",
"updateAvailable": "{0} verrà aggiornato dopo il riavvio.",
"updateNow": "Aggiorna adesso"
} | i18n/ita/src/vs/workbench/electron-browser/update.i18n.json | 0 | https://github.com/microsoft/vscode/commit/3978edfa64c9a7b8a8ba823e3ab30767457dc5c6 | [
0.00017586760804988444,
0.00017499236855655909,
0.00017411712906323373,
0.00017499236855655909,
8.752394933253527e-7
] |
{
"id": 3,
"code_window": [
"\t\t\t\t\t}\n",
"\t\t\t\t\tthis.children = TPromise.as(chunks);\n",
"\t\t\t\t} else {\n",
"\t\t\t\t\tconst start = this.getChildrenInChunks ? this.chunkIndex * ExpressionContainer.CHUNK_SIZE : undefined;\n"
],
"labels": [
"keep",
"replace",
"replace",
"keep"
],
"after_edit": [
"\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debugModel.ts",
"type": "replace",
"edit_start_line_idx": 258
} | /*---------------------------------------------------------------------------------------------
* 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.
{
"iframeEditor": "Visionneuse IFrame"
} | i18n/fra/src/vs/workbench/browser/parts/editor/iframeEditor.i18n.json | 0 | https://github.com/microsoft/vscode/commit/3978edfa64c9a7b8a8ba823e3ab30767457dc5c6 | [
0.00017827724514063448,
0.00017827724514063448,
0.00017827724514063448,
0.00017827724514063448,
0
] |
{
"id": 3,
"code_window": [
"\t\t\t\t\t}\n",
"\t\t\t\t\tthis.children = TPromise.as(chunks);\n",
"\t\t\t\t} else {\n",
"\t\t\t\t\tconst start = this.getChildrenInChunks ? this.chunkIndex * ExpressionContainer.CHUNK_SIZE : undefined;\n"
],
"labels": [
"keep",
"replace",
"replace",
"keep"
],
"after_edit": [
"\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debugModel.ts",
"type": "replace",
"edit_start_line_idx": 258
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Do not edit this file. It is machine generated.
{
"status.400": "잘못된 요청. 잘못된 구문으로 인해 요청을 수행할 수 없습니다.",
"status.401": "권한이 없음. 서버에서 응답을 거부합니다.",
"status.403": "금지됨. 서버에서 응답을 거부합니다.",
"status.404": "찾을 수 없음. 요청된 위치를 찾을 수 없습니다.",
"status.405": "메서드가 허용되지 않음. 요청 메서드를 사용하여 생성된 요청은 해당 위치에서 지원되지 않습니다.",
"status.406": "허용되지 않음. 서버는 클라이언트에서 허용하지 않는 응답만 생성할 수 있습니다.",
"status.407": "프록시 인증 필요. 클라이언트에서 먼저 프록시에 자체적으로 인증해야 합니다.",
"status.408": "요청 시간 초과. 서버에서 요청을 기다리는 동안 시간이 초과되었습니다.",
"status.409": "충돌이 발생했습니다. 요청에 충돌이 발생하여 요청을 완료할 수 없습니다.",
"status.410": "없음. 요청된 페이지를 더 이상 사용할 수 없습니다.",
"status.411": "길이 필요. \"Content-Length\"가 정의되지 않았습니다.",
"status.412": "사전 조건 실패. 요청에 지정된 사전 조건이 서버에서 false로 평가되었습니다.",
"status.413": "요청 엔터티가 너무 큼. 요청 엔터티가 너무 크므로 서버에서 요청을 수락하지 않습니다.",
"status.414": "요청 URI가 너무 깁니다. URL이 너무 길어 서버에서 요청을 수락하지 않습니다.",
"status.415": "지원되지 않는 미디어 유형. 미디어 유형이 지원되지 않으므로 서버에서 요청을 수락하지 않습니다.",
"status.416": "HTTP 상태 코드 {0}",
"status.500": "내부 서버 오류.",
"status.501": "구현되지 않음. 서버가 요청 메서드를 인식하지 않거나 요청을 수행할 수 있는 기능이 없습니다.",
"status.503": "서비스를 사용할 수 없음. 서버를 현재 사용할 수 없습니다(오버로드 또는 다운됨)."
} | i18n/kor/extensions/json/server/out/utils/httpRequest.i18n.json | 0 | https://github.com/microsoft/vscode/commit/3978edfa64c9a7b8a8ba823e3ab30767457dc5c6 | [
0.0004803588381037116,
0.0002967572072520852,
0.00016839371528476477,
0.00024151908291969448,
0.00013321411097422242
] |
{
"id": 4,
"code_window": [
"\t\t\t\t\tconst start = this.getChildrenInChunks ? this.chunkIndex * ExpressionContainer.CHUNK_SIZE : undefined;\n",
"\t\t\t\t\tconst count = this.getChildrenInChunks ? this.childrenCount : undefined;\n",
"\t\t\t\t\tthis.children = session.variables({\n",
"\t\t\t\t\t\tvariablesReference: this.reference,\n",
"\t\t\t\t\t\tstart,\n",
"\t\t\t\t\t\tcount\n",
"\t\t\t\t\t}).then(response => {\n",
"\t\t\t\t\t\treturn arrays.distinct(response.body.variables.filter(v => !!v), v => v.name).map(\n",
"\t\t\t\t\t\t\tv => new Variable(this, v.variablesReference, v.name, v.value, v.indexedVariables, v.type)\n",
"\t\t\t\t\t\t);\n",
"\t\t\t\t\t}, (e: Error) => [new Variable(this, 0, null, e.message, 0, null, false)]);\n",
"\t\t\t\t}\n",
"\t\t\t}\n",
"\t\t}\n",
"\n"
],
"labels": [
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\t\tconst count = this.getChildrenInChunks ? this.indexedVariables : undefined;\n",
"\t\t\t\t\treturn this.fetchVariables(session, start, count, 'indexed').then(variables => childrenArray.concat(variables));\n",
"\t\t\t\t});\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debugModel.ts",
"type": "replace",
"edit_start_line_idx": 261
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { TPromise } from 'vs/base/common/winjs.base';
import nls = require('vs/nls');
import lifecycle = require('vs/base/common/lifecycle');
import Event, { Emitter } from 'vs/base/common/event';
import uuid = require('vs/base/common/uuid');
import objects = require('vs/base/common/objects');
import severity from 'vs/base/common/severity';
import types = require('vs/base/common/types');
import arrays = require('vs/base/common/arrays');
import debug = require('vs/workbench/parts/debug/common/debug');
import { Source } from 'vs/workbench/parts/debug/common/debugSource';
const MAX_REPL_LENGTH = 10000;
const UNKNOWN_SOURCE_LABEL = nls.localize('unknownSource', "Unknown Source");
function massageValue(value: string): string {
return value ? value.replace(/\n/g, '\\n').replace(/\r/g, '\\r').replace(/\t/g, '\\t') : value;
}
export function evaluateExpression(session: debug.IRawDebugSession, stackFrame: debug.IStackFrame, expression: Expression, context: string): TPromise<Expression> {
if (!session) {
expression.value = context === 'repl' ? nls.localize('startDebugFirst', "Please start a debug session to evaluate") : Expression.DEFAULT_VALUE;
expression.available = false;
expression.reference = 0;
return TPromise.as(expression);
}
return session.evaluate({
expression: expression.name,
frameId: stackFrame ? stackFrame.frameId : undefined,
context
}).then(response => {
expression.available = !!(response && response.body);
if (response.body) {
expression.value = response.body.result;
expression.reference = response.body.variablesReference;
expression.childrenCount = response.body.indexedVariables;
expression.type = response.body.type;
}
return expression;
}, err => {
expression.value = err.message;
expression.available = false;
expression.reference = 0;
return expression;
});
}
const notPropertySyntax = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
const arrayElementSyntax = /\[.*\]$/;
export function getFullExpressionName(expression: debug.IExpression, sessionType: string): string {
let names = [expression.name];
if (expression instanceof Variable) {
let v = (<Variable> expression).parent;
while (v instanceof Variable || v instanceof Expression) {
names.push((<Variable> v).name);
v = (<Variable> v).parent;
}
}
names = names.reverse();
let result = null;
names.forEach(name => {
if (!result) {
result = name;
} else if (arrayElementSyntax.test(name) || (sessionType === 'node' && !notPropertySyntax.test(name))) {
// use safe way to access node properties a['property_name']. Also handles array elements.
result = name && name.indexOf('[') === 0 ? `${ result }${ name }` : `${ result }['${ name }']`;
} else {
result = `${ result }.${ name }`;
}
});
return result;
}
export class Thread implements debug.IThread {
private promisedCallStack: TPromise<debug.IStackFrame[]>;
private cachedCallStack: debug.IStackFrame[];
public stoppedDetails: debug.IRawStoppedDetails;
public stopped: boolean;
constructor(public name: string, public threadId: number) {
this.promisedCallStack = undefined;
this.stoppedDetails = undefined;
this.cachedCallStack = undefined;
this.stopped = false;
}
public getId(): string {
return `thread:${ this.name }:${ this.threadId }`;
}
public clearCallStack(): void {
this.promisedCallStack = undefined;
this.cachedCallStack = undefined;
}
public getCachedCallStack(): debug.IStackFrame[] {
return this.cachedCallStack;
}
public getCallStack(debugService: debug.IDebugService, getAdditionalStackFrames = false): TPromise<debug.IStackFrame[]> {
if (!this.stopped) {
return TPromise.as([]);
}
if (!this.promisedCallStack) {
this.promisedCallStack = this.getCallStackImpl(debugService, 0).then(callStack => {
this.cachedCallStack = callStack;
return callStack;
});
} else if (getAdditionalStackFrames) {
this.promisedCallStack = this.promisedCallStack.then(callStackFirstPart => this.getCallStackImpl(debugService, callStackFirstPart.length).then(callStackSecondPart => {
this.cachedCallStack = callStackFirstPart.concat(callStackSecondPart);
return this.cachedCallStack;
}));
}
return this.promisedCallStack;
}
private getCallStackImpl(debugService: debug.IDebugService, startFrame: number): TPromise<debug.IStackFrame[]> {
let session = debugService.getActiveSession();
return session.stackTrace({ threadId: this.threadId, startFrame, levels: 20 }).then(response => {
this.stoppedDetails.totalFrames = response.body.totalFrames;
return response.body.stackFrames.map((rsf, level) => {
if (!rsf) {
return new StackFrame(this.threadId, 0, new Source({ name: UNKNOWN_SOURCE_LABEL }, false), nls.localize('unknownStack', "Unknown stack location"), undefined, undefined);
}
return new StackFrame(this.threadId, rsf.id, rsf.source ? new Source(rsf.source) : new Source({ name: UNKNOWN_SOURCE_LABEL }, false), rsf.name, rsf.line, rsf.column);
});
}, (err: Error) => {
this.stoppedDetails.framesErrorMessage = err.message;
return [];
});
}
}
export class OutputElement implements debug.ITreeElement {
private static ID_COUNTER = 0;
constructor(private id = OutputElement.ID_COUNTER++) {
// noop
}
public getId(): string {
return `outputelement:${ this.id }`;
}
}
export class ValueOutputElement extends OutputElement {
constructor(
public value: string,
public severity: severity,
public category?: string,
public counter: number = 1
) {
super();
}
}
export class KeyValueOutputElement extends OutputElement {
private static MAX_CHILDREN = 1000; // upper bound of children per value
private children: debug.ITreeElement[];
private _valueName: string;
constructor(public key: string, public valueObj: any, public annotation?: string) {
super();
this._valueName = null;
}
public get value(): string {
if (this._valueName === null) {
if (this.valueObj === null) {
this._valueName = 'null';
} else if (Array.isArray(this.valueObj)) {
this._valueName = `Array[${this.valueObj.length}]`;
} else if (types.isObject(this.valueObj)) {
this._valueName = 'Object';
} else if (types.isString(this.valueObj)) {
this._valueName = `"${massageValue(this.valueObj)}"`;
} else {
this._valueName = String(this.valueObj);
}
if (!this._valueName) {
this._valueName = '';
}
}
return this._valueName;
}
public getChildren(): debug.ITreeElement[] {
if (!this.children) {
if (Array.isArray(this.valueObj)) {
this.children = (<any[]>this.valueObj).slice(0, KeyValueOutputElement.MAX_CHILDREN).map((v, index) => new KeyValueOutputElement(String(index), v, null));
} else if (types.isObject(this.valueObj)) {
this.children = Object.getOwnPropertyNames(this.valueObj).slice(0, KeyValueOutputElement.MAX_CHILDREN).map(key => new KeyValueOutputElement(key, this.valueObj[key], null));
} else {
this.children = [];
}
}
return this.children;
}
}
export abstract class ExpressionContainer implements debug.IExpressionContainer {
public static allValues: { [id: string]: string } = {};
// Use chunks to support variable paging #9537
private static CHUNK_SIZE = 100;
public valueChanged: boolean;
private children: TPromise<debug.IExpression[]>;
private _value: string;
constructor(
public reference: number,
private id: string,
private cacheChildren: boolean,
public childrenCount: number,
private chunkIndex = 0
) {
// noop
}
public getChildren(debugService: debug.IDebugService): TPromise<debug.IExpression[]> {
if (!this.cacheChildren || !this.children) {
const session = debugService.getActiveSession();
// only variables with reference > 0 have children.
if (!session || this.reference <= 0) {
this.children = TPromise.as([]);
} else {
if (this.childrenCount > ExpressionContainer.CHUNK_SIZE) {
// There are a lot of children, create fake intermediate values that represent chunks #9537
const chunks = [];
const numberOfChunks = this.childrenCount / ExpressionContainer.CHUNK_SIZE;
for (let i = 0; i < numberOfChunks; i++) {
const chunkSize = (i < numberOfChunks - 1) ? ExpressionContainer.CHUNK_SIZE : this.childrenCount % ExpressionContainer.CHUNK_SIZE;
const chunkName = `${i * ExpressionContainer.CHUNK_SIZE}..${i * ExpressionContainer.CHUNK_SIZE + chunkSize - 1}`;
chunks.push(new Variable(this, this.reference, chunkName, '', chunkSize, null, true, i));
}
this.children = TPromise.as(chunks);
} else {
const start = this.getChildrenInChunks ? this.chunkIndex * ExpressionContainer.CHUNK_SIZE : undefined;
const count = this.getChildrenInChunks ? this.childrenCount : undefined;
this.children = session.variables({
variablesReference: this.reference,
start,
count
}).then(response => {
return arrays.distinct(response.body.variables.filter(v => !!v), v => v.name).map(
v => new Variable(this, v.variablesReference, v.name, v.value, v.indexedVariables, v.type)
);
}, (e: Error) => [new Variable(this, 0, null, e.message, 0, null, false)]);
}
}
}
return this.children;
}
public getId(): string {
return this.id;
}
public get value(): string {
return this._value;
}
// The adapter explicitly sents the children count of an expression only if there are lots of children which should be chunked.
private get getChildrenInChunks(): boolean {
return !!this.childrenCount;
}
public set value(value: string) {
this._value = massageValue(value);
this.valueChanged = ExpressionContainer.allValues[this.getId()] &&
ExpressionContainer.allValues[this.getId()] !== Expression.DEFAULT_VALUE && ExpressionContainer.allValues[this.getId()] !== value;
ExpressionContainer.allValues[this.getId()] = value;
}
}
export class Expression extends ExpressionContainer implements debug.IExpression {
static DEFAULT_VALUE = 'not available';
public available: boolean;
public type: string;
constructor(public name: string, cacheChildren: boolean, id = uuid.generateUuid()) {
super(0, id, cacheChildren, 0);
this.value = Expression.DEFAULT_VALUE;
this.available = false;
}
}
export class Variable extends ExpressionContainer implements debug.IExpression {
// Used to show the error message coming from the adapter when setting the value #7807
public errorMessage: string;
constructor(
public parent: debug.IExpressionContainer,
reference: number,
public name: string,
value: string,
childrenCount: number,
public type: string = null,
public available = true,
chunkIndex = 0
) {
super(reference, `variable:${ parent.getId() }:${ name }`, true, childrenCount, chunkIndex);
this.value = massageValue(value);
}
}
export class Scope extends ExpressionContainer implements debug.IScope {
constructor(
private threadId: number,
public name: string,
reference: number,
public expensive: boolean,
childrenCount: number
) {
super(reference, `scope:${threadId}:${name}:${reference}`, true, childrenCount);
}
}
export class StackFrame implements debug.IStackFrame {
private scopes: TPromise<Scope[]>;
constructor(
public threadId: number,
public frameId: number,
public source: Source,
public name: string,
public lineNumber: number,
public column: number
) {
this.scopes = null;
}
public getId(): string {
return `stackframe:${ this.threadId }:${ this.frameId }`;
}
public getScopes(debugService: debug.IDebugService): TPromise<debug.IScope[]> {
if (!this.scopes) {
this.scopes = debugService.getActiveSession().scopes({ frameId: this.frameId }).then(response => {
return response.body.scopes.map(rs => new Scope(this.threadId, rs.name, rs.variablesReference, rs.expensive, rs.indexedVariables));
}, err => []);
}
return this.scopes;
}
}
export class Breakpoint implements debug.IBreakpoint {
public lineNumber: number;
public verified: boolean;
public idFromAdapter: number;
public message: string;
private id: string;
constructor(
public source: Source,
public desiredLineNumber: number,
public enabled: boolean,
public condition: string
) {
if (enabled === undefined) {
this.enabled = true;
}
this.lineNumber = this.desiredLineNumber;
this.verified = false;
this.id = uuid.generateUuid();
}
public getId(): string {
return this.id;
}
}
export class FunctionBreakpoint implements debug.IFunctionBreakpoint {
private id: string;
public verified: boolean;
public idFromAdapter: number;
constructor(public name: string, public enabled: boolean) {
this.verified = false;
this.id = uuid.generateUuid();
}
public getId(): string {
return this.id;
}
}
export class ExceptionBreakpoint implements debug.IExceptionBreakpoint {
private id: string;
constructor(public filter: string, public label: string, public enabled: boolean) {
this.id = uuid.generateUuid();
}
public getId(): string {
return this.id;
}
}
export class Model implements debug.IModel {
private threads: { [reference: number]: debug.IThread; };
private toDispose: lifecycle.IDisposable[];
private replElements: debug.ITreeElement[];
private _onDidChangeBreakpoints: Emitter<void>;
private _onDidChangeCallStack: Emitter<void>;
private _onDidChangeWatchExpressions: Emitter<debug.IExpression>;
private _onDidChangeREPLElements: Emitter<void>;
constructor(
private breakpoints: debug.IBreakpoint[],
private breakpointsActivated: boolean,
private functionBreakpoints: debug.IFunctionBreakpoint[],
private exceptionBreakpoints: debug.IExceptionBreakpoint[],
private watchExpressions: Expression[]
) {
this.threads = {};
this.replElements = [];
this.toDispose = [];
this._onDidChangeBreakpoints = new Emitter<void>();
this._onDidChangeCallStack = new Emitter<void>();
this._onDidChangeWatchExpressions = new Emitter<debug.IExpression>();
this._onDidChangeREPLElements = new Emitter<void>();
}
public getId(): string {
return 'root';
}
public get onDidChangeBreakpoints(): Event<void> {
return this._onDidChangeBreakpoints.event;
}
public get onDidChangeCallStack(): Event<void> {
return this._onDidChangeCallStack.event;
}
public get onDidChangeWatchExpressions(): Event<debug.IExpression> {
return this._onDidChangeWatchExpressions.event;
}
public get onDidChangeReplElements(): Event<void> {
return this._onDidChangeREPLElements.event;
}
public getThreads(): { [reference: number]: debug.IThread; } {
return this.threads;
}
public clearThreads(removeThreads: boolean, reference: number = undefined): void {
if (reference) {
if (this.threads[reference]) {
this.threads[reference].clearCallStack();
this.threads[reference].stoppedDetails = undefined;
this.threads[reference].stopped = false;
if (removeThreads) {
delete this.threads[reference];
}
}
} else {
Object.keys(this.threads).forEach(ref => {
this.threads[ref].clearCallStack();
this.threads[ref].stoppedDetails = undefined;
this.threads[ref].stopped = false;
});
if (removeThreads) {
this.threads = {};
ExpressionContainer.allValues = {};
}
}
this._onDidChangeCallStack.fire();
}
public getBreakpoints(): debug.IBreakpoint[] {
return this.breakpoints;
}
public getFunctionBreakpoints(): debug.IFunctionBreakpoint[] {
return this.functionBreakpoints;
}
public getExceptionBreakpoints(): debug.IExceptionBreakpoint[] {
return this.exceptionBreakpoints;
}
public setExceptionBreakpoints(data: DebugProtocol.ExceptionBreakpointsFilter[]): void {
if (data) {
this.exceptionBreakpoints = data.map(d => {
const ebp = this.exceptionBreakpoints.filter(ebp => ebp.filter === d.filter).pop();
return new ExceptionBreakpoint(d.filter, d.label, ebp ? ebp.enabled : d.default);
});
}
}
public areBreakpointsActivated(): boolean {
return this.breakpointsActivated;
}
public setBreakpointsActivated(activated: boolean): void {
this.breakpointsActivated = activated;
this._onDidChangeBreakpoints.fire();
}
public addBreakpoints(rawData: debug.IRawBreakpoint[]): void {
this.breakpoints = this.breakpoints.concat(rawData.map(rawBp =>
new Breakpoint(new Source(Source.toRawSource(rawBp.uri, this)), rawBp.lineNumber, rawBp.enabled, rawBp.condition)));
this.breakpointsActivated = true;
this._onDidChangeBreakpoints.fire();
}
public removeBreakpoints(toRemove: debug.IBreakpoint[]): void {
this.breakpoints = this.breakpoints.filter(bp => !toRemove.some(toRemove => toRemove.getId() === bp.getId()));
this._onDidChangeBreakpoints.fire();
}
public updateBreakpoints(data: { [id: string]: DebugProtocol.Breakpoint }): void {
this.breakpoints.forEach(bp => {
const bpData = data[bp.getId()];
if (bpData) {
bp.lineNumber = bpData.line ? bpData.line : bp.lineNumber;
bp.verified = bpData.verified;
bp.idFromAdapter = bpData.id;
bp.message = bpData.message;
}
});
this._onDidChangeBreakpoints.fire();
}
public setEnablement(element: debug.IEnablement, enable: boolean): void {
element.enabled = enable;
if (element instanceof Breakpoint && !element.enabled) {
var breakpoint = <Breakpoint> element;
breakpoint.lineNumber = breakpoint.desiredLineNumber;
breakpoint.verified = false;
}
this._onDidChangeBreakpoints.fire();
}
public enableOrDisableAllBreakpoints(enable: boolean): void {
this.breakpoints.forEach(bp => {
bp.enabled = enable;
if (!enable) {
bp.lineNumber = bp.desiredLineNumber;
bp.verified = false;
}
});
this.exceptionBreakpoints.forEach(ebp => ebp.enabled = enable);
this.functionBreakpoints.forEach(fbp => fbp.enabled = enable);
this._onDidChangeBreakpoints.fire();
}
public addFunctionBreakpoint(functionName: string): void {
this.functionBreakpoints.push(new FunctionBreakpoint(functionName, true));
this._onDidChangeBreakpoints.fire();
}
public updateFunctionBreakpoints(data: { [id: string]: { name?: string, verified?: boolean; id?: number } }): void {
this.functionBreakpoints.forEach(fbp => {
const fbpData = data[fbp.getId()];
if (fbpData) {
fbp.name = fbpData.name || fbp.name;
fbp.verified = fbpData.verified;
fbp.idFromAdapter = fbpData.id;
}
});
this._onDidChangeBreakpoints.fire();
}
public removeFunctionBreakpoints(id?: string): void {
this.functionBreakpoints = id ? this.functionBreakpoints.filter(fbp => fbp.getId() !== id) : [];
this._onDidChangeBreakpoints.fire();
}
public getReplElements(): debug.ITreeElement[] {
return this.replElements;
}
public addReplExpression(session: debug.IRawDebugSession, stackFrame: debug.IStackFrame, name: string): TPromise<void> {
const expression = new Expression(name, true);
this.addReplElements([expression]);
return evaluateExpression(session, stackFrame, expression, 'repl')
.then(() => this._onDidChangeREPLElements.fire());
}
public logToRepl(value: string | { [key: string]: any }, severity?: severity): void {
let elements:OutputElement[] = [];
let previousOutput = this.replElements.length && (<ValueOutputElement>this.replElements[this.replElements.length - 1]);
// string message
if (typeof value === 'string') {
if (value && value.trim() && previousOutput && previousOutput.value === value && previousOutput.severity === severity) {
previousOutput.counter++; // we got the same output (but not an empty string when trimmed) so we just increment the counter
} else {
let lines = value.trim().split('\n');
lines.forEach((line, index) => {
elements.push(new ValueOutputElement(line, severity));
});
}
}
// key-value output
else {
elements.push(new KeyValueOutputElement((<any>value).prototype, value, nls.localize('snapshotObj', "Only primitive values are shown for this object.")));
}
if (elements.length) {
this.addReplElements(elements);
}
this._onDidChangeREPLElements.fire();
}
public appendReplOutput(value: string, severity?: severity): void {
const elements: OutputElement[] = [];
let previousOutput = this.replElements.length && (<ValueOutputElement>this.replElements[this.replElements.length - 1]);
let lines = value.split('\n');
let groupTogether = !!previousOutput && (previousOutput.category === 'output' && severity === previousOutput.severity);
if (groupTogether) {
// append to previous line if same group
previousOutput.value += lines.shift();
} else if (previousOutput && previousOutput.value === '') {
// remove potential empty lines between different output types
this.replElements.pop();
}
// fill in lines as output value elements
lines.forEach((line, index) => {
elements.push(new ValueOutputElement(line, severity, 'output'));
});
this.addReplElements(elements);
this._onDidChangeREPLElements.fire();
}
private addReplElements(newElements: debug.ITreeElement[]): void {
this.replElements.push(...newElements);
if (this.replElements.length > MAX_REPL_LENGTH) {
this.replElements.splice(0, this.replElements.length - MAX_REPL_LENGTH);
}
}
public removeReplExpressions(): void {
if (this.replElements.length > 0) {
this.replElements = [];
this._onDidChangeREPLElements.fire();
}
}
public getWatchExpressions(): Expression[] {
return this.watchExpressions;
}
public addWatchExpression(session: debug.IRawDebugSession, stackFrame: debug.IStackFrame, name: string): TPromise<void> {
const we = new Expression(name, false);
this.watchExpressions.push(we);
if (!name) {
this._onDidChangeWatchExpressions.fire(we);
return TPromise.as(null);
}
return this.evaluateWatchExpressions(session, stackFrame, we.getId());
}
public renameWatchExpression(session: debug.IRawDebugSession, stackFrame: debug.IStackFrame, id: string, newName: string): TPromise<void> {
const filtered = this.watchExpressions.filter(we => we.getId() === id);
if (filtered.length === 1) {
filtered[0].name = newName;
return evaluateExpression(session, stackFrame, filtered[0], 'watch').then(() => {
this._onDidChangeWatchExpressions.fire(filtered[0]);
});
}
return TPromise.as(null);
}
public evaluateWatchExpressions(session: debug.IRawDebugSession, stackFrame: debug.IStackFrame, id: string = null): TPromise<void> {
if (id) {
const filtered = this.watchExpressions.filter(we => we.getId() === id);
if (filtered.length !== 1) {
return TPromise.as(null);
}
return evaluateExpression(session, stackFrame, filtered[0], 'watch').then(() => {
this._onDidChangeWatchExpressions.fire(filtered[0]);
});
}
return TPromise.join(this.watchExpressions.map(we => evaluateExpression(session, stackFrame, we, 'watch'))).then(() => {
this._onDidChangeWatchExpressions.fire();
});
}
public clearWatchExpressionValues(): void {
this.watchExpressions.forEach(we => {
we.value = Expression.DEFAULT_VALUE;
we.available = false;
we.reference = 0;
});
this._onDidChangeWatchExpressions.fire();
}
public removeWatchExpressions(id: string = null): void {
this.watchExpressions = id ? this.watchExpressions.filter(we => we.getId() !== id) : [];
this._onDidChangeWatchExpressions.fire();
}
public sourceIsUnavailable(source: Source): void {
Object.keys(this.threads).forEach(key => {
if (this.threads[key].getCachedCallStack()) {
this.threads[key].getCachedCallStack().forEach(stackFrame => {
if (stackFrame.source.uri.toString() === source.uri.toString()) {
stackFrame.source.available = false;
}
});
}
});
this._onDidChangeCallStack.fire();
}
public rawUpdate(data: debug.IRawModelUpdate): void {
if (data.thread && !this.threads[data.threadId]) {
// A new thread came in, initialize it.
this.threads[data.threadId] = new Thread(data.thread.name, data.thread.id);
}
if (data.stoppedDetails) {
// Set the availability of the threads' callstacks depending on
// whether the thread is stopped or not
if (data.allThreadsStopped) {
Object.keys(this.threads).forEach(ref => {
// Only update the details if all the threads are stopped
// because we don't want to overwrite the details of other
// threads that have stopped for a different reason
this.threads[ref].stoppedDetails = objects.clone(data.stoppedDetails);
this.threads[ref].stopped = true;
this.threads[ref].clearCallStack();
});
} else {
// One thread is stopped, only update that thread.
this.threads[data.threadId].stoppedDetails = data.stoppedDetails;
this.threads[data.threadId].clearCallStack();
this.threads[data.threadId].stopped = true;
}
}
this._onDidChangeCallStack.fire();
}
public dispose(): void {
this.threads = null;
this.breakpoints = null;
this.exceptionBreakpoints = null;
this.functionBreakpoints = null;
this.watchExpressions = null;
this.replElements = null;
this.toDispose = lifecycle.dispose(this.toDispose);
}
}
| src/vs/workbench/parts/debug/common/debugModel.ts | 1 | https://github.com/microsoft/vscode/commit/3978edfa64c9a7b8a8ba823e3ab30767457dc5c6 | [
0.9985253214836121,
0.012930290773510933,
0.0001608285092515871,
0.00017068075248971581,
0.1108984425663948
] |
{
"id": 4,
"code_window": [
"\t\t\t\t\tconst start = this.getChildrenInChunks ? this.chunkIndex * ExpressionContainer.CHUNK_SIZE : undefined;\n",
"\t\t\t\t\tconst count = this.getChildrenInChunks ? this.childrenCount : undefined;\n",
"\t\t\t\t\tthis.children = session.variables({\n",
"\t\t\t\t\t\tvariablesReference: this.reference,\n",
"\t\t\t\t\t\tstart,\n",
"\t\t\t\t\t\tcount\n",
"\t\t\t\t\t}).then(response => {\n",
"\t\t\t\t\t\treturn arrays.distinct(response.body.variables.filter(v => !!v), v => v.name).map(\n",
"\t\t\t\t\t\t\tv => new Variable(this, v.variablesReference, v.name, v.value, v.indexedVariables, v.type)\n",
"\t\t\t\t\t\t);\n",
"\t\t\t\t\t}, (e: Error) => [new Variable(this, 0, null, e.message, 0, null, false)]);\n",
"\t\t\t\t}\n",
"\t\t\t}\n",
"\t\t}\n",
"\n"
],
"labels": [
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\t\tconst count = this.getChildrenInChunks ? this.indexedVariables : undefined;\n",
"\t\t\t\t\treturn this.fetchVariables(session, start, count, 'indexed').then(variables => childrenArray.concat(variables));\n",
"\t\t\t\t});\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debugModel.ts",
"type": "replace",
"edit_start_line_idx": 261
} | <svg width="16" height="16" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><g fill="none" fill-rule="evenodd"><g fill="#c10"><circle cx="8" cy="8" r="5"/></g></g></svg> | src/vs/workbench/parts/debug/browser/media/breakpoint-dark.svg | 0 | https://github.com/microsoft/vscode/commit/3978edfa64c9a7b8a8ba823e3ab30767457dc5c6 | [
0.00017211078375112265,
0.00017211078375112265,
0.00017211078375112265,
0.00017211078375112265,
0
] |
{
"id": 4,
"code_window": [
"\t\t\t\t\tconst start = this.getChildrenInChunks ? this.chunkIndex * ExpressionContainer.CHUNK_SIZE : undefined;\n",
"\t\t\t\t\tconst count = this.getChildrenInChunks ? this.childrenCount : undefined;\n",
"\t\t\t\t\tthis.children = session.variables({\n",
"\t\t\t\t\t\tvariablesReference: this.reference,\n",
"\t\t\t\t\t\tstart,\n",
"\t\t\t\t\t\tcount\n",
"\t\t\t\t\t}).then(response => {\n",
"\t\t\t\t\t\treturn arrays.distinct(response.body.variables.filter(v => !!v), v => v.name).map(\n",
"\t\t\t\t\t\t\tv => new Variable(this, v.variablesReference, v.name, v.value, v.indexedVariables, v.type)\n",
"\t\t\t\t\t\t);\n",
"\t\t\t\t\t}, (e: Error) => [new Variable(this, 0, null, e.message, 0, null, false)]);\n",
"\t\t\t\t}\n",
"\t\t\t}\n",
"\t\t}\n",
"\n"
],
"labels": [
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\t\tconst count = this.getChildrenInChunks ? this.indexedVariables : undefined;\n",
"\t\t\t\t\treturn this.fetchVariables(session, start, count, 'indexed').then(variables => childrenArray.concat(variables));\n",
"\t\t\t\t});\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debugModel.ts",
"type": "replace",
"edit_start_line_idx": 261
} | /*---------------------------------------------------------------------------------------------
* 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.
{
"authFailed": "L'autenticazione non è riuscita su git remote.",
"branch": "Branch",
"branch2": "Branch",
"checkout": "Checkout",
"cleanChangesLabel": "&&Pulisci modifiche",
"commit": "Commit",
"commitAll": "Esegui commit di tutto",
"commitAll2": "Esegui commit di tutto",
"commitStaged": "Esegui commit delle righe preparate",
"commitStaged2": "Esegui commit delle righe preparate",
"confirmPublishMessage": "Pubblicare '{0}' in '{1}'?",
"confirmPublishMessageButton": "&&Pubblica",
"confirmUndo": "Pulire le modifiche in '{0}'?",
"confirmUndoAllMultiple": "In {0} file ci sono modifiche non preparate per il commit.\n\nQuesta azione è irreversibile.",
"confirmUndoAllOne": "In {0} file ci sono modifiche non preparate per il commit.\n\nQuesta azione è irreversibile.",
"confirmUndoMessage": "Pulire tutte le modifiche?",
"currentBranch": "Il ramo corrente '{0}' è aggiornato.",
"currentBranchPlural": "Il ramo corrente '{0}' è {1} commit indietro e {2} commit avanti rispetto a '{3}'.",
"currentBranchPluralSingle": "Il ramo corrente '{0}' è {1} commit indietro e {2} commit avanti rispetto a '{3}'.",
"currentBranchSingle": "Il ramo corrente '{0}' è {1} commit indietro e {2} commit avanti rispetto a '{3}'.",
"currentBranchSinglePlural": "Il ramo corrente '{0}' è {1} commit indietro e {2} commit avanti rispetto a '{3}'.",
"currentlyDetached": "Non è possibile eseguire la sincronizzazione se non si è collegati.",
"dirtyChanges": "Eseguire il commit delle modifiche, annullarle o salvarle con il comando stash prima della sincronizzazione.",
"dirtyTreeCheckout": "Non è possibile eseguire l'estrazione. Eseguire prima il commit del lavoro o prepararlo per il commit.",
"dirtyTreePull": "Non è possibile eseguire il pull. Eseguire prima il commit del lavoro o prepararlo per il commit.",
"init": "Init",
"irreversible": "Questa azione è irreversibile.",
"noUpstream": "Il ramo '{0}' corrente non contiene un ramo a monte configurato.",
"openChange": "Apri modifica",
"openFile": "Apri file",
"publish": "Pubblica",
"publishPickMessage": "Selezionare un repository remoto in cui pubblicare il ramo '{0}':",
"pull": "Pull",
"pullWithRebase": "Esegui pull (Riassegna)",
"push": "Push",
"refresh": "Aggiorna",
"stageAllChanges": "Gestisci tutto temporaneamente",
"stageChanges": "Prepara",
"sync": "Sincronizza",
"synchronizing": "Sincronizzazione...",
"undoAllChanges": "Pulisci tutto",
"undoChanges": "Pulisci",
"undoLastCommit": "Annulla ultimo commit",
"unstage": "Annulla preparazione",
"unstageAllChanges": "Annulla la gestione temporanea di tutto"
} | i18n/ita/src/vs/workbench/parts/git/browser/gitActions.i18n.json | 0 | https://github.com/microsoft/vscode/commit/3978edfa64c9a7b8a8ba823e3ab30767457dc5c6 | [
0.00017727731028571725,
0.00017440046940464526,
0.00017029422451741993,
0.00017422705423086882,
0.0000024386322365899105
] |
{
"id": 4,
"code_window": [
"\t\t\t\t\tconst start = this.getChildrenInChunks ? this.chunkIndex * ExpressionContainer.CHUNK_SIZE : undefined;\n",
"\t\t\t\t\tconst count = this.getChildrenInChunks ? this.childrenCount : undefined;\n",
"\t\t\t\t\tthis.children = session.variables({\n",
"\t\t\t\t\t\tvariablesReference: this.reference,\n",
"\t\t\t\t\t\tstart,\n",
"\t\t\t\t\t\tcount\n",
"\t\t\t\t\t}).then(response => {\n",
"\t\t\t\t\t\treturn arrays.distinct(response.body.variables.filter(v => !!v), v => v.name).map(\n",
"\t\t\t\t\t\t\tv => new Variable(this, v.variablesReference, v.name, v.value, v.indexedVariables, v.type)\n",
"\t\t\t\t\t\t);\n",
"\t\t\t\t\t}, (e: Error) => [new Variable(this, 0, null, e.message, 0, null, false)]);\n",
"\t\t\t\t}\n",
"\t\t\t}\n",
"\t\t}\n",
"\n"
],
"labels": [
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\t\t\tconst count = this.getChildrenInChunks ? this.indexedVariables : undefined;\n",
"\t\t\t\t\treturn this.fetchVariables(session, start, count, 'indexed').then(variables => childrenArray.concat(variables));\n",
"\t\t\t\t});\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debugModel.ts",
"type": "replace",
"edit_start_line_idx": 261
} | /*---------------------------------------------------------------------------------------------
* 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.
{
"": "{0}: {1}",
"QuickCommandsAction.label": "Показать команды редактора",
"actionNotEnabled": "Команда {0} не разрешена в текущем контексте.",
"canNotRun": "Выполнить команду {0} отсюда невозможно.",
"commandLabel": "{0}: {1}",
"entryAriaLabel": "{0}, команды",
"entryAriaLabelWithKey": "{0}, {1}, команды",
"noCommandsMatching": "Нет соответствующих команд",
"showTriggerActions": "Показать все команды"
} | i18n/rus/src/vs/workbench/parts/quickopen/browser/commandsHandler.i18n.json | 0 | https://github.com/microsoft/vscode/commit/3978edfa64c9a7b8a8ba823e3ab30767457dc5c6 | [
0.00017279961321037263,
0.0001727764611132443,
0.00017275330901611596,
0.0001727764611132443,
2.315209712833166e-8
] |
{
"id": 5,
"code_window": [
"\n",
"\tpublic get value(): string {\n",
"\t\treturn this._value;\n",
"\t}\n",
"\n",
"\t// The adapter explicitly sents the children count of an expression only if there are lots of children which should be chunked.\n",
"\tprivate get getChildrenInChunks(): boolean {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep"
],
"after_edit": [
"\tprivate fetchVariables(session: debug.IRawDebugSession, start: number, count: number, filter: 'indexed'|'named'): TPromise<Variable[]> {\n",
"\t\treturn session.variables({\n",
"\t\t\tvariablesReference: this.reference,\n",
"\t\t\tstart,\n",
"\t\t\tcount,\n",
"\t\t\tfilter\n",
"\t\t}).then(response => {\n",
"\t\t\treturn arrays.distinct(response.body.variables.filter(v => !!v), v => v.name).map(\n",
"\t\t\t\tv => new Variable(this, v.variablesReference, v.name, v.value, v.namedVariables, v.indexedVariables, v.type)\n",
"\t\t\t);\n",
"\t\t}, (e: Error) => [new Variable(this, 0, null, e.message, 0, 0, null, false)]);\n",
"\t}\n",
"\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debugModel.ts",
"type": "add",
"edit_start_line_idx": 286
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { TPromise } from 'vs/base/common/winjs.base';
import nls = require('vs/nls');
import lifecycle = require('vs/base/common/lifecycle');
import Event, { Emitter } from 'vs/base/common/event';
import uuid = require('vs/base/common/uuid');
import objects = require('vs/base/common/objects');
import severity from 'vs/base/common/severity';
import types = require('vs/base/common/types');
import arrays = require('vs/base/common/arrays');
import debug = require('vs/workbench/parts/debug/common/debug');
import { Source } from 'vs/workbench/parts/debug/common/debugSource';
const MAX_REPL_LENGTH = 10000;
const UNKNOWN_SOURCE_LABEL = nls.localize('unknownSource', "Unknown Source");
function massageValue(value: string): string {
return value ? value.replace(/\n/g, '\\n').replace(/\r/g, '\\r').replace(/\t/g, '\\t') : value;
}
export function evaluateExpression(session: debug.IRawDebugSession, stackFrame: debug.IStackFrame, expression: Expression, context: string): TPromise<Expression> {
if (!session) {
expression.value = context === 'repl' ? nls.localize('startDebugFirst', "Please start a debug session to evaluate") : Expression.DEFAULT_VALUE;
expression.available = false;
expression.reference = 0;
return TPromise.as(expression);
}
return session.evaluate({
expression: expression.name,
frameId: stackFrame ? stackFrame.frameId : undefined,
context
}).then(response => {
expression.available = !!(response && response.body);
if (response.body) {
expression.value = response.body.result;
expression.reference = response.body.variablesReference;
expression.childrenCount = response.body.indexedVariables;
expression.type = response.body.type;
}
return expression;
}, err => {
expression.value = err.message;
expression.available = false;
expression.reference = 0;
return expression;
});
}
const notPropertySyntax = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
const arrayElementSyntax = /\[.*\]$/;
export function getFullExpressionName(expression: debug.IExpression, sessionType: string): string {
let names = [expression.name];
if (expression instanceof Variable) {
let v = (<Variable> expression).parent;
while (v instanceof Variable || v instanceof Expression) {
names.push((<Variable> v).name);
v = (<Variable> v).parent;
}
}
names = names.reverse();
let result = null;
names.forEach(name => {
if (!result) {
result = name;
} else if (arrayElementSyntax.test(name) || (sessionType === 'node' && !notPropertySyntax.test(name))) {
// use safe way to access node properties a['property_name']. Also handles array elements.
result = name && name.indexOf('[') === 0 ? `${ result }${ name }` : `${ result }['${ name }']`;
} else {
result = `${ result }.${ name }`;
}
});
return result;
}
export class Thread implements debug.IThread {
private promisedCallStack: TPromise<debug.IStackFrame[]>;
private cachedCallStack: debug.IStackFrame[];
public stoppedDetails: debug.IRawStoppedDetails;
public stopped: boolean;
constructor(public name: string, public threadId: number) {
this.promisedCallStack = undefined;
this.stoppedDetails = undefined;
this.cachedCallStack = undefined;
this.stopped = false;
}
public getId(): string {
return `thread:${ this.name }:${ this.threadId }`;
}
public clearCallStack(): void {
this.promisedCallStack = undefined;
this.cachedCallStack = undefined;
}
public getCachedCallStack(): debug.IStackFrame[] {
return this.cachedCallStack;
}
public getCallStack(debugService: debug.IDebugService, getAdditionalStackFrames = false): TPromise<debug.IStackFrame[]> {
if (!this.stopped) {
return TPromise.as([]);
}
if (!this.promisedCallStack) {
this.promisedCallStack = this.getCallStackImpl(debugService, 0).then(callStack => {
this.cachedCallStack = callStack;
return callStack;
});
} else if (getAdditionalStackFrames) {
this.promisedCallStack = this.promisedCallStack.then(callStackFirstPart => this.getCallStackImpl(debugService, callStackFirstPart.length).then(callStackSecondPart => {
this.cachedCallStack = callStackFirstPart.concat(callStackSecondPart);
return this.cachedCallStack;
}));
}
return this.promisedCallStack;
}
private getCallStackImpl(debugService: debug.IDebugService, startFrame: number): TPromise<debug.IStackFrame[]> {
let session = debugService.getActiveSession();
return session.stackTrace({ threadId: this.threadId, startFrame, levels: 20 }).then(response => {
this.stoppedDetails.totalFrames = response.body.totalFrames;
return response.body.stackFrames.map((rsf, level) => {
if (!rsf) {
return new StackFrame(this.threadId, 0, new Source({ name: UNKNOWN_SOURCE_LABEL }, false), nls.localize('unknownStack', "Unknown stack location"), undefined, undefined);
}
return new StackFrame(this.threadId, rsf.id, rsf.source ? new Source(rsf.source) : new Source({ name: UNKNOWN_SOURCE_LABEL }, false), rsf.name, rsf.line, rsf.column);
});
}, (err: Error) => {
this.stoppedDetails.framesErrorMessage = err.message;
return [];
});
}
}
export class OutputElement implements debug.ITreeElement {
private static ID_COUNTER = 0;
constructor(private id = OutputElement.ID_COUNTER++) {
// noop
}
public getId(): string {
return `outputelement:${ this.id }`;
}
}
export class ValueOutputElement extends OutputElement {
constructor(
public value: string,
public severity: severity,
public category?: string,
public counter: number = 1
) {
super();
}
}
export class KeyValueOutputElement extends OutputElement {
private static MAX_CHILDREN = 1000; // upper bound of children per value
private children: debug.ITreeElement[];
private _valueName: string;
constructor(public key: string, public valueObj: any, public annotation?: string) {
super();
this._valueName = null;
}
public get value(): string {
if (this._valueName === null) {
if (this.valueObj === null) {
this._valueName = 'null';
} else if (Array.isArray(this.valueObj)) {
this._valueName = `Array[${this.valueObj.length}]`;
} else if (types.isObject(this.valueObj)) {
this._valueName = 'Object';
} else if (types.isString(this.valueObj)) {
this._valueName = `"${massageValue(this.valueObj)}"`;
} else {
this._valueName = String(this.valueObj);
}
if (!this._valueName) {
this._valueName = '';
}
}
return this._valueName;
}
public getChildren(): debug.ITreeElement[] {
if (!this.children) {
if (Array.isArray(this.valueObj)) {
this.children = (<any[]>this.valueObj).slice(0, KeyValueOutputElement.MAX_CHILDREN).map((v, index) => new KeyValueOutputElement(String(index), v, null));
} else if (types.isObject(this.valueObj)) {
this.children = Object.getOwnPropertyNames(this.valueObj).slice(0, KeyValueOutputElement.MAX_CHILDREN).map(key => new KeyValueOutputElement(key, this.valueObj[key], null));
} else {
this.children = [];
}
}
return this.children;
}
}
export abstract class ExpressionContainer implements debug.IExpressionContainer {
public static allValues: { [id: string]: string } = {};
// Use chunks to support variable paging #9537
private static CHUNK_SIZE = 100;
public valueChanged: boolean;
private children: TPromise<debug.IExpression[]>;
private _value: string;
constructor(
public reference: number,
private id: string,
private cacheChildren: boolean,
public childrenCount: number,
private chunkIndex = 0
) {
// noop
}
public getChildren(debugService: debug.IDebugService): TPromise<debug.IExpression[]> {
if (!this.cacheChildren || !this.children) {
const session = debugService.getActiveSession();
// only variables with reference > 0 have children.
if (!session || this.reference <= 0) {
this.children = TPromise.as([]);
} else {
if (this.childrenCount > ExpressionContainer.CHUNK_SIZE) {
// There are a lot of children, create fake intermediate values that represent chunks #9537
const chunks = [];
const numberOfChunks = this.childrenCount / ExpressionContainer.CHUNK_SIZE;
for (let i = 0; i < numberOfChunks; i++) {
const chunkSize = (i < numberOfChunks - 1) ? ExpressionContainer.CHUNK_SIZE : this.childrenCount % ExpressionContainer.CHUNK_SIZE;
const chunkName = `${i * ExpressionContainer.CHUNK_SIZE}..${i * ExpressionContainer.CHUNK_SIZE + chunkSize - 1}`;
chunks.push(new Variable(this, this.reference, chunkName, '', chunkSize, null, true, i));
}
this.children = TPromise.as(chunks);
} else {
const start = this.getChildrenInChunks ? this.chunkIndex * ExpressionContainer.CHUNK_SIZE : undefined;
const count = this.getChildrenInChunks ? this.childrenCount : undefined;
this.children = session.variables({
variablesReference: this.reference,
start,
count
}).then(response => {
return arrays.distinct(response.body.variables.filter(v => !!v), v => v.name).map(
v => new Variable(this, v.variablesReference, v.name, v.value, v.indexedVariables, v.type)
);
}, (e: Error) => [new Variable(this, 0, null, e.message, 0, null, false)]);
}
}
}
return this.children;
}
public getId(): string {
return this.id;
}
public get value(): string {
return this._value;
}
// The adapter explicitly sents the children count of an expression only if there are lots of children which should be chunked.
private get getChildrenInChunks(): boolean {
return !!this.childrenCount;
}
public set value(value: string) {
this._value = massageValue(value);
this.valueChanged = ExpressionContainer.allValues[this.getId()] &&
ExpressionContainer.allValues[this.getId()] !== Expression.DEFAULT_VALUE && ExpressionContainer.allValues[this.getId()] !== value;
ExpressionContainer.allValues[this.getId()] = value;
}
}
export class Expression extends ExpressionContainer implements debug.IExpression {
static DEFAULT_VALUE = 'not available';
public available: boolean;
public type: string;
constructor(public name: string, cacheChildren: boolean, id = uuid.generateUuid()) {
super(0, id, cacheChildren, 0);
this.value = Expression.DEFAULT_VALUE;
this.available = false;
}
}
export class Variable extends ExpressionContainer implements debug.IExpression {
// Used to show the error message coming from the adapter when setting the value #7807
public errorMessage: string;
constructor(
public parent: debug.IExpressionContainer,
reference: number,
public name: string,
value: string,
childrenCount: number,
public type: string = null,
public available = true,
chunkIndex = 0
) {
super(reference, `variable:${ parent.getId() }:${ name }`, true, childrenCount, chunkIndex);
this.value = massageValue(value);
}
}
export class Scope extends ExpressionContainer implements debug.IScope {
constructor(
private threadId: number,
public name: string,
reference: number,
public expensive: boolean,
childrenCount: number
) {
super(reference, `scope:${threadId}:${name}:${reference}`, true, childrenCount);
}
}
export class StackFrame implements debug.IStackFrame {
private scopes: TPromise<Scope[]>;
constructor(
public threadId: number,
public frameId: number,
public source: Source,
public name: string,
public lineNumber: number,
public column: number
) {
this.scopes = null;
}
public getId(): string {
return `stackframe:${ this.threadId }:${ this.frameId }`;
}
public getScopes(debugService: debug.IDebugService): TPromise<debug.IScope[]> {
if (!this.scopes) {
this.scopes = debugService.getActiveSession().scopes({ frameId: this.frameId }).then(response => {
return response.body.scopes.map(rs => new Scope(this.threadId, rs.name, rs.variablesReference, rs.expensive, rs.indexedVariables));
}, err => []);
}
return this.scopes;
}
}
export class Breakpoint implements debug.IBreakpoint {
public lineNumber: number;
public verified: boolean;
public idFromAdapter: number;
public message: string;
private id: string;
constructor(
public source: Source,
public desiredLineNumber: number,
public enabled: boolean,
public condition: string
) {
if (enabled === undefined) {
this.enabled = true;
}
this.lineNumber = this.desiredLineNumber;
this.verified = false;
this.id = uuid.generateUuid();
}
public getId(): string {
return this.id;
}
}
export class FunctionBreakpoint implements debug.IFunctionBreakpoint {
private id: string;
public verified: boolean;
public idFromAdapter: number;
constructor(public name: string, public enabled: boolean) {
this.verified = false;
this.id = uuid.generateUuid();
}
public getId(): string {
return this.id;
}
}
export class ExceptionBreakpoint implements debug.IExceptionBreakpoint {
private id: string;
constructor(public filter: string, public label: string, public enabled: boolean) {
this.id = uuid.generateUuid();
}
public getId(): string {
return this.id;
}
}
export class Model implements debug.IModel {
private threads: { [reference: number]: debug.IThread; };
private toDispose: lifecycle.IDisposable[];
private replElements: debug.ITreeElement[];
private _onDidChangeBreakpoints: Emitter<void>;
private _onDidChangeCallStack: Emitter<void>;
private _onDidChangeWatchExpressions: Emitter<debug.IExpression>;
private _onDidChangeREPLElements: Emitter<void>;
constructor(
private breakpoints: debug.IBreakpoint[],
private breakpointsActivated: boolean,
private functionBreakpoints: debug.IFunctionBreakpoint[],
private exceptionBreakpoints: debug.IExceptionBreakpoint[],
private watchExpressions: Expression[]
) {
this.threads = {};
this.replElements = [];
this.toDispose = [];
this._onDidChangeBreakpoints = new Emitter<void>();
this._onDidChangeCallStack = new Emitter<void>();
this._onDidChangeWatchExpressions = new Emitter<debug.IExpression>();
this._onDidChangeREPLElements = new Emitter<void>();
}
public getId(): string {
return 'root';
}
public get onDidChangeBreakpoints(): Event<void> {
return this._onDidChangeBreakpoints.event;
}
public get onDidChangeCallStack(): Event<void> {
return this._onDidChangeCallStack.event;
}
public get onDidChangeWatchExpressions(): Event<debug.IExpression> {
return this._onDidChangeWatchExpressions.event;
}
public get onDidChangeReplElements(): Event<void> {
return this._onDidChangeREPLElements.event;
}
public getThreads(): { [reference: number]: debug.IThread; } {
return this.threads;
}
public clearThreads(removeThreads: boolean, reference: number = undefined): void {
if (reference) {
if (this.threads[reference]) {
this.threads[reference].clearCallStack();
this.threads[reference].stoppedDetails = undefined;
this.threads[reference].stopped = false;
if (removeThreads) {
delete this.threads[reference];
}
}
} else {
Object.keys(this.threads).forEach(ref => {
this.threads[ref].clearCallStack();
this.threads[ref].stoppedDetails = undefined;
this.threads[ref].stopped = false;
});
if (removeThreads) {
this.threads = {};
ExpressionContainer.allValues = {};
}
}
this._onDidChangeCallStack.fire();
}
public getBreakpoints(): debug.IBreakpoint[] {
return this.breakpoints;
}
public getFunctionBreakpoints(): debug.IFunctionBreakpoint[] {
return this.functionBreakpoints;
}
public getExceptionBreakpoints(): debug.IExceptionBreakpoint[] {
return this.exceptionBreakpoints;
}
public setExceptionBreakpoints(data: DebugProtocol.ExceptionBreakpointsFilter[]): void {
if (data) {
this.exceptionBreakpoints = data.map(d => {
const ebp = this.exceptionBreakpoints.filter(ebp => ebp.filter === d.filter).pop();
return new ExceptionBreakpoint(d.filter, d.label, ebp ? ebp.enabled : d.default);
});
}
}
public areBreakpointsActivated(): boolean {
return this.breakpointsActivated;
}
public setBreakpointsActivated(activated: boolean): void {
this.breakpointsActivated = activated;
this._onDidChangeBreakpoints.fire();
}
public addBreakpoints(rawData: debug.IRawBreakpoint[]): void {
this.breakpoints = this.breakpoints.concat(rawData.map(rawBp =>
new Breakpoint(new Source(Source.toRawSource(rawBp.uri, this)), rawBp.lineNumber, rawBp.enabled, rawBp.condition)));
this.breakpointsActivated = true;
this._onDidChangeBreakpoints.fire();
}
public removeBreakpoints(toRemove: debug.IBreakpoint[]): void {
this.breakpoints = this.breakpoints.filter(bp => !toRemove.some(toRemove => toRemove.getId() === bp.getId()));
this._onDidChangeBreakpoints.fire();
}
public updateBreakpoints(data: { [id: string]: DebugProtocol.Breakpoint }): void {
this.breakpoints.forEach(bp => {
const bpData = data[bp.getId()];
if (bpData) {
bp.lineNumber = bpData.line ? bpData.line : bp.lineNumber;
bp.verified = bpData.verified;
bp.idFromAdapter = bpData.id;
bp.message = bpData.message;
}
});
this._onDidChangeBreakpoints.fire();
}
public setEnablement(element: debug.IEnablement, enable: boolean): void {
element.enabled = enable;
if (element instanceof Breakpoint && !element.enabled) {
var breakpoint = <Breakpoint> element;
breakpoint.lineNumber = breakpoint.desiredLineNumber;
breakpoint.verified = false;
}
this._onDidChangeBreakpoints.fire();
}
public enableOrDisableAllBreakpoints(enable: boolean): void {
this.breakpoints.forEach(bp => {
bp.enabled = enable;
if (!enable) {
bp.lineNumber = bp.desiredLineNumber;
bp.verified = false;
}
});
this.exceptionBreakpoints.forEach(ebp => ebp.enabled = enable);
this.functionBreakpoints.forEach(fbp => fbp.enabled = enable);
this._onDidChangeBreakpoints.fire();
}
public addFunctionBreakpoint(functionName: string): void {
this.functionBreakpoints.push(new FunctionBreakpoint(functionName, true));
this._onDidChangeBreakpoints.fire();
}
public updateFunctionBreakpoints(data: { [id: string]: { name?: string, verified?: boolean; id?: number } }): void {
this.functionBreakpoints.forEach(fbp => {
const fbpData = data[fbp.getId()];
if (fbpData) {
fbp.name = fbpData.name || fbp.name;
fbp.verified = fbpData.verified;
fbp.idFromAdapter = fbpData.id;
}
});
this._onDidChangeBreakpoints.fire();
}
public removeFunctionBreakpoints(id?: string): void {
this.functionBreakpoints = id ? this.functionBreakpoints.filter(fbp => fbp.getId() !== id) : [];
this._onDidChangeBreakpoints.fire();
}
public getReplElements(): debug.ITreeElement[] {
return this.replElements;
}
public addReplExpression(session: debug.IRawDebugSession, stackFrame: debug.IStackFrame, name: string): TPromise<void> {
const expression = new Expression(name, true);
this.addReplElements([expression]);
return evaluateExpression(session, stackFrame, expression, 'repl')
.then(() => this._onDidChangeREPLElements.fire());
}
public logToRepl(value: string | { [key: string]: any }, severity?: severity): void {
let elements:OutputElement[] = [];
let previousOutput = this.replElements.length && (<ValueOutputElement>this.replElements[this.replElements.length - 1]);
// string message
if (typeof value === 'string') {
if (value && value.trim() && previousOutput && previousOutput.value === value && previousOutput.severity === severity) {
previousOutput.counter++; // we got the same output (but not an empty string when trimmed) so we just increment the counter
} else {
let lines = value.trim().split('\n');
lines.forEach((line, index) => {
elements.push(new ValueOutputElement(line, severity));
});
}
}
// key-value output
else {
elements.push(new KeyValueOutputElement((<any>value).prototype, value, nls.localize('snapshotObj', "Only primitive values are shown for this object.")));
}
if (elements.length) {
this.addReplElements(elements);
}
this._onDidChangeREPLElements.fire();
}
public appendReplOutput(value: string, severity?: severity): void {
const elements: OutputElement[] = [];
let previousOutput = this.replElements.length && (<ValueOutputElement>this.replElements[this.replElements.length - 1]);
let lines = value.split('\n');
let groupTogether = !!previousOutput && (previousOutput.category === 'output' && severity === previousOutput.severity);
if (groupTogether) {
// append to previous line if same group
previousOutput.value += lines.shift();
} else if (previousOutput && previousOutput.value === '') {
// remove potential empty lines between different output types
this.replElements.pop();
}
// fill in lines as output value elements
lines.forEach((line, index) => {
elements.push(new ValueOutputElement(line, severity, 'output'));
});
this.addReplElements(elements);
this._onDidChangeREPLElements.fire();
}
private addReplElements(newElements: debug.ITreeElement[]): void {
this.replElements.push(...newElements);
if (this.replElements.length > MAX_REPL_LENGTH) {
this.replElements.splice(0, this.replElements.length - MAX_REPL_LENGTH);
}
}
public removeReplExpressions(): void {
if (this.replElements.length > 0) {
this.replElements = [];
this._onDidChangeREPLElements.fire();
}
}
public getWatchExpressions(): Expression[] {
return this.watchExpressions;
}
public addWatchExpression(session: debug.IRawDebugSession, stackFrame: debug.IStackFrame, name: string): TPromise<void> {
const we = new Expression(name, false);
this.watchExpressions.push(we);
if (!name) {
this._onDidChangeWatchExpressions.fire(we);
return TPromise.as(null);
}
return this.evaluateWatchExpressions(session, stackFrame, we.getId());
}
public renameWatchExpression(session: debug.IRawDebugSession, stackFrame: debug.IStackFrame, id: string, newName: string): TPromise<void> {
const filtered = this.watchExpressions.filter(we => we.getId() === id);
if (filtered.length === 1) {
filtered[0].name = newName;
return evaluateExpression(session, stackFrame, filtered[0], 'watch').then(() => {
this._onDidChangeWatchExpressions.fire(filtered[0]);
});
}
return TPromise.as(null);
}
public evaluateWatchExpressions(session: debug.IRawDebugSession, stackFrame: debug.IStackFrame, id: string = null): TPromise<void> {
if (id) {
const filtered = this.watchExpressions.filter(we => we.getId() === id);
if (filtered.length !== 1) {
return TPromise.as(null);
}
return evaluateExpression(session, stackFrame, filtered[0], 'watch').then(() => {
this._onDidChangeWatchExpressions.fire(filtered[0]);
});
}
return TPromise.join(this.watchExpressions.map(we => evaluateExpression(session, stackFrame, we, 'watch'))).then(() => {
this._onDidChangeWatchExpressions.fire();
});
}
public clearWatchExpressionValues(): void {
this.watchExpressions.forEach(we => {
we.value = Expression.DEFAULT_VALUE;
we.available = false;
we.reference = 0;
});
this._onDidChangeWatchExpressions.fire();
}
public removeWatchExpressions(id: string = null): void {
this.watchExpressions = id ? this.watchExpressions.filter(we => we.getId() !== id) : [];
this._onDidChangeWatchExpressions.fire();
}
public sourceIsUnavailable(source: Source): void {
Object.keys(this.threads).forEach(key => {
if (this.threads[key].getCachedCallStack()) {
this.threads[key].getCachedCallStack().forEach(stackFrame => {
if (stackFrame.source.uri.toString() === source.uri.toString()) {
stackFrame.source.available = false;
}
});
}
});
this._onDidChangeCallStack.fire();
}
public rawUpdate(data: debug.IRawModelUpdate): void {
if (data.thread && !this.threads[data.threadId]) {
// A new thread came in, initialize it.
this.threads[data.threadId] = new Thread(data.thread.name, data.thread.id);
}
if (data.stoppedDetails) {
// Set the availability of the threads' callstacks depending on
// whether the thread is stopped or not
if (data.allThreadsStopped) {
Object.keys(this.threads).forEach(ref => {
// Only update the details if all the threads are stopped
// because we don't want to overwrite the details of other
// threads that have stopped for a different reason
this.threads[ref].stoppedDetails = objects.clone(data.stoppedDetails);
this.threads[ref].stopped = true;
this.threads[ref].clearCallStack();
});
} else {
// One thread is stopped, only update that thread.
this.threads[data.threadId].stoppedDetails = data.stoppedDetails;
this.threads[data.threadId].clearCallStack();
this.threads[data.threadId].stopped = true;
}
}
this._onDidChangeCallStack.fire();
}
public dispose(): void {
this.threads = null;
this.breakpoints = null;
this.exceptionBreakpoints = null;
this.functionBreakpoints = null;
this.watchExpressions = null;
this.replElements = null;
this.toDispose = lifecycle.dispose(this.toDispose);
}
}
| src/vs/workbench/parts/debug/common/debugModel.ts | 1 | https://github.com/microsoft/vscode/commit/3978edfa64c9a7b8a8ba823e3ab30767457dc5c6 | [
0.9991088509559631,
0.03578139841556549,
0.0001654675870668143,
0.0001742903550621122,
0.1646253615617752
] |
{
"id": 5,
"code_window": [
"\n",
"\tpublic get value(): string {\n",
"\t\treturn this._value;\n",
"\t}\n",
"\n",
"\t// The adapter explicitly sents the children count of an expression only if there are lots of children which should be chunked.\n",
"\tprivate get getChildrenInChunks(): boolean {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep"
],
"after_edit": [
"\tprivate fetchVariables(session: debug.IRawDebugSession, start: number, count: number, filter: 'indexed'|'named'): TPromise<Variable[]> {\n",
"\t\treturn session.variables({\n",
"\t\t\tvariablesReference: this.reference,\n",
"\t\t\tstart,\n",
"\t\t\tcount,\n",
"\t\t\tfilter\n",
"\t\t}).then(response => {\n",
"\t\t\treturn arrays.distinct(response.body.variables.filter(v => !!v), v => v.name).map(\n",
"\t\t\t\tv => new Variable(this, v.variablesReference, v.name, v.value, v.namedVariables, v.indexedVariables, v.type)\n",
"\t\t\t);\n",
"\t\t}, (e: Error) => [new Variable(this, 0, null, e.message, 0, 0, null, false)]);\n",
"\t}\n",
"\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debugModel.ts",
"type": "add",
"edit_start_line_idx": 286
} | /*---------------------------------------------------------------------------------------------
* 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.
{
"resolve.files.N": "Caricamento dei file aggiuntivi in corso..."
} | i18n/ita/src/vs/languages/typescript.workbench/common/projectResolver.i18n.json | 0 | https://github.com/microsoft/vscode/commit/3978edfa64c9a7b8a8ba823e3ab30767457dc5c6 | [
0.00017583122826181352,
0.00017583122826181352,
0.00017583122826181352,
0.00017583122826181352,
0
] |
{
"id": 5,
"code_window": [
"\n",
"\tpublic get value(): string {\n",
"\t\treturn this._value;\n",
"\t}\n",
"\n",
"\t// The adapter explicitly sents the children count of an expression only if there are lots of children which should be chunked.\n",
"\tprivate get getChildrenInChunks(): boolean {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep"
],
"after_edit": [
"\tprivate fetchVariables(session: debug.IRawDebugSession, start: number, count: number, filter: 'indexed'|'named'): TPromise<Variable[]> {\n",
"\t\treturn session.variables({\n",
"\t\t\tvariablesReference: this.reference,\n",
"\t\t\tstart,\n",
"\t\t\tcount,\n",
"\t\t\tfilter\n",
"\t\t}).then(response => {\n",
"\t\t\treturn arrays.distinct(response.body.variables.filter(v => !!v), v => v.name).map(\n",
"\t\t\t\tv => new Variable(this, v.variablesReference, v.name, v.value, v.namedVariables, v.indexedVariables, v.type)\n",
"\t\t\t);\n",
"\t\t}, (e: Error) => [new Variable(this, 0, null, e.message, 0, 0, null, false)]);\n",
"\t}\n",
"\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debugModel.ts",
"type": "add",
"edit_start_line_idx": 286
} | /*---------------------------------------------------------------------------------------------
* 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 Event, {Emitter} from 'vs/base/common/event';
import {IEditorRegistry, Extensions, EditorInput, getUntitledOrFileResource, IEditorStacksModel, IEditorGroup, IEditorIdentifier, IGroupEvent, GroupIdentifier, IStacksModelChangeEvent, IWorkbenchEditorConfiguration, EditorOpenPositioning} from 'vs/workbench/common/editor';
import URI from 'vs/base/common/uri';
import {IStorageService, StorageScope} from 'vs/platform/storage/common/storage';
import {IInstantiationService} from 'vs/platform/instantiation/common/instantiation';
import {IConfigurationService} from 'vs/platform/configuration/common/configuration';
import {ILifecycleService} from 'vs/platform/lifecycle/common/lifecycle';
import {IWorkspaceContextService} from 'vs/workbench/services/workspace/common/contextService';
import {dispose, IDisposable} from 'vs/base/common/lifecycle';
import {Registry} from 'vs/platform/platform';
import {Position, Direction} from 'vs/platform/editor/common/editor';
import {DiffEditorInput} from 'vs/workbench/common/editor/diffEditorInput';
// TODO@Ben currently only files and untitled editors are tracked with their resources in the stacks model
// Once the resource is a base concept of all editor inputs, every resource should be tracked for any editor
export interface GroupEvent extends IGroupEvent {
editor: EditorInput;
}
export interface EditorIdentifier extends IEditorIdentifier {
group: EditorGroup;
editor: EditorInput;
}
export interface IEditorOpenOptions {
pinned?: boolean;
active?: boolean;
index?: number;
}
export interface ISerializedEditorInput {
id: string;
value: string;
}
export interface ISerializedEditorGroup {
label: string;
editors: ISerializedEditorInput[];
mru: number[];
preview: number;
}
export class EditorGroup implements IEditorGroup {
private static IDS = 0;
private _id: GroupIdentifier;
private _label: string;
private editors: EditorInput[];
private mru: EditorInput[];
private mapResourceToEditorCount: { [resource: string]: number };
private preview: EditorInput; // editor in preview state
private active: EditorInput; // editor in active state
private toDispose: IDisposable[];
private editorOpenPositioning: string;
private _onEditorActivated: Emitter<EditorInput>;
private _onEditorOpened: Emitter<EditorInput>;
private _onEditorClosed: Emitter<GroupEvent>;
private _onEditorDisposed: Emitter<EditorInput>;
private _onEditorDirty: Emitter<EditorInput>;
private _onEditorMoved: Emitter<EditorInput>;
private _onEditorPinned: Emitter<EditorInput>;
private _onEditorUnpinned: Emitter<EditorInput>;
private _onEditorStateChanged: Emitter<EditorInput>;
private _onEditorsStructureChanged: Emitter<EditorInput>;
constructor(
arg1: string | ISerializedEditorGroup,
@IInstantiationService private instantiationService: IInstantiationService,
@IConfigurationService private configurationService: IConfigurationService
) {
this._id = EditorGroup.IDS++;
this.editors = [];
this.mru = [];
this.toDispose = [];
this.mapResourceToEditorCount = Object.create(null);
this.onConfigurationUpdated(configurationService.getConfiguration<IWorkbenchEditorConfiguration>());
this._onEditorActivated = new Emitter<EditorInput>();
this._onEditorOpened = new Emitter<EditorInput>();
this._onEditorClosed = new Emitter<GroupEvent>();
this._onEditorDisposed = new Emitter<EditorInput>();
this._onEditorDirty = new Emitter<EditorInput>();
this._onEditorMoved = new Emitter<EditorInput>();
this._onEditorPinned = new Emitter<EditorInput>();
this._onEditorUnpinned = new Emitter<EditorInput>();
this._onEditorStateChanged = new Emitter<EditorInput>();
this._onEditorsStructureChanged = new Emitter<EditorInput>();
this.toDispose.push(this._onEditorActivated, this._onEditorOpened, this._onEditorClosed, this._onEditorDisposed, this._onEditorDirty, this._onEditorMoved, this._onEditorPinned, this._onEditorUnpinned, this._onEditorStateChanged, this._onEditorsStructureChanged);
if (typeof arg1 === 'object') {
this.deserialize(arg1);
} else {
this._label = arg1;
}
this.registerListeners();
}
private registerListeners(): void {
this.toDispose.push(this.configurationService.onDidUpdateConfiguration(e => this.onConfigurationUpdated(e.config)));
}
private onConfigurationUpdated(config: IWorkbenchEditorConfiguration): void {
this.editorOpenPositioning = config.workbench.editor.openPositioning;
}
public get id(): GroupIdentifier {
return this._id;
}
public get label(): string {
return this._label;
}
public set label(label: string) {
this._label = label;
}
public get count(): number {
return this.editors.length;
}
public get onEditorActivated(): Event<EditorInput> {
return this._onEditorActivated.event;
}
public get onEditorOpened(): Event<EditorInput> {
return this._onEditorOpened.event;
}
public get onEditorClosed(): Event<GroupEvent> {
return this._onEditorClosed.event;
}
public get onEditorDisposed(): Event<EditorInput> {
return this._onEditorDisposed.event;
}
public get onEditorDirty(): Event<EditorInput> {
return this._onEditorDirty.event;
}
public get onEditorMoved(): Event<EditorInput> {
return this._onEditorMoved.event;
}
public get onEditorPinned(): Event<EditorInput> {
return this._onEditorPinned.event;
}
public get onEditorUnpinned(): Event<EditorInput> {
return this._onEditorUnpinned.event;
}
public get onEditorStateChanged(): Event<EditorInput> {
return this._onEditorStateChanged.event;
}
public get onEditorsStructureChanged(): Event<EditorInput> {
return this._onEditorsStructureChanged.event;
}
public getEditors(mru?: boolean): EditorInput[] {
return mru ? this.mru.slice(0) : this.editors.slice(0);
}
public getEditor(index: number): EditorInput {
return this.editors[index];
}
public get activeEditor(): EditorInput {
return this.active;
}
public isActive(editor: EditorInput): boolean {
return this.matches(this.active, editor);
}
public get previewEditor(): EditorInput {
return this.preview;
}
public isPreview(editor: EditorInput): boolean {
return this.matches(this.preview, editor);
}
public openEditor(editor: EditorInput, options?: IEditorOpenOptions): void {
const index = this.indexOf(editor);
const makePinned = options && options.pinned;
const makeActive = (options && options.active) || !this.activeEditor || (!makePinned && this.matches(this.preview, this.activeEditor));
// New editor
if (index === -1) {
let targetIndex: number;
const indexOfActive = this.indexOf(this.active);
// Insert into specific position
if (options && typeof options.index === 'number') {
targetIndex = options.index;
}
// Insert to the BEGINNING
else if (this.editorOpenPositioning === EditorOpenPositioning.FIRST) {
targetIndex = 0;
}
// Insert to the END
else if (this.editorOpenPositioning === EditorOpenPositioning.LAST) {
targetIndex = this.editors.length;
}
// Insert to the LEFT of active editor
else if (this.editorOpenPositioning === EditorOpenPositioning.LEFT) {
if (indexOfActive === 0 || !this.editors.length) {
targetIndex = 0; // to the left becoming first editor in list
} else {
targetIndex = indexOfActive; // to the left of active editor
}
}
// Insert to the RIGHT of active editor
else {
targetIndex = indexOfActive + 1;
}
// Insert into our list of editors if pinned or we have no preview editor
if (makePinned || !this.preview) {
this.splice(targetIndex, false, editor);
}
// Handle preview
if (!makePinned) {
// Replace existing preview with this editor if we have a preview
if (this.preview) {
const indexOfPreview = this.indexOf(this.preview);
if (targetIndex > indexOfPreview) {
targetIndex--; // accomodate for the fact that the preview editor closes
}
this.closeEditor(this.preview, !makeActive); // optimization to prevent multiple setActive() in one call
this.splice(targetIndex, false, editor);
}
this.preview = editor;
}
// Listeners
this.hookEditorListeners(editor);
// Event
this.fireEvent(this._onEditorOpened, editor, true);
// Handle active
if (makeActive) {
this.setActive(editor);
}
}
// Existing editor
else {
// Pin it
if (makePinned) {
this.pin(editor);
}
// Activate it
if (makeActive) {
this.setActive(editor);
}
// Respect index
if (options && typeof options.index === 'number') {
this.moveEditor(editor, options.index);
}
}
}
private hookEditorListeners(editor: EditorInput): void {
const unbind: IDisposable[] = [];
// Re-emit disposal of editor input as our own event
unbind.push(editor.addOneTimeDisposableListener('dispose', () => {
if (this.indexOf(editor) >= 0) {
this._onEditorDisposed.fire(editor);
}
}));
// Re-Emit dirty state changes
unbind.push(editor.onDidChangeDirty(() => {
this.fireEvent(this._onEditorDirty, editor, false);
}));
// Clean up dispose listeners once the editor gets closed
unbind.push(this.onEditorClosed(event => {
if (event.editor.matches(editor)) {
dispose(unbind);
}
}));
}
public closeEditor(editor: EditorInput, openNext = true): void {
const index = this.indexOf(editor);
if (index === -1) {
return; // not found
}
// Active Editor closed
if (openNext && this.matches(this.active, editor)) {
// More than one editor
if (this.mru.length > 1) {
this.setActive(this.mru[1]); // active editor is always first in MRU, so pick second editor after as new active
}
// One Editor
else {
this.active = null;
}
}
// Preview Editor closed
let pinned = true;
if (this.matches(this.preview, editor)) {
this.preview = null;
pinned = false;
}
// Remove from arrays
this.splice(index, true);
// Event
this.fireEvent(this._onEditorClosed, { editor, pinned }, true);
}
public closeEditors(except: EditorInput, direction?: Direction): void {
const index = this.indexOf(except);
if (index === -1) {
return; // not found
}
// Close to the left
if (direction === Direction.LEFT) {
for (let i = index - 1; i >= 0; i--) {
this.closeEditor(this.editors[i]);
}
}
// Close to the right
else if (direction === Direction.RIGHT) {
for (let i = this.editors.length - 1; i > index; i--) {
this.closeEditor(this.editors[i]);
}
}
// Both directions
else {
this.mru.filter(e => !this.matches(e, except)).forEach(e => this.closeEditor(e));
}
}
public closeAllEditors(): void {
// Optimize: close all non active editors first to produce less upstream work
this.mru.filter(e => !this.matches(e, this.active)).forEach(e => this.closeEditor(e));
this.closeEditor(this.active);
}
public moveEditor(editor: EditorInput, toIndex: number): void {
const index = this.indexOf(editor);
if (index < 0) {
return;
}
// Move
this.editors.splice(index, 1);
this.editors.splice(toIndex, 0, editor);
// Event
this.fireEvent(this._onEditorMoved, editor, true);
}
public setActive(editor: EditorInput): void {
const index = this.indexOf(editor);
if (index === -1) {
return; // not found
}
if (this.matches(this.active, editor)) {
return; // already active
}
this.active = editor;
// Bring to front in MRU list
this.setMostRecentlyUsed(editor);
// Event
this.fireEvent(this._onEditorActivated, editor, false);
}
public pin(editor: EditorInput): void {
const index = this.indexOf(editor);
if (index === -1) {
return; // not found
}
if (!this.isPreview(editor)) {
return; // can only pin a preview editor
}
// Convert the preview editor to be a pinned editor
this.preview = null;
// Event
this.fireEvent(this._onEditorPinned, editor, false);
}
public unpin(editor: EditorInput): void {
const index = this.indexOf(editor);
if (index === -1) {
return; // not found
}
if (!this.isPinned(editor)) {
return; // can only unpin a pinned editor
}
// Set new
const oldPreview = this.preview;
this.preview = editor;
// Event
this.fireEvent(this._onEditorUnpinned, editor, false);
// Close old preview editor if any
this.closeEditor(oldPreview);
}
public isPinned(editor: EditorInput): boolean {
const index = this.indexOf(editor);
if (index === -1) {
return false; // editor not found
}
if (!this.preview) {
return true; // no preview editor
}
return !this.matches(this.preview, editor);
}
private fireEvent(emitter: Emitter<EditorInput | GroupEvent>, arg2: EditorInput | GroupEvent, isStructuralChange: boolean): void {
emitter.fire(arg2);
if (isStructuralChange) {
this._onEditorsStructureChanged.fire(arg2 instanceof EditorInput ? arg2 : arg2.editor);
} else {
this._onEditorStateChanged.fire(arg2 instanceof EditorInput ? arg2 : arg2.editor);
}
}
private splice(index: number, del: boolean, editor?: EditorInput): void {
const editorToDeleteOrReplace = this.editors[index];
const args: any[] = [index, del ? 1 : 0];
if (editor) {
args.push(editor);
}
// Perform on editors array
this.editors.splice.apply(this.editors, args);
// Add
if (!del && editor) {
this.mru.push(editor); // make it LRU editor
this.updateResourceMap(editor, false /* add */); // add new to resource map
}
// Remove / Replace
else {
const indexInMRU = this.indexOf(editorToDeleteOrReplace, this.mru);
// Remove
if (del && !editor) {
this.mru.splice(indexInMRU, 1); // remove from MRU
this.updateResourceMap(editorToDeleteOrReplace, true /* delete */); // remove from resource map
}
// Replace
else {
this.mru.splice(indexInMRU, 1, editor); // replace MRU at location
this.updateResourceMap(editor, false /* add */); // add new to resource map
this.updateResourceMap(editorToDeleteOrReplace, true /* delete */); // remove replaced from resource map
}
}
}
private updateResourceMap(editor: EditorInput, remove: boolean): void {
const resource = getUntitledOrFileResource(editor, true /* include diff editors */);
if (resource) {
// It is possible to have the same resource opened twice (once as normal input and once as diff input)
// So we need to do ref counting on the resource to provide the correct picture
let counter = this.mapResourceToEditorCount[resource.toString()] || 0;
let newCounter;
if (remove) {
if (counter > 1) {
newCounter = counter - 1;
}
} else {
newCounter = counter + 1;
}
this.mapResourceToEditorCount[resource.toString()] = newCounter;
}
}
public indexOf(candidate: EditorInput, editors = this.editors): number {
if (!candidate) {
return -1;
}
for (let i = 0; i < editors.length; i++) {
if (this.matches(editors[i], candidate)) {
return i;
}
}
return -1;
}
public contains(candidate: EditorInput): boolean;
public contains(resource: URI): boolean;
public contains(arg1: any): boolean {
if (arg1 instanceof EditorInput) {
return this.indexOf(arg1) >= 0;
}
const counter = this.mapResourceToEditorCount[(<URI>arg1).toString()];
return typeof counter === 'number' && counter > 0;
}
private setMostRecentlyUsed(editor: EditorInput): void {
const index = this.indexOf(editor);
if (index === -1) {
return; // editor not found
}
const mruIndex = this.indexOf(editor, this.mru);
// Remove old index
this.mru.splice(mruIndex, 1);
// Set editor to front
this.mru.unshift(editor);
}
private matches(editorA: EditorInput, editorB: EditorInput): boolean {
return !!editorA && !!editorB && editorA.matches(editorB);
}
public serialize(): ISerializedEditorGroup {
const registry = Registry.as<IEditorRegistry>(Extensions.Editors);
// Serialize all editor inputs so that we can store them.
// Editors that cannot be serialized need to be ignored
// from mru, active and preview if any.
let serializableEditors: EditorInput[] = [];
let serializedEditors: ISerializedEditorInput[] = [];
let serializablePreviewIndex: number;
this.editors.forEach(e => {
let factory = registry.getEditorInputFactory(e.getTypeId());
if (factory) {
let value = factory.serialize(e);
if (typeof value === 'string') {
serializedEditors.push({ id: e.getTypeId(), value });
serializableEditors.push(e);
if (this.preview === e) {
serializablePreviewIndex = serializableEditors.length - 1;
}
}
}
});
const serializableMru = this.mru.map(e => this.indexOf(e, serializableEditors)).filter(i => i >= 0);
return {
label: this.label,
editors: serializedEditors,
mru: serializableMru,
preview: serializablePreviewIndex,
};
}
private deserialize(data: ISerializedEditorGroup): void {
const registry = Registry.as<IEditorRegistry>(Extensions.Editors);
this._label = data.label;
this.editors = data.editors.map(e => {
const factory = registry.getEditorInputFactory(e.id);
if (factory) {
const editor = factory.deserialize(this.instantiationService, e.value);
this.hookEditorListeners(editor);
this.updateResourceMap(editor, false /* add */);
return editor;
}
return null;
}).filter(e => !!e);
this.mru = data.mru.map(i => this.editors[i]);
this.active = this.mru[0];
this.preview = this.editors[data.preview];
}
public dispose(): void {
dispose(this.toDispose);
}
}
interface ISerializedEditorStacksModel {
groups: ISerializedEditorGroup[];
active: number;
}
export class EditorStacksModel implements IEditorStacksModel {
private static STORAGE_KEY = 'editorStacks.model';
private toDispose: IDisposable[];
private loaded: boolean;
private _groups: EditorGroup[];
private _activeGroup: EditorGroup;
private groupToIdentifier: { [id: number]: EditorGroup };
private _onGroupOpened: Emitter<EditorGroup>;
private _onGroupClosed: Emitter<EditorGroup>;
private _onGroupMoved: Emitter<EditorGroup>;
private _onGroupActivated: Emitter<EditorGroup>;
private _onGroupDeactivated: Emitter<EditorGroup>;
private _onGroupRenamed: Emitter<EditorGroup>;
private _onEditorDisposed: Emitter<EditorIdentifier>;
private _onEditorDirty: Emitter<EditorIdentifier>;
private _onEditorClosed: Emitter<GroupEvent>;
private _onModelChanged: Emitter<IStacksModelChangeEvent>;
constructor(
@IStorageService private storageService: IStorageService,
@ILifecycleService private lifecycleService: ILifecycleService,
@IWorkspaceContextService private contextService: IWorkspaceContextService,
@IInstantiationService private instantiationService: IInstantiationService
) {
this.toDispose = [];
this._groups = [];
this.groupToIdentifier = Object.create(null);
this._onGroupOpened = new Emitter<EditorGroup>();
this._onGroupClosed = new Emitter<EditorGroup>();
this._onGroupActivated = new Emitter<EditorGroup>();
this._onGroupDeactivated = new Emitter<EditorGroup>();
this._onGroupMoved = new Emitter<EditorGroup>();
this._onGroupRenamed = new Emitter<EditorGroup>();
this._onModelChanged = new Emitter<IStacksModelChangeEvent>();
this._onEditorDisposed = new Emitter<EditorIdentifier>();
this._onEditorDirty = new Emitter<EditorIdentifier>();
this._onEditorClosed = new Emitter<GroupEvent>();
this.toDispose.push(this._onGroupOpened, this._onGroupClosed, this._onGroupActivated, this._onGroupDeactivated, this._onGroupMoved, this._onGroupRenamed, this._onModelChanged, this._onEditorDisposed, this._onEditorDirty, this._onEditorClosed);
this.registerListeners();
}
private registerListeners(): void {
this.toDispose.push(this.lifecycleService.onShutdown(() => this.onShutdown()));
}
public get onGroupOpened(): Event<EditorGroup> {
return this._onGroupOpened.event;
}
public get onGroupClosed(): Event<EditorGroup> {
return this._onGroupClosed.event;
}
public get onGroupActivated(): Event<EditorGroup> {
return this._onGroupActivated.event;
}
public get onGroupDeactivated(): Event<EditorGroup> {
return this._onGroupDeactivated.event;
}
public get onGroupMoved(): Event<EditorGroup> {
return this._onGroupMoved.event;
}
public get onGroupRenamed(): Event<EditorGroup> {
return this._onGroupRenamed.event;
}
public get onModelChanged(): Event<IStacksModelChangeEvent> {
return this._onModelChanged.event;
}
public get onEditorDisposed(): Event<EditorIdentifier> {
return this._onEditorDisposed.event;
}
public get onEditorDirty(): Event<EditorIdentifier> {
return this._onEditorDirty.event;
}
public get onEditorClosed(): Event<GroupEvent> {
return this._onEditorClosed.event;
}
public get groups(): EditorGroup[] {
this.ensureLoaded();
return this._groups.slice(0);
}
public get activeGroup(): EditorGroup {
this.ensureLoaded();
return this._activeGroup;
}
public isActive(group: EditorGroup): boolean {
return this.activeGroup === group;
}
public getGroup(id: GroupIdentifier): EditorGroup {
this.ensureLoaded();
return this.groupToIdentifier[id];
}
public openGroup(label: string, activate = true, index?: number): EditorGroup {
this.ensureLoaded();
const group = this.doCreateGroup(label);
// Direct index provided
if (typeof index === 'number') {
this._groups[index] = group;
}
// First group
else if (!this._activeGroup) {
this._groups.push(group);
}
// Subsequent group (open to the right of active one)
else {
this._groups.splice(this.indexOf(this._activeGroup) + 1, 0, group);
}
// Event
this.fireEvent(this._onGroupOpened, group, true);
// Activate if we are first or set to activate groups
if (!this._activeGroup || activate) {
this.setActive(group);
}
return group;
}
public renameGroup(group: EditorGroup, label: string): void {
this.ensureLoaded();
if (group.label !== label) {
group.label = label;
this.fireEvent(this._onGroupRenamed, group, false);
}
}
public closeGroup(group: EditorGroup): void {
this.ensureLoaded();
const index = this.indexOf(group);
if (index < 0) {
return; // group does not exist
}
// Active group closed: Find a new active one to the right
if (group === this._activeGroup) {
// More than one group
if (this._groups.length > 1) {
let newActiveGroup: EditorGroup;
if (this._groups.length > index + 1) {
newActiveGroup = this._groups[index + 1]; // make next group to the right active
} else {
newActiveGroup = this._groups[index - 1]; // make next group to the left active
}
this.setActive(newActiveGroup);
}
// One group
else {
this._activeGroup = null;
}
}
// Close Editors in Group first and dispose then
group.closeAllEditors();
group.dispose();
// Splice from groups
this._groups.splice(index, 1);
this.groupToIdentifier[group.id] = void 0;
// Events
this.fireEvent(this._onGroupClosed, group, true);
for (let i = index; i < this._groups.length; i++) {
this.fireEvent(this._onGroupMoved, this._groups[i], true); // send move event for groups to the right that moved to the left into the closed group position
}
}
public closeGroups(except?: EditorGroup): void {
this.ensureLoaded();
// Optimize: close all non active groups first to produce less upstream work
this.groups.filter(g => g !== this._activeGroup && g !== except).forEach(g => this.closeGroup(g));
// Close active unless configured to skip
if (this._activeGroup !== except) {
this.closeGroup(this._activeGroup);
}
}
public setActive(group: EditorGroup): void {
this.ensureLoaded();
if (this._activeGroup === group) {
return;
}
const oldActiveGroup = this._activeGroup;
this._activeGroup = group;
this.fireEvent(this._onGroupActivated, group, false);
if (oldActiveGroup) {
this.fireEvent(this._onGroupDeactivated, oldActiveGroup, false);
}
}
public moveGroup(group: EditorGroup, toIndex: number): void {
this.ensureLoaded();
const index = this.indexOf(group);
if (index < 0) {
return;
}
// Move
this._groups.splice(index, 1);
this._groups.splice(toIndex, 0, group);
// Event
for (let i = Math.min(index, toIndex); i <= Math.max(index, toIndex) && i < this._groups.length; i++) {
this.fireEvent(this._onGroupMoved, this._groups[i], true); // send move event for groups to the right that moved to the left into the closed group position
}
}
private indexOf(group: EditorGroup): number {
return this._groups.indexOf(group);
}
public positionOfGroup(group: IEditorGroup): Position;
public positionOfGroup(group: EditorGroup): Position;
public positionOfGroup(group: EditorGroup): Position {
return this.indexOf(group);
}
public groupAt(position: Position): EditorGroup {
this.ensureLoaded();
return this._groups[position];
}
public next(): IEditorIdentifier {
this.ensureLoaded();
if (!this.activeGroup) {
return null;
}
const index = this.activeGroup.indexOf(this.activeGroup.activeEditor);
// Return next in group
if (index + 1 < this.activeGroup.count) {
return { group: this.activeGroup, editor: this.activeGroup.getEditor(index + 1) };
}
// Return first in next group
const indexOfGroup = this.indexOf(this.activeGroup);
const nextGroup = this.groups[indexOfGroup + 1];
if (nextGroup) {
return { group: nextGroup, editor: nextGroup.getEditor(0) };
}
// Return first in first group
const firstGroup = this.groups[0];
return { group: firstGroup, editor: firstGroup.getEditor(0) };
}
public previous(): IEditorIdentifier {
this.ensureLoaded();
if (!this.activeGroup) {
return null;
}
const index = this.activeGroup.indexOf(this.activeGroup.activeEditor);
// Return previous in group
if (index > 0) {
return { group: this.activeGroup, editor: this.activeGroup.getEditor(index - 1) };
}
// Return last in previous group
const indexOfGroup = this.indexOf(this.activeGroup);
const previousGroup = this.groups[indexOfGroup - 1];
if (previousGroup) {
return { group: previousGroup, editor: previousGroup.getEditor(previousGroup.count - 1) };
}
// Return last in last group
const lastGroup = this.groups[this.groups.length - 1];
return { group: lastGroup, editor: lastGroup.getEditor(lastGroup.count - 1) };
}
private save(): void {
const serialized = this.serialize();
this.storageService.store(EditorStacksModel.STORAGE_KEY, JSON.stringify(serialized), StorageScope.WORKSPACE);
}
private serialize(): ISerializedEditorStacksModel {
// Exclude now empty groups (can happen if an editor cannot be serialized)
let serializableGroups = this._groups.map(g => g.serialize()).filter(g => g.editors.length > 0);
// Only consider active index if we do not have empty groups
let serializableActiveIndex: number;
if (serializableGroups.length > 0) {
if (serializableGroups.length === this._groups.length) {
serializableActiveIndex = this.indexOf(this._activeGroup);
} else {
serializableActiveIndex = 0;
}
}
return {
groups: serializableGroups,
active: serializableActiveIndex
};
}
private fireEvent(emitter: Emitter<EditorGroup>, group: EditorGroup, isStructuralChange: boolean): void {
emitter.fire(group);
this._onModelChanged.fire({ group, structural: isStructuralChange });
}
private ensureLoaded(): void {
if (!this.loaded) {
this.loaded = true;
this.load();
}
}
private load(): void {
const options = this.contextService.getOptions();
if ((options.filesToCreate && options.filesToCreate.length) || (options.filesToOpen && options.filesToOpen.length) || (options.filesToDiff && options.filesToDiff.length)) {
return; // do not load from last session if the user explicitly asks to open a set of files
}
const modelRaw = this.storageService.get(EditorStacksModel.STORAGE_KEY, StorageScope.WORKSPACE);
if (modelRaw) {
const serialized: ISerializedEditorStacksModel = JSON.parse(modelRaw);
const invalidId = this.doValidate(serialized);
if (invalidId) {
console.warn(`Ignoring invalid stacks model (Error code: ${invalidId}): ${JSON.stringify(serialized)}`);
console.warn(serialized);
return;
}
this._groups = serialized.groups.map(s => this.doCreateGroup(s));
this._activeGroup = this._groups[serialized.active];
}
}
private doValidate(serialized: ISerializedEditorStacksModel): number {
if (!serialized.groups.length && typeof serialized.active === 'number') {
return 1; // Invalid active (we have no groups, but an active one)
}
if (serialized.groups.length && !serialized.groups[serialized.active]) {
return 2; // Invalid active (we cannot find the active one in group)
}
if (serialized.groups.length > 3) {
return 3; // Too many groups
}
if (serialized.groups.some(g => !g.editors.length)) {
return 4; // Some empty groups
}
if (serialized.groups.some(g => g.editors.length !== g.mru.length)) {
return 5; // MRU out of sync with editors
}
if (serialized.groups.some(g => typeof g.preview === 'number' && !g.editors[g.preview])) {
return 6; // Invalid preview editor
}
if (serialized.groups.some(g => !g.label)) {
return 7; // Group without label
}
return 0;
}
private doCreateGroup(arg1: string | ISerializedEditorGroup): EditorGroup {
const group = this.instantiationService.createInstance(EditorGroup, arg1);
this.groupToIdentifier[group.id] = group;
// Funnel editor changes in the group through our event aggregator
const unbind: IDisposable[] = [];
unbind.push(group.onEditorsStructureChanged(editor => this._onModelChanged.fire({ group, editor, structural: true })));
unbind.push(group.onEditorStateChanged(editor => this._onModelChanged.fire({ group, editor })));
unbind.push(group.onEditorClosed(event => {
this.handleOnEditorClosed(event);
this._onEditorClosed.fire(event);
}));
unbind.push(group.onEditorDisposed(editor => this._onEditorDisposed.fire({ editor, group })));
unbind.push(group.onEditorDirty(editor => this._onEditorDirty.fire({ editor, group })));
unbind.push(this.onGroupClosed(g => {
if (g === group) {
dispose(unbind);
}
}));
return group;
}
private handleOnEditorClosed(event: GroupEvent): void {
const editor = event.editor;
// Close the editor when it is no longer open in any group
if (!this.isOpen(editor)) {
editor.close();
// Also take care of diff editor inputs that wrap around 2 editors
if (editor instanceof DiffEditorInput) {
[editor.originalInput, editor.modifiedInput].forEach(editor => {
if (!this.isOpen(editor)) {
editor.close();
}
});
}
}
}
public isOpen(resource: URI): boolean;
public isOpen(editor: EditorInput): boolean;
public isOpen(arg1: any): boolean {
if (arg1 instanceof EditorInput) {
return this._groups.some(g => g.indexOf(arg1) >= 0);
}
return this._groups.some(group => group.contains(<URI>arg1));
}
private onShutdown(): void {
this.save();
dispose(this.toDispose);
}
public validate(): void {
const serialized = this.serialize();
const invalidId = this.doValidate(serialized);
if (invalidId) {
console.warn(`Ignoring invalid stacks model (Error code: ${invalidId}): ${JSON.stringify(serialized)}`);
console.warn(serialized);
} else {
console.log('Stacks Model OK!');
}
}
public toString(): string {
this.ensureLoaded();
const lines: string[] = [];
if (!this.groups.length) {
return '<No Groups>';
}
this.groups.forEach(g => {
let label = `Group: ${g.label}`;
if (this._activeGroup === g) {
label = `${label} [active]`;
}
lines.push(label);
g.getEditors().forEach(e => {
let label = `\t${e.getName()}`;
if (g.previewEditor === e) {
label = `${label} [preview]`;
}
if (g.activeEditor === e) {
label = `${label} [active]`;
}
lines.push(label);
});
});
return lines.join('\n');
}
} | src/vs/workbench/common/editor/editorStacksModel.ts | 0 | https://github.com/microsoft/vscode/commit/3978edfa64c9a7b8a8ba823e3ab30767457dc5c6 | [
0.0003310535103082657,
0.0001730981603031978,
0.00016480468912050128,
0.00017077350639738142,
0.000017131673303083517
] |
{
"id": 5,
"code_window": [
"\n",
"\tpublic get value(): string {\n",
"\t\treturn this._value;\n",
"\t}\n",
"\n",
"\t// The adapter explicitly sents the children count of an expression only if there are lots of children which should be chunked.\n",
"\tprivate get getChildrenInChunks(): boolean {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep"
],
"after_edit": [
"\tprivate fetchVariables(session: debug.IRawDebugSession, start: number, count: number, filter: 'indexed'|'named'): TPromise<Variable[]> {\n",
"\t\treturn session.variables({\n",
"\t\t\tvariablesReference: this.reference,\n",
"\t\t\tstart,\n",
"\t\t\tcount,\n",
"\t\t\tfilter\n",
"\t\t}).then(response => {\n",
"\t\t\treturn arrays.distinct(response.body.variables.filter(v => !!v), v => v.name).map(\n",
"\t\t\t\tv => new Variable(this, v.variablesReference, v.name, v.value, v.namedVariables, v.indexedVariables, v.type)\n",
"\t\t\t);\n",
"\t\t}, (e: Error) => [new Variable(this, 0, null, e.message, 0, 0, null, false)]);\n",
"\t}\n",
"\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debugModel.ts",
"type": "add",
"edit_start_line_idx": 286
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import {TPromise} from 'vs/base/common/winjs.base';
import {ServiceCollection} from './serviceCollection';
import * as descriptors from './descriptors';
// ------ internal util
export namespace _util {
export const DI_TARGET = '$di$target';
export const DI_DEPENDENCIES = '$di$dependencies';
export function getServiceDependencies(ctor: any): { id: ServiceIdentifier<any>, index: number, optional: boolean }[] {
return ctor[DI_DEPENDENCIES] || [];
}
}
// --- interfaces ------
export interface IConstructorSignature0<T> {
new (...services: { _serviceBrand: any; }[]): T;
}
export interface IConstructorSignature1<A1, T> {
new (first: A1, ...services: { _serviceBrand: any; }[]): T;
}
export interface IConstructorSignature2<A1, A2, T> {
new (first: A1, second: A2, ...services: { _serviceBrand: any; }[]): T;
}
export interface IConstructorSignature3<A1, A2, A3, T> {
new (first: A1, second: A2, third: A3, ...services: { _serviceBrand: any; }[]): T;
}
export interface IConstructorSignature4<A1, A2, A3, A4, T> {
new (first: A1, second: A2, third: A3, forth: A4, ...services: { _serviceBrand: any; }[]): T;
}
export interface IConstructorSignature5<A1, A2, A3, A4, A5, T> {
new (first: A1, second: A2, third: A3, forth: A4, fifth: A5, ...services: { _serviceBrand: any; }[]): T;
}
export interface IConstructorSignature6<A1, A2, A3, A4, A5, A6, T> {
new (first: A1, second: A2, third: A3, forth: A4, fifth: A5, sixth: A6, ...services: { _serviceBrand: any; }[]): T;
}
export interface IConstructorSignature7<A1, A2, A3, A4, A5, A6, A7, T> {
new (first: A1, second: A2, third: A3, forth: A4, fifth: A5, sixth: A6, seventh: A7, ...services: { _serviceBrand: any; }[]): T;
}
export interface IConstructorSignature8<A1, A2, A3, A4, A5, A6, A7, A8, T> {
new (first: A1, second: A2, third: A3, forth: A4, fifth: A5, sixth: A6, seventh: A7, eigth: A8, ...services: { _serviceBrand: any; }[]): T;
}
export interface ServicesAccessor {
get<T>(id: ServiceIdentifier<T>, isOptional?: typeof optional): T;
}
export interface IFunctionSignature0<R> {
(accessor: ServicesAccessor): R;
}
export interface IFunctionSignature1<A1, R> {
(accessor: ServicesAccessor, first: A1): R;
}
export interface IFunctionSignature2<A1, A2, R> {
(accessor: ServicesAccessor, first: A1, second: A2): R;
}
export interface IFunctionSignature3<A1, A2, A3, R> {
(accessor: ServicesAccessor, first: A1, second: A2, third: A3): R;
}
export interface IFunctionSignature4<A1, A2, A3, A4, R> {
(accessor: ServicesAccessor, first: A1, second: A2, third: A3, forth: A4): R;
}
export interface IFunctionSignature5<A1, A2, A3, A4, A5, R> {
(accessor: ServicesAccessor, first: A1, second: A2, third: A3, forth: A4, fifth: A5): R;
}
export interface IFunctionSignature6<A1, A2, A3, A4, A5, A6, R> {
(accessor: ServicesAccessor, first: A1, second: A2, third: A3, forth: A4, fifth: A5, sixth: A6): R;
}
export interface IFunctionSignature7<A1, A2, A3, A4, A5, A6, A7, R> {
(accessor: ServicesAccessor, first: A1, second: A2, third: A3, forth: A4, fifth: A5, sixth: A6, seventh: A7): R;
}
export interface IFunctionSignature8<A1, A2, A3, A4, A5, A6, A7, A8, R> {
(accessor: ServicesAccessor, first: A1, second: A2, third: A3, forth: A4, fifth: A5, sixth: A6, seventh: A7, eigth: A8): R;
}
export var IInstantiationService = createDecorator<IInstantiationService>('instantiationService');
export interface IInstantiationService {
_serviceBrand: any;
/**
* Synchronously creates an instance that is denoted by
* the descriptor
*/
createInstance<T>(descriptor: descriptors.SyncDescriptor0<T>): T;
createInstance<A1, T>(descriptor: descriptors.SyncDescriptor1<A1, T>, a1: A1): T;
createInstance<A1, A2, T>(descriptor: descriptors.SyncDescriptor2<A1, A2, T>, a1: A1, a2: A2): T;
createInstance<A1, A2, A3, T>(descriptor: descriptors.SyncDescriptor3<A1, A2, A3, T>, a1: A1, a2: A2, a3: A3): T;
createInstance<A1, A2, A3, A4, T>(descriptor: descriptors.SyncDescriptor4<A1, A2, A3, A4, T>, a1: A1, a2: A2, a3: A3, a4: A4): T;
createInstance<A1, A2, A3, A4, A5, T>(descriptor: descriptors.SyncDescriptor5<A1, A2, A3, A4, A5, T>, a1: A1, a2: A2, a3: A3, a4: A4, a5: A5): T;
createInstance<A1, A2, A3, A4, A5, A6, T>(descriptor: descriptors.SyncDescriptor6<A1, A2, A3, A4, A5, A6, T>, a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6): T;
createInstance<A1, A2, A3, A4, A5, A6, A7, T>(descriptor: descriptors.SyncDescriptor7<A1, A2, A3, A4, A5, A6, A7, T>, a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6, a7: A7): T;
createInstance<A1, A2, A3, A4, A5, A6, A7, A8, T>(descriptor: descriptors.SyncDescriptor8<A1, A2, A3, A4, A5, A6, A7, A8, T>, a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6, a7: A7, a8: A8): T;
createInstance<T>(ctor: IConstructorSignature0<T>): T;
createInstance<A1, T>(ctor: IConstructorSignature1<A1, T>, first: A1): T;
createInstance<A1, A2, T>(ctor: IConstructorSignature2<A1, A2, T>, first: A1, second: A2): T;
createInstance<A1, A2, A3, T>(ctor: IConstructorSignature3<A1, A2, A3, T>, first: A1, second: A2, third: A3): T;
createInstance<A1, A2, A3, A4, T>(ctor: IConstructorSignature4<A1, A2, A3, A4, T>, first: A1, second: A2, third: A3, fourth: A4): T;
createInstance<A1, A2, A3, A4, A5, T>(ctor: IConstructorSignature5<A1, A2, A3, A4, A5, T>, first: A1, second: A2, third: A3, fourth: A4, fifth: A5): T;
createInstance<A1, A2, A3, A4, A5, A6, T>(ctor: IConstructorSignature6<A1, A2, A3, A4, A5, A6, T>, first: A1, second: A2, third: A3, fourth: A4, fifth: A5, sixth: A6): T;
createInstance<A1, A2, A3, A4, A5, A6, A7, T>(ctor: IConstructorSignature7<A1, A2, A3, A4, A5, A6, A7, T>, first: A1, second: A2, third: A3, fourth: A4, fifth: A5, sixth: A6, seventh: A7): T;
createInstance<A1, A2, A3, A4, A5, A6, A7, A8, T>(ctor: IConstructorSignature8<A1, A2, A3, A4, A5, A6, A7, A8, T>, first: A1, second: A2, third: A3, fourth: A4, fifth: A5, sixth: A6, seventh: A7, eigth: A8): T;
/**
* Asynchronously creates an instance that is denoted by
* the descriptor
*/
createInstance<T>(descriptor: descriptors.AsyncDescriptor0<T>): TPromise<T>;
createInstance<A1, T>(descriptor: descriptors.AsyncDescriptor1<A1, T>, a1: A1): TPromise<T>;
createInstance<A1, A2, T>(descriptor: descriptors.AsyncDescriptor2<A1, A2, T>, a1: A1, a2: A2): TPromise<T>;
createInstance<A1, A2, A3, T>(descriptor: descriptors.AsyncDescriptor3<A1, A2, A3, T>, a1: A1, a2: A2, a3: A3): TPromise<T>;
createInstance<A1, A2, A3, A4, T>(descriptor: descriptors.AsyncDescriptor4<A1, A2, A3, A4, T>, a1: A1, a2: A2, a3: A3, a4: A4): TPromise<T>;
createInstance<A1, A2, A3, A4, A5, T>(descriptor: descriptors.AsyncDescriptor5<A1, A2, A3, A4, A5, T>, a1: A1, a2: A2, a3: A3, a4: A4, a5: A5): TPromise<T>;
createInstance<A1, A2, A3, A4, A5, A6, T>(descriptor: descriptors.AsyncDescriptor6<A1, A2, A3, A4, A5, A6, T>, a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6): TPromise<T>;
createInstance<A1, A2, A3, A4, A5, A6, A7, T>(descriptor: descriptors.AsyncDescriptor7<A1, A2, A3, A4, A5, A6, A7, T>, a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6, a7: A7): TPromise<T>;
createInstance<A1, A2, A3, A4, A5, A6, A7, A8, T>(descriptor: descriptors.AsyncDescriptor8<A1, A2, A3, A4, A5, A6, A7, A8, T>, a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6, a7: A7, a8: A8): TPromise<T>;
/**
*
*/
invokeFunction<R>(ctor: IFunctionSignature0<R>): R;
invokeFunction<A1, R>(ctor: IFunctionSignature1<A1, R>, first: A1): R;
invokeFunction<A1, A2, R>(ctor: IFunctionSignature2<A1, A2, R>, first: A1, second: A2): R;
invokeFunction<A1, A2, A3, R>(ctor: IFunctionSignature3<A1, A2, A3, R>, first: A1, second: A2, third: A3): R;
invokeFunction<A1, A2, A3, A4, R>(ctor: IFunctionSignature4<A1, A2, A3, A4, R>, first: A1, second: A2, third: A3, fourth: A4): R;
invokeFunction<A1, A2, A3, A4, A5, R>(ctor: IFunctionSignature5<A1, A2, A3, A4, A5, R>, first: A1, second: A2, third: A3, fourth: A4, fifth: A5): R;
invokeFunction<A1, A2, A3, A4, A5, A6, R>(ctor: IFunctionSignature6<A1, A2, A3, A4, A5, A6, R>, first: A1, second: A2, third: A3, fourth: A4, fifth: A5, sixth: A6): R;
invokeFunction<A1, A2, A3, A4, A5, A6, A7, R>(ctor: IFunctionSignature7<A1, A2, A3, A4, A5, A6, A7, R>, first: A1, second: A2, third: A3, fourth: A4, fifth: A5, sixth: A6, seventh: A7): R;
invokeFunction<A1, A2, A3, A4, A5, A6, A7, A8, R>(ctor: IFunctionSignature8<A1, A2, A3, A4, A5, A6, A7, A8, R>, first: A1, second: A2, third: A3, fourth: A4, fifth: A5, sixth: A6, seventh: A7, eigth: A8): R;
/**
* Creates a child of this service which inherts all current services
* and adds/overwrites the given services
*/
createChild(services: ServiceCollection): IInstantiationService;
}
/**
* Identifies a service of type T
*/
export interface ServiceIdentifier<T> {
(...args: any[]): void;
type: T;
}
function storeServiceDependency(id: Function, target: Function, index: number, optional: boolean): void {
if (target[_util.DI_TARGET] === target) {
target[_util.DI_DEPENDENCIES].push({ id, index, optional });
} else {
target[_util.DI_DEPENDENCIES] = [{ id, index, optional }];
target[_util.DI_TARGET] = target;
}
}
/**
* A *only* valid way to create a {{ServiceIdentifier}}.
*/
export function createDecorator<T>(serviceId: string): { (...args: any[]): void; type: T; } {
let id = function(target: Function, key: string, index: number): any {
if (arguments.length !== 3) {
throw new Error('@IServiceName-decorator can only be used to decorate a parameter');
}
storeServiceDependency(id, target, index, false);
};
id.toString = () => serviceId;
return <any>id;
}
/**
* Mark a service dependency as optional.
*/
export function optional<T>(serviceIdentifier: ServiceIdentifier<T>) {
return function (target: Function, key: string, index: number){
if (arguments.length !== 3) {
throw new Error('@optional-decorator can only be used to decorate a parameter');
}
storeServiceDependency(serviceIdentifier, target, index, true);
};
}
| src/vs/platform/instantiation/common/instantiation.ts | 0 | https://github.com/microsoft/vscode/commit/3978edfa64c9a7b8a8ba823e3ab30767457dc5c6 | [
0.0002185425255447626,
0.0001736697886371985,
0.0001652438659220934,
0.00016933698498178273,
0.000012160065125499386
] |
{
"id": 6,
"code_window": [
"\t// The adapter explicitly sents the children count of an expression only if there are lots of children which should be chunked.\n",
"\tprivate get getChildrenInChunks(): boolean {\n",
"\t\treturn !!this.childrenCount;\n",
"\t}\n",
"\n",
"\tpublic set value(value: string) {\n",
"\t\tthis._value = massageValue(value);\n",
"\t\tthis.valueChanged = ExpressionContainer.allValues[this.getId()] &&\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\treturn !!this.indexedVariables;\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debugModel.ts",
"type": "replace",
"edit_start_line_idx": 288
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { TPromise } from 'vs/base/common/winjs.base';
import nls = require('vs/nls');
import lifecycle = require('vs/base/common/lifecycle');
import Event, { Emitter } from 'vs/base/common/event';
import uuid = require('vs/base/common/uuid');
import objects = require('vs/base/common/objects');
import severity from 'vs/base/common/severity';
import types = require('vs/base/common/types');
import arrays = require('vs/base/common/arrays');
import debug = require('vs/workbench/parts/debug/common/debug');
import { Source } from 'vs/workbench/parts/debug/common/debugSource';
const MAX_REPL_LENGTH = 10000;
const UNKNOWN_SOURCE_LABEL = nls.localize('unknownSource', "Unknown Source");
function massageValue(value: string): string {
return value ? value.replace(/\n/g, '\\n').replace(/\r/g, '\\r').replace(/\t/g, '\\t') : value;
}
export function evaluateExpression(session: debug.IRawDebugSession, stackFrame: debug.IStackFrame, expression: Expression, context: string): TPromise<Expression> {
if (!session) {
expression.value = context === 'repl' ? nls.localize('startDebugFirst', "Please start a debug session to evaluate") : Expression.DEFAULT_VALUE;
expression.available = false;
expression.reference = 0;
return TPromise.as(expression);
}
return session.evaluate({
expression: expression.name,
frameId: stackFrame ? stackFrame.frameId : undefined,
context
}).then(response => {
expression.available = !!(response && response.body);
if (response.body) {
expression.value = response.body.result;
expression.reference = response.body.variablesReference;
expression.childrenCount = response.body.indexedVariables;
expression.type = response.body.type;
}
return expression;
}, err => {
expression.value = err.message;
expression.available = false;
expression.reference = 0;
return expression;
});
}
const notPropertySyntax = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
const arrayElementSyntax = /\[.*\]$/;
export function getFullExpressionName(expression: debug.IExpression, sessionType: string): string {
let names = [expression.name];
if (expression instanceof Variable) {
let v = (<Variable> expression).parent;
while (v instanceof Variable || v instanceof Expression) {
names.push((<Variable> v).name);
v = (<Variable> v).parent;
}
}
names = names.reverse();
let result = null;
names.forEach(name => {
if (!result) {
result = name;
} else if (arrayElementSyntax.test(name) || (sessionType === 'node' && !notPropertySyntax.test(name))) {
// use safe way to access node properties a['property_name']. Also handles array elements.
result = name && name.indexOf('[') === 0 ? `${ result }${ name }` : `${ result }['${ name }']`;
} else {
result = `${ result }.${ name }`;
}
});
return result;
}
export class Thread implements debug.IThread {
private promisedCallStack: TPromise<debug.IStackFrame[]>;
private cachedCallStack: debug.IStackFrame[];
public stoppedDetails: debug.IRawStoppedDetails;
public stopped: boolean;
constructor(public name: string, public threadId: number) {
this.promisedCallStack = undefined;
this.stoppedDetails = undefined;
this.cachedCallStack = undefined;
this.stopped = false;
}
public getId(): string {
return `thread:${ this.name }:${ this.threadId }`;
}
public clearCallStack(): void {
this.promisedCallStack = undefined;
this.cachedCallStack = undefined;
}
public getCachedCallStack(): debug.IStackFrame[] {
return this.cachedCallStack;
}
public getCallStack(debugService: debug.IDebugService, getAdditionalStackFrames = false): TPromise<debug.IStackFrame[]> {
if (!this.stopped) {
return TPromise.as([]);
}
if (!this.promisedCallStack) {
this.promisedCallStack = this.getCallStackImpl(debugService, 0).then(callStack => {
this.cachedCallStack = callStack;
return callStack;
});
} else if (getAdditionalStackFrames) {
this.promisedCallStack = this.promisedCallStack.then(callStackFirstPart => this.getCallStackImpl(debugService, callStackFirstPart.length).then(callStackSecondPart => {
this.cachedCallStack = callStackFirstPart.concat(callStackSecondPart);
return this.cachedCallStack;
}));
}
return this.promisedCallStack;
}
private getCallStackImpl(debugService: debug.IDebugService, startFrame: number): TPromise<debug.IStackFrame[]> {
let session = debugService.getActiveSession();
return session.stackTrace({ threadId: this.threadId, startFrame, levels: 20 }).then(response => {
this.stoppedDetails.totalFrames = response.body.totalFrames;
return response.body.stackFrames.map((rsf, level) => {
if (!rsf) {
return new StackFrame(this.threadId, 0, new Source({ name: UNKNOWN_SOURCE_LABEL }, false), nls.localize('unknownStack', "Unknown stack location"), undefined, undefined);
}
return new StackFrame(this.threadId, rsf.id, rsf.source ? new Source(rsf.source) : new Source({ name: UNKNOWN_SOURCE_LABEL }, false), rsf.name, rsf.line, rsf.column);
});
}, (err: Error) => {
this.stoppedDetails.framesErrorMessage = err.message;
return [];
});
}
}
export class OutputElement implements debug.ITreeElement {
private static ID_COUNTER = 0;
constructor(private id = OutputElement.ID_COUNTER++) {
// noop
}
public getId(): string {
return `outputelement:${ this.id }`;
}
}
export class ValueOutputElement extends OutputElement {
constructor(
public value: string,
public severity: severity,
public category?: string,
public counter: number = 1
) {
super();
}
}
export class KeyValueOutputElement extends OutputElement {
private static MAX_CHILDREN = 1000; // upper bound of children per value
private children: debug.ITreeElement[];
private _valueName: string;
constructor(public key: string, public valueObj: any, public annotation?: string) {
super();
this._valueName = null;
}
public get value(): string {
if (this._valueName === null) {
if (this.valueObj === null) {
this._valueName = 'null';
} else if (Array.isArray(this.valueObj)) {
this._valueName = `Array[${this.valueObj.length}]`;
} else if (types.isObject(this.valueObj)) {
this._valueName = 'Object';
} else if (types.isString(this.valueObj)) {
this._valueName = `"${massageValue(this.valueObj)}"`;
} else {
this._valueName = String(this.valueObj);
}
if (!this._valueName) {
this._valueName = '';
}
}
return this._valueName;
}
public getChildren(): debug.ITreeElement[] {
if (!this.children) {
if (Array.isArray(this.valueObj)) {
this.children = (<any[]>this.valueObj).slice(0, KeyValueOutputElement.MAX_CHILDREN).map((v, index) => new KeyValueOutputElement(String(index), v, null));
} else if (types.isObject(this.valueObj)) {
this.children = Object.getOwnPropertyNames(this.valueObj).slice(0, KeyValueOutputElement.MAX_CHILDREN).map(key => new KeyValueOutputElement(key, this.valueObj[key], null));
} else {
this.children = [];
}
}
return this.children;
}
}
export abstract class ExpressionContainer implements debug.IExpressionContainer {
public static allValues: { [id: string]: string } = {};
// Use chunks to support variable paging #9537
private static CHUNK_SIZE = 100;
public valueChanged: boolean;
private children: TPromise<debug.IExpression[]>;
private _value: string;
constructor(
public reference: number,
private id: string,
private cacheChildren: boolean,
public childrenCount: number,
private chunkIndex = 0
) {
// noop
}
public getChildren(debugService: debug.IDebugService): TPromise<debug.IExpression[]> {
if (!this.cacheChildren || !this.children) {
const session = debugService.getActiveSession();
// only variables with reference > 0 have children.
if (!session || this.reference <= 0) {
this.children = TPromise.as([]);
} else {
if (this.childrenCount > ExpressionContainer.CHUNK_SIZE) {
// There are a lot of children, create fake intermediate values that represent chunks #9537
const chunks = [];
const numberOfChunks = this.childrenCount / ExpressionContainer.CHUNK_SIZE;
for (let i = 0; i < numberOfChunks; i++) {
const chunkSize = (i < numberOfChunks - 1) ? ExpressionContainer.CHUNK_SIZE : this.childrenCount % ExpressionContainer.CHUNK_SIZE;
const chunkName = `${i * ExpressionContainer.CHUNK_SIZE}..${i * ExpressionContainer.CHUNK_SIZE + chunkSize - 1}`;
chunks.push(new Variable(this, this.reference, chunkName, '', chunkSize, null, true, i));
}
this.children = TPromise.as(chunks);
} else {
const start = this.getChildrenInChunks ? this.chunkIndex * ExpressionContainer.CHUNK_SIZE : undefined;
const count = this.getChildrenInChunks ? this.childrenCount : undefined;
this.children = session.variables({
variablesReference: this.reference,
start,
count
}).then(response => {
return arrays.distinct(response.body.variables.filter(v => !!v), v => v.name).map(
v => new Variable(this, v.variablesReference, v.name, v.value, v.indexedVariables, v.type)
);
}, (e: Error) => [new Variable(this, 0, null, e.message, 0, null, false)]);
}
}
}
return this.children;
}
public getId(): string {
return this.id;
}
public get value(): string {
return this._value;
}
// The adapter explicitly sents the children count of an expression only if there are lots of children which should be chunked.
private get getChildrenInChunks(): boolean {
return !!this.childrenCount;
}
public set value(value: string) {
this._value = massageValue(value);
this.valueChanged = ExpressionContainer.allValues[this.getId()] &&
ExpressionContainer.allValues[this.getId()] !== Expression.DEFAULT_VALUE && ExpressionContainer.allValues[this.getId()] !== value;
ExpressionContainer.allValues[this.getId()] = value;
}
}
export class Expression extends ExpressionContainer implements debug.IExpression {
static DEFAULT_VALUE = 'not available';
public available: boolean;
public type: string;
constructor(public name: string, cacheChildren: boolean, id = uuid.generateUuid()) {
super(0, id, cacheChildren, 0);
this.value = Expression.DEFAULT_VALUE;
this.available = false;
}
}
export class Variable extends ExpressionContainer implements debug.IExpression {
// Used to show the error message coming from the adapter when setting the value #7807
public errorMessage: string;
constructor(
public parent: debug.IExpressionContainer,
reference: number,
public name: string,
value: string,
childrenCount: number,
public type: string = null,
public available = true,
chunkIndex = 0
) {
super(reference, `variable:${ parent.getId() }:${ name }`, true, childrenCount, chunkIndex);
this.value = massageValue(value);
}
}
export class Scope extends ExpressionContainer implements debug.IScope {
constructor(
private threadId: number,
public name: string,
reference: number,
public expensive: boolean,
childrenCount: number
) {
super(reference, `scope:${threadId}:${name}:${reference}`, true, childrenCount);
}
}
export class StackFrame implements debug.IStackFrame {
private scopes: TPromise<Scope[]>;
constructor(
public threadId: number,
public frameId: number,
public source: Source,
public name: string,
public lineNumber: number,
public column: number
) {
this.scopes = null;
}
public getId(): string {
return `stackframe:${ this.threadId }:${ this.frameId }`;
}
public getScopes(debugService: debug.IDebugService): TPromise<debug.IScope[]> {
if (!this.scopes) {
this.scopes = debugService.getActiveSession().scopes({ frameId: this.frameId }).then(response => {
return response.body.scopes.map(rs => new Scope(this.threadId, rs.name, rs.variablesReference, rs.expensive, rs.indexedVariables));
}, err => []);
}
return this.scopes;
}
}
export class Breakpoint implements debug.IBreakpoint {
public lineNumber: number;
public verified: boolean;
public idFromAdapter: number;
public message: string;
private id: string;
constructor(
public source: Source,
public desiredLineNumber: number,
public enabled: boolean,
public condition: string
) {
if (enabled === undefined) {
this.enabled = true;
}
this.lineNumber = this.desiredLineNumber;
this.verified = false;
this.id = uuid.generateUuid();
}
public getId(): string {
return this.id;
}
}
export class FunctionBreakpoint implements debug.IFunctionBreakpoint {
private id: string;
public verified: boolean;
public idFromAdapter: number;
constructor(public name: string, public enabled: boolean) {
this.verified = false;
this.id = uuid.generateUuid();
}
public getId(): string {
return this.id;
}
}
export class ExceptionBreakpoint implements debug.IExceptionBreakpoint {
private id: string;
constructor(public filter: string, public label: string, public enabled: boolean) {
this.id = uuid.generateUuid();
}
public getId(): string {
return this.id;
}
}
export class Model implements debug.IModel {
private threads: { [reference: number]: debug.IThread; };
private toDispose: lifecycle.IDisposable[];
private replElements: debug.ITreeElement[];
private _onDidChangeBreakpoints: Emitter<void>;
private _onDidChangeCallStack: Emitter<void>;
private _onDidChangeWatchExpressions: Emitter<debug.IExpression>;
private _onDidChangeREPLElements: Emitter<void>;
constructor(
private breakpoints: debug.IBreakpoint[],
private breakpointsActivated: boolean,
private functionBreakpoints: debug.IFunctionBreakpoint[],
private exceptionBreakpoints: debug.IExceptionBreakpoint[],
private watchExpressions: Expression[]
) {
this.threads = {};
this.replElements = [];
this.toDispose = [];
this._onDidChangeBreakpoints = new Emitter<void>();
this._onDidChangeCallStack = new Emitter<void>();
this._onDidChangeWatchExpressions = new Emitter<debug.IExpression>();
this._onDidChangeREPLElements = new Emitter<void>();
}
public getId(): string {
return 'root';
}
public get onDidChangeBreakpoints(): Event<void> {
return this._onDidChangeBreakpoints.event;
}
public get onDidChangeCallStack(): Event<void> {
return this._onDidChangeCallStack.event;
}
public get onDidChangeWatchExpressions(): Event<debug.IExpression> {
return this._onDidChangeWatchExpressions.event;
}
public get onDidChangeReplElements(): Event<void> {
return this._onDidChangeREPLElements.event;
}
public getThreads(): { [reference: number]: debug.IThread; } {
return this.threads;
}
public clearThreads(removeThreads: boolean, reference: number = undefined): void {
if (reference) {
if (this.threads[reference]) {
this.threads[reference].clearCallStack();
this.threads[reference].stoppedDetails = undefined;
this.threads[reference].stopped = false;
if (removeThreads) {
delete this.threads[reference];
}
}
} else {
Object.keys(this.threads).forEach(ref => {
this.threads[ref].clearCallStack();
this.threads[ref].stoppedDetails = undefined;
this.threads[ref].stopped = false;
});
if (removeThreads) {
this.threads = {};
ExpressionContainer.allValues = {};
}
}
this._onDidChangeCallStack.fire();
}
public getBreakpoints(): debug.IBreakpoint[] {
return this.breakpoints;
}
public getFunctionBreakpoints(): debug.IFunctionBreakpoint[] {
return this.functionBreakpoints;
}
public getExceptionBreakpoints(): debug.IExceptionBreakpoint[] {
return this.exceptionBreakpoints;
}
public setExceptionBreakpoints(data: DebugProtocol.ExceptionBreakpointsFilter[]): void {
if (data) {
this.exceptionBreakpoints = data.map(d => {
const ebp = this.exceptionBreakpoints.filter(ebp => ebp.filter === d.filter).pop();
return new ExceptionBreakpoint(d.filter, d.label, ebp ? ebp.enabled : d.default);
});
}
}
public areBreakpointsActivated(): boolean {
return this.breakpointsActivated;
}
public setBreakpointsActivated(activated: boolean): void {
this.breakpointsActivated = activated;
this._onDidChangeBreakpoints.fire();
}
public addBreakpoints(rawData: debug.IRawBreakpoint[]): void {
this.breakpoints = this.breakpoints.concat(rawData.map(rawBp =>
new Breakpoint(new Source(Source.toRawSource(rawBp.uri, this)), rawBp.lineNumber, rawBp.enabled, rawBp.condition)));
this.breakpointsActivated = true;
this._onDidChangeBreakpoints.fire();
}
public removeBreakpoints(toRemove: debug.IBreakpoint[]): void {
this.breakpoints = this.breakpoints.filter(bp => !toRemove.some(toRemove => toRemove.getId() === bp.getId()));
this._onDidChangeBreakpoints.fire();
}
public updateBreakpoints(data: { [id: string]: DebugProtocol.Breakpoint }): void {
this.breakpoints.forEach(bp => {
const bpData = data[bp.getId()];
if (bpData) {
bp.lineNumber = bpData.line ? bpData.line : bp.lineNumber;
bp.verified = bpData.verified;
bp.idFromAdapter = bpData.id;
bp.message = bpData.message;
}
});
this._onDidChangeBreakpoints.fire();
}
public setEnablement(element: debug.IEnablement, enable: boolean): void {
element.enabled = enable;
if (element instanceof Breakpoint && !element.enabled) {
var breakpoint = <Breakpoint> element;
breakpoint.lineNumber = breakpoint.desiredLineNumber;
breakpoint.verified = false;
}
this._onDidChangeBreakpoints.fire();
}
public enableOrDisableAllBreakpoints(enable: boolean): void {
this.breakpoints.forEach(bp => {
bp.enabled = enable;
if (!enable) {
bp.lineNumber = bp.desiredLineNumber;
bp.verified = false;
}
});
this.exceptionBreakpoints.forEach(ebp => ebp.enabled = enable);
this.functionBreakpoints.forEach(fbp => fbp.enabled = enable);
this._onDidChangeBreakpoints.fire();
}
public addFunctionBreakpoint(functionName: string): void {
this.functionBreakpoints.push(new FunctionBreakpoint(functionName, true));
this._onDidChangeBreakpoints.fire();
}
public updateFunctionBreakpoints(data: { [id: string]: { name?: string, verified?: boolean; id?: number } }): void {
this.functionBreakpoints.forEach(fbp => {
const fbpData = data[fbp.getId()];
if (fbpData) {
fbp.name = fbpData.name || fbp.name;
fbp.verified = fbpData.verified;
fbp.idFromAdapter = fbpData.id;
}
});
this._onDidChangeBreakpoints.fire();
}
public removeFunctionBreakpoints(id?: string): void {
this.functionBreakpoints = id ? this.functionBreakpoints.filter(fbp => fbp.getId() !== id) : [];
this._onDidChangeBreakpoints.fire();
}
public getReplElements(): debug.ITreeElement[] {
return this.replElements;
}
public addReplExpression(session: debug.IRawDebugSession, stackFrame: debug.IStackFrame, name: string): TPromise<void> {
const expression = new Expression(name, true);
this.addReplElements([expression]);
return evaluateExpression(session, stackFrame, expression, 'repl')
.then(() => this._onDidChangeREPLElements.fire());
}
public logToRepl(value: string | { [key: string]: any }, severity?: severity): void {
let elements:OutputElement[] = [];
let previousOutput = this.replElements.length && (<ValueOutputElement>this.replElements[this.replElements.length - 1]);
// string message
if (typeof value === 'string') {
if (value && value.trim() && previousOutput && previousOutput.value === value && previousOutput.severity === severity) {
previousOutput.counter++; // we got the same output (but not an empty string when trimmed) so we just increment the counter
} else {
let lines = value.trim().split('\n');
lines.forEach((line, index) => {
elements.push(new ValueOutputElement(line, severity));
});
}
}
// key-value output
else {
elements.push(new KeyValueOutputElement((<any>value).prototype, value, nls.localize('snapshotObj', "Only primitive values are shown for this object.")));
}
if (elements.length) {
this.addReplElements(elements);
}
this._onDidChangeREPLElements.fire();
}
public appendReplOutput(value: string, severity?: severity): void {
const elements: OutputElement[] = [];
let previousOutput = this.replElements.length && (<ValueOutputElement>this.replElements[this.replElements.length - 1]);
let lines = value.split('\n');
let groupTogether = !!previousOutput && (previousOutput.category === 'output' && severity === previousOutput.severity);
if (groupTogether) {
// append to previous line if same group
previousOutput.value += lines.shift();
} else if (previousOutput && previousOutput.value === '') {
// remove potential empty lines between different output types
this.replElements.pop();
}
// fill in lines as output value elements
lines.forEach((line, index) => {
elements.push(new ValueOutputElement(line, severity, 'output'));
});
this.addReplElements(elements);
this._onDidChangeREPLElements.fire();
}
private addReplElements(newElements: debug.ITreeElement[]): void {
this.replElements.push(...newElements);
if (this.replElements.length > MAX_REPL_LENGTH) {
this.replElements.splice(0, this.replElements.length - MAX_REPL_LENGTH);
}
}
public removeReplExpressions(): void {
if (this.replElements.length > 0) {
this.replElements = [];
this._onDidChangeREPLElements.fire();
}
}
public getWatchExpressions(): Expression[] {
return this.watchExpressions;
}
public addWatchExpression(session: debug.IRawDebugSession, stackFrame: debug.IStackFrame, name: string): TPromise<void> {
const we = new Expression(name, false);
this.watchExpressions.push(we);
if (!name) {
this._onDidChangeWatchExpressions.fire(we);
return TPromise.as(null);
}
return this.evaluateWatchExpressions(session, stackFrame, we.getId());
}
public renameWatchExpression(session: debug.IRawDebugSession, stackFrame: debug.IStackFrame, id: string, newName: string): TPromise<void> {
const filtered = this.watchExpressions.filter(we => we.getId() === id);
if (filtered.length === 1) {
filtered[0].name = newName;
return evaluateExpression(session, stackFrame, filtered[0], 'watch').then(() => {
this._onDidChangeWatchExpressions.fire(filtered[0]);
});
}
return TPromise.as(null);
}
public evaluateWatchExpressions(session: debug.IRawDebugSession, stackFrame: debug.IStackFrame, id: string = null): TPromise<void> {
if (id) {
const filtered = this.watchExpressions.filter(we => we.getId() === id);
if (filtered.length !== 1) {
return TPromise.as(null);
}
return evaluateExpression(session, stackFrame, filtered[0], 'watch').then(() => {
this._onDidChangeWatchExpressions.fire(filtered[0]);
});
}
return TPromise.join(this.watchExpressions.map(we => evaluateExpression(session, stackFrame, we, 'watch'))).then(() => {
this._onDidChangeWatchExpressions.fire();
});
}
public clearWatchExpressionValues(): void {
this.watchExpressions.forEach(we => {
we.value = Expression.DEFAULT_VALUE;
we.available = false;
we.reference = 0;
});
this._onDidChangeWatchExpressions.fire();
}
public removeWatchExpressions(id: string = null): void {
this.watchExpressions = id ? this.watchExpressions.filter(we => we.getId() !== id) : [];
this._onDidChangeWatchExpressions.fire();
}
public sourceIsUnavailable(source: Source): void {
Object.keys(this.threads).forEach(key => {
if (this.threads[key].getCachedCallStack()) {
this.threads[key].getCachedCallStack().forEach(stackFrame => {
if (stackFrame.source.uri.toString() === source.uri.toString()) {
stackFrame.source.available = false;
}
});
}
});
this._onDidChangeCallStack.fire();
}
public rawUpdate(data: debug.IRawModelUpdate): void {
if (data.thread && !this.threads[data.threadId]) {
// A new thread came in, initialize it.
this.threads[data.threadId] = new Thread(data.thread.name, data.thread.id);
}
if (data.stoppedDetails) {
// Set the availability of the threads' callstacks depending on
// whether the thread is stopped or not
if (data.allThreadsStopped) {
Object.keys(this.threads).forEach(ref => {
// Only update the details if all the threads are stopped
// because we don't want to overwrite the details of other
// threads that have stopped for a different reason
this.threads[ref].stoppedDetails = objects.clone(data.stoppedDetails);
this.threads[ref].stopped = true;
this.threads[ref].clearCallStack();
});
} else {
// One thread is stopped, only update that thread.
this.threads[data.threadId].stoppedDetails = data.stoppedDetails;
this.threads[data.threadId].clearCallStack();
this.threads[data.threadId].stopped = true;
}
}
this._onDidChangeCallStack.fire();
}
public dispose(): void {
this.threads = null;
this.breakpoints = null;
this.exceptionBreakpoints = null;
this.functionBreakpoints = null;
this.watchExpressions = null;
this.replElements = null;
this.toDispose = lifecycle.dispose(this.toDispose);
}
}
| src/vs/workbench/parts/debug/common/debugModel.ts | 1 | https://github.com/microsoft/vscode/commit/3978edfa64c9a7b8a8ba823e3ab30767457dc5c6 | [
0.9990365505218506,
0.11402636766433716,
0.00016749423230066895,
0.00018921715673059225,
0.31144124269485474
] |
{
"id": 6,
"code_window": [
"\t// The adapter explicitly sents the children count of an expression only if there are lots of children which should be chunked.\n",
"\tprivate get getChildrenInChunks(): boolean {\n",
"\t\treturn !!this.childrenCount;\n",
"\t}\n",
"\n",
"\tpublic set value(value: string) {\n",
"\t\tthis._value = massageValue(value);\n",
"\t\tthis.valueChanged = ExpressionContainer.allValues[this.getId()] &&\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\treturn !!this.indexedVariables;\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debugModel.ts",
"type": "replace",
"edit_start_line_idx": 288
} | /*---------------------------------------------------------------------------------------------
* 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.
{
"editorCommands": "comandos del editor",
"entryAriaLabel": "{0}, ayuda del selector",
"globalCommands": "comandos globales"
} | i18n/esn/src/vs/workbench/parts/quickopen/browser/helpHandler.i18n.json | 0 | https://github.com/microsoft/vscode/commit/3978edfa64c9a7b8a8ba823e3ab30767457dc5c6 | [
0.0001769522059476003,
0.00017409311840310693,
0.00017123403085861355,
0.00017409311840310693,
0.000002859087544493377
] |
{
"id": 6,
"code_window": [
"\t// The adapter explicitly sents the children count of an expression only if there are lots of children which should be chunked.\n",
"\tprivate get getChildrenInChunks(): boolean {\n",
"\t\treturn !!this.childrenCount;\n",
"\t}\n",
"\n",
"\tpublic set value(value: string) {\n",
"\t\tthis._value = massageValue(value);\n",
"\t\tthis.valueChanged = ExpressionContainer.allValues[this.getId()] &&\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\treturn !!this.indexedVariables;\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debugModel.ts",
"type": "replace",
"edit_start_line_idx": 288
} | /*---------------------------------------------------------------------------------------------
* 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 {CommandsRegistry} from 'vs/platform/commands/common/commands';
suite('Command Tests', function () {
test('register command - no handler', function () {
assert.throws(() => CommandsRegistry.registerCommand('foo', null));
});
// test('register command - dupe', function () {
// CommandsRegistry.registerCommand('foo', () => { });
// assert.throws(() => CommandsRegistry.registerCommand('foo', () => { }));
// });
test('command with description', function() {
CommandsRegistry.registerCommand('test', function (accessor, args) {
assert.ok(typeof args === 'string');
});
CommandsRegistry.registerCommand('test2', function (accessor, args) {
assert.ok(typeof args === 'string');
});
CommandsRegistry.registerCommand('test3', {
handler: function (accessor, args) {
return true;
},
description: {
description: 'a command',
args: [{ name: 'value', constraint: Number }]
}
});
CommandsRegistry.getCommands()['test'].handler.apply(undefined, [undefined, 'string']);
CommandsRegistry.getCommands()['test2'].handler.apply(undefined, [undefined, 'string']);
assert.throws(() => CommandsRegistry.getCommands()['test3'].handler.apply(undefined, [undefined, 'string']));
assert.equal(CommandsRegistry.getCommands()['test3'].handler.apply(undefined, [undefined, 1]), true);
});
});
| src/vs/platform/commands/test/commands.test.ts | 0 | https://github.com/microsoft/vscode/commit/3978edfa64c9a7b8a8ba823e3ab30767457dc5c6 | [
0.00017730081162881106,
0.00017580973508302122,
0.00017421692609786987,
0.00017637055134400725,
0.0000011577681107155513
] |
{
"id": 6,
"code_window": [
"\t// The adapter explicitly sents the children count of an expression only if there are lots of children which should be chunked.\n",
"\tprivate get getChildrenInChunks(): boolean {\n",
"\t\treturn !!this.childrenCount;\n",
"\t}\n",
"\n",
"\tpublic set value(value: string) {\n",
"\t\tthis._value = massageValue(value);\n",
"\t\tthis.valueChanged = ExpressionContainer.allValues[this.getId()] &&\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\treturn !!this.indexedVariables;\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debugModel.ts",
"type": "replace",
"edit_start_line_idx": 288
} | /*---------------------------------------------------------------------------------------------
* 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.
{
"actions.clipboard.copyLabel": "Copia",
"actions.clipboard.cutLabel": "Taglia",
"actions.clipboard.pasteLabel": "Incolla"
} | i18n/ita/src/vs/editor/contrib/clipboard/browser/clipboard.i18n.json | 0 | https://github.com/microsoft/vscode/commit/3978edfa64c9a7b8a8ba823e3ab30767457dc5c6 | [
0.00017750632832758129,
0.00017437018686905503,
0.00017123403085861355,
0.00017437018686905503,
0.000003136148734483868
] |
{
"id": 7,
"code_window": [
"\n",
"\tpublic available: boolean;\n",
"\tpublic type: string;\n",
"\n",
"\tconstructor(public name: string, cacheChildren: boolean, id = uuid.generateUuid()) {\n",
"\t\tsuper(0, id, cacheChildren, 0);\n",
"\t\tthis.value = Expression.DEFAULT_VALUE;\n",
"\t\tthis.available = false;\n",
"\t}\n",
"}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tsuper(0, id, cacheChildren, 0, 0);\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debugModel.ts",
"type": "replace",
"edit_start_line_idx": 306
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { TPromise } from 'vs/base/common/winjs.base';
import nls = require('vs/nls');
import lifecycle = require('vs/base/common/lifecycle');
import Event, { Emitter } from 'vs/base/common/event';
import uuid = require('vs/base/common/uuid');
import objects = require('vs/base/common/objects');
import severity from 'vs/base/common/severity';
import types = require('vs/base/common/types');
import arrays = require('vs/base/common/arrays');
import debug = require('vs/workbench/parts/debug/common/debug');
import { Source } from 'vs/workbench/parts/debug/common/debugSource';
const MAX_REPL_LENGTH = 10000;
const UNKNOWN_SOURCE_LABEL = nls.localize('unknownSource', "Unknown Source");
function massageValue(value: string): string {
return value ? value.replace(/\n/g, '\\n').replace(/\r/g, '\\r').replace(/\t/g, '\\t') : value;
}
export function evaluateExpression(session: debug.IRawDebugSession, stackFrame: debug.IStackFrame, expression: Expression, context: string): TPromise<Expression> {
if (!session) {
expression.value = context === 'repl' ? nls.localize('startDebugFirst', "Please start a debug session to evaluate") : Expression.DEFAULT_VALUE;
expression.available = false;
expression.reference = 0;
return TPromise.as(expression);
}
return session.evaluate({
expression: expression.name,
frameId: stackFrame ? stackFrame.frameId : undefined,
context
}).then(response => {
expression.available = !!(response && response.body);
if (response.body) {
expression.value = response.body.result;
expression.reference = response.body.variablesReference;
expression.childrenCount = response.body.indexedVariables;
expression.type = response.body.type;
}
return expression;
}, err => {
expression.value = err.message;
expression.available = false;
expression.reference = 0;
return expression;
});
}
const notPropertySyntax = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
const arrayElementSyntax = /\[.*\]$/;
export function getFullExpressionName(expression: debug.IExpression, sessionType: string): string {
let names = [expression.name];
if (expression instanceof Variable) {
let v = (<Variable> expression).parent;
while (v instanceof Variable || v instanceof Expression) {
names.push((<Variable> v).name);
v = (<Variable> v).parent;
}
}
names = names.reverse();
let result = null;
names.forEach(name => {
if (!result) {
result = name;
} else if (arrayElementSyntax.test(name) || (sessionType === 'node' && !notPropertySyntax.test(name))) {
// use safe way to access node properties a['property_name']. Also handles array elements.
result = name && name.indexOf('[') === 0 ? `${ result }${ name }` : `${ result }['${ name }']`;
} else {
result = `${ result }.${ name }`;
}
});
return result;
}
export class Thread implements debug.IThread {
private promisedCallStack: TPromise<debug.IStackFrame[]>;
private cachedCallStack: debug.IStackFrame[];
public stoppedDetails: debug.IRawStoppedDetails;
public stopped: boolean;
constructor(public name: string, public threadId: number) {
this.promisedCallStack = undefined;
this.stoppedDetails = undefined;
this.cachedCallStack = undefined;
this.stopped = false;
}
public getId(): string {
return `thread:${ this.name }:${ this.threadId }`;
}
public clearCallStack(): void {
this.promisedCallStack = undefined;
this.cachedCallStack = undefined;
}
public getCachedCallStack(): debug.IStackFrame[] {
return this.cachedCallStack;
}
public getCallStack(debugService: debug.IDebugService, getAdditionalStackFrames = false): TPromise<debug.IStackFrame[]> {
if (!this.stopped) {
return TPromise.as([]);
}
if (!this.promisedCallStack) {
this.promisedCallStack = this.getCallStackImpl(debugService, 0).then(callStack => {
this.cachedCallStack = callStack;
return callStack;
});
} else if (getAdditionalStackFrames) {
this.promisedCallStack = this.promisedCallStack.then(callStackFirstPart => this.getCallStackImpl(debugService, callStackFirstPart.length).then(callStackSecondPart => {
this.cachedCallStack = callStackFirstPart.concat(callStackSecondPart);
return this.cachedCallStack;
}));
}
return this.promisedCallStack;
}
private getCallStackImpl(debugService: debug.IDebugService, startFrame: number): TPromise<debug.IStackFrame[]> {
let session = debugService.getActiveSession();
return session.stackTrace({ threadId: this.threadId, startFrame, levels: 20 }).then(response => {
this.stoppedDetails.totalFrames = response.body.totalFrames;
return response.body.stackFrames.map((rsf, level) => {
if (!rsf) {
return new StackFrame(this.threadId, 0, new Source({ name: UNKNOWN_SOURCE_LABEL }, false), nls.localize('unknownStack', "Unknown stack location"), undefined, undefined);
}
return new StackFrame(this.threadId, rsf.id, rsf.source ? new Source(rsf.source) : new Source({ name: UNKNOWN_SOURCE_LABEL }, false), rsf.name, rsf.line, rsf.column);
});
}, (err: Error) => {
this.stoppedDetails.framesErrorMessage = err.message;
return [];
});
}
}
export class OutputElement implements debug.ITreeElement {
private static ID_COUNTER = 0;
constructor(private id = OutputElement.ID_COUNTER++) {
// noop
}
public getId(): string {
return `outputelement:${ this.id }`;
}
}
export class ValueOutputElement extends OutputElement {
constructor(
public value: string,
public severity: severity,
public category?: string,
public counter: number = 1
) {
super();
}
}
export class KeyValueOutputElement extends OutputElement {
private static MAX_CHILDREN = 1000; // upper bound of children per value
private children: debug.ITreeElement[];
private _valueName: string;
constructor(public key: string, public valueObj: any, public annotation?: string) {
super();
this._valueName = null;
}
public get value(): string {
if (this._valueName === null) {
if (this.valueObj === null) {
this._valueName = 'null';
} else if (Array.isArray(this.valueObj)) {
this._valueName = `Array[${this.valueObj.length}]`;
} else if (types.isObject(this.valueObj)) {
this._valueName = 'Object';
} else if (types.isString(this.valueObj)) {
this._valueName = `"${massageValue(this.valueObj)}"`;
} else {
this._valueName = String(this.valueObj);
}
if (!this._valueName) {
this._valueName = '';
}
}
return this._valueName;
}
public getChildren(): debug.ITreeElement[] {
if (!this.children) {
if (Array.isArray(this.valueObj)) {
this.children = (<any[]>this.valueObj).slice(0, KeyValueOutputElement.MAX_CHILDREN).map((v, index) => new KeyValueOutputElement(String(index), v, null));
} else if (types.isObject(this.valueObj)) {
this.children = Object.getOwnPropertyNames(this.valueObj).slice(0, KeyValueOutputElement.MAX_CHILDREN).map(key => new KeyValueOutputElement(key, this.valueObj[key], null));
} else {
this.children = [];
}
}
return this.children;
}
}
export abstract class ExpressionContainer implements debug.IExpressionContainer {
public static allValues: { [id: string]: string } = {};
// Use chunks to support variable paging #9537
private static CHUNK_SIZE = 100;
public valueChanged: boolean;
private children: TPromise<debug.IExpression[]>;
private _value: string;
constructor(
public reference: number,
private id: string,
private cacheChildren: boolean,
public childrenCount: number,
private chunkIndex = 0
) {
// noop
}
public getChildren(debugService: debug.IDebugService): TPromise<debug.IExpression[]> {
if (!this.cacheChildren || !this.children) {
const session = debugService.getActiveSession();
// only variables with reference > 0 have children.
if (!session || this.reference <= 0) {
this.children = TPromise.as([]);
} else {
if (this.childrenCount > ExpressionContainer.CHUNK_SIZE) {
// There are a lot of children, create fake intermediate values that represent chunks #9537
const chunks = [];
const numberOfChunks = this.childrenCount / ExpressionContainer.CHUNK_SIZE;
for (let i = 0; i < numberOfChunks; i++) {
const chunkSize = (i < numberOfChunks - 1) ? ExpressionContainer.CHUNK_SIZE : this.childrenCount % ExpressionContainer.CHUNK_SIZE;
const chunkName = `${i * ExpressionContainer.CHUNK_SIZE}..${i * ExpressionContainer.CHUNK_SIZE + chunkSize - 1}`;
chunks.push(new Variable(this, this.reference, chunkName, '', chunkSize, null, true, i));
}
this.children = TPromise.as(chunks);
} else {
const start = this.getChildrenInChunks ? this.chunkIndex * ExpressionContainer.CHUNK_SIZE : undefined;
const count = this.getChildrenInChunks ? this.childrenCount : undefined;
this.children = session.variables({
variablesReference: this.reference,
start,
count
}).then(response => {
return arrays.distinct(response.body.variables.filter(v => !!v), v => v.name).map(
v => new Variable(this, v.variablesReference, v.name, v.value, v.indexedVariables, v.type)
);
}, (e: Error) => [new Variable(this, 0, null, e.message, 0, null, false)]);
}
}
}
return this.children;
}
public getId(): string {
return this.id;
}
public get value(): string {
return this._value;
}
// The adapter explicitly sents the children count of an expression only if there are lots of children which should be chunked.
private get getChildrenInChunks(): boolean {
return !!this.childrenCount;
}
public set value(value: string) {
this._value = massageValue(value);
this.valueChanged = ExpressionContainer.allValues[this.getId()] &&
ExpressionContainer.allValues[this.getId()] !== Expression.DEFAULT_VALUE && ExpressionContainer.allValues[this.getId()] !== value;
ExpressionContainer.allValues[this.getId()] = value;
}
}
export class Expression extends ExpressionContainer implements debug.IExpression {
static DEFAULT_VALUE = 'not available';
public available: boolean;
public type: string;
constructor(public name: string, cacheChildren: boolean, id = uuid.generateUuid()) {
super(0, id, cacheChildren, 0);
this.value = Expression.DEFAULT_VALUE;
this.available = false;
}
}
export class Variable extends ExpressionContainer implements debug.IExpression {
// Used to show the error message coming from the adapter when setting the value #7807
public errorMessage: string;
constructor(
public parent: debug.IExpressionContainer,
reference: number,
public name: string,
value: string,
childrenCount: number,
public type: string = null,
public available = true,
chunkIndex = 0
) {
super(reference, `variable:${ parent.getId() }:${ name }`, true, childrenCount, chunkIndex);
this.value = massageValue(value);
}
}
export class Scope extends ExpressionContainer implements debug.IScope {
constructor(
private threadId: number,
public name: string,
reference: number,
public expensive: boolean,
childrenCount: number
) {
super(reference, `scope:${threadId}:${name}:${reference}`, true, childrenCount);
}
}
export class StackFrame implements debug.IStackFrame {
private scopes: TPromise<Scope[]>;
constructor(
public threadId: number,
public frameId: number,
public source: Source,
public name: string,
public lineNumber: number,
public column: number
) {
this.scopes = null;
}
public getId(): string {
return `stackframe:${ this.threadId }:${ this.frameId }`;
}
public getScopes(debugService: debug.IDebugService): TPromise<debug.IScope[]> {
if (!this.scopes) {
this.scopes = debugService.getActiveSession().scopes({ frameId: this.frameId }).then(response => {
return response.body.scopes.map(rs => new Scope(this.threadId, rs.name, rs.variablesReference, rs.expensive, rs.indexedVariables));
}, err => []);
}
return this.scopes;
}
}
export class Breakpoint implements debug.IBreakpoint {
public lineNumber: number;
public verified: boolean;
public idFromAdapter: number;
public message: string;
private id: string;
constructor(
public source: Source,
public desiredLineNumber: number,
public enabled: boolean,
public condition: string
) {
if (enabled === undefined) {
this.enabled = true;
}
this.lineNumber = this.desiredLineNumber;
this.verified = false;
this.id = uuid.generateUuid();
}
public getId(): string {
return this.id;
}
}
export class FunctionBreakpoint implements debug.IFunctionBreakpoint {
private id: string;
public verified: boolean;
public idFromAdapter: number;
constructor(public name: string, public enabled: boolean) {
this.verified = false;
this.id = uuid.generateUuid();
}
public getId(): string {
return this.id;
}
}
export class ExceptionBreakpoint implements debug.IExceptionBreakpoint {
private id: string;
constructor(public filter: string, public label: string, public enabled: boolean) {
this.id = uuid.generateUuid();
}
public getId(): string {
return this.id;
}
}
export class Model implements debug.IModel {
private threads: { [reference: number]: debug.IThread; };
private toDispose: lifecycle.IDisposable[];
private replElements: debug.ITreeElement[];
private _onDidChangeBreakpoints: Emitter<void>;
private _onDidChangeCallStack: Emitter<void>;
private _onDidChangeWatchExpressions: Emitter<debug.IExpression>;
private _onDidChangeREPLElements: Emitter<void>;
constructor(
private breakpoints: debug.IBreakpoint[],
private breakpointsActivated: boolean,
private functionBreakpoints: debug.IFunctionBreakpoint[],
private exceptionBreakpoints: debug.IExceptionBreakpoint[],
private watchExpressions: Expression[]
) {
this.threads = {};
this.replElements = [];
this.toDispose = [];
this._onDidChangeBreakpoints = new Emitter<void>();
this._onDidChangeCallStack = new Emitter<void>();
this._onDidChangeWatchExpressions = new Emitter<debug.IExpression>();
this._onDidChangeREPLElements = new Emitter<void>();
}
public getId(): string {
return 'root';
}
public get onDidChangeBreakpoints(): Event<void> {
return this._onDidChangeBreakpoints.event;
}
public get onDidChangeCallStack(): Event<void> {
return this._onDidChangeCallStack.event;
}
public get onDidChangeWatchExpressions(): Event<debug.IExpression> {
return this._onDidChangeWatchExpressions.event;
}
public get onDidChangeReplElements(): Event<void> {
return this._onDidChangeREPLElements.event;
}
public getThreads(): { [reference: number]: debug.IThread; } {
return this.threads;
}
public clearThreads(removeThreads: boolean, reference: number = undefined): void {
if (reference) {
if (this.threads[reference]) {
this.threads[reference].clearCallStack();
this.threads[reference].stoppedDetails = undefined;
this.threads[reference].stopped = false;
if (removeThreads) {
delete this.threads[reference];
}
}
} else {
Object.keys(this.threads).forEach(ref => {
this.threads[ref].clearCallStack();
this.threads[ref].stoppedDetails = undefined;
this.threads[ref].stopped = false;
});
if (removeThreads) {
this.threads = {};
ExpressionContainer.allValues = {};
}
}
this._onDidChangeCallStack.fire();
}
public getBreakpoints(): debug.IBreakpoint[] {
return this.breakpoints;
}
public getFunctionBreakpoints(): debug.IFunctionBreakpoint[] {
return this.functionBreakpoints;
}
public getExceptionBreakpoints(): debug.IExceptionBreakpoint[] {
return this.exceptionBreakpoints;
}
public setExceptionBreakpoints(data: DebugProtocol.ExceptionBreakpointsFilter[]): void {
if (data) {
this.exceptionBreakpoints = data.map(d => {
const ebp = this.exceptionBreakpoints.filter(ebp => ebp.filter === d.filter).pop();
return new ExceptionBreakpoint(d.filter, d.label, ebp ? ebp.enabled : d.default);
});
}
}
public areBreakpointsActivated(): boolean {
return this.breakpointsActivated;
}
public setBreakpointsActivated(activated: boolean): void {
this.breakpointsActivated = activated;
this._onDidChangeBreakpoints.fire();
}
public addBreakpoints(rawData: debug.IRawBreakpoint[]): void {
this.breakpoints = this.breakpoints.concat(rawData.map(rawBp =>
new Breakpoint(new Source(Source.toRawSource(rawBp.uri, this)), rawBp.lineNumber, rawBp.enabled, rawBp.condition)));
this.breakpointsActivated = true;
this._onDidChangeBreakpoints.fire();
}
public removeBreakpoints(toRemove: debug.IBreakpoint[]): void {
this.breakpoints = this.breakpoints.filter(bp => !toRemove.some(toRemove => toRemove.getId() === bp.getId()));
this._onDidChangeBreakpoints.fire();
}
public updateBreakpoints(data: { [id: string]: DebugProtocol.Breakpoint }): void {
this.breakpoints.forEach(bp => {
const bpData = data[bp.getId()];
if (bpData) {
bp.lineNumber = bpData.line ? bpData.line : bp.lineNumber;
bp.verified = bpData.verified;
bp.idFromAdapter = bpData.id;
bp.message = bpData.message;
}
});
this._onDidChangeBreakpoints.fire();
}
public setEnablement(element: debug.IEnablement, enable: boolean): void {
element.enabled = enable;
if (element instanceof Breakpoint && !element.enabled) {
var breakpoint = <Breakpoint> element;
breakpoint.lineNumber = breakpoint.desiredLineNumber;
breakpoint.verified = false;
}
this._onDidChangeBreakpoints.fire();
}
public enableOrDisableAllBreakpoints(enable: boolean): void {
this.breakpoints.forEach(bp => {
bp.enabled = enable;
if (!enable) {
bp.lineNumber = bp.desiredLineNumber;
bp.verified = false;
}
});
this.exceptionBreakpoints.forEach(ebp => ebp.enabled = enable);
this.functionBreakpoints.forEach(fbp => fbp.enabled = enable);
this._onDidChangeBreakpoints.fire();
}
public addFunctionBreakpoint(functionName: string): void {
this.functionBreakpoints.push(new FunctionBreakpoint(functionName, true));
this._onDidChangeBreakpoints.fire();
}
public updateFunctionBreakpoints(data: { [id: string]: { name?: string, verified?: boolean; id?: number } }): void {
this.functionBreakpoints.forEach(fbp => {
const fbpData = data[fbp.getId()];
if (fbpData) {
fbp.name = fbpData.name || fbp.name;
fbp.verified = fbpData.verified;
fbp.idFromAdapter = fbpData.id;
}
});
this._onDidChangeBreakpoints.fire();
}
public removeFunctionBreakpoints(id?: string): void {
this.functionBreakpoints = id ? this.functionBreakpoints.filter(fbp => fbp.getId() !== id) : [];
this._onDidChangeBreakpoints.fire();
}
public getReplElements(): debug.ITreeElement[] {
return this.replElements;
}
public addReplExpression(session: debug.IRawDebugSession, stackFrame: debug.IStackFrame, name: string): TPromise<void> {
const expression = new Expression(name, true);
this.addReplElements([expression]);
return evaluateExpression(session, stackFrame, expression, 'repl')
.then(() => this._onDidChangeREPLElements.fire());
}
public logToRepl(value: string | { [key: string]: any }, severity?: severity): void {
let elements:OutputElement[] = [];
let previousOutput = this.replElements.length && (<ValueOutputElement>this.replElements[this.replElements.length - 1]);
// string message
if (typeof value === 'string') {
if (value && value.trim() && previousOutput && previousOutput.value === value && previousOutput.severity === severity) {
previousOutput.counter++; // we got the same output (but not an empty string when trimmed) so we just increment the counter
} else {
let lines = value.trim().split('\n');
lines.forEach((line, index) => {
elements.push(new ValueOutputElement(line, severity));
});
}
}
// key-value output
else {
elements.push(new KeyValueOutputElement((<any>value).prototype, value, nls.localize('snapshotObj', "Only primitive values are shown for this object.")));
}
if (elements.length) {
this.addReplElements(elements);
}
this._onDidChangeREPLElements.fire();
}
public appendReplOutput(value: string, severity?: severity): void {
const elements: OutputElement[] = [];
let previousOutput = this.replElements.length && (<ValueOutputElement>this.replElements[this.replElements.length - 1]);
let lines = value.split('\n');
let groupTogether = !!previousOutput && (previousOutput.category === 'output' && severity === previousOutput.severity);
if (groupTogether) {
// append to previous line if same group
previousOutput.value += lines.shift();
} else if (previousOutput && previousOutput.value === '') {
// remove potential empty lines between different output types
this.replElements.pop();
}
// fill in lines as output value elements
lines.forEach((line, index) => {
elements.push(new ValueOutputElement(line, severity, 'output'));
});
this.addReplElements(elements);
this._onDidChangeREPLElements.fire();
}
private addReplElements(newElements: debug.ITreeElement[]): void {
this.replElements.push(...newElements);
if (this.replElements.length > MAX_REPL_LENGTH) {
this.replElements.splice(0, this.replElements.length - MAX_REPL_LENGTH);
}
}
public removeReplExpressions(): void {
if (this.replElements.length > 0) {
this.replElements = [];
this._onDidChangeREPLElements.fire();
}
}
public getWatchExpressions(): Expression[] {
return this.watchExpressions;
}
public addWatchExpression(session: debug.IRawDebugSession, stackFrame: debug.IStackFrame, name: string): TPromise<void> {
const we = new Expression(name, false);
this.watchExpressions.push(we);
if (!name) {
this._onDidChangeWatchExpressions.fire(we);
return TPromise.as(null);
}
return this.evaluateWatchExpressions(session, stackFrame, we.getId());
}
public renameWatchExpression(session: debug.IRawDebugSession, stackFrame: debug.IStackFrame, id: string, newName: string): TPromise<void> {
const filtered = this.watchExpressions.filter(we => we.getId() === id);
if (filtered.length === 1) {
filtered[0].name = newName;
return evaluateExpression(session, stackFrame, filtered[0], 'watch').then(() => {
this._onDidChangeWatchExpressions.fire(filtered[0]);
});
}
return TPromise.as(null);
}
public evaluateWatchExpressions(session: debug.IRawDebugSession, stackFrame: debug.IStackFrame, id: string = null): TPromise<void> {
if (id) {
const filtered = this.watchExpressions.filter(we => we.getId() === id);
if (filtered.length !== 1) {
return TPromise.as(null);
}
return evaluateExpression(session, stackFrame, filtered[0], 'watch').then(() => {
this._onDidChangeWatchExpressions.fire(filtered[0]);
});
}
return TPromise.join(this.watchExpressions.map(we => evaluateExpression(session, stackFrame, we, 'watch'))).then(() => {
this._onDidChangeWatchExpressions.fire();
});
}
public clearWatchExpressionValues(): void {
this.watchExpressions.forEach(we => {
we.value = Expression.DEFAULT_VALUE;
we.available = false;
we.reference = 0;
});
this._onDidChangeWatchExpressions.fire();
}
public removeWatchExpressions(id: string = null): void {
this.watchExpressions = id ? this.watchExpressions.filter(we => we.getId() !== id) : [];
this._onDidChangeWatchExpressions.fire();
}
public sourceIsUnavailable(source: Source): void {
Object.keys(this.threads).forEach(key => {
if (this.threads[key].getCachedCallStack()) {
this.threads[key].getCachedCallStack().forEach(stackFrame => {
if (stackFrame.source.uri.toString() === source.uri.toString()) {
stackFrame.source.available = false;
}
});
}
});
this._onDidChangeCallStack.fire();
}
public rawUpdate(data: debug.IRawModelUpdate): void {
if (data.thread && !this.threads[data.threadId]) {
// A new thread came in, initialize it.
this.threads[data.threadId] = new Thread(data.thread.name, data.thread.id);
}
if (data.stoppedDetails) {
// Set the availability of the threads' callstacks depending on
// whether the thread is stopped or not
if (data.allThreadsStopped) {
Object.keys(this.threads).forEach(ref => {
// Only update the details if all the threads are stopped
// because we don't want to overwrite the details of other
// threads that have stopped for a different reason
this.threads[ref].stoppedDetails = objects.clone(data.stoppedDetails);
this.threads[ref].stopped = true;
this.threads[ref].clearCallStack();
});
} else {
// One thread is stopped, only update that thread.
this.threads[data.threadId].stoppedDetails = data.stoppedDetails;
this.threads[data.threadId].clearCallStack();
this.threads[data.threadId].stopped = true;
}
}
this._onDidChangeCallStack.fire();
}
public dispose(): void {
this.threads = null;
this.breakpoints = null;
this.exceptionBreakpoints = null;
this.functionBreakpoints = null;
this.watchExpressions = null;
this.replElements = null;
this.toDispose = lifecycle.dispose(this.toDispose);
}
}
| src/vs/workbench/parts/debug/common/debugModel.ts | 1 | https://github.com/microsoft/vscode/commit/3978edfa64c9a7b8a8ba823e3ab30767457dc5c6 | [
0.9978371262550354,
0.026259828358888626,
0.00016629909805487841,
0.00017395828035660088,
0.15467126667499542
] |
{
"id": 7,
"code_window": [
"\n",
"\tpublic available: boolean;\n",
"\tpublic type: string;\n",
"\n",
"\tconstructor(public name: string, cacheChildren: boolean, id = uuid.generateUuid()) {\n",
"\t\tsuper(0, id, cacheChildren, 0);\n",
"\t\tthis.value = Expression.DEFAULT_VALUE;\n",
"\t\tthis.available = false;\n",
"\t}\n",
"}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tsuper(0, id, cacheChildren, 0, 0);\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debugModel.ts",
"type": "replace",
"edit_start_line_idx": 306
} | /*---------------------------------------------------------------------------------------------
* 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 URI from 'vs/base/common/uri';
import {IKeybindingService, IKeybindingContextKey} from 'vs/platform/keybinding/common/keybinding';
import {IModeService} from 'vs/editor/common/services/modeService';
export class ResourceContextKey implements IKeybindingContextKey<URI> {
static Scheme = 'resourceScheme';
static LangId = 'resourceLangId';
static Resource = 'resource';
private _resourceKey: IKeybindingContextKey<URI>;
private _schemeKey: IKeybindingContextKey<string>;
private _langIdKey: IKeybindingContextKey<string>;
constructor(
@IKeybindingService keybindingService: IKeybindingService,
@IModeService private _modeService: IModeService
) {
this._schemeKey = keybindingService.createKey(ResourceContextKey.Scheme, undefined);
this._langIdKey = keybindingService.createKey(ResourceContextKey.LangId, undefined);
this._resourceKey = keybindingService.createKey(ResourceContextKey.Resource, undefined);
}
set(value: URI) {
this._resourceKey.set(value);
this._schemeKey.set(value && value.scheme);
this._langIdKey.set(value && this._modeService.getModeIdByFilenameOrFirstLine(value.fsPath));
}
reset(): void {
this._schemeKey.reset();
this._langIdKey.reset();
this._resourceKey.reset();
}
} | src/vs/platform/actions/common/resourceContextKey.ts | 0 | https://github.com/microsoft/vscode/commit/3978edfa64c9a7b8a8ba823e3ab30767457dc5c6 | [
0.00019942027574870735,
0.00017876908532343805,
0.00016710962518118322,
0.0001775813288986683,
0.000011086884114774875
] |
{
"id": 7,
"code_window": [
"\n",
"\tpublic available: boolean;\n",
"\tpublic type: string;\n",
"\n",
"\tconstructor(public name: string, cacheChildren: boolean, id = uuid.generateUuid()) {\n",
"\t\tsuper(0, id, cacheChildren, 0);\n",
"\t\tthis.value = Expression.DEFAULT_VALUE;\n",
"\t\tthis.available = false;\n",
"\t}\n",
"}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tsuper(0, id, cacheChildren, 0, 0);\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debugModel.ts",
"type": "replace",
"edit_start_line_idx": 306
} | // ATTENTION - THIS DIRECTORY CONTAINS THIRD PARTY OPEN SOURCE MATERIALS:
[{
"name": "textmate/xml.tmbundle",
"version": "0.0.0",
"license": "TextMate Bundle License",
"repositoryURL": "https://github.com/textmate/xml.tmbundle",
"licenseDetail": [
"Copyright (c) textmate-xml.tmbundle project authors",
"",
"If not otherwise specified (see below), files in this repository fall under the following license:",
"",
"Permission to copy, use, modify, sell and distribute this",
"software is granted. This software is provided \"as is\" without",
"express or implied warranty, and with no claim as to its",
"suitability for any purpose.",
"",
"An exception is made for files in readable text which contain their own license information,",
"or files where an accompanying file exists (in the same directory) with a \"-license\" suffix added",
"to the base-name name of the original file, and an extension of txt, html, or similar. For example",
"\"tidy\" is accompanied by \"tidy-license.txt\"."
]
}]
| extensions/xml/OSSREADME.json | 0 | https://github.com/microsoft/vscode/commit/3978edfa64c9a7b8a8ba823e3ab30767457dc5c6 | [
0.00017638687859289348,
0.00017473856860306114,
0.00017222092719748616,
0.00017560788546688855,
0.0000018084206203639042
] |
{
"id": 7,
"code_window": [
"\n",
"\tpublic available: boolean;\n",
"\tpublic type: string;\n",
"\n",
"\tconstructor(public name: string, cacheChildren: boolean, id = uuid.generateUuid()) {\n",
"\t\tsuper(0, id, cacheChildren, 0);\n",
"\t\tthis.value = Expression.DEFAULT_VALUE;\n",
"\t\tthis.available = false;\n",
"\t}\n",
"}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tsuper(0, id, cacheChildren, 0, 0);\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debugModel.ts",
"type": "replace",
"edit_start_line_idx": 306
} | /*---------------------------------------------------------------------------------------------
* 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.
{
"confirmOverwriteMessage": "目标文件夹中已存在“{0}”。是否要将其替换?",
"fileInputAriaLabel": "键入文件名。按 Enter 以确认或按 Esc 以取消。",
"filesExplorerViewerAriaLabel": "{0},文件资源管理器",
"irreversible": "此操作不可逆!",
"replaceButtonLabel": "替换(&&R)",
"warningFileDirty": "正在保存文件“{0}”,请稍后重试。"
} | i18n/chs/src/vs/workbench/parts/files/browser/views/explorerViewer.i18n.json | 0 | https://github.com/microsoft/vscode/commit/3978edfa64c9a7b8a8ba823e3ab30767457dc5c6 | [
0.00017477982328273356,
0.00017372622096445411,
0.00017267261864617467,
0.00017372622096445411,
0.0000010536023182794452
] |
{
"id": 8,
"code_window": [
"\tconstructor(\n",
"\t\tpublic parent: debug.IExpressionContainer,\n",
"\t\treference: number,\n",
"\t\tpublic name: string,\n",
"\t\tvalue: string,\n",
"\t\tchildrenCount: number,\n",
"\t\tpublic type: string = null,\n",
"\t\tpublic available = true,\n",
"\t\tchunkIndex = 0\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tnamedVariables: number,\n",
"\t\tindexedVariables: number,\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debugModel.ts",
"type": "replace",
"edit_start_line_idx": 322
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { TPromise } from 'vs/base/common/winjs.base';
import nls = require('vs/nls');
import lifecycle = require('vs/base/common/lifecycle');
import Event, { Emitter } from 'vs/base/common/event';
import uuid = require('vs/base/common/uuid');
import objects = require('vs/base/common/objects');
import severity from 'vs/base/common/severity';
import types = require('vs/base/common/types');
import arrays = require('vs/base/common/arrays');
import debug = require('vs/workbench/parts/debug/common/debug');
import { Source } from 'vs/workbench/parts/debug/common/debugSource';
const MAX_REPL_LENGTH = 10000;
const UNKNOWN_SOURCE_LABEL = nls.localize('unknownSource', "Unknown Source");
function massageValue(value: string): string {
return value ? value.replace(/\n/g, '\\n').replace(/\r/g, '\\r').replace(/\t/g, '\\t') : value;
}
export function evaluateExpression(session: debug.IRawDebugSession, stackFrame: debug.IStackFrame, expression: Expression, context: string): TPromise<Expression> {
if (!session) {
expression.value = context === 'repl' ? nls.localize('startDebugFirst', "Please start a debug session to evaluate") : Expression.DEFAULT_VALUE;
expression.available = false;
expression.reference = 0;
return TPromise.as(expression);
}
return session.evaluate({
expression: expression.name,
frameId: stackFrame ? stackFrame.frameId : undefined,
context
}).then(response => {
expression.available = !!(response && response.body);
if (response.body) {
expression.value = response.body.result;
expression.reference = response.body.variablesReference;
expression.childrenCount = response.body.indexedVariables;
expression.type = response.body.type;
}
return expression;
}, err => {
expression.value = err.message;
expression.available = false;
expression.reference = 0;
return expression;
});
}
const notPropertySyntax = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
const arrayElementSyntax = /\[.*\]$/;
export function getFullExpressionName(expression: debug.IExpression, sessionType: string): string {
let names = [expression.name];
if (expression instanceof Variable) {
let v = (<Variable> expression).parent;
while (v instanceof Variable || v instanceof Expression) {
names.push((<Variable> v).name);
v = (<Variable> v).parent;
}
}
names = names.reverse();
let result = null;
names.forEach(name => {
if (!result) {
result = name;
} else if (arrayElementSyntax.test(name) || (sessionType === 'node' && !notPropertySyntax.test(name))) {
// use safe way to access node properties a['property_name']. Also handles array elements.
result = name && name.indexOf('[') === 0 ? `${ result }${ name }` : `${ result }['${ name }']`;
} else {
result = `${ result }.${ name }`;
}
});
return result;
}
export class Thread implements debug.IThread {
private promisedCallStack: TPromise<debug.IStackFrame[]>;
private cachedCallStack: debug.IStackFrame[];
public stoppedDetails: debug.IRawStoppedDetails;
public stopped: boolean;
constructor(public name: string, public threadId: number) {
this.promisedCallStack = undefined;
this.stoppedDetails = undefined;
this.cachedCallStack = undefined;
this.stopped = false;
}
public getId(): string {
return `thread:${ this.name }:${ this.threadId }`;
}
public clearCallStack(): void {
this.promisedCallStack = undefined;
this.cachedCallStack = undefined;
}
public getCachedCallStack(): debug.IStackFrame[] {
return this.cachedCallStack;
}
public getCallStack(debugService: debug.IDebugService, getAdditionalStackFrames = false): TPromise<debug.IStackFrame[]> {
if (!this.stopped) {
return TPromise.as([]);
}
if (!this.promisedCallStack) {
this.promisedCallStack = this.getCallStackImpl(debugService, 0).then(callStack => {
this.cachedCallStack = callStack;
return callStack;
});
} else if (getAdditionalStackFrames) {
this.promisedCallStack = this.promisedCallStack.then(callStackFirstPart => this.getCallStackImpl(debugService, callStackFirstPart.length).then(callStackSecondPart => {
this.cachedCallStack = callStackFirstPart.concat(callStackSecondPart);
return this.cachedCallStack;
}));
}
return this.promisedCallStack;
}
private getCallStackImpl(debugService: debug.IDebugService, startFrame: number): TPromise<debug.IStackFrame[]> {
let session = debugService.getActiveSession();
return session.stackTrace({ threadId: this.threadId, startFrame, levels: 20 }).then(response => {
this.stoppedDetails.totalFrames = response.body.totalFrames;
return response.body.stackFrames.map((rsf, level) => {
if (!rsf) {
return new StackFrame(this.threadId, 0, new Source({ name: UNKNOWN_SOURCE_LABEL }, false), nls.localize('unknownStack', "Unknown stack location"), undefined, undefined);
}
return new StackFrame(this.threadId, rsf.id, rsf.source ? new Source(rsf.source) : new Source({ name: UNKNOWN_SOURCE_LABEL }, false), rsf.name, rsf.line, rsf.column);
});
}, (err: Error) => {
this.stoppedDetails.framesErrorMessage = err.message;
return [];
});
}
}
export class OutputElement implements debug.ITreeElement {
private static ID_COUNTER = 0;
constructor(private id = OutputElement.ID_COUNTER++) {
// noop
}
public getId(): string {
return `outputelement:${ this.id }`;
}
}
export class ValueOutputElement extends OutputElement {
constructor(
public value: string,
public severity: severity,
public category?: string,
public counter: number = 1
) {
super();
}
}
export class KeyValueOutputElement extends OutputElement {
private static MAX_CHILDREN = 1000; // upper bound of children per value
private children: debug.ITreeElement[];
private _valueName: string;
constructor(public key: string, public valueObj: any, public annotation?: string) {
super();
this._valueName = null;
}
public get value(): string {
if (this._valueName === null) {
if (this.valueObj === null) {
this._valueName = 'null';
} else if (Array.isArray(this.valueObj)) {
this._valueName = `Array[${this.valueObj.length}]`;
} else if (types.isObject(this.valueObj)) {
this._valueName = 'Object';
} else if (types.isString(this.valueObj)) {
this._valueName = `"${massageValue(this.valueObj)}"`;
} else {
this._valueName = String(this.valueObj);
}
if (!this._valueName) {
this._valueName = '';
}
}
return this._valueName;
}
public getChildren(): debug.ITreeElement[] {
if (!this.children) {
if (Array.isArray(this.valueObj)) {
this.children = (<any[]>this.valueObj).slice(0, KeyValueOutputElement.MAX_CHILDREN).map((v, index) => new KeyValueOutputElement(String(index), v, null));
} else if (types.isObject(this.valueObj)) {
this.children = Object.getOwnPropertyNames(this.valueObj).slice(0, KeyValueOutputElement.MAX_CHILDREN).map(key => new KeyValueOutputElement(key, this.valueObj[key], null));
} else {
this.children = [];
}
}
return this.children;
}
}
export abstract class ExpressionContainer implements debug.IExpressionContainer {
public static allValues: { [id: string]: string } = {};
// Use chunks to support variable paging #9537
private static CHUNK_SIZE = 100;
public valueChanged: boolean;
private children: TPromise<debug.IExpression[]>;
private _value: string;
constructor(
public reference: number,
private id: string,
private cacheChildren: boolean,
public childrenCount: number,
private chunkIndex = 0
) {
// noop
}
public getChildren(debugService: debug.IDebugService): TPromise<debug.IExpression[]> {
if (!this.cacheChildren || !this.children) {
const session = debugService.getActiveSession();
// only variables with reference > 0 have children.
if (!session || this.reference <= 0) {
this.children = TPromise.as([]);
} else {
if (this.childrenCount > ExpressionContainer.CHUNK_SIZE) {
// There are a lot of children, create fake intermediate values that represent chunks #9537
const chunks = [];
const numberOfChunks = this.childrenCount / ExpressionContainer.CHUNK_SIZE;
for (let i = 0; i < numberOfChunks; i++) {
const chunkSize = (i < numberOfChunks - 1) ? ExpressionContainer.CHUNK_SIZE : this.childrenCount % ExpressionContainer.CHUNK_SIZE;
const chunkName = `${i * ExpressionContainer.CHUNK_SIZE}..${i * ExpressionContainer.CHUNK_SIZE + chunkSize - 1}`;
chunks.push(new Variable(this, this.reference, chunkName, '', chunkSize, null, true, i));
}
this.children = TPromise.as(chunks);
} else {
const start = this.getChildrenInChunks ? this.chunkIndex * ExpressionContainer.CHUNK_SIZE : undefined;
const count = this.getChildrenInChunks ? this.childrenCount : undefined;
this.children = session.variables({
variablesReference: this.reference,
start,
count
}).then(response => {
return arrays.distinct(response.body.variables.filter(v => !!v), v => v.name).map(
v => new Variable(this, v.variablesReference, v.name, v.value, v.indexedVariables, v.type)
);
}, (e: Error) => [new Variable(this, 0, null, e.message, 0, null, false)]);
}
}
}
return this.children;
}
public getId(): string {
return this.id;
}
public get value(): string {
return this._value;
}
// The adapter explicitly sents the children count of an expression only if there are lots of children which should be chunked.
private get getChildrenInChunks(): boolean {
return !!this.childrenCount;
}
public set value(value: string) {
this._value = massageValue(value);
this.valueChanged = ExpressionContainer.allValues[this.getId()] &&
ExpressionContainer.allValues[this.getId()] !== Expression.DEFAULT_VALUE && ExpressionContainer.allValues[this.getId()] !== value;
ExpressionContainer.allValues[this.getId()] = value;
}
}
export class Expression extends ExpressionContainer implements debug.IExpression {
static DEFAULT_VALUE = 'not available';
public available: boolean;
public type: string;
constructor(public name: string, cacheChildren: boolean, id = uuid.generateUuid()) {
super(0, id, cacheChildren, 0);
this.value = Expression.DEFAULT_VALUE;
this.available = false;
}
}
export class Variable extends ExpressionContainer implements debug.IExpression {
// Used to show the error message coming from the adapter when setting the value #7807
public errorMessage: string;
constructor(
public parent: debug.IExpressionContainer,
reference: number,
public name: string,
value: string,
childrenCount: number,
public type: string = null,
public available = true,
chunkIndex = 0
) {
super(reference, `variable:${ parent.getId() }:${ name }`, true, childrenCount, chunkIndex);
this.value = massageValue(value);
}
}
export class Scope extends ExpressionContainer implements debug.IScope {
constructor(
private threadId: number,
public name: string,
reference: number,
public expensive: boolean,
childrenCount: number
) {
super(reference, `scope:${threadId}:${name}:${reference}`, true, childrenCount);
}
}
export class StackFrame implements debug.IStackFrame {
private scopes: TPromise<Scope[]>;
constructor(
public threadId: number,
public frameId: number,
public source: Source,
public name: string,
public lineNumber: number,
public column: number
) {
this.scopes = null;
}
public getId(): string {
return `stackframe:${ this.threadId }:${ this.frameId }`;
}
public getScopes(debugService: debug.IDebugService): TPromise<debug.IScope[]> {
if (!this.scopes) {
this.scopes = debugService.getActiveSession().scopes({ frameId: this.frameId }).then(response => {
return response.body.scopes.map(rs => new Scope(this.threadId, rs.name, rs.variablesReference, rs.expensive, rs.indexedVariables));
}, err => []);
}
return this.scopes;
}
}
export class Breakpoint implements debug.IBreakpoint {
public lineNumber: number;
public verified: boolean;
public idFromAdapter: number;
public message: string;
private id: string;
constructor(
public source: Source,
public desiredLineNumber: number,
public enabled: boolean,
public condition: string
) {
if (enabled === undefined) {
this.enabled = true;
}
this.lineNumber = this.desiredLineNumber;
this.verified = false;
this.id = uuid.generateUuid();
}
public getId(): string {
return this.id;
}
}
export class FunctionBreakpoint implements debug.IFunctionBreakpoint {
private id: string;
public verified: boolean;
public idFromAdapter: number;
constructor(public name: string, public enabled: boolean) {
this.verified = false;
this.id = uuid.generateUuid();
}
public getId(): string {
return this.id;
}
}
export class ExceptionBreakpoint implements debug.IExceptionBreakpoint {
private id: string;
constructor(public filter: string, public label: string, public enabled: boolean) {
this.id = uuid.generateUuid();
}
public getId(): string {
return this.id;
}
}
export class Model implements debug.IModel {
private threads: { [reference: number]: debug.IThread; };
private toDispose: lifecycle.IDisposable[];
private replElements: debug.ITreeElement[];
private _onDidChangeBreakpoints: Emitter<void>;
private _onDidChangeCallStack: Emitter<void>;
private _onDidChangeWatchExpressions: Emitter<debug.IExpression>;
private _onDidChangeREPLElements: Emitter<void>;
constructor(
private breakpoints: debug.IBreakpoint[],
private breakpointsActivated: boolean,
private functionBreakpoints: debug.IFunctionBreakpoint[],
private exceptionBreakpoints: debug.IExceptionBreakpoint[],
private watchExpressions: Expression[]
) {
this.threads = {};
this.replElements = [];
this.toDispose = [];
this._onDidChangeBreakpoints = new Emitter<void>();
this._onDidChangeCallStack = new Emitter<void>();
this._onDidChangeWatchExpressions = new Emitter<debug.IExpression>();
this._onDidChangeREPLElements = new Emitter<void>();
}
public getId(): string {
return 'root';
}
public get onDidChangeBreakpoints(): Event<void> {
return this._onDidChangeBreakpoints.event;
}
public get onDidChangeCallStack(): Event<void> {
return this._onDidChangeCallStack.event;
}
public get onDidChangeWatchExpressions(): Event<debug.IExpression> {
return this._onDidChangeWatchExpressions.event;
}
public get onDidChangeReplElements(): Event<void> {
return this._onDidChangeREPLElements.event;
}
public getThreads(): { [reference: number]: debug.IThread; } {
return this.threads;
}
public clearThreads(removeThreads: boolean, reference: number = undefined): void {
if (reference) {
if (this.threads[reference]) {
this.threads[reference].clearCallStack();
this.threads[reference].stoppedDetails = undefined;
this.threads[reference].stopped = false;
if (removeThreads) {
delete this.threads[reference];
}
}
} else {
Object.keys(this.threads).forEach(ref => {
this.threads[ref].clearCallStack();
this.threads[ref].stoppedDetails = undefined;
this.threads[ref].stopped = false;
});
if (removeThreads) {
this.threads = {};
ExpressionContainer.allValues = {};
}
}
this._onDidChangeCallStack.fire();
}
public getBreakpoints(): debug.IBreakpoint[] {
return this.breakpoints;
}
public getFunctionBreakpoints(): debug.IFunctionBreakpoint[] {
return this.functionBreakpoints;
}
public getExceptionBreakpoints(): debug.IExceptionBreakpoint[] {
return this.exceptionBreakpoints;
}
public setExceptionBreakpoints(data: DebugProtocol.ExceptionBreakpointsFilter[]): void {
if (data) {
this.exceptionBreakpoints = data.map(d => {
const ebp = this.exceptionBreakpoints.filter(ebp => ebp.filter === d.filter).pop();
return new ExceptionBreakpoint(d.filter, d.label, ebp ? ebp.enabled : d.default);
});
}
}
public areBreakpointsActivated(): boolean {
return this.breakpointsActivated;
}
public setBreakpointsActivated(activated: boolean): void {
this.breakpointsActivated = activated;
this._onDidChangeBreakpoints.fire();
}
public addBreakpoints(rawData: debug.IRawBreakpoint[]): void {
this.breakpoints = this.breakpoints.concat(rawData.map(rawBp =>
new Breakpoint(new Source(Source.toRawSource(rawBp.uri, this)), rawBp.lineNumber, rawBp.enabled, rawBp.condition)));
this.breakpointsActivated = true;
this._onDidChangeBreakpoints.fire();
}
public removeBreakpoints(toRemove: debug.IBreakpoint[]): void {
this.breakpoints = this.breakpoints.filter(bp => !toRemove.some(toRemove => toRemove.getId() === bp.getId()));
this._onDidChangeBreakpoints.fire();
}
public updateBreakpoints(data: { [id: string]: DebugProtocol.Breakpoint }): void {
this.breakpoints.forEach(bp => {
const bpData = data[bp.getId()];
if (bpData) {
bp.lineNumber = bpData.line ? bpData.line : bp.lineNumber;
bp.verified = bpData.verified;
bp.idFromAdapter = bpData.id;
bp.message = bpData.message;
}
});
this._onDidChangeBreakpoints.fire();
}
public setEnablement(element: debug.IEnablement, enable: boolean): void {
element.enabled = enable;
if (element instanceof Breakpoint && !element.enabled) {
var breakpoint = <Breakpoint> element;
breakpoint.lineNumber = breakpoint.desiredLineNumber;
breakpoint.verified = false;
}
this._onDidChangeBreakpoints.fire();
}
public enableOrDisableAllBreakpoints(enable: boolean): void {
this.breakpoints.forEach(bp => {
bp.enabled = enable;
if (!enable) {
bp.lineNumber = bp.desiredLineNumber;
bp.verified = false;
}
});
this.exceptionBreakpoints.forEach(ebp => ebp.enabled = enable);
this.functionBreakpoints.forEach(fbp => fbp.enabled = enable);
this._onDidChangeBreakpoints.fire();
}
public addFunctionBreakpoint(functionName: string): void {
this.functionBreakpoints.push(new FunctionBreakpoint(functionName, true));
this._onDidChangeBreakpoints.fire();
}
public updateFunctionBreakpoints(data: { [id: string]: { name?: string, verified?: boolean; id?: number } }): void {
this.functionBreakpoints.forEach(fbp => {
const fbpData = data[fbp.getId()];
if (fbpData) {
fbp.name = fbpData.name || fbp.name;
fbp.verified = fbpData.verified;
fbp.idFromAdapter = fbpData.id;
}
});
this._onDidChangeBreakpoints.fire();
}
public removeFunctionBreakpoints(id?: string): void {
this.functionBreakpoints = id ? this.functionBreakpoints.filter(fbp => fbp.getId() !== id) : [];
this._onDidChangeBreakpoints.fire();
}
public getReplElements(): debug.ITreeElement[] {
return this.replElements;
}
public addReplExpression(session: debug.IRawDebugSession, stackFrame: debug.IStackFrame, name: string): TPromise<void> {
const expression = new Expression(name, true);
this.addReplElements([expression]);
return evaluateExpression(session, stackFrame, expression, 'repl')
.then(() => this._onDidChangeREPLElements.fire());
}
public logToRepl(value: string | { [key: string]: any }, severity?: severity): void {
let elements:OutputElement[] = [];
let previousOutput = this.replElements.length && (<ValueOutputElement>this.replElements[this.replElements.length - 1]);
// string message
if (typeof value === 'string') {
if (value && value.trim() && previousOutput && previousOutput.value === value && previousOutput.severity === severity) {
previousOutput.counter++; // we got the same output (but not an empty string when trimmed) so we just increment the counter
} else {
let lines = value.trim().split('\n');
lines.forEach((line, index) => {
elements.push(new ValueOutputElement(line, severity));
});
}
}
// key-value output
else {
elements.push(new KeyValueOutputElement((<any>value).prototype, value, nls.localize('snapshotObj', "Only primitive values are shown for this object.")));
}
if (elements.length) {
this.addReplElements(elements);
}
this._onDidChangeREPLElements.fire();
}
public appendReplOutput(value: string, severity?: severity): void {
const elements: OutputElement[] = [];
let previousOutput = this.replElements.length && (<ValueOutputElement>this.replElements[this.replElements.length - 1]);
let lines = value.split('\n');
let groupTogether = !!previousOutput && (previousOutput.category === 'output' && severity === previousOutput.severity);
if (groupTogether) {
// append to previous line if same group
previousOutput.value += lines.shift();
} else if (previousOutput && previousOutput.value === '') {
// remove potential empty lines between different output types
this.replElements.pop();
}
// fill in lines as output value elements
lines.forEach((line, index) => {
elements.push(new ValueOutputElement(line, severity, 'output'));
});
this.addReplElements(elements);
this._onDidChangeREPLElements.fire();
}
private addReplElements(newElements: debug.ITreeElement[]): void {
this.replElements.push(...newElements);
if (this.replElements.length > MAX_REPL_LENGTH) {
this.replElements.splice(0, this.replElements.length - MAX_REPL_LENGTH);
}
}
public removeReplExpressions(): void {
if (this.replElements.length > 0) {
this.replElements = [];
this._onDidChangeREPLElements.fire();
}
}
public getWatchExpressions(): Expression[] {
return this.watchExpressions;
}
public addWatchExpression(session: debug.IRawDebugSession, stackFrame: debug.IStackFrame, name: string): TPromise<void> {
const we = new Expression(name, false);
this.watchExpressions.push(we);
if (!name) {
this._onDidChangeWatchExpressions.fire(we);
return TPromise.as(null);
}
return this.evaluateWatchExpressions(session, stackFrame, we.getId());
}
public renameWatchExpression(session: debug.IRawDebugSession, stackFrame: debug.IStackFrame, id: string, newName: string): TPromise<void> {
const filtered = this.watchExpressions.filter(we => we.getId() === id);
if (filtered.length === 1) {
filtered[0].name = newName;
return evaluateExpression(session, stackFrame, filtered[0], 'watch').then(() => {
this._onDidChangeWatchExpressions.fire(filtered[0]);
});
}
return TPromise.as(null);
}
public evaluateWatchExpressions(session: debug.IRawDebugSession, stackFrame: debug.IStackFrame, id: string = null): TPromise<void> {
if (id) {
const filtered = this.watchExpressions.filter(we => we.getId() === id);
if (filtered.length !== 1) {
return TPromise.as(null);
}
return evaluateExpression(session, stackFrame, filtered[0], 'watch').then(() => {
this._onDidChangeWatchExpressions.fire(filtered[0]);
});
}
return TPromise.join(this.watchExpressions.map(we => evaluateExpression(session, stackFrame, we, 'watch'))).then(() => {
this._onDidChangeWatchExpressions.fire();
});
}
public clearWatchExpressionValues(): void {
this.watchExpressions.forEach(we => {
we.value = Expression.DEFAULT_VALUE;
we.available = false;
we.reference = 0;
});
this._onDidChangeWatchExpressions.fire();
}
public removeWatchExpressions(id: string = null): void {
this.watchExpressions = id ? this.watchExpressions.filter(we => we.getId() !== id) : [];
this._onDidChangeWatchExpressions.fire();
}
public sourceIsUnavailable(source: Source): void {
Object.keys(this.threads).forEach(key => {
if (this.threads[key].getCachedCallStack()) {
this.threads[key].getCachedCallStack().forEach(stackFrame => {
if (stackFrame.source.uri.toString() === source.uri.toString()) {
stackFrame.source.available = false;
}
});
}
});
this._onDidChangeCallStack.fire();
}
public rawUpdate(data: debug.IRawModelUpdate): void {
if (data.thread && !this.threads[data.threadId]) {
// A new thread came in, initialize it.
this.threads[data.threadId] = new Thread(data.thread.name, data.thread.id);
}
if (data.stoppedDetails) {
// Set the availability of the threads' callstacks depending on
// whether the thread is stopped or not
if (data.allThreadsStopped) {
Object.keys(this.threads).forEach(ref => {
// Only update the details if all the threads are stopped
// because we don't want to overwrite the details of other
// threads that have stopped for a different reason
this.threads[ref].stoppedDetails = objects.clone(data.stoppedDetails);
this.threads[ref].stopped = true;
this.threads[ref].clearCallStack();
});
} else {
// One thread is stopped, only update that thread.
this.threads[data.threadId].stoppedDetails = data.stoppedDetails;
this.threads[data.threadId].clearCallStack();
this.threads[data.threadId].stopped = true;
}
}
this._onDidChangeCallStack.fire();
}
public dispose(): void {
this.threads = null;
this.breakpoints = null;
this.exceptionBreakpoints = null;
this.functionBreakpoints = null;
this.watchExpressions = null;
this.replElements = null;
this.toDispose = lifecycle.dispose(this.toDispose);
}
}
| src/vs/workbench/parts/debug/common/debugModel.ts | 1 | https://github.com/microsoft/vscode/commit/3978edfa64c9a7b8a8ba823e3ab30767457dc5c6 | [
0.006614436861127615,
0.0005851399037055671,
0.00016524655802641064,
0.000174014872754924,
0.001018207403831184
] |
{
"id": 8,
"code_window": [
"\tconstructor(\n",
"\t\tpublic parent: debug.IExpressionContainer,\n",
"\t\treference: number,\n",
"\t\tpublic name: string,\n",
"\t\tvalue: string,\n",
"\t\tchildrenCount: number,\n",
"\t\tpublic type: string = null,\n",
"\t\tpublic available = true,\n",
"\t\tchunkIndex = 0\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tnamedVariables: number,\n",
"\t\tindexedVariables: number,\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debugModel.ts",
"type": "replace",
"edit_start_line_idx": 322
} | /*---------------------------------------------------------------------------------------------
* 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.
{
"alertErrorMessage": "Errore: {0}",
"alertInfoMessage": "Info: {0}",
"alertWarningMessage": "Avviso: {0}"
} | i18n/ita/src/vs/base/browser/ui/inputbox/inputBox.i18n.json | 0 | https://github.com/microsoft/vscode/commit/3978edfa64c9a7b8a8ba823e3ab30767457dc5c6 | [
0.00017519078392069787,
0.00017479245434515178,
0.00017439411021769047,
0.00017479245434515178,
3.983368515037e-7
] |
{
"id": 8,
"code_window": [
"\tconstructor(\n",
"\t\tpublic parent: debug.IExpressionContainer,\n",
"\t\treference: number,\n",
"\t\tpublic name: string,\n",
"\t\tvalue: string,\n",
"\t\tchildrenCount: number,\n",
"\t\tpublic type: string = null,\n",
"\t\tpublic available = true,\n",
"\t\tchunkIndex = 0\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tnamedVariables: number,\n",
"\t\tindexedVariables: number,\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debugModel.ts",
"type": "replace",
"edit_start_line_idx": 322
} | /*---------------------------------------------------------------------------------------------
* 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 {onUnexpectedError} from 'vs/base/common/errors';
import { TPromise } from 'vs/base/common/winjs.base';
import { ExtensionHostMain, IInitData, exit } from 'vs/workbench/node/extensionHostMain';
import { Client, connect } from 'vs/base/parts/ipc/node/ipc.net';
import { create as createIPC, IMainProcessExtHostIPC } from 'vs/platform/extensions/common/ipcRemoteCom';
import marshalling = require('vs/base/common/marshalling');
interface IRendererConnection {
remoteCom: IMainProcessExtHostIPC;
initData: IInitData;
}
// This calls exit directly in case the initialization is not finished and we need to exit
// Otherwise, if initialization completed we go to extensionHostMain.terminate()
let onTerminate = function() {
exit();
};
function connectToRenderer(): TPromise<IRendererConnection> {
return new TPromise<IRendererConnection>((c, e) => {
const stats: number[] = [];
// Listen init data message
process.once('message', raw => {
let msg = marshalling.parse(raw);
const remoteCom = createIPC(data => {
process.send(data);
stats.push(data.length);
});
// Listen to all other messages
process.on('message', (msg) => {
if (msg.type === '__$terminate') {
onTerminate();
return;
}
remoteCom.handle(msg);
});
// Print a console message when rejection isn't handled within N seconds. For details:
// see https://nodejs.org/api/process.html#process_event_unhandledrejection
// and https://nodejs.org/api/process.html#process_event_rejectionhandled
const unhandledPromises: Promise<any>[] = [];
process.on('unhandledRejection', (reason, promise) => {
unhandledPromises.push(promise);
setTimeout(() => {
const idx = unhandledPromises.indexOf(promise);
if (idx >= 0) {
unhandledPromises.splice(idx, 1);
console.warn('rejected promise not handled with 1 second');
onUnexpectedError(reason);
}
}, 1000);
});
process.on('rejectionHandled', promise => {
const idx = unhandledPromises.indexOf(promise);
if (idx >= 0) {
unhandledPromises.splice(idx, 1);
}
});
// Print a console message when an exception isn't handled.
process.on('uncaughtException', function(err) {
onUnexpectedError(err);
});
// Kill oneself if one's parent dies. Much drama.
setInterval(function () {
try {
process.kill(msg.parentPid, 0); // throws an exception if the main process doesn't exist anymore.
} catch (e) {
onTerminate();
}
}, 5000);
// Check stats
setInterval(function() {
if (stats.length >= 250) {
let total = stats.reduce((prev, current) => prev + current, 0);
console.warn(`MANY messages are being SEND FROM the extension host!`);
console.warn(`SEND during 1sec: message_count=${stats.length}, total_len=${total}`);
}
stats.length = 0;
}, 1000);
// Tell the outside that we are initialized
process.send('initialized');
c({ remoteCom, initData: msg });
});
// Tell the outside that we are ready to receive messages
process.send('ready');
});
}
function connectToSharedProcess(): TPromise<Client> {
return connect(process.env['VSCODE_SHARED_IPC_HOOK']);
}
TPromise.join<any>([connectToRenderer(), connectToSharedProcess()])
.done(result => {
const renderer: IRendererConnection = result[0];
const sharedProcessClient: Client = result[1];
const extensionHostMain = new ExtensionHostMain(renderer.remoteCom, renderer.initData, sharedProcessClient);
onTerminate = () => {
extensionHostMain.terminate();
};
extensionHostMain.start()
.done(null, err => console.error(err));
}); | src/vs/workbench/node/extensionHostProcess.ts | 0 | https://github.com/microsoft/vscode/commit/3978edfa64c9a7b8a8ba823e3ab30767457dc5c6 | [
0.00022647171863354743,
0.00017340999329462647,
0.00016479195619467646,
0.00016894906002562493,
0.00001548417640151456
] |
{
"id": 8,
"code_window": [
"\tconstructor(\n",
"\t\tpublic parent: debug.IExpressionContainer,\n",
"\t\treference: number,\n",
"\t\tpublic name: string,\n",
"\t\tvalue: string,\n",
"\t\tchildrenCount: number,\n",
"\t\tpublic type: string = null,\n",
"\t\tpublic available = true,\n",
"\t\tchunkIndex = 0\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tnamedVariables: number,\n",
"\t\tindexedVariables: number,\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debugModel.ts",
"type": "replace",
"edit_start_line_idx": 322
} | /*---------------------------------------------------------------------------------------------
* 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 Platform = require('vs/base/common/platform');
import errors = require('vs/base/common/errors');
import precision = require('vs/base/common/stopwatch');
import {IDisposable} from 'vs/base/common/lifecycle';
export var ENABLE_TIMER = false;
var msWriteProfilerMark = Platform.globals['msWriteProfilerMark'];
export enum Topic {
EDITOR,
LANGUAGES,
WORKER,
WORKBENCH,
STARTUP
}
export interface ITimerEvent {
id: number;
topic: string;
name: string;
description: string;
data: any;
startTime: Date;
stopTime: Date;
stop(stopTime?: Date): void;
timeTaken(): number;
}
export interface IExistingTimerEvent {
topic: string;
name: string;
description?: string;
startTime: Date;
stopTime: Date;
}
class NullTimerEvent implements ITimerEvent {
public id: number;
public topic: string;
public name: string;
public description: string;
public data: any;
public startTime: Date;
public stopTime: Date;
public stop(): void {
return;
}
public timeTaken(): number {
return -1;
}
}
class TimerEvent implements ITimerEvent {
public id: number;
public topic: string;
public name: string;
public description: string;
public data: any;
public startTime: Date;
public stopTime: Date;
private timeKeeper: TimeKeeper;
private sw: precision.StopWatch;
constructor(timeKeeper: TimeKeeper, name: string, topic: string, startTime?: Date, description?: string) {
this.timeKeeper = timeKeeper;
this.name = name;
this.description = description;
this.topic = topic;
this.stopTime = null;
if (startTime) {
this.startTime = startTime;
return;
}
this.startTime = new Date();
this.sw = precision.StopWatch.create();
if (msWriteProfilerMark) {
var profilerName = ['Monaco', this.topic, this.name, 'start'];
msWriteProfilerMark(profilerName.join('|'));
}
}
public stop(stopTime?: Date): void {
// already stopped
if (this.stopTime !== null) {
return;
}
if (stopTime) {
this.stopTime = stopTime;
this.sw = null;
this.timeKeeper._onEventStopped(this);
return;
}
this.stopTime = new Date();
if (this.sw) {
this.sw.stop();
}
this.timeKeeper._onEventStopped(this);
if (msWriteProfilerMark) {
var profilerName = ['Monaco', this.topic, this.name, 'stop'];
msWriteProfilerMark(profilerName.join('|'));
}
}
public timeTaken(): number {
if (this.sw) {
return this.sw.elapsed();
}
if (this.stopTime) {
return this.stopTime.getTime() - this.startTime.getTime();
}
return -1;
}
}
export interface IEventsListener {
(events: ITimerEvent[]): void;
}
export class TimeKeeper {
/**
* After being started for 1 minute, all timers are automatically stopped.
*/
private static _MAX_TIMER_LENGTH = 60000; // 1 minute
/**
* Every 2 minutes, a sweep of current started timers is done.
*/
private static _CLEAN_UP_INTERVAL = 120000; // 2 minutes
/**
* Collect at most 1000 events.
*/
private static _EVENT_CACHE_LIMIT = 1000;
private static EVENT_ID = 1;
public static PARSE_TIME = new Date();
private cleaningIntervalId: Platform.IntervalToken;
private collectedEvents: ITimerEvent[];
private listeners: IEventsListener[];
constructor() {
this.cleaningIntervalId = -1;
this.collectedEvents = [];
this.listeners = [];
}
public isEnabled(): boolean {
return ENABLE_TIMER;
}
public start(topic: Topic|string, name: string, start?: Date, description?: string): ITimerEvent {
if (!this.isEnabled()) {
return nullEvent;
}
var strTopic: string;
if (typeof topic === 'string') {
strTopic = topic;
} else if (topic === Topic.EDITOR) {
strTopic = 'Editor';
} else if (topic === Topic.LANGUAGES) {
strTopic = 'Languages';
} else if (topic === Topic.WORKER) {
strTopic = 'Worker';
} else if (topic === Topic.WORKBENCH) {
strTopic = 'Workbench';
} else if (topic === Topic.STARTUP) {
strTopic = 'Startup';
}
this.initAutoCleaning();
var event = new TimerEvent(this, name, strTopic, start, description);
this.addEvent(event);
return event;
}
public dispose(): void {
if (this.cleaningIntervalId !== -1) {
Platform.clearInterval(this.cleaningIntervalId);
this.cleaningIntervalId = -1;
}
}
public addListener(listener: IEventsListener): IDisposable {
this.listeners.push(listener);
return {
dispose: () => {
for (var i = 0; i < this.listeners.length; i++) {
if (this.listeners[i] === listener) {
this.listeners.splice(i, 1);
return;
}
}
}
};
}
private addEvent(event: ITimerEvent): void {
event.id = TimeKeeper.EVENT_ID;
TimeKeeper.EVENT_ID++;
this.collectedEvents.push(event);
// expire items from the front of the cache
if (this.collectedEvents.length > TimeKeeper._EVENT_CACHE_LIMIT) {
this.collectedEvents.shift();
}
}
private initAutoCleaning(): void {
if (this.cleaningIntervalId === -1) {
this.cleaningIntervalId = Platform.setInterval(() => {
var now = Date.now();
this.collectedEvents.forEach((event) => {
if (!event.stopTime && (now - event.startTime.getTime()) >= TimeKeeper._MAX_TIMER_LENGTH) {
event.stop();
}
});
}, TimeKeeper._CLEAN_UP_INTERVAL);
}
}
public getCollectedEvents(): ITimerEvent[] {
return this.collectedEvents.slice(0);
}
public clearCollectedEvents(): void {
this.collectedEvents = [];
}
_onEventStopped(event: ITimerEvent): void {
var emitEvents = [event];
var listeners = this.listeners.slice(0);
for (var i = 0; i < listeners.length; i++) {
try {
listeners[i](emitEvents);
} catch (e) {
errors.onUnexpectedError(e);
}
}
}
public setInitialCollectedEvents(events: IExistingTimerEvent[], startTime?: Date): void {
if (!this.isEnabled()) {
return;
}
if (startTime) {
TimeKeeper.PARSE_TIME = startTime;
}
events.forEach((event) => {
var e = new TimerEvent(this, event.name, event.topic, event.startTime, event.description);
e.stop(event.stopTime);
this.addEvent(e);
});
}
}
var timeKeeper = new TimeKeeper();
export var nullEvent: ITimerEvent = new NullTimerEvent();
export function start(topic: Topic|string, name: string, start?: Date, description?: string): ITimerEvent {
return timeKeeper.start(topic, name, start, description);
}
export function getTimeKeeper(): TimeKeeper {
return timeKeeper;
}
| src/vs/base/common/timer.ts | 0 | https://github.com/microsoft/vscode/commit/3978edfa64c9a7b8a8ba823e3ab30767457dc5c6 | [
0.00037808495108038187,
0.00018595991423353553,
0.0001643768628127873,
0.00016979451174847782,
0.00004699803685070947
] |
{
"id": 9,
"code_window": [
"\t\tpublic type: string = null,\n",
"\t\tpublic available = true,\n",
"\t\tchunkIndex = 0\n",
"\t) {\n",
"\t\tsuper(reference, `variable:${ parent.getId() }:${ name }`, true, childrenCount, chunkIndex);\n",
"\t\tthis.value = massageValue(value);\n",
"\t}\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tsuper(reference, `variable:${ parent.getId() }:${ name }`, true, namedVariables, indexedVariables, chunkIndex);\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debugModel.ts",
"type": "replace",
"edit_start_line_idx": 327
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { TPromise } from 'vs/base/common/winjs.base';
import nls = require('vs/nls');
import lifecycle = require('vs/base/common/lifecycle');
import Event, { Emitter } from 'vs/base/common/event';
import uuid = require('vs/base/common/uuid');
import objects = require('vs/base/common/objects');
import severity from 'vs/base/common/severity';
import types = require('vs/base/common/types');
import arrays = require('vs/base/common/arrays');
import debug = require('vs/workbench/parts/debug/common/debug');
import { Source } from 'vs/workbench/parts/debug/common/debugSource';
const MAX_REPL_LENGTH = 10000;
const UNKNOWN_SOURCE_LABEL = nls.localize('unknownSource', "Unknown Source");
function massageValue(value: string): string {
return value ? value.replace(/\n/g, '\\n').replace(/\r/g, '\\r').replace(/\t/g, '\\t') : value;
}
export function evaluateExpression(session: debug.IRawDebugSession, stackFrame: debug.IStackFrame, expression: Expression, context: string): TPromise<Expression> {
if (!session) {
expression.value = context === 'repl' ? nls.localize('startDebugFirst', "Please start a debug session to evaluate") : Expression.DEFAULT_VALUE;
expression.available = false;
expression.reference = 0;
return TPromise.as(expression);
}
return session.evaluate({
expression: expression.name,
frameId: stackFrame ? stackFrame.frameId : undefined,
context
}).then(response => {
expression.available = !!(response && response.body);
if (response.body) {
expression.value = response.body.result;
expression.reference = response.body.variablesReference;
expression.childrenCount = response.body.indexedVariables;
expression.type = response.body.type;
}
return expression;
}, err => {
expression.value = err.message;
expression.available = false;
expression.reference = 0;
return expression;
});
}
const notPropertySyntax = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
const arrayElementSyntax = /\[.*\]$/;
export function getFullExpressionName(expression: debug.IExpression, sessionType: string): string {
let names = [expression.name];
if (expression instanceof Variable) {
let v = (<Variable> expression).parent;
while (v instanceof Variable || v instanceof Expression) {
names.push((<Variable> v).name);
v = (<Variable> v).parent;
}
}
names = names.reverse();
let result = null;
names.forEach(name => {
if (!result) {
result = name;
} else if (arrayElementSyntax.test(name) || (sessionType === 'node' && !notPropertySyntax.test(name))) {
// use safe way to access node properties a['property_name']. Also handles array elements.
result = name && name.indexOf('[') === 0 ? `${ result }${ name }` : `${ result }['${ name }']`;
} else {
result = `${ result }.${ name }`;
}
});
return result;
}
export class Thread implements debug.IThread {
private promisedCallStack: TPromise<debug.IStackFrame[]>;
private cachedCallStack: debug.IStackFrame[];
public stoppedDetails: debug.IRawStoppedDetails;
public stopped: boolean;
constructor(public name: string, public threadId: number) {
this.promisedCallStack = undefined;
this.stoppedDetails = undefined;
this.cachedCallStack = undefined;
this.stopped = false;
}
public getId(): string {
return `thread:${ this.name }:${ this.threadId }`;
}
public clearCallStack(): void {
this.promisedCallStack = undefined;
this.cachedCallStack = undefined;
}
public getCachedCallStack(): debug.IStackFrame[] {
return this.cachedCallStack;
}
public getCallStack(debugService: debug.IDebugService, getAdditionalStackFrames = false): TPromise<debug.IStackFrame[]> {
if (!this.stopped) {
return TPromise.as([]);
}
if (!this.promisedCallStack) {
this.promisedCallStack = this.getCallStackImpl(debugService, 0).then(callStack => {
this.cachedCallStack = callStack;
return callStack;
});
} else if (getAdditionalStackFrames) {
this.promisedCallStack = this.promisedCallStack.then(callStackFirstPart => this.getCallStackImpl(debugService, callStackFirstPart.length).then(callStackSecondPart => {
this.cachedCallStack = callStackFirstPart.concat(callStackSecondPart);
return this.cachedCallStack;
}));
}
return this.promisedCallStack;
}
private getCallStackImpl(debugService: debug.IDebugService, startFrame: number): TPromise<debug.IStackFrame[]> {
let session = debugService.getActiveSession();
return session.stackTrace({ threadId: this.threadId, startFrame, levels: 20 }).then(response => {
this.stoppedDetails.totalFrames = response.body.totalFrames;
return response.body.stackFrames.map((rsf, level) => {
if (!rsf) {
return new StackFrame(this.threadId, 0, new Source({ name: UNKNOWN_SOURCE_LABEL }, false), nls.localize('unknownStack', "Unknown stack location"), undefined, undefined);
}
return new StackFrame(this.threadId, rsf.id, rsf.source ? new Source(rsf.source) : new Source({ name: UNKNOWN_SOURCE_LABEL }, false), rsf.name, rsf.line, rsf.column);
});
}, (err: Error) => {
this.stoppedDetails.framesErrorMessage = err.message;
return [];
});
}
}
export class OutputElement implements debug.ITreeElement {
private static ID_COUNTER = 0;
constructor(private id = OutputElement.ID_COUNTER++) {
// noop
}
public getId(): string {
return `outputelement:${ this.id }`;
}
}
export class ValueOutputElement extends OutputElement {
constructor(
public value: string,
public severity: severity,
public category?: string,
public counter: number = 1
) {
super();
}
}
export class KeyValueOutputElement extends OutputElement {
private static MAX_CHILDREN = 1000; // upper bound of children per value
private children: debug.ITreeElement[];
private _valueName: string;
constructor(public key: string, public valueObj: any, public annotation?: string) {
super();
this._valueName = null;
}
public get value(): string {
if (this._valueName === null) {
if (this.valueObj === null) {
this._valueName = 'null';
} else if (Array.isArray(this.valueObj)) {
this._valueName = `Array[${this.valueObj.length}]`;
} else if (types.isObject(this.valueObj)) {
this._valueName = 'Object';
} else if (types.isString(this.valueObj)) {
this._valueName = `"${massageValue(this.valueObj)}"`;
} else {
this._valueName = String(this.valueObj);
}
if (!this._valueName) {
this._valueName = '';
}
}
return this._valueName;
}
public getChildren(): debug.ITreeElement[] {
if (!this.children) {
if (Array.isArray(this.valueObj)) {
this.children = (<any[]>this.valueObj).slice(0, KeyValueOutputElement.MAX_CHILDREN).map((v, index) => new KeyValueOutputElement(String(index), v, null));
} else if (types.isObject(this.valueObj)) {
this.children = Object.getOwnPropertyNames(this.valueObj).slice(0, KeyValueOutputElement.MAX_CHILDREN).map(key => new KeyValueOutputElement(key, this.valueObj[key], null));
} else {
this.children = [];
}
}
return this.children;
}
}
export abstract class ExpressionContainer implements debug.IExpressionContainer {
public static allValues: { [id: string]: string } = {};
// Use chunks to support variable paging #9537
private static CHUNK_SIZE = 100;
public valueChanged: boolean;
private children: TPromise<debug.IExpression[]>;
private _value: string;
constructor(
public reference: number,
private id: string,
private cacheChildren: boolean,
public childrenCount: number,
private chunkIndex = 0
) {
// noop
}
public getChildren(debugService: debug.IDebugService): TPromise<debug.IExpression[]> {
if (!this.cacheChildren || !this.children) {
const session = debugService.getActiveSession();
// only variables with reference > 0 have children.
if (!session || this.reference <= 0) {
this.children = TPromise.as([]);
} else {
if (this.childrenCount > ExpressionContainer.CHUNK_SIZE) {
// There are a lot of children, create fake intermediate values that represent chunks #9537
const chunks = [];
const numberOfChunks = this.childrenCount / ExpressionContainer.CHUNK_SIZE;
for (let i = 0; i < numberOfChunks; i++) {
const chunkSize = (i < numberOfChunks - 1) ? ExpressionContainer.CHUNK_SIZE : this.childrenCount % ExpressionContainer.CHUNK_SIZE;
const chunkName = `${i * ExpressionContainer.CHUNK_SIZE}..${i * ExpressionContainer.CHUNK_SIZE + chunkSize - 1}`;
chunks.push(new Variable(this, this.reference, chunkName, '', chunkSize, null, true, i));
}
this.children = TPromise.as(chunks);
} else {
const start = this.getChildrenInChunks ? this.chunkIndex * ExpressionContainer.CHUNK_SIZE : undefined;
const count = this.getChildrenInChunks ? this.childrenCount : undefined;
this.children = session.variables({
variablesReference: this.reference,
start,
count
}).then(response => {
return arrays.distinct(response.body.variables.filter(v => !!v), v => v.name).map(
v => new Variable(this, v.variablesReference, v.name, v.value, v.indexedVariables, v.type)
);
}, (e: Error) => [new Variable(this, 0, null, e.message, 0, null, false)]);
}
}
}
return this.children;
}
public getId(): string {
return this.id;
}
public get value(): string {
return this._value;
}
// The adapter explicitly sents the children count of an expression only if there are lots of children which should be chunked.
private get getChildrenInChunks(): boolean {
return !!this.childrenCount;
}
public set value(value: string) {
this._value = massageValue(value);
this.valueChanged = ExpressionContainer.allValues[this.getId()] &&
ExpressionContainer.allValues[this.getId()] !== Expression.DEFAULT_VALUE && ExpressionContainer.allValues[this.getId()] !== value;
ExpressionContainer.allValues[this.getId()] = value;
}
}
export class Expression extends ExpressionContainer implements debug.IExpression {
static DEFAULT_VALUE = 'not available';
public available: boolean;
public type: string;
constructor(public name: string, cacheChildren: boolean, id = uuid.generateUuid()) {
super(0, id, cacheChildren, 0);
this.value = Expression.DEFAULT_VALUE;
this.available = false;
}
}
export class Variable extends ExpressionContainer implements debug.IExpression {
// Used to show the error message coming from the adapter when setting the value #7807
public errorMessage: string;
constructor(
public parent: debug.IExpressionContainer,
reference: number,
public name: string,
value: string,
childrenCount: number,
public type: string = null,
public available = true,
chunkIndex = 0
) {
super(reference, `variable:${ parent.getId() }:${ name }`, true, childrenCount, chunkIndex);
this.value = massageValue(value);
}
}
export class Scope extends ExpressionContainer implements debug.IScope {
constructor(
private threadId: number,
public name: string,
reference: number,
public expensive: boolean,
childrenCount: number
) {
super(reference, `scope:${threadId}:${name}:${reference}`, true, childrenCount);
}
}
export class StackFrame implements debug.IStackFrame {
private scopes: TPromise<Scope[]>;
constructor(
public threadId: number,
public frameId: number,
public source: Source,
public name: string,
public lineNumber: number,
public column: number
) {
this.scopes = null;
}
public getId(): string {
return `stackframe:${ this.threadId }:${ this.frameId }`;
}
public getScopes(debugService: debug.IDebugService): TPromise<debug.IScope[]> {
if (!this.scopes) {
this.scopes = debugService.getActiveSession().scopes({ frameId: this.frameId }).then(response => {
return response.body.scopes.map(rs => new Scope(this.threadId, rs.name, rs.variablesReference, rs.expensive, rs.indexedVariables));
}, err => []);
}
return this.scopes;
}
}
export class Breakpoint implements debug.IBreakpoint {
public lineNumber: number;
public verified: boolean;
public idFromAdapter: number;
public message: string;
private id: string;
constructor(
public source: Source,
public desiredLineNumber: number,
public enabled: boolean,
public condition: string
) {
if (enabled === undefined) {
this.enabled = true;
}
this.lineNumber = this.desiredLineNumber;
this.verified = false;
this.id = uuid.generateUuid();
}
public getId(): string {
return this.id;
}
}
export class FunctionBreakpoint implements debug.IFunctionBreakpoint {
private id: string;
public verified: boolean;
public idFromAdapter: number;
constructor(public name: string, public enabled: boolean) {
this.verified = false;
this.id = uuid.generateUuid();
}
public getId(): string {
return this.id;
}
}
export class ExceptionBreakpoint implements debug.IExceptionBreakpoint {
private id: string;
constructor(public filter: string, public label: string, public enabled: boolean) {
this.id = uuid.generateUuid();
}
public getId(): string {
return this.id;
}
}
export class Model implements debug.IModel {
private threads: { [reference: number]: debug.IThread; };
private toDispose: lifecycle.IDisposable[];
private replElements: debug.ITreeElement[];
private _onDidChangeBreakpoints: Emitter<void>;
private _onDidChangeCallStack: Emitter<void>;
private _onDidChangeWatchExpressions: Emitter<debug.IExpression>;
private _onDidChangeREPLElements: Emitter<void>;
constructor(
private breakpoints: debug.IBreakpoint[],
private breakpointsActivated: boolean,
private functionBreakpoints: debug.IFunctionBreakpoint[],
private exceptionBreakpoints: debug.IExceptionBreakpoint[],
private watchExpressions: Expression[]
) {
this.threads = {};
this.replElements = [];
this.toDispose = [];
this._onDidChangeBreakpoints = new Emitter<void>();
this._onDidChangeCallStack = new Emitter<void>();
this._onDidChangeWatchExpressions = new Emitter<debug.IExpression>();
this._onDidChangeREPLElements = new Emitter<void>();
}
public getId(): string {
return 'root';
}
public get onDidChangeBreakpoints(): Event<void> {
return this._onDidChangeBreakpoints.event;
}
public get onDidChangeCallStack(): Event<void> {
return this._onDidChangeCallStack.event;
}
public get onDidChangeWatchExpressions(): Event<debug.IExpression> {
return this._onDidChangeWatchExpressions.event;
}
public get onDidChangeReplElements(): Event<void> {
return this._onDidChangeREPLElements.event;
}
public getThreads(): { [reference: number]: debug.IThread; } {
return this.threads;
}
public clearThreads(removeThreads: boolean, reference: number = undefined): void {
if (reference) {
if (this.threads[reference]) {
this.threads[reference].clearCallStack();
this.threads[reference].stoppedDetails = undefined;
this.threads[reference].stopped = false;
if (removeThreads) {
delete this.threads[reference];
}
}
} else {
Object.keys(this.threads).forEach(ref => {
this.threads[ref].clearCallStack();
this.threads[ref].stoppedDetails = undefined;
this.threads[ref].stopped = false;
});
if (removeThreads) {
this.threads = {};
ExpressionContainer.allValues = {};
}
}
this._onDidChangeCallStack.fire();
}
public getBreakpoints(): debug.IBreakpoint[] {
return this.breakpoints;
}
public getFunctionBreakpoints(): debug.IFunctionBreakpoint[] {
return this.functionBreakpoints;
}
public getExceptionBreakpoints(): debug.IExceptionBreakpoint[] {
return this.exceptionBreakpoints;
}
public setExceptionBreakpoints(data: DebugProtocol.ExceptionBreakpointsFilter[]): void {
if (data) {
this.exceptionBreakpoints = data.map(d => {
const ebp = this.exceptionBreakpoints.filter(ebp => ebp.filter === d.filter).pop();
return new ExceptionBreakpoint(d.filter, d.label, ebp ? ebp.enabled : d.default);
});
}
}
public areBreakpointsActivated(): boolean {
return this.breakpointsActivated;
}
public setBreakpointsActivated(activated: boolean): void {
this.breakpointsActivated = activated;
this._onDidChangeBreakpoints.fire();
}
public addBreakpoints(rawData: debug.IRawBreakpoint[]): void {
this.breakpoints = this.breakpoints.concat(rawData.map(rawBp =>
new Breakpoint(new Source(Source.toRawSource(rawBp.uri, this)), rawBp.lineNumber, rawBp.enabled, rawBp.condition)));
this.breakpointsActivated = true;
this._onDidChangeBreakpoints.fire();
}
public removeBreakpoints(toRemove: debug.IBreakpoint[]): void {
this.breakpoints = this.breakpoints.filter(bp => !toRemove.some(toRemove => toRemove.getId() === bp.getId()));
this._onDidChangeBreakpoints.fire();
}
public updateBreakpoints(data: { [id: string]: DebugProtocol.Breakpoint }): void {
this.breakpoints.forEach(bp => {
const bpData = data[bp.getId()];
if (bpData) {
bp.lineNumber = bpData.line ? bpData.line : bp.lineNumber;
bp.verified = bpData.verified;
bp.idFromAdapter = bpData.id;
bp.message = bpData.message;
}
});
this._onDidChangeBreakpoints.fire();
}
public setEnablement(element: debug.IEnablement, enable: boolean): void {
element.enabled = enable;
if (element instanceof Breakpoint && !element.enabled) {
var breakpoint = <Breakpoint> element;
breakpoint.lineNumber = breakpoint.desiredLineNumber;
breakpoint.verified = false;
}
this._onDidChangeBreakpoints.fire();
}
public enableOrDisableAllBreakpoints(enable: boolean): void {
this.breakpoints.forEach(bp => {
bp.enabled = enable;
if (!enable) {
bp.lineNumber = bp.desiredLineNumber;
bp.verified = false;
}
});
this.exceptionBreakpoints.forEach(ebp => ebp.enabled = enable);
this.functionBreakpoints.forEach(fbp => fbp.enabled = enable);
this._onDidChangeBreakpoints.fire();
}
public addFunctionBreakpoint(functionName: string): void {
this.functionBreakpoints.push(new FunctionBreakpoint(functionName, true));
this._onDidChangeBreakpoints.fire();
}
public updateFunctionBreakpoints(data: { [id: string]: { name?: string, verified?: boolean; id?: number } }): void {
this.functionBreakpoints.forEach(fbp => {
const fbpData = data[fbp.getId()];
if (fbpData) {
fbp.name = fbpData.name || fbp.name;
fbp.verified = fbpData.verified;
fbp.idFromAdapter = fbpData.id;
}
});
this._onDidChangeBreakpoints.fire();
}
public removeFunctionBreakpoints(id?: string): void {
this.functionBreakpoints = id ? this.functionBreakpoints.filter(fbp => fbp.getId() !== id) : [];
this._onDidChangeBreakpoints.fire();
}
public getReplElements(): debug.ITreeElement[] {
return this.replElements;
}
public addReplExpression(session: debug.IRawDebugSession, stackFrame: debug.IStackFrame, name: string): TPromise<void> {
const expression = new Expression(name, true);
this.addReplElements([expression]);
return evaluateExpression(session, stackFrame, expression, 'repl')
.then(() => this._onDidChangeREPLElements.fire());
}
public logToRepl(value: string | { [key: string]: any }, severity?: severity): void {
let elements:OutputElement[] = [];
let previousOutput = this.replElements.length && (<ValueOutputElement>this.replElements[this.replElements.length - 1]);
// string message
if (typeof value === 'string') {
if (value && value.trim() && previousOutput && previousOutput.value === value && previousOutput.severity === severity) {
previousOutput.counter++; // we got the same output (but not an empty string when trimmed) so we just increment the counter
} else {
let lines = value.trim().split('\n');
lines.forEach((line, index) => {
elements.push(new ValueOutputElement(line, severity));
});
}
}
// key-value output
else {
elements.push(new KeyValueOutputElement((<any>value).prototype, value, nls.localize('snapshotObj', "Only primitive values are shown for this object.")));
}
if (elements.length) {
this.addReplElements(elements);
}
this._onDidChangeREPLElements.fire();
}
public appendReplOutput(value: string, severity?: severity): void {
const elements: OutputElement[] = [];
let previousOutput = this.replElements.length && (<ValueOutputElement>this.replElements[this.replElements.length - 1]);
let lines = value.split('\n');
let groupTogether = !!previousOutput && (previousOutput.category === 'output' && severity === previousOutput.severity);
if (groupTogether) {
// append to previous line if same group
previousOutput.value += lines.shift();
} else if (previousOutput && previousOutput.value === '') {
// remove potential empty lines between different output types
this.replElements.pop();
}
// fill in lines as output value elements
lines.forEach((line, index) => {
elements.push(new ValueOutputElement(line, severity, 'output'));
});
this.addReplElements(elements);
this._onDidChangeREPLElements.fire();
}
private addReplElements(newElements: debug.ITreeElement[]): void {
this.replElements.push(...newElements);
if (this.replElements.length > MAX_REPL_LENGTH) {
this.replElements.splice(0, this.replElements.length - MAX_REPL_LENGTH);
}
}
public removeReplExpressions(): void {
if (this.replElements.length > 0) {
this.replElements = [];
this._onDidChangeREPLElements.fire();
}
}
public getWatchExpressions(): Expression[] {
return this.watchExpressions;
}
public addWatchExpression(session: debug.IRawDebugSession, stackFrame: debug.IStackFrame, name: string): TPromise<void> {
const we = new Expression(name, false);
this.watchExpressions.push(we);
if (!name) {
this._onDidChangeWatchExpressions.fire(we);
return TPromise.as(null);
}
return this.evaluateWatchExpressions(session, stackFrame, we.getId());
}
public renameWatchExpression(session: debug.IRawDebugSession, stackFrame: debug.IStackFrame, id: string, newName: string): TPromise<void> {
const filtered = this.watchExpressions.filter(we => we.getId() === id);
if (filtered.length === 1) {
filtered[0].name = newName;
return evaluateExpression(session, stackFrame, filtered[0], 'watch').then(() => {
this._onDidChangeWatchExpressions.fire(filtered[0]);
});
}
return TPromise.as(null);
}
public evaluateWatchExpressions(session: debug.IRawDebugSession, stackFrame: debug.IStackFrame, id: string = null): TPromise<void> {
if (id) {
const filtered = this.watchExpressions.filter(we => we.getId() === id);
if (filtered.length !== 1) {
return TPromise.as(null);
}
return evaluateExpression(session, stackFrame, filtered[0], 'watch').then(() => {
this._onDidChangeWatchExpressions.fire(filtered[0]);
});
}
return TPromise.join(this.watchExpressions.map(we => evaluateExpression(session, stackFrame, we, 'watch'))).then(() => {
this._onDidChangeWatchExpressions.fire();
});
}
public clearWatchExpressionValues(): void {
this.watchExpressions.forEach(we => {
we.value = Expression.DEFAULT_VALUE;
we.available = false;
we.reference = 0;
});
this._onDidChangeWatchExpressions.fire();
}
public removeWatchExpressions(id: string = null): void {
this.watchExpressions = id ? this.watchExpressions.filter(we => we.getId() !== id) : [];
this._onDidChangeWatchExpressions.fire();
}
public sourceIsUnavailable(source: Source): void {
Object.keys(this.threads).forEach(key => {
if (this.threads[key].getCachedCallStack()) {
this.threads[key].getCachedCallStack().forEach(stackFrame => {
if (stackFrame.source.uri.toString() === source.uri.toString()) {
stackFrame.source.available = false;
}
});
}
});
this._onDidChangeCallStack.fire();
}
public rawUpdate(data: debug.IRawModelUpdate): void {
if (data.thread && !this.threads[data.threadId]) {
// A new thread came in, initialize it.
this.threads[data.threadId] = new Thread(data.thread.name, data.thread.id);
}
if (data.stoppedDetails) {
// Set the availability of the threads' callstacks depending on
// whether the thread is stopped or not
if (data.allThreadsStopped) {
Object.keys(this.threads).forEach(ref => {
// Only update the details if all the threads are stopped
// because we don't want to overwrite the details of other
// threads that have stopped for a different reason
this.threads[ref].stoppedDetails = objects.clone(data.stoppedDetails);
this.threads[ref].stopped = true;
this.threads[ref].clearCallStack();
});
} else {
// One thread is stopped, only update that thread.
this.threads[data.threadId].stoppedDetails = data.stoppedDetails;
this.threads[data.threadId].clearCallStack();
this.threads[data.threadId].stopped = true;
}
}
this._onDidChangeCallStack.fire();
}
public dispose(): void {
this.threads = null;
this.breakpoints = null;
this.exceptionBreakpoints = null;
this.functionBreakpoints = null;
this.watchExpressions = null;
this.replElements = null;
this.toDispose = lifecycle.dispose(this.toDispose);
}
}
| src/vs/workbench/parts/debug/common/debugModel.ts | 1 | https://github.com/microsoft/vscode/commit/3978edfa64c9a7b8a8ba823e3ab30767457dc5c6 | [
0.9977503418922424,
0.013069948181509972,
0.00016540622164029628,
0.00017289494280703366,
0.11078786104917526
] |
{
"id": 9,
"code_window": [
"\t\tpublic type: string = null,\n",
"\t\tpublic available = true,\n",
"\t\tchunkIndex = 0\n",
"\t) {\n",
"\t\tsuper(reference, `variable:${ parent.getId() }:${ name }`, true, childrenCount, chunkIndex);\n",
"\t\tthis.value = massageValue(value);\n",
"\t}\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tsuper(reference, `variable:${ parent.getId() }:${ name }`, true, namedVariables, indexedVariables, chunkIndex);\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debugModel.ts",
"type": "replace",
"edit_start_line_idx": 327
} | /*---------------------------------------------------------------------------------------------
* 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 nls = require('vs/nls');
import {BasicEmmetEditorAction} from 'vs/workbench/parts/emmet/node/emmetActions';
import {CommonEditorRegistry, EditorActionDescriptor} from 'vs/editor/common/editorCommonExtensions';
import {IEditorActionDescriptorData, ICommonCodeEditor} from 'vs/editor/common/editorCommon';
import {IConfigurationService} from 'vs/platform/configuration/common/configuration';
class GoToMatchingPairAction extends BasicEmmetEditorAction {
static ID = 'editor.emmet.action.matchingPair';
constructor(descriptor: IEditorActionDescriptorData, editor: ICommonCodeEditor, @IConfigurationService configurationService: IConfigurationService) {
super(descriptor, editor, configurationService, 'matching_pair');
}
}
CommonEditorRegistry.registerEditorAction(new EditorActionDescriptor(GoToMatchingPairAction,
GoToMatchingPairAction.ID,
nls.localize('matchingPair', "Emmet: Go to Matching Pair"), void 0, 'Emmet: Go to Matching Pair'));
| src/vs/workbench/parts/emmet/node/actions/matchingPair.ts | 0 | https://github.com/microsoft/vscode/commit/3978edfa64c9a7b8a8ba823e3ab30767457dc5c6 | [
0.00017682705947663635,
0.00017583364387974143,
0.00017424933321308345,
0.00017642455350141972,
0.0000011322674708935665
] |
{
"id": 9,
"code_window": [
"\t\tpublic type: string = null,\n",
"\t\tpublic available = true,\n",
"\t\tchunkIndex = 0\n",
"\t) {\n",
"\t\tsuper(reference, `variable:${ parent.getId() }:${ name }`, true, childrenCount, chunkIndex);\n",
"\t\tthis.value = massageValue(value);\n",
"\t}\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tsuper(reference, `variable:${ parent.getId() }:${ name }`, true, namedVariables, indexedVariables, chunkIndex);\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debugModel.ts",
"type": "replace",
"edit_start_line_idx": 327
} | /*---------------------------------------------------------------------------------------------
* 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.
{
"commitMessage": "Nachricht (drücken Sie {0}, um den Commit auszuführen)",
"commitMessageAriaLabel": "Git: Geben Sie die Commitnachricht ein, und drücken Sie {0}, um den Commit auszuführen.",
"longCommit": "Es wird empfohlen, dass die erste Zeile des Commits weniger als 50 Zeichen lang ist. Sie können weitere Zeilen für zusätzliche Informationen verwenden.",
"needMessage": "Geben Sie eine Commit-Meldung an. Sie können jederzeit **{0}** drücken, um einen Commit für die Änderungen auszuführen. Wenn bereitgestellte Änderungen vorliegen, wird nur für diese ein Commit ausgeführt; andernfalls für alle Änderungen.",
"nothingToCommit": "Sobald Änderungen für einen Commit vorliegen, geben Sie die Commit-Meldung ein, und drücken Sie **{0}**, um den Commit für die Änderungen auszuführen. Wenn bereitgestellte Änderungen vorliegen, wird nur für diese ein Commit ausgeführt; andernfalls für alle Änderungen.",
"showOutput": "Git-Ausgabe anzeigen",
"treeAriaLabel": "Ansicht \"Git-Änderungen\""
} | i18n/deu/src/vs/workbench/parts/git/browser/views/changes/changesView.i18n.json | 0 | https://github.com/microsoft/vscode/commit/3978edfa64c9a7b8a8ba823e3ab30767457dc5c6 | [
0.00016988374409265816,
0.00016834845882840455,
0.00016681318811606616,
0.00016834845882840455,
0.0000015352779882960021
] |
{
"id": 9,
"code_window": [
"\t\tpublic type: string = null,\n",
"\t\tpublic available = true,\n",
"\t\tchunkIndex = 0\n",
"\t) {\n",
"\t\tsuper(reference, `variable:${ parent.getId() }:${ name }`, true, childrenCount, chunkIndex);\n",
"\t\tthis.value = massageValue(value);\n",
"\t}\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tsuper(reference, `variable:${ parent.getId() }:${ name }`, true, namedVariables, indexedVariables, chunkIndex);\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debugModel.ts",
"type": "replace",
"edit_start_line_idx": 327
} | /*---------------------------------------------------------------------------------------------
* 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.
{
"keyframes.standardrule.missing": "Defina siempre la regla estándar '@keyframes' al definir fotogramas clave.",
"keyframes.vendorspecific.missing": "Incluya siempre todas las reglas específicas del proveedor: Falta: {0}",
"namelist.concatenated": "{0}, '{1}'",
"namelist.single": "'{0}'",
"property.standard.missing": "Defina también la propiedad estándar '{0}' para la compatibilidad.",
"property.vendorspecific.missing": "Incluya siempre todas las propiedades específicas del proveedor: Falta: {0}"
} | i18n/esn/src/vs/languages/css/common/services/lint.i18n.json | 0 | https://github.com/microsoft/vscode/commit/3978edfa64c9a7b8a8ba823e3ab30767457dc5c6 | [
0.0001754097465891391,
0.00017372376169078052,
0.0001720377622405067,
0.00017372376169078052,
0.0000016859921743161976
] |
{
"id": 10,
"code_window": [
"\t\tpublic name: string,\n",
"\t\treference: number,\n",
"\t\tpublic expensive: boolean,\n",
"\t\tchildrenCount: number\n",
"\t) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"\t\tnamedVariables: number,\n",
"\t\tindexedVariables: number\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debugModel.ts",
"type": "replace",
"edit_start_line_idx": 339
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { TPromise } from 'vs/base/common/winjs.base';
import nls = require('vs/nls');
import lifecycle = require('vs/base/common/lifecycle');
import Event, { Emitter } from 'vs/base/common/event';
import uuid = require('vs/base/common/uuid');
import objects = require('vs/base/common/objects');
import severity from 'vs/base/common/severity';
import types = require('vs/base/common/types');
import arrays = require('vs/base/common/arrays');
import debug = require('vs/workbench/parts/debug/common/debug');
import { Source } from 'vs/workbench/parts/debug/common/debugSource';
const MAX_REPL_LENGTH = 10000;
const UNKNOWN_SOURCE_LABEL = nls.localize('unknownSource', "Unknown Source");
function massageValue(value: string): string {
return value ? value.replace(/\n/g, '\\n').replace(/\r/g, '\\r').replace(/\t/g, '\\t') : value;
}
export function evaluateExpression(session: debug.IRawDebugSession, stackFrame: debug.IStackFrame, expression: Expression, context: string): TPromise<Expression> {
if (!session) {
expression.value = context === 'repl' ? nls.localize('startDebugFirst', "Please start a debug session to evaluate") : Expression.DEFAULT_VALUE;
expression.available = false;
expression.reference = 0;
return TPromise.as(expression);
}
return session.evaluate({
expression: expression.name,
frameId: stackFrame ? stackFrame.frameId : undefined,
context
}).then(response => {
expression.available = !!(response && response.body);
if (response.body) {
expression.value = response.body.result;
expression.reference = response.body.variablesReference;
expression.childrenCount = response.body.indexedVariables;
expression.type = response.body.type;
}
return expression;
}, err => {
expression.value = err.message;
expression.available = false;
expression.reference = 0;
return expression;
});
}
const notPropertySyntax = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
const arrayElementSyntax = /\[.*\]$/;
export function getFullExpressionName(expression: debug.IExpression, sessionType: string): string {
let names = [expression.name];
if (expression instanceof Variable) {
let v = (<Variable> expression).parent;
while (v instanceof Variable || v instanceof Expression) {
names.push((<Variable> v).name);
v = (<Variable> v).parent;
}
}
names = names.reverse();
let result = null;
names.forEach(name => {
if (!result) {
result = name;
} else if (arrayElementSyntax.test(name) || (sessionType === 'node' && !notPropertySyntax.test(name))) {
// use safe way to access node properties a['property_name']. Also handles array elements.
result = name && name.indexOf('[') === 0 ? `${ result }${ name }` : `${ result }['${ name }']`;
} else {
result = `${ result }.${ name }`;
}
});
return result;
}
export class Thread implements debug.IThread {
private promisedCallStack: TPromise<debug.IStackFrame[]>;
private cachedCallStack: debug.IStackFrame[];
public stoppedDetails: debug.IRawStoppedDetails;
public stopped: boolean;
constructor(public name: string, public threadId: number) {
this.promisedCallStack = undefined;
this.stoppedDetails = undefined;
this.cachedCallStack = undefined;
this.stopped = false;
}
public getId(): string {
return `thread:${ this.name }:${ this.threadId }`;
}
public clearCallStack(): void {
this.promisedCallStack = undefined;
this.cachedCallStack = undefined;
}
public getCachedCallStack(): debug.IStackFrame[] {
return this.cachedCallStack;
}
public getCallStack(debugService: debug.IDebugService, getAdditionalStackFrames = false): TPromise<debug.IStackFrame[]> {
if (!this.stopped) {
return TPromise.as([]);
}
if (!this.promisedCallStack) {
this.promisedCallStack = this.getCallStackImpl(debugService, 0).then(callStack => {
this.cachedCallStack = callStack;
return callStack;
});
} else if (getAdditionalStackFrames) {
this.promisedCallStack = this.promisedCallStack.then(callStackFirstPart => this.getCallStackImpl(debugService, callStackFirstPart.length).then(callStackSecondPart => {
this.cachedCallStack = callStackFirstPart.concat(callStackSecondPart);
return this.cachedCallStack;
}));
}
return this.promisedCallStack;
}
private getCallStackImpl(debugService: debug.IDebugService, startFrame: number): TPromise<debug.IStackFrame[]> {
let session = debugService.getActiveSession();
return session.stackTrace({ threadId: this.threadId, startFrame, levels: 20 }).then(response => {
this.stoppedDetails.totalFrames = response.body.totalFrames;
return response.body.stackFrames.map((rsf, level) => {
if (!rsf) {
return new StackFrame(this.threadId, 0, new Source({ name: UNKNOWN_SOURCE_LABEL }, false), nls.localize('unknownStack', "Unknown stack location"), undefined, undefined);
}
return new StackFrame(this.threadId, rsf.id, rsf.source ? new Source(rsf.source) : new Source({ name: UNKNOWN_SOURCE_LABEL }, false), rsf.name, rsf.line, rsf.column);
});
}, (err: Error) => {
this.stoppedDetails.framesErrorMessage = err.message;
return [];
});
}
}
export class OutputElement implements debug.ITreeElement {
private static ID_COUNTER = 0;
constructor(private id = OutputElement.ID_COUNTER++) {
// noop
}
public getId(): string {
return `outputelement:${ this.id }`;
}
}
export class ValueOutputElement extends OutputElement {
constructor(
public value: string,
public severity: severity,
public category?: string,
public counter: number = 1
) {
super();
}
}
export class KeyValueOutputElement extends OutputElement {
private static MAX_CHILDREN = 1000; // upper bound of children per value
private children: debug.ITreeElement[];
private _valueName: string;
constructor(public key: string, public valueObj: any, public annotation?: string) {
super();
this._valueName = null;
}
public get value(): string {
if (this._valueName === null) {
if (this.valueObj === null) {
this._valueName = 'null';
} else if (Array.isArray(this.valueObj)) {
this._valueName = `Array[${this.valueObj.length}]`;
} else if (types.isObject(this.valueObj)) {
this._valueName = 'Object';
} else if (types.isString(this.valueObj)) {
this._valueName = `"${massageValue(this.valueObj)}"`;
} else {
this._valueName = String(this.valueObj);
}
if (!this._valueName) {
this._valueName = '';
}
}
return this._valueName;
}
public getChildren(): debug.ITreeElement[] {
if (!this.children) {
if (Array.isArray(this.valueObj)) {
this.children = (<any[]>this.valueObj).slice(0, KeyValueOutputElement.MAX_CHILDREN).map((v, index) => new KeyValueOutputElement(String(index), v, null));
} else if (types.isObject(this.valueObj)) {
this.children = Object.getOwnPropertyNames(this.valueObj).slice(0, KeyValueOutputElement.MAX_CHILDREN).map(key => new KeyValueOutputElement(key, this.valueObj[key], null));
} else {
this.children = [];
}
}
return this.children;
}
}
export abstract class ExpressionContainer implements debug.IExpressionContainer {
public static allValues: { [id: string]: string } = {};
// Use chunks to support variable paging #9537
private static CHUNK_SIZE = 100;
public valueChanged: boolean;
private children: TPromise<debug.IExpression[]>;
private _value: string;
constructor(
public reference: number,
private id: string,
private cacheChildren: boolean,
public childrenCount: number,
private chunkIndex = 0
) {
// noop
}
public getChildren(debugService: debug.IDebugService): TPromise<debug.IExpression[]> {
if (!this.cacheChildren || !this.children) {
const session = debugService.getActiveSession();
// only variables with reference > 0 have children.
if (!session || this.reference <= 0) {
this.children = TPromise.as([]);
} else {
if (this.childrenCount > ExpressionContainer.CHUNK_SIZE) {
// There are a lot of children, create fake intermediate values that represent chunks #9537
const chunks = [];
const numberOfChunks = this.childrenCount / ExpressionContainer.CHUNK_SIZE;
for (let i = 0; i < numberOfChunks; i++) {
const chunkSize = (i < numberOfChunks - 1) ? ExpressionContainer.CHUNK_SIZE : this.childrenCount % ExpressionContainer.CHUNK_SIZE;
const chunkName = `${i * ExpressionContainer.CHUNK_SIZE}..${i * ExpressionContainer.CHUNK_SIZE + chunkSize - 1}`;
chunks.push(new Variable(this, this.reference, chunkName, '', chunkSize, null, true, i));
}
this.children = TPromise.as(chunks);
} else {
const start = this.getChildrenInChunks ? this.chunkIndex * ExpressionContainer.CHUNK_SIZE : undefined;
const count = this.getChildrenInChunks ? this.childrenCount : undefined;
this.children = session.variables({
variablesReference: this.reference,
start,
count
}).then(response => {
return arrays.distinct(response.body.variables.filter(v => !!v), v => v.name).map(
v => new Variable(this, v.variablesReference, v.name, v.value, v.indexedVariables, v.type)
);
}, (e: Error) => [new Variable(this, 0, null, e.message, 0, null, false)]);
}
}
}
return this.children;
}
public getId(): string {
return this.id;
}
public get value(): string {
return this._value;
}
// The adapter explicitly sents the children count of an expression only if there are lots of children which should be chunked.
private get getChildrenInChunks(): boolean {
return !!this.childrenCount;
}
public set value(value: string) {
this._value = massageValue(value);
this.valueChanged = ExpressionContainer.allValues[this.getId()] &&
ExpressionContainer.allValues[this.getId()] !== Expression.DEFAULT_VALUE && ExpressionContainer.allValues[this.getId()] !== value;
ExpressionContainer.allValues[this.getId()] = value;
}
}
export class Expression extends ExpressionContainer implements debug.IExpression {
static DEFAULT_VALUE = 'not available';
public available: boolean;
public type: string;
constructor(public name: string, cacheChildren: boolean, id = uuid.generateUuid()) {
super(0, id, cacheChildren, 0);
this.value = Expression.DEFAULT_VALUE;
this.available = false;
}
}
export class Variable extends ExpressionContainer implements debug.IExpression {
// Used to show the error message coming from the adapter when setting the value #7807
public errorMessage: string;
constructor(
public parent: debug.IExpressionContainer,
reference: number,
public name: string,
value: string,
childrenCount: number,
public type: string = null,
public available = true,
chunkIndex = 0
) {
super(reference, `variable:${ parent.getId() }:${ name }`, true, childrenCount, chunkIndex);
this.value = massageValue(value);
}
}
export class Scope extends ExpressionContainer implements debug.IScope {
constructor(
private threadId: number,
public name: string,
reference: number,
public expensive: boolean,
childrenCount: number
) {
super(reference, `scope:${threadId}:${name}:${reference}`, true, childrenCount);
}
}
export class StackFrame implements debug.IStackFrame {
private scopes: TPromise<Scope[]>;
constructor(
public threadId: number,
public frameId: number,
public source: Source,
public name: string,
public lineNumber: number,
public column: number
) {
this.scopes = null;
}
public getId(): string {
return `stackframe:${ this.threadId }:${ this.frameId }`;
}
public getScopes(debugService: debug.IDebugService): TPromise<debug.IScope[]> {
if (!this.scopes) {
this.scopes = debugService.getActiveSession().scopes({ frameId: this.frameId }).then(response => {
return response.body.scopes.map(rs => new Scope(this.threadId, rs.name, rs.variablesReference, rs.expensive, rs.indexedVariables));
}, err => []);
}
return this.scopes;
}
}
export class Breakpoint implements debug.IBreakpoint {
public lineNumber: number;
public verified: boolean;
public idFromAdapter: number;
public message: string;
private id: string;
constructor(
public source: Source,
public desiredLineNumber: number,
public enabled: boolean,
public condition: string
) {
if (enabled === undefined) {
this.enabled = true;
}
this.lineNumber = this.desiredLineNumber;
this.verified = false;
this.id = uuid.generateUuid();
}
public getId(): string {
return this.id;
}
}
export class FunctionBreakpoint implements debug.IFunctionBreakpoint {
private id: string;
public verified: boolean;
public idFromAdapter: number;
constructor(public name: string, public enabled: boolean) {
this.verified = false;
this.id = uuid.generateUuid();
}
public getId(): string {
return this.id;
}
}
export class ExceptionBreakpoint implements debug.IExceptionBreakpoint {
private id: string;
constructor(public filter: string, public label: string, public enabled: boolean) {
this.id = uuid.generateUuid();
}
public getId(): string {
return this.id;
}
}
export class Model implements debug.IModel {
private threads: { [reference: number]: debug.IThread; };
private toDispose: lifecycle.IDisposable[];
private replElements: debug.ITreeElement[];
private _onDidChangeBreakpoints: Emitter<void>;
private _onDidChangeCallStack: Emitter<void>;
private _onDidChangeWatchExpressions: Emitter<debug.IExpression>;
private _onDidChangeREPLElements: Emitter<void>;
constructor(
private breakpoints: debug.IBreakpoint[],
private breakpointsActivated: boolean,
private functionBreakpoints: debug.IFunctionBreakpoint[],
private exceptionBreakpoints: debug.IExceptionBreakpoint[],
private watchExpressions: Expression[]
) {
this.threads = {};
this.replElements = [];
this.toDispose = [];
this._onDidChangeBreakpoints = new Emitter<void>();
this._onDidChangeCallStack = new Emitter<void>();
this._onDidChangeWatchExpressions = new Emitter<debug.IExpression>();
this._onDidChangeREPLElements = new Emitter<void>();
}
public getId(): string {
return 'root';
}
public get onDidChangeBreakpoints(): Event<void> {
return this._onDidChangeBreakpoints.event;
}
public get onDidChangeCallStack(): Event<void> {
return this._onDidChangeCallStack.event;
}
public get onDidChangeWatchExpressions(): Event<debug.IExpression> {
return this._onDidChangeWatchExpressions.event;
}
public get onDidChangeReplElements(): Event<void> {
return this._onDidChangeREPLElements.event;
}
public getThreads(): { [reference: number]: debug.IThread; } {
return this.threads;
}
public clearThreads(removeThreads: boolean, reference: number = undefined): void {
if (reference) {
if (this.threads[reference]) {
this.threads[reference].clearCallStack();
this.threads[reference].stoppedDetails = undefined;
this.threads[reference].stopped = false;
if (removeThreads) {
delete this.threads[reference];
}
}
} else {
Object.keys(this.threads).forEach(ref => {
this.threads[ref].clearCallStack();
this.threads[ref].stoppedDetails = undefined;
this.threads[ref].stopped = false;
});
if (removeThreads) {
this.threads = {};
ExpressionContainer.allValues = {};
}
}
this._onDidChangeCallStack.fire();
}
public getBreakpoints(): debug.IBreakpoint[] {
return this.breakpoints;
}
public getFunctionBreakpoints(): debug.IFunctionBreakpoint[] {
return this.functionBreakpoints;
}
public getExceptionBreakpoints(): debug.IExceptionBreakpoint[] {
return this.exceptionBreakpoints;
}
public setExceptionBreakpoints(data: DebugProtocol.ExceptionBreakpointsFilter[]): void {
if (data) {
this.exceptionBreakpoints = data.map(d => {
const ebp = this.exceptionBreakpoints.filter(ebp => ebp.filter === d.filter).pop();
return new ExceptionBreakpoint(d.filter, d.label, ebp ? ebp.enabled : d.default);
});
}
}
public areBreakpointsActivated(): boolean {
return this.breakpointsActivated;
}
public setBreakpointsActivated(activated: boolean): void {
this.breakpointsActivated = activated;
this._onDidChangeBreakpoints.fire();
}
public addBreakpoints(rawData: debug.IRawBreakpoint[]): void {
this.breakpoints = this.breakpoints.concat(rawData.map(rawBp =>
new Breakpoint(new Source(Source.toRawSource(rawBp.uri, this)), rawBp.lineNumber, rawBp.enabled, rawBp.condition)));
this.breakpointsActivated = true;
this._onDidChangeBreakpoints.fire();
}
public removeBreakpoints(toRemove: debug.IBreakpoint[]): void {
this.breakpoints = this.breakpoints.filter(bp => !toRemove.some(toRemove => toRemove.getId() === bp.getId()));
this._onDidChangeBreakpoints.fire();
}
public updateBreakpoints(data: { [id: string]: DebugProtocol.Breakpoint }): void {
this.breakpoints.forEach(bp => {
const bpData = data[bp.getId()];
if (bpData) {
bp.lineNumber = bpData.line ? bpData.line : bp.lineNumber;
bp.verified = bpData.verified;
bp.idFromAdapter = bpData.id;
bp.message = bpData.message;
}
});
this._onDidChangeBreakpoints.fire();
}
public setEnablement(element: debug.IEnablement, enable: boolean): void {
element.enabled = enable;
if (element instanceof Breakpoint && !element.enabled) {
var breakpoint = <Breakpoint> element;
breakpoint.lineNumber = breakpoint.desiredLineNumber;
breakpoint.verified = false;
}
this._onDidChangeBreakpoints.fire();
}
public enableOrDisableAllBreakpoints(enable: boolean): void {
this.breakpoints.forEach(bp => {
bp.enabled = enable;
if (!enable) {
bp.lineNumber = bp.desiredLineNumber;
bp.verified = false;
}
});
this.exceptionBreakpoints.forEach(ebp => ebp.enabled = enable);
this.functionBreakpoints.forEach(fbp => fbp.enabled = enable);
this._onDidChangeBreakpoints.fire();
}
public addFunctionBreakpoint(functionName: string): void {
this.functionBreakpoints.push(new FunctionBreakpoint(functionName, true));
this._onDidChangeBreakpoints.fire();
}
public updateFunctionBreakpoints(data: { [id: string]: { name?: string, verified?: boolean; id?: number } }): void {
this.functionBreakpoints.forEach(fbp => {
const fbpData = data[fbp.getId()];
if (fbpData) {
fbp.name = fbpData.name || fbp.name;
fbp.verified = fbpData.verified;
fbp.idFromAdapter = fbpData.id;
}
});
this._onDidChangeBreakpoints.fire();
}
public removeFunctionBreakpoints(id?: string): void {
this.functionBreakpoints = id ? this.functionBreakpoints.filter(fbp => fbp.getId() !== id) : [];
this._onDidChangeBreakpoints.fire();
}
public getReplElements(): debug.ITreeElement[] {
return this.replElements;
}
public addReplExpression(session: debug.IRawDebugSession, stackFrame: debug.IStackFrame, name: string): TPromise<void> {
const expression = new Expression(name, true);
this.addReplElements([expression]);
return evaluateExpression(session, stackFrame, expression, 'repl')
.then(() => this._onDidChangeREPLElements.fire());
}
public logToRepl(value: string | { [key: string]: any }, severity?: severity): void {
let elements:OutputElement[] = [];
let previousOutput = this.replElements.length && (<ValueOutputElement>this.replElements[this.replElements.length - 1]);
// string message
if (typeof value === 'string') {
if (value && value.trim() && previousOutput && previousOutput.value === value && previousOutput.severity === severity) {
previousOutput.counter++; // we got the same output (but not an empty string when trimmed) so we just increment the counter
} else {
let lines = value.trim().split('\n');
lines.forEach((line, index) => {
elements.push(new ValueOutputElement(line, severity));
});
}
}
// key-value output
else {
elements.push(new KeyValueOutputElement((<any>value).prototype, value, nls.localize('snapshotObj', "Only primitive values are shown for this object.")));
}
if (elements.length) {
this.addReplElements(elements);
}
this._onDidChangeREPLElements.fire();
}
public appendReplOutput(value: string, severity?: severity): void {
const elements: OutputElement[] = [];
let previousOutput = this.replElements.length && (<ValueOutputElement>this.replElements[this.replElements.length - 1]);
let lines = value.split('\n');
let groupTogether = !!previousOutput && (previousOutput.category === 'output' && severity === previousOutput.severity);
if (groupTogether) {
// append to previous line if same group
previousOutput.value += lines.shift();
} else if (previousOutput && previousOutput.value === '') {
// remove potential empty lines between different output types
this.replElements.pop();
}
// fill in lines as output value elements
lines.forEach((line, index) => {
elements.push(new ValueOutputElement(line, severity, 'output'));
});
this.addReplElements(elements);
this._onDidChangeREPLElements.fire();
}
private addReplElements(newElements: debug.ITreeElement[]): void {
this.replElements.push(...newElements);
if (this.replElements.length > MAX_REPL_LENGTH) {
this.replElements.splice(0, this.replElements.length - MAX_REPL_LENGTH);
}
}
public removeReplExpressions(): void {
if (this.replElements.length > 0) {
this.replElements = [];
this._onDidChangeREPLElements.fire();
}
}
public getWatchExpressions(): Expression[] {
return this.watchExpressions;
}
public addWatchExpression(session: debug.IRawDebugSession, stackFrame: debug.IStackFrame, name: string): TPromise<void> {
const we = new Expression(name, false);
this.watchExpressions.push(we);
if (!name) {
this._onDidChangeWatchExpressions.fire(we);
return TPromise.as(null);
}
return this.evaluateWatchExpressions(session, stackFrame, we.getId());
}
public renameWatchExpression(session: debug.IRawDebugSession, stackFrame: debug.IStackFrame, id: string, newName: string): TPromise<void> {
const filtered = this.watchExpressions.filter(we => we.getId() === id);
if (filtered.length === 1) {
filtered[0].name = newName;
return evaluateExpression(session, stackFrame, filtered[0], 'watch').then(() => {
this._onDidChangeWatchExpressions.fire(filtered[0]);
});
}
return TPromise.as(null);
}
public evaluateWatchExpressions(session: debug.IRawDebugSession, stackFrame: debug.IStackFrame, id: string = null): TPromise<void> {
if (id) {
const filtered = this.watchExpressions.filter(we => we.getId() === id);
if (filtered.length !== 1) {
return TPromise.as(null);
}
return evaluateExpression(session, stackFrame, filtered[0], 'watch').then(() => {
this._onDidChangeWatchExpressions.fire(filtered[0]);
});
}
return TPromise.join(this.watchExpressions.map(we => evaluateExpression(session, stackFrame, we, 'watch'))).then(() => {
this._onDidChangeWatchExpressions.fire();
});
}
public clearWatchExpressionValues(): void {
this.watchExpressions.forEach(we => {
we.value = Expression.DEFAULT_VALUE;
we.available = false;
we.reference = 0;
});
this._onDidChangeWatchExpressions.fire();
}
public removeWatchExpressions(id: string = null): void {
this.watchExpressions = id ? this.watchExpressions.filter(we => we.getId() !== id) : [];
this._onDidChangeWatchExpressions.fire();
}
public sourceIsUnavailable(source: Source): void {
Object.keys(this.threads).forEach(key => {
if (this.threads[key].getCachedCallStack()) {
this.threads[key].getCachedCallStack().forEach(stackFrame => {
if (stackFrame.source.uri.toString() === source.uri.toString()) {
stackFrame.source.available = false;
}
});
}
});
this._onDidChangeCallStack.fire();
}
public rawUpdate(data: debug.IRawModelUpdate): void {
if (data.thread && !this.threads[data.threadId]) {
// A new thread came in, initialize it.
this.threads[data.threadId] = new Thread(data.thread.name, data.thread.id);
}
if (data.stoppedDetails) {
// Set the availability of the threads' callstacks depending on
// whether the thread is stopped or not
if (data.allThreadsStopped) {
Object.keys(this.threads).forEach(ref => {
// Only update the details if all the threads are stopped
// because we don't want to overwrite the details of other
// threads that have stopped for a different reason
this.threads[ref].stoppedDetails = objects.clone(data.stoppedDetails);
this.threads[ref].stopped = true;
this.threads[ref].clearCallStack();
});
} else {
// One thread is stopped, only update that thread.
this.threads[data.threadId].stoppedDetails = data.stoppedDetails;
this.threads[data.threadId].clearCallStack();
this.threads[data.threadId].stopped = true;
}
}
this._onDidChangeCallStack.fire();
}
public dispose(): void {
this.threads = null;
this.breakpoints = null;
this.exceptionBreakpoints = null;
this.functionBreakpoints = null;
this.watchExpressions = null;
this.replElements = null;
this.toDispose = lifecycle.dispose(this.toDispose);
}
}
| src/vs/workbench/parts/debug/common/debugModel.ts | 1 | https://github.com/microsoft/vscode/commit/3978edfa64c9a7b8a8ba823e3ab30767457dc5c6 | [
0.9844448566436768,
0.024238422513008118,
0.00016578233044128865,
0.00017337975441478193,
0.13032257556915283
] |
{
"id": 10,
"code_window": [
"\t\tpublic name: string,\n",
"\t\treference: number,\n",
"\t\tpublic expensive: boolean,\n",
"\t\tchildrenCount: number\n",
"\t) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
"\t\tnamedVariables: number,\n",
"\t\tindexedVariables: number\n"
],
"file_path": "src/vs/workbench/parts/debug/common/debugModel.ts",
"type": "replace",
"edit_start_line_idx": 339
} | [
{
"c": "\"\"\"",
"t": "begin.coffee.definition.double.heredoc.punctuation.quoted.string",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.string rgb(206, 145, 120)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.string rgb(163, 21, 21)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string rgb(206, 145, 120)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string rgb(163, 21, 21)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string rgb(206, 145, 120)"
}
},
{
"c": "A CoffeeScript sample.",
"t": "coffee.double.heredoc.quoted.string",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.string rgb(206, 145, 120)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.string rgb(163, 21, 21)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string rgb(206, 145, 120)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string rgb(163, 21, 21)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string rgb(206, 145, 120)"
}
},
{
"c": "\"\"\"",
"t": "coffee.definition.double.end.heredoc.punctuation.quoted.string",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.string rgb(206, 145, 120)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.string rgb(163, 21, 21)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string rgb(206, 145, 120)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string rgb(163, 21, 21)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string rgb(206, 145, 120)"
}
},
{
"c": "class",
"t": "class.coffee.meta.storage.type",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.storage.type rgb(86, 156, 214)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.storage.type rgb(0, 0, 255)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.storage.type rgb(86, 156, 214)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.storage.type rgb(0, 0, 255)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.storage.type rgb(86, 156, 214)"
}
},
{
"c": " ",
"t": "class.coffee.meta",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "Vehicle",
"t": "class.coffee.entity.meta.name.type",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.entity.name.type rgb(78, 201, 176)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.entity.name.type rgb(38, 127, 153)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.entity.name.class rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": " ",
"t": "",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "constructor",
"t": "coffee.entity.function.meta.name",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.entity.name.function rgb(220, 220, 170)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.entity.name.function rgb(121, 94, 38)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.entity.name.function rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": ":",
"t": "coffee.keyword.operator",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.keyword.operator rgb(212, 212, 212)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.keyword.operator rgb(0, 0, 0)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.keyword.operator rgb(212, 212, 212)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.keyword.operator rgb(0, 0, 0)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.keyword.operator rgb(212, 212, 212)"
}
},
{
"c": " ",
"t": "",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "(",
"t": "begin.coffee.definition.function.inline.meta.parameters.punctuation",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "@name",
"t": "coffee.function.inline.meta.parameter.variable",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.variable.parameter rgb(156, 220, 254)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.variable.parameter rgb(0, 16, 128)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": ")",
"t": "begin.coffee.definition.function.inline.meta.parameters.punctuation",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": " ",
"t": "coffee.function.inline.meta",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "=>",
"t": "coffee.function.inline.meta.storage.type",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.storage.type rgb(86, 156, 214)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.storage.type rgb(0, 0, 255)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.storage.type rgb(86, 156, 214)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.storage.type rgb(0, 0, 255)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.storage.type rgb(86, 156, 214)"
}
},
{
"c": " ",
"t": "",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "drive",
"t": "coffee.entity.function.meta.name",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.entity.name.function rgb(220, 220, 170)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.entity.name.function rgb(121, 94, 38)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.entity.name.function rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": ":",
"t": "coffee.keyword.operator",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.keyword.operator rgb(212, 212, 212)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.keyword.operator rgb(0, 0, 0)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.keyword.operator rgb(212, 212, 212)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.keyword.operator rgb(0, 0, 0)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.keyword.operator rgb(212, 212, 212)"
}
},
{
"c": " ",
"t": "",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "()",
"t": "begin.coffee.definition.function.inline.meta.parameters.punctuation",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": " ",
"t": "coffee.function.inline.meta",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "=>",
"t": "coffee.function.inline.meta.storage.type",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.storage.type rgb(86, 156, 214)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.storage.type rgb(0, 0, 255)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.storage.type rgb(86, 156, 214)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.storage.type rgb(0, 0, 255)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.storage.type rgb(86, 156, 214)"
}
},
{
"c": " alert ",
"t": "",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "\"",
"t": "begin.coffee.definition.double.punctuation.quoted.string",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.string rgb(206, 145, 120)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.string rgb(163, 21, 21)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string rgb(206, 145, 120)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string rgb(163, 21, 21)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string rgb(206, 145, 120)"
}
},
{
"c": "Drive ",
"t": "coffee.double.quoted.string",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.string rgb(206, 145, 120)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.string rgb(163, 21, 21)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string rgb(206, 145, 120)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string rgb(163, 21, 21)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string rgb(206, 145, 120)"
}
},
{
"c": "#{",
"t": "begin.coffee.double.embedded.line.meta.punctuation.quoted.section.string",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.string rgb(206, 145, 120)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.string rgb(163, 21, 21)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string rgb(206, 145, 120)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string rgb(163, 21, 21)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string rgb(206, 145, 120)"
}
},
{
"c": "@",
"t": "coffee.definition.double.embedded.instance.line.meta.other.punctuation.quoted.readwrite.source.string.variable",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.variable rgb(156, 220, 254)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.variable rgb(0, 16, 128)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string rgb(206, 145, 120)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string rgb(163, 21, 21)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string rgb(206, 145, 120)"
}
},
{
"c": "name",
"t": "coffee.double.embedded.instance.line.meta.other.quoted.readwrite.source.string.variable",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.variable rgb(156, 220, 254)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.variable rgb(0, 16, 128)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string rgb(206, 145, 120)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string rgb(163, 21, 21)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string rgb(206, 145, 120)"
}
},
{
"c": "}",
"t": "coffee.double.embedded.end.line.meta.punctuation.quoted.section.source.string",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.string rgb(206, 145, 120)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.string rgb(163, 21, 21)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string rgb(206, 145, 120)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string rgb(163, 21, 21)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string rgb(206, 145, 120)"
}
},
{
"c": "\"",
"t": "coffee.definition.double.end.punctuation.quoted.string",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.string rgb(206, 145, 120)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.string rgb(163, 21, 21)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string rgb(206, 145, 120)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string rgb(163, 21, 21)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string rgb(206, 145, 120)"
}
},
{
"c": "class",
"t": "class.coffee.meta.storage.type",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.storage.type rgb(86, 156, 214)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.storage.type rgb(0, 0, 255)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.storage.type rgb(86, 156, 214)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.storage.type rgb(0, 0, 255)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.storage.type rgb(86, 156, 214)"
}
},
{
"c": " ",
"t": "class.coffee.meta",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "Car",
"t": "class.coffee.entity.meta.name.type",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.entity.name.type rgb(78, 201, 176)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.entity.name.type rgb(38, 127, 153)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.entity.name.class rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": " ",
"t": "class.coffee.meta",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "extends",
"t": "class.coffee.control.inheritance.keyword.meta",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.keyword.control rgb(197, 134, 192)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.keyword.control rgb(175, 0, 219)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.keyword.control rgb(86, 156, 214)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.keyword.control rgb(0, 0, 255)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.keyword.control rgb(86, 156, 214)"
}
},
{
"c": " ",
"t": "class.coffee.meta",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "Vehicle",
"t": "class.coffee.entity.inherited-class.meta.other",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": " ",
"t": "",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "drive",
"t": "coffee.entity.function.meta.name",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.entity.name.function rgb(220, 220, 170)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.entity.name.function rgb(121, 94, 38)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.entity.name.function rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": ":",
"t": "coffee.keyword.operator",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.keyword.operator rgb(212, 212, 212)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.keyword.operator rgb(0, 0, 0)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.keyword.operator rgb(212, 212, 212)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.keyword.operator rgb(0, 0, 0)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.keyword.operator rgb(212, 212, 212)"
}
},
{
"c": " ",
"t": "",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "()",
"t": "begin.coffee.definition.function.inline.meta.parameters.punctuation",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": " ",
"t": "coffee.function.inline.meta",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "=>",
"t": "coffee.function.inline.meta.storage.type",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.storage.type rgb(86, 156, 214)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.storage.type rgb(0, 0, 255)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.storage.type rgb(86, 156, 214)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.storage.type rgb(0, 0, 255)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.storage.type rgb(86, 156, 214)"
}
},
{
"c": " alert ",
"t": "",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "\"",
"t": "begin.coffee.definition.double.punctuation.quoted.string",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.string rgb(206, 145, 120)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.string rgb(163, 21, 21)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string rgb(206, 145, 120)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string rgb(163, 21, 21)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string rgb(206, 145, 120)"
}
},
{
"c": "Driving ",
"t": "coffee.double.quoted.string",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.string rgb(206, 145, 120)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.string rgb(163, 21, 21)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string rgb(206, 145, 120)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string rgb(163, 21, 21)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string rgb(206, 145, 120)"
}
},
{
"c": "#{",
"t": "begin.coffee.double.embedded.line.meta.punctuation.quoted.section.string",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.string rgb(206, 145, 120)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.string rgb(163, 21, 21)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string rgb(206, 145, 120)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string rgb(163, 21, 21)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string rgb(206, 145, 120)"
}
},
{
"c": "@",
"t": "coffee.definition.double.embedded.instance.line.meta.other.punctuation.quoted.readwrite.source.string.variable",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.variable rgb(156, 220, 254)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.variable rgb(0, 16, 128)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string rgb(206, 145, 120)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string rgb(163, 21, 21)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string rgb(206, 145, 120)"
}
},
{
"c": "name",
"t": "coffee.double.embedded.instance.line.meta.other.quoted.readwrite.source.string.variable",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.variable rgb(156, 220, 254)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.variable rgb(0, 16, 128)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string rgb(206, 145, 120)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string rgb(163, 21, 21)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string rgb(206, 145, 120)"
}
},
{
"c": "}",
"t": "coffee.double.embedded.end.line.meta.punctuation.quoted.section.source.string",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.string rgb(206, 145, 120)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.string rgb(163, 21, 21)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string rgb(206, 145, 120)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string rgb(163, 21, 21)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string rgb(206, 145, 120)"
}
},
{
"c": "\"",
"t": "coffee.definition.double.end.punctuation.quoted.string",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.string rgb(206, 145, 120)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.string rgb(163, 21, 21)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string rgb(206, 145, 120)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string rgb(163, 21, 21)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string rgb(206, 145, 120)"
}
},
{
"c": "c",
"t": "assignment.coffee.other.variable",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.variable rgb(156, 220, 254)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.variable rgb(0, 16, 128)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": " ",
"t": "",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "=",
"t": "coffee.keyword.operator",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.keyword.operator rgb(212, 212, 212)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.keyword.operator rgb(0, 0, 0)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.keyword.operator rgb(212, 212, 212)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.keyword.operator rgb(0, 0, 0)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.keyword.operator rgb(212, 212, 212)"
}
},
{
"c": " ",
"t": "",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "new",
"t": "class.coffee.constructor.instance.keyword.meta.new.operator",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.keyword.operator.new rgb(86, 156, 214)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.keyword.operator.new rgb(0, 0, 255)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.keyword.operator.new rgb(86, 156, 214)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.keyword.operator.new rgb(0, 0, 255)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.keyword.operator.new rgb(86, 156, 214)"
}
},
{
"c": " ",
"t": "class.constructor.instance.meta",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "Car",
"t": "class.coffee.constructor.entity.instance.meta.name.type",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.entity.name.type rgb(78, 201, 176)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.entity.name.type rgb(38, 127, 153)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.entity.name.class rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": " ",
"t": "",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "\"",
"t": "begin.coffee.definition.double.punctuation.quoted.string",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.string rgb(206, 145, 120)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.string rgb(163, 21, 21)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string rgb(206, 145, 120)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string rgb(163, 21, 21)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string rgb(206, 145, 120)"
}
},
{
"c": "Volvo",
"t": "coffee.double.quoted.string",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.string rgb(206, 145, 120)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.string rgb(163, 21, 21)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string rgb(206, 145, 120)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string rgb(163, 21, 21)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string rgb(206, 145, 120)"
}
},
{
"c": "\"",
"t": "coffee.definition.double.end.punctuation.quoted.string",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.string rgb(206, 145, 120)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.string rgb(163, 21, 21)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string rgb(206, 145, 120)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string rgb(163, 21, 21)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string rgb(206, 145, 120)"
}
},
{
"c": "while",
"t": "coffee.control.keyword",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.keyword.control rgb(197, 134, 192)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.keyword.control rgb(175, 0, 219)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.keyword.control rgb(86, 156, 214)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.keyword.control rgb(0, 0, 255)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.keyword.control rgb(86, 156, 214)"
}
},
{
"c": " onTheRoad",
"t": "",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "()",
"t": "brace.coffee.meta.round",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": " c",
"t": "",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": ".",
"t": "coffee.delimiter.meta.method.period",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "drive",
"t": "",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "()",
"t": "brace.coffee.meta.round",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "vehicles",
"t": "assignment.coffee.other.variable",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.variable rgb(156, 220, 254)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.variable rgb(0, 16, 128)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": " ",
"t": "",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "=",
"t": "coffee.keyword.operator",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.keyword.operator rgb(212, 212, 212)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.keyword.operator rgb(0, 0, 0)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.keyword.operator rgb(212, 212, 212)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.keyword.operator rgb(0, 0, 0)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.keyword.operator rgb(212, 212, 212)"
}
},
{
"c": " ",
"t": "",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "(",
"t": "brace.coffee.meta.round",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "new",
"t": "class.coffee.constructor.instance.keyword.meta.new.operator",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.keyword.operator.new rgb(86, 156, 214)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.keyword.operator.new rgb(0, 0, 255)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.keyword.operator.new rgb(86, 156, 214)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.keyword.operator.new rgb(0, 0, 255)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.keyword.operator.new rgb(86, 156, 214)"
}
},
{
"c": " ",
"t": "class.constructor.instance.meta",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "Car",
"t": "class.coffee.constructor.entity.instance.meta.name.type",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.entity.name.type rgb(78, 201, 176)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.entity.name.type rgb(38, 127, 153)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.entity.name.class rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": " ",
"t": "",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "for",
"t": "coffee.control.keyword",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.keyword.control rgb(197, 134, 192)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.keyword.control rgb(175, 0, 219)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.keyword.control rgb(86, 156, 214)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.keyword.control rgb(0, 0, 255)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.keyword.control rgb(86, 156, 214)"
}
},
{
"c": " i ",
"t": "",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "in",
"t": "coffee.control.keyword",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.keyword.control rgb(197, 134, 192)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.keyword.control rgb(175, 0, 219)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.keyword.control rgb(86, 156, 214)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.keyword.control rgb(0, 0, 255)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.keyword.control rgb(86, 156, 214)"
}
},
{
"c": " ",
"t": "",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "[",
"t": "brace.coffee.meta.square",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "1",
"t": "coffee.constant.numeric",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.constant.numeric rgb(181, 206, 168)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.constant.numeric rgb(9, 136, 90)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.constant.numeric rgb(181, 206, 168)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.constant.numeric rgb(9, 136, 90)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.constant.numeric rgb(181, 206, 168)"
}
},
{
"c": "..",
"t": "coffee.keyword.operator",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.keyword.operator rgb(212, 212, 212)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.keyword.operator rgb(0, 0, 0)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.keyword.operator rgb(212, 212, 212)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.keyword.operator rgb(0, 0, 0)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.keyword.operator rgb(212, 212, 212)"
}
},
{
"c": "100",
"t": "coffee.constant.numeric",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.constant.numeric rgb(181, 206, 168)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.constant.numeric rgb(9, 136, 90)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.constant.numeric rgb(181, 206, 168)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.constant.numeric rgb(9, 136, 90)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.constant.numeric rgb(181, 206, 168)"
}
},
{
"c": "]",
"t": "brace.coffee.meta.square",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": ")",
"t": "brace.coffee.meta.round",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "startRace ",
"t": "coffee.entity.function.meta.name",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.entity.name.function rgb(220, 220, 170)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.entity.name.function rgb(121, 94, 38)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.entity.name.function rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "=",
"t": "coffee.keyword.operator",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.keyword.operator rgb(212, 212, 212)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.keyword.operator rgb(0, 0, 0)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.keyword.operator rgb(212, 212, 212)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.keyword.operator rgb(0, 0, 0)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.keyword.operator rgb(212, 212, 212)"
}
},
{
"c": " ",
"t": "",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "(",
"t": "begin.coffee.definition.function.inline.meta.parameters.punctuation",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "vehicles",
"t": "coffee.function.inline.meta.parameter.variable",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.variable.parameter rgb(156, 220, 254)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.variable.parameter rgb(0, 16, 128)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": ")",
"t": "begin.coffee.definition.function.inline.meta.parameters.punctuation",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": " ",
"t": "coffee.function.inline.meta",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "->",
"t": "coffee.function.inline.meta.storage.type",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.storage.type rgb(86, 156, 214)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.storage.type rgb(0, 0, 255)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.storage.type rgb(86, 156, 214)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.storage.type rgb(0, 0, 255)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.storage.type rgb(86, 156, 214)"
}
},
{
"c": " ",
"t": "",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "[",
"t": "brace.coffee.meta.square",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "vehicle",
"t": "",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": ".",
"t": "coffee.delimiter.meta.method.period",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "drive",
"t": "",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "()",
"t": "brace.coffee.meta.round",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": " ",
"t": "",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "for",
"t": "coffee.control.keyword",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.keyword.control rgb(197, 134, 192)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.keyword.control rgb(175, 0, 219)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.keyword.control rgb(86, 156, 214)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.keyword.control rgb(0, 0, 255)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.keyword.control rgb(86, 156, 214)"
}
},
{
"c": " vehicle ",
"t": "",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "in",
"t": "coffee.control.keyword",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.keyword.control rgb(197, 134, 192)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.keyword.control rgb(175, 0, 219)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.keyword.control rgb(86, 156, 214)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.keyword.control rgb(0, 0, 255)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.keyword.control rgb(86, 156, 214)"
}
},
{
"c": " vehicles",
"t": "",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "]",
"t": "brace.coffee.meta.square",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "fancyRegExp",
"t": "assignment.coffee.other.variable",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.variable rgb(156, 220, 254)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.variable rgb(0, 16, 128)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": " ",
"t": "",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "=",
"t": "coffee.keyword.operator",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.keyword.operator rgb(212, 212, 212)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.keyword.operator rgb(0, 0, 0)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.keyword.operator rgb(212, 212, 212)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.keyword.operator rgb(0, 0, 0)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.keyword.operator rgb(212, 212, 212)"
}
},
{
"c": " ",
"t": "",
"r": {
"dark_plus": ".vs-dark .token rgb(212, 212, 212)",
"light_plus": ".vs .token rgb(0, 0, 0)",
"dark_vs": ".vs-dark .token rgb(212, 212, 212)",
"light_vs": ".vs .token rgb(0, 0, 0)",
"hc_black": ".hc-black .token rgb(255, 255, 255)"
}
},
{
"c": "///",
"t": "begin.block.coffee.definition.punctuation.regexp.string",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.string.regexp rgb(209, 105, 105)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.string.regexp rgb(129, 31, 63)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string.regexp rgb(209, 105, 105)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string.regexp rgb(129, 31, 63)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string.regexp rgb(209, 105, 105)"
}
},
{
"c": "\t",
"t": "block.coffee.regexp.string",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.string.regexp rgb(209, 105, 105)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.string.regexp rgb(129, 31, 63)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string.regexp rgb(209, 105, 105)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string.regexp rgb(129, 31, 63)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string.regexp rgb(209, 105, 105)"
}
},
{
"c": "(",
"t": "block.coffee.definition.group.meta.punctuation.regexp.string",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.string.regexp rgb(209, 105, 105)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.string.regexp rgb(129, 31, 63)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string.regexp rgb(209, 105, 105)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string.regexp rgb(129, 31, 63)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string.regexp rgb(209, 105, 105)"
}
},
{
"c": "\\d",
"t": "block.character.character-class.coffee.constant.group.meta.regexp.string",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.string.regexp rgb(209, 105, 105)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.string.regexp rgb(129, 31, 63)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string.regexp rgb(209, 105, 105)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string.regexp rgb(129, 31, 63)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string.regexp rgb(209, 105, 105)"
}
},
{
"c": "+",
"t": "block.coffee.group.keyword.meta.operator.quantifier.regexp.string",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.keyword.operator rgb(212, 212, 212)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.keyword.operator rgb(0, 0, 0)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.keyword.operator rgb(212, 212, 212)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.keyword.operator rgb(0, 0, 0)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.keyword.operator rgb(212, 212, 212)"
}
},
{
"c": ")",
"t": "block.coffee.definition.group.meta.punctuation.regexp.string",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.string.regexp rgb(209, 105, 105)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.string.regexp rgb(129, 31, 63)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string.regexp rgb(209, 105, 105)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string.regexp rgb(129, 31, 63)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string.regexp rgb(209, 105, 105)"
}
},
{
"c": "\t",
"t": "block.coffee.regexp.string",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.string.regexp rgb(209, 105, 105)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.string.regexp rgb(129, 31, 63)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string.regexp rgb(209, 105, 105)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string.regexp rgb(129, 31, 63)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string.regexp rgb(209, 105, 105)"
}
},
{
"c": "#",
"t": "block.coffee.comment.definition.line.number-sign.punctuation.regexp.string",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.string.regexp rgb(209, 105, 105)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.string.regexp rgb(129, 31, 63)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string.regexp rgb(209, 105, 105)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string.regexp rgb(129, 31, 63)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string.regexp rgb(209, 105, 105)"
}
},
{
"c": " numbers",
"t": "block.coffee.comment.line.number-sign.regexp.string",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.string.regexp rgb(209, 105, 105)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.string.regexp rgb(129, 31, 63)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string.regexp rgb(209, 105, 105)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string.regexp rgb(129, 31, 63)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string.regexp rgb(209, 105, 105)"
}
},
{
"c": "\t",
"t": "block.coffee.regexp.string",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.string.regexp rgb(209, 105, 105)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.string.regexp rgb(129, 31, 63)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string.regexp rgb(209, 105, 105)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string.regexp rgb(129, 31, 63)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string.regexp rgb(209, 105, 105)"
}
},
{
"c": "(",
"t": "block.coffee.definition.group.meta.punctuation.regexp.string",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.string.regexp rgb(209, 105, 105)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.string.regexp rgb(129, 31, 63)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string.regexp rgb(209, 105, 105)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string.regexp rgb(129, 31, 63)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string.regexp rgb(209, 105, 105)"
}
},
{
"c": "\\w",
"t": "block.character.character-class.coffee.constant.group.meta.regexp.string",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.string.regexp rgb(209, 105, 105)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.string.regexp rgb(129, 31, 63)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string.regexp rgb(209, 105, 105)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string.regexp rgb(129, 31, 63)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string.regexp rgb(209, 105, 105)"
}
},
{
"c": "*",
"t": "block.coffee.group.keyword.meta.operator.quantifier.regexp.string",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.keyword.operator rgb(212, 212, 212)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.keyword.operator rgb(0, 0, 0)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.keyword.operator rgb(212, 212, 212)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.keyword.operator rgb(0, 0, 0)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.keyword.operator rgb(212, 212, 212)"
}
},
{
"c": ")",
"t": "block.coffee.definition.group.meta.punctuation.regexp.string",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.string.regexp rgb(209, 105, 105)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.string.regexp rgb(129, 31, 63)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string.regexp rgb(209, 105, 105)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string.regexp rgb(129, 31, 63)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string.regexp rgb(209, 105, 105)"
}
},
{
"c": "\t",
"t": "block.coffee.regexp.string",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.string.regexp rgb(209, 105, 105)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.string.regexp rgb(129, 31, 63)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string.regexp rgb(209, 105, 105)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string.regexp rgb(129, 31, 63)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string.regexp rgb(209, 105, 105)"
}
},
{
"c": "#",
"t": "block.coffee.comment.definition.line.number-sign.punctuation.regexp.string",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.string.regexp rgb(209, 105, 105)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.string.regexp rgb(129, 31, 63)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string.regexp rgb(209, 105, 105)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string.regexp rgb(129, 31, 63)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string.regexp rgb(209, 105, 105)"
}
},
{
"c": " letters",
"t": "block.coffee.comment.line.number-sign.regexp.string",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.string.regexp rgb(209, 105, 105)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.string.regexp rgb(129, 31, 63)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string.regexp rgb(209, 105, 105)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string.regexp rgb(129, 31, 63)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string.regexp rgb(209, 105, 105)"
}
},
{
"c": "\t",
"t": "block.coffee.regexp.string",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.string.regexp rgb(209, 105, 105)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.string.regexp rgb(129, 31, 63)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string.regexp rgb(209, 105, 105)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string.regexp rgb(129, 31, 63)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string.regexp rgb(209, 105, 105)"
}
},
{
"c": "$",
"t": "anchor.block.coffee.control.keyword.regexp.string",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.keyword.control rgb(197, 134, 192)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.keyword.control rgb(175, 0, 219)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.keyword.control rgb(86, 156, 214)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.keyword.control rgb(0, 0, 255)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.keyword.control rgb(86, 156, 214)"
}
},
{
"c": "\t\t",
"t": "block.coffee.regexp.string",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.string.regexp rgb(209, 105, 105)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.string.regexp rgb(129, 31, 63)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string.regexp rgb(209, 105, 105)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string.regexp rgb(129, 31, 63)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string.regexp rgb(209, 105, 105)"
}
},
{
"c": "#",
"t": "block.coffee.comment.definition.line.number-sign.punctuation.regexp.string",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.string.regexp rgb(209, 105, 105)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.string.regexp rgb(129, 31, 63)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string.regexp rgb(209, 105, 105)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string.regexp rgb(129, 31, 63)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string.regexp rgb(209, 105, 105)"
}
},
{
"c": " the end",
"t": "block.coffee.comment.line.number-sign.regexp.string",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.string.regexp rgb(209, 105, 105)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.string.regexp rgb(129, 31, 63)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string.regexp rgb(209, 105, 105)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string.regexp rgb(129, 31, 63)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string.regexp rgb(209, 105, 105)"
}
},
{
"c": "///",
"t": "block.coffee.definition.end.punctuation.regexp.string",
"r": {
"dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.string.regexp rgb(209, 105, 105)",
"light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.string.regexp rgb(129, 31, 63)",
"dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string.regexp rgb(209, 105, 105)",
"light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string.regexp rgb(129, 31, 63)",
"hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string.regexp rgb(209, 105, 105)"
}
}
] | extensions/coffeescript/test/colorize-results/test_coffee.json | 0 | https://github.com/microsoft/vscode/commit/3978edfa64c9a7b8a8ba823e3ab30767457dc5c6 | [
0.00017495673091616482,
0.0001698755513643846,
0.00016453211719635874,
0.00016989806317724288,
0.0000021012226625316544
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.