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": 11, "code_window": [ "}\n", "\n", "// AzureMonitorQuery is the query for all the services as they have similar queries\n", "// with a url, a querystring and an alias field\n", "type AzureMonitorQuery struct {\n", "\tURL string\n", "\tTarget string\n", "\tParams url.Values\n", "\tRefID string\n", "\tAlias string\n", "\tTimeRange backend.TimeRange\n", "\tFilter string\n", "}\n", "\n", "// AzureMonitorResponse is the json response from the Azure Monitor API\n", "type AzureMonitorResponse struct {\n", "\tCost int `json:\"cost\"`\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tURL string\n", "\tTarget string\n", "\tParams url.Values\n", "\tRefID string\n", "\tAlias string\n", "\tTimeRange backend.TimeRange\n", "\tBodyFilter string\n" ], "file_path": "pkg/tsdb/azuremonitor/types/types.go", "type": "replace", "edit_start_line_idx": 61 }
package correlations import ( "bytes" "context" "fmt" "net/http" "testing" "github.com/grafana/grafana/pkg/server" "github.com/grafana/grafana/pkg/services/correlations" "github.com/grafana/grafana/pkg/services/datasources" "github.com/grafana/grafana/pkg/services/user" "github.com/grafana/grafana/pkg/tests/testinfra" "github.com/stretchr/testify/require" ) type errorResponseBody struct { Message string `json:"message"` Error string `json:"error"` } type TestContext struct { env server.TestEnv t *testing.T } func NewTestEnv(t *testing.T) TestContext { t.Helper() dir, path := testinfra.CreateGrafDir(t, testinfra.GrafanaOpts{ DisableAnonymous: true, }) _, env := testinfra.StartGrafanaEnv(t, dir, path) return TestContext{ env: *env, t: t, } } type User struct { username string password string } type GetParams struct { url string user User } func (c TestContext) Get(params GetParams) *http.Response { c.t.Helper() resp, err := http.Get(c.getURL(params.url, params.user)) require.NoError(c.t, err) return resp } type PostParams struct { url string body string user User } func (c TestContext) Post(params PostParams) *http.Response { c.t.Helper() buf := bytes.NewReader([]byte(params.body)) // nolint:gosec resp, err := http.Post( c.getURL(params.url, params.user), "application/json", buf, ) require.NoError(c.t, err) return resp } type PatchParams struct { url string body string user User } func (c TestContext) Patch(params PatchParams) *http.Response { c.t.Helper() req, err := http.NewRequest(http.MethodPatch, c.getURL(params.url, params.user), bytes.NewBuffer([]byte(params.body))) req.Header.Set("Content-Type", "application/json") require.NoError(c.t, err) resp, err := http.DefaultClient.Do(req) require.NoError(c.t, err) require.NoError(c.t, err) return resp } type DeleteParams struct { url string user User } func (c TestContext) Delete(params DeleteParams) *http.Response { c.t.Helper() req, err := http.NewRequest("DELETE", c.getURL(params.url, params.user), nil) require.NoError(c.t, err) resp, err := http.DefaultClient.Do(req) require.NoError(c.t, err) return resp } func (c TestContext) getURL(url string, user User) string { c.t.Helper() baseUrl := fmt.Sprintf("http://%s", c.env.Server.HTTPServer.Listener.Addr()) if user.username != "" && user.password != "" { baseUrl = fmt.Sprintf("http://%s:%s@%s", user.username, user.password, c.env.Server.HTTPServer.Listener.Addr()) } return fmt.Sprintf( "%s%s", baseUrl, url, ) } func (c TestContext) createUser(cmd user.CreateUserCommand) { c.t.Helper() c.env.SQLStore.Cfg.AutoAssignOrg = true c.env.SQLStore.Cfg.AutoAssignOrgId = 1 _, err := c.env.SQLStore.CreateUser(context.Background(), cmd) require.NoError(c.t, err) } func (c TestContext) createDs(cmd *datasources.AddDataSourceCommand) { c.t.Helper() err := c.env.Server.HTTPServer.DataSourcesService.AddDataSource(context.Background(), cmd) require.NoError(c.t, err) } func (c TestContext) createCorrelation(cmd correlations.CreateCorrelationCommand) correlations.Correlation { c.t.Helper() correlation, err := c.env.Server.HTTPServer.CorrelationsService.CreateCorrelation(context.Background(), cmd) require.NoError(c.t, err) return correlation }
pkg/tests/api/correlations/common_test.go
0
https://github.com/grafana/grafana/commit/a7d4bbf0248d0c6e5c6fd9f9ca55ffd399781c12
[ 0.004115755204111338, 0.0004426828818395734, 0.00016496410535182804, 0.0001715120451990515, 0.0009497192222625017 ]
{ "id": 11, "code_window": [ "}\n", "\n", "// AzureMonitorQuery is the query for all the services as they have similar queries\n", "// with a url, a querystring and an alias field\n", "type AzureMonitorQuery struct {\n", "\tURL string\n", "\tTarget string\n", "\tParams url.Values\n", "\tRefID string\n", "\tAlias string\n", "\tTimeRange backend.TimeRange\n", "\tFilter string\n", "}\n", "\n", "// AzureMonitorResponse is the json response from the Azure Monitor API\n", "type AzureMonitorResponse struct {\n", "\tCost int `json:\"cost\"`\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tURL string\n", "\tTarget string\n", "\tParams url.Values\n", "\tRefID string\n", "\tAlias string\n", "\tTimeRange backend.TimeRange\n", "\tBodyFilter string\n" ], "file_path": "pkg/tsdb/azuremonitor/types/types.go", "type": "replace", "edit_start_line_idx": 61 }
#!/bin/bash DEFAULT_RUNDIR=scripts/grafana-server/tmp RUNDIR=${RUNDIR:-$DEFAULT_RUNDIR} DEFAULT_ARCH= HOME_PATH=$PWD/$RUNDIR PIDFILE=$RUNDIR/pid PROV_DIR=$RUNDIR/conf/provisioning DEFAULT_HOST=localhost DEFAULT_PORT=3001
scripts/grafana-server/variables
0
https://github.com/grafana/grafana/commit/a7d4bbf0248d0c6e5c6fd9f9ca55ffd399781c12
[ 0.001806681975722313, 0.0009920698357746005, 0.000177457754034549, 0.0009920698357746005, 0.0008146121399477124 ]
{ "id": 0, "code_window": [ "\t\t\t}\n", "\t\t});\n", "\t}\n", "\n", "\tisKnownCommand(commandId: string): boolean {\n", "\t\tconst command = CommandsRegistry.getCommand(commandId);\n", "\n", "\t\tif (!command) {\n", "\t\t\treturn false;\n", "\t\t}\n", "\n", "\t\treturn true;\n", "\t}\n", "}" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep" ], "after_edit": [], "file_path": "src/vs/platform/commands/common/commandService.ts", "type": "replace", "edit_start_line_idx": 39 }
/*--------------------------------------------------------------------------------------------- * 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 {TypeConstraint, validateConstraints} from 'vs/base/common/types'; import {ServicesAccessor, createDecorator} from 'vs/platform/instantiation/common/instantiation'; export const ICommandService = createDecorator<ICommandService>('commandService'); export interface ICommandService { _serviceBrand: any; executeCommand<T>(commandId: string, ...args: any[]): TPromise<T>; executeCommand(commandId: string, ...args: any[]): TPromise<any>; isKnownCommand(commandId: string): boolean; } export interface ICommandsMap { [id: string]: ICommand; } export interface ICommandHandler { (accessor: ServicesAccessor, ...args: any[]): void; } export interface ICommand { handler: ICommandHandler; description?: ICommandHandlerDescription; } export interface ICommandHandlerDescription { description: string; args: { name: string; description?: string; constraint?: TypeConstraint; }[]; returns?: string; } export interface ICommandRegistry { registerCommand(id: string, command: ICommandHandler): void; registerCommand(id: string, command: ICommand): void; getCommand(id: string): ICommand; getCommands(): ICommandsMap; } function isCommand(thing: any): thing is ICommand { return typeof thing === 'object' && typeof (<ICommand>thing).handler === 'function' && (!(<ICommand>thing).description || typeof (<ICommand>thing).description === 'object'); } export const CommandsRegistry: ICommandRegistry = new class implements ICommandRegistry { private _commands: { [id: string]: ICommand } = Object.create(null); registerCommand(id: string, commandOrDesc: ICommandHandler | ICommand): void { // if (this._commands[id] !== void 0) { // throw new Error(`command already exists: '${id}'`); // } if (!commandOrDesc) { throw new Error(`invalid command`); } if (!isCommand(commandOrDesc)) { // simple handler this._commands[id] = { handler: commandOrDesc }; } else { const {handler, description} = commandOrDesc; if (description) { // add argument validation if rich command metadata is provided const constraints: TypeConstraint[] = []; for (let arg of description.args) { constraints.push(arg.constraint); } this._commands[id] = { description, handler(accessor, ...args: any[]) { validateConstraints(args, constraints); return handler(accessor, ...args); } }; } else { // add as simple handler this._commands[id] = { handler }; } } } getCommand(id: string): ICommand { return this._commands[id]; } getCommands(): ICommandsMap { return this._commands; } }; export const NullCommandService: ICommandService = { _serviceBrand: undefined, executeCommand() { return TPromise.as(undefined); }, isKnownCommand() { return false; } };
src/vs/platform/commands/common/commands.ts
1
https://github.com/microsoft/vscode/commit/f632cf311d6e97dbffd778d35bd4d4e92a818123
[ 0.013164625503122807, 0.003432811703532934, 0.00017642270540818572, 0.003146592527627945, 0.003527011489495635 ]
{ "id": 0, "code_window": [ "\t\t\t}\n", "\t\t});\n", "\t}\n", "\n", "\tisKnownCommand(commandId: string): boolean {\n", "\t\tconst command = CommandsRegistry.getCommand(commandId);\n", "\n", "\t\tif (!command) {\n", "\t\t\treturn false;\n", "\t\t}\n", "\n", "\t\treturn true;\n", "\t}\n", "}" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep" ], "after_edit": [], "file_path": "src/vs/platform/commands/common/commandService.ts", "type": "replace", "edit_start_line_idx": 39 }
/*--------------------------------------------------------------------------------------------- * 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. { "html.voidInput": "L'input dell'editor non è valido.", "iframeEditor": "Anteprima HTML" }
i18n/ita/src/vs/workbench/parts/html/browser/htmlPreviewPart.i18n.json
0
https://github.com/microsoft/vscode/commit/f632cf311d6e97dbffd778d35bd4d4e92a818123
[ 0.0001772845716914162, 0.0001772845716914162, 0.0001772845716914162, 0.0001772845716914162, 0 ]
{ "id": 0, "code_window": [ "\t\t\t}\n", "\t\t});\n", "\t}\n", "\n", "\tisKnownCommand(commandId: string): boolean {\n", "\t\tconst command = CommandsRegistry.getCommand(commandId);\n", "\n", "\t\tif (!command) {\n", "\t\t\treturn false;\n", "\t\t}\n", "\n", "\t\treturn true;\n", "\t}\n", "}" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep" ], "after_edit": [], "file_path": "src/vs/platform/commands/common/commandService.ts", "type": "replace", "edit_start_line_idx": 39 }
/*--------------------------------------------------------------------------------------------- * 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 strings from 'vs/base/common/strings'; import {WrappingIndent} from 'vs/editor/common/editorCommon'; import {PrefixSumComputer} from 'vs/editor/common/viewModel/prefixSumComputer'; import {ILineMapperFactory, ILineMapping, OutputPosition} from 'vs/editor/common/viewModel/splitLinesCollection'; enum CharacterClass { NONE = 0, BREAK_BEFORE = 1, BREAK_AFTER = 2, BREAK_OBTRUSIVE = 3, BREAK_IDEOGRAPHIC = 4 // for Han and Kana. } class CharacterClassifier { /** * Maintain a compact (fully initialized ASCII map for quickly classifying ASCII characters - used more often in code). */ private _asciiMap: CharacterClass[]; /** * The entire map (sparse array). */ private _map: CharacterClass[]; constructor(BREAK_BEFORE:string, BREAK_AFTER:string, BREAK_OBTRUSIVE:string) { this._asciiMap = []; for (let i = 0; i < 256; i++) { this._asciiMap[i] = CharacterClass.NONE; } this._map = []; for (let i = 0; i < BREAK_BEFORE.length; i++) { this._set(BREAK_BEFORE.charCodeAt(i), CharacterClass.BREAK_BEFORE); } for (let i = 0; i < BREAK_AFTER.length; i++) { this._set(BREAK_AFTER.charCodeAt(i), CharacterClass.BREAK_AFTER); } for (let i = 0; i < BREAK_OBTRUSIVE.length; i++) { this._set(BREAK_OBTRUSIVE.charCodeAt(i), CharacterClass.BREAK_OBTRUSIVE); } } private _set(charCode:number, charClass:CharacterClass): void { if (charCode < 256) { this._asciiMap[charCode] = charClass; } this._map[charCode] = charClass; } public classify(charCode:number): CharacterClass { if (charCode < 256) { return this._asciiMap[charCode]; } let charClass = this._map[charCode]; if (charClass) { return charClass; } // Initialize CharacterClass.BREAK_IDEOGRAPHIC for these Unicode ranges: // 1. CJK Unified Ideographs (0x4E00 -- 0x9FFF) // 2. CJK Unified Ideographs Extension A (0x3400 -- 0x4DBF) // 3. Hiragana and Katakana (0x3040 -- 0x30FF) if ( (charCode >= 0x3040 && charCode <= 0x30FF) || (charCode >= 0x3400 && charCode <= 0x4DBF) || (charCode >= 0x4E00 && charCode <= 0x9FFF) ) { return CharacterClass.BREAK_IDEOGRAPHIC; } return CharacterClass.NONE; } } export class CharacterHardWrappingLineMapperFactory implements ILineMapperFactory { private classifier:CharacterClassifier; constructor(breakBeforeChars:string, breakAfterChars:string, breakObtrusiveChars:string) { this.classifier = new CharacterClassifier(breakBeforeChars, breakAfterChars, breakObtrusiveChars); } // TODO@Alex -> duplicated in lineCommentCommand private static nextVisibleColumn(currentVisibleColumn:number, tabSize:number, isTab:boolean, columnSize:number): number { currentVisibleColumn = +currentVisibleColumn; //@perf tabSize = +tabSize; //@perf columnSize = +columnSize; //@perf if (isTab) { return currentVisibleColumn + (tabSize - (currentVisibleColumn % tabSize)); } return currentVisibleColumn + columnSize; } public createLineMapping(lineText: string, tabSize: number, breakingColumn: number, columnsForFullWidthChar:number, hardWrappingIndent:WrappingIndent): ILineMapping { if (breakingColumn === -1) { return null; } tabSize = +tabSize; //@perf breakingColumn = +breakingColumn; //@perf columnsForFullWidthChar = +columnsForFullWidthChar; //@perf hardWrappingIndent = +hardWrappingIndent; //@perf let wrappedTextIndentVisibleColumn = 0; let wrappedTextIndent = ''; const TAB_CHAR_CODE = '\t'.charCodeAt(0); let firstNonWhitespaceIndex = -1; if (hardWrappingIndent !== WrappingIndent.None) { firstNonWhitespaceIndex = strings.firstNonWhitespaceIndex(lineText); if (firstNonWhitespaceIndex !== -1) { wrappedTextIndent = lineText.substring(0, firstNonWhitespaceIndex); for (let i = 0; i < firstNonWhitespaceIndex; i++) { wrappedTextIndentVisibleColumn = CharacterHardWrappingLineMapperFactory.nextVisibleColumn(wrappedTextIndentVisibleColumn, tabSize, lineText.charCodeAt(i) === TAB_CHAR_CODE, 1); } if (hardWrappingIndent === WrappingIndent.Indent) { wrappedTextIndent += '\t'; wrappedTextIndentVisibleColumn = CharacterHardWrappingLineMapperFactory.nextVisibleColumn(wrappedTextIndentVisibleColumn, tabSize, true, 1); } // Force sticking to beginning of line if indentColumn > 66% breakingColumn if (wrappedTextIndentVisibleColumn > 1/2 * breakingColumn) { wrappedTextIndent = ''; wrappedTextIndentVisibleColumn = 0; } } } let classifier = this.classifier; let lastBreakingOffset = 0; // Last 0-based offset in the lineText at which a break happened let breakingLengths:number[] = []; // The length of each broken-up line text let breakingLengthsIndex:number = 0; // The count of breaks already done let visibleColumn = 0; // Visible column since the beginning of the current line let breakBeforeOffset:number; // 0-based offset in the lineText before which breaking let restoreVisibleColumnFrom:number; let niceBreakOffset = -1; // Last index of a character that indicates a break should happen before it (more desirable) let niceBreakVisibleColumn = 0; // visible column if a break were to be later introduced before `niceBreakOffset` let obtrusiveBreakOffset = -1; // Last index of a character that indicates a break should happen before it (less desirable) let obtrusiveBreakVisibleColumn = 0; // visible column if a break were to be later introduced before `obtrusiveBreakOffset` let len = lineText.length; for (let i = 0; i < len; i++) { // At this point, there is a certainty that the character before `i` fits on the current line, // but the character at `i` might not fit let charCode = lineText.charCodeAt(i); let charCodeIsTab = (charCode === TAB_CHAR_CODE); let charCodeClass = classifier.classify(charCode); if (charCodeClass === CharacterClass.BREAK_BEFORE) { // This is a character that indicates that a break should happen before it // Since we are certain the character before `i` fits, there's no extra checking needed, // just mark it as a nice breaking opportunity niceBreakOffset = i; niceBreakVisibleColumn = 0; } // CJK breaking : before break if (charCodeClass === CharacterClass.BREAK_IDEOGRAPHIC && i > 0) { let prevCode = lineText.charCodeAt(i - 1); let prevClass = classifier.classify(prevCode); if (prevClass !== CharacterClass.BREAK_BEFORE) { // Kinsoku Shori: Don't break after a leading character, like an open bracket niceBreakOffset = i; niceBreakVisibleColumn = 0; } } let charColumnSize = 1; if (strings.isFullWidthCharacter(charCode)) { charColumnSize = columnsForFullWidthChar; } // Advance visibleColumn with character at `i` visibleColumn = CharacterHardWrappingLineMapperFactory.nextVisibleColumn(visibleColumn, tabSize, charCodeIsTab, charColumnSize); if (visibleColumn > breakingColumn && i !== 0) { // We need to break at least before character at `i`: // - break before niceBreakLastOffset if it exists (and re-establish a correct visibleColumn by using niceBreakVisibleColumn + charAt(i)) // - otherwise, break before obtrusiveBreakLastOffset if it exists (and re-establish a correct visibleColumn by using obtrusiveBreakVisibleColumn + charAt(i)) // - otherwise, break before i (and re-establish a correct visibleColumn by charAt(i)) if (niceBreakOffset !== -1) { // We will break before `niceBreakLastOffset` breakBeforeOffset = niceBreakOffset; restoreVisibleColumnFrom = niceBreakVisibleColumn; } else if (obtrusiveBreakOffset !== -1) { // We will break before `obtrusiveBreakLastOffset` breakBeforeOffset = obtrusiveBreakOffset; restoreVisibleColumnFrom = obtrusiveBreakVisibleColumn; } else { // We will break before `i` breakBeforeOffset = i; restoreVisibleColumnFrom = wrappedTextIndentVisibleColumn; } // Break before character at `breakBeforeOffset` breakingLengths[breakingLengthsIndex++] = breakBeforeOffset - lastBreakingOffset; lastBreakingOffset = breakBeforeOffset; // Re-establish visibleColumn by taking character at `i` into account visibleColumn = CharacterHardWrappingLineMapperFactory.nextVisibleColumn(restoreVisibleColumnFrom, tabSize, charCodeIsTab, charColumnSize); // Reset markers niceBreakOffset = -1; niceBreakVisibleColumn = 0; obtrusiveBreakOffset = -1; obtrusiveBreakVisibleColumn = 0; } // At this point, there is a certainty that the character at `i` fits on the current line if (niceBreakOffset !== -1) { // Advance niceBreakVisibleColumn niceBreakVisibleColumn = CharacterHardWrappingLineMapperFactory.nextVisibleColumn(niceBreakVisibleColumn, tabSize, charCodeIsTab, charColumnSize); } if (obtrusiveBreakOffset !== -1) { // Advance obtrusiveBreakVisibleColumn obtrusiveBreakVisibleColumn = CharacterHardWrappingLineMapperFactory.nextVisibleColumn(obtrusiveBreakVisibleColumn, tabSize, charCodeIsTab, charColumnSize); } if (charCodeClass === CharacterClass.BREAK_AFTER && (hardWrappingIndent === WrappingIndent.None || i >= firstNonWhitespaceIndex)) { // This is a character that indicates that a break should happen after it niceBreakOffset = i + 1; niceBreakVisibleColumn = wrappedTextIndentVisibleColumn; } // CJK breaking : after break if (charCodeClass === CharacterClass.BREAK_IDEOGRAPHIC && i < len - 1) { let nextCode = lineText.charCodeAt(i + 1); let nextClass = classifier.classify(nextCode); if (nextClass !== CharacterClass.BREAK_AFTER) { // Kinsoku Shori: Don't break before a trailing character, like a period niceBreakOffset = i + 1; niceBreakVisibleColumn = wrappedTextIndentVisibleColumn; } } if (charCodeClass === CharacterClass.BREAK_OBTRUSIVE) { // This is an obtrusive character that indicates that a break should happen after it obtrusiveBreakOffset = i + 1; obtrusiveBreakVisibleColumn = wrappedTextIndentVisibleColumn; } } if (breakingLengthsIndex === 0) { return null; } // Add last segment breakingLengths[breakingLengthsIndex++] = len - lastBreakingOffset; return new CharacterHardWrappingLineMapping(new PrefixSumComputer(breakingLengths), wrappedTextIndent); } } export class CharacterHardWrappingLineMapping implements ILineMapping { private _prefixSums:PrefixSumComputer; private _wrappedLinesIndent:string; constructor(prefixSums:PrefixSumComputer, wrappedLinesIndent:string) { this._prefixSums = prefixSums; this._wrappedLinesIndent = wrappedLinesIndent; } public getOutputLineCount(): number { return this._prefixSums.getCount(); } public getWrappedLinesIndent(): string { return this._wrappedLinesIndent; } public getInputOffsetOfOutputPosition(outputLineIndex:number, outputOffset:number): number { if (outputLineIndex === 0) { return outputOffset; } else { return this._prefixSums.getAccumulatedValue(outputLineIndex - 1) + outputOffset; } } public getOutputPositionOfInputOffset(inputOffset:number): OutputPosition { let r = this._prefixSums.getIndexOf(inputOffset); return new OutputPosition(r.index, r.remainder); } }
src/vs/editor/common/viewModel/characterHardWrappingLineMapper.ts
0
https://github.com/microsoft/vscode/commit/f632cf311d6e97dbffd778d35bd4d4e92a818123
[ 0.00030028808396309614, 0.0001800104946596548, 0.00016416948346886784, 0.00017377396579831839, 0.00002705924998736009 ]
{ "id": 0, "code_window": [ "\t\t\t}\n", "\t\t});\n", "\t}\n", "\n", "\tisKnownCommand(commandId: string): boolean {\n", "\t\tconst command = CommandsRegistry.getCommand(commandId);\n", "\n", "\t\tif (!command) {\n", "\t\t\treturn false;\n", "\t\t}\n", "\n", "\t\treturn true;\n", "\t}\n", "}" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep" ], "after_edit": [], "file_path": "src/vs/platform/commands/common/commandService.ts", "type": "replace", "edit_start_line_idx": 39 }
[ { "c": "FROM", "t": "dockerfile.keyword.other.special-method", "r": { "dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.keyword rgb(86, 156, 214)", "light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.keyword rgb(0, 0, 255)", "dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.keyword rgb(86, 156, 214)", "light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.keyword rgb(0, 0, 255)", "hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.keyword rgb(86, 156, 214)" } }, { "c": " ubuntu", "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": "MAINTAINER", "t": "dockerfile.keyword.other.special-method", "r": { "dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.keyword rgb(86, 156, 214)", "light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.keyword rgb(0, 0, 255)", "dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.keyword rgb(86, 156, 214)", "light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.keyword rgb(0, 0, 255)", "hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.keyword rgb(86, 156, 214)" } }, { "c": " Kimbro Staken", "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": "RUN", "t": "dockerfile.keyword.other.special-method", "r": { "dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.keyword rgb(86, 156, 214)", "light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.keyword rgb(0, 0, 255)", "dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.keyword rgb(86, 156, 214)", "light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.keyword rgb(0, 0, 255)", "hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.keyword rgb(86, 156, 214)" } }, { "c": " apt-get install -y software-properties-common python", "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": "RUN", "t": "dockerfile.keyword.other.special-method", "r": { "dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.keyword rgb(86, 156, 214)", "light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.keyword rgb(0, 0, 255)", "dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.keyword rgb(86, 156, 214)", "light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.keyword rgb(0, 0, 255)", "hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.keyword rgb(86, 156, 214)" } }, { "c": " add-apt-repository ppa:chris-lea/node.js", "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": "RUN", "t": "dockerfile.keyword.other.special-method", "r": { "dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.keyword rgb(86, 156, 214)", "light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.keyword rgb(0, 0, 255)", "dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.keyword rgb(86, 156, 214)", "light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.keyword rgb(0, 0, 255)", "hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.keyword rgb(86, 156, 214)" } }, { "c": " echo ", "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": "\"deb http://us.archive.ubuntu.com/ubuntu/ precise universe\"", "t": "dockerfile.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": " >> /etc/apt/sources.list", "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": "RUN", "t": "dockerfile.keyword.other.special-method", "r": { "dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.keyword rgb(86, 156, 214)", "light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.keyword rgb(0, 0, 255)", "dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.keyword rgb(86, 156, 214)", "light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.keyword rgb(0, 0, 255)", "hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.keyword rgb(86, 156, 214)" } }, { "c": " apt-get update", "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": "RUN", "t": "dockerfile.keyword.other.special-method", "r": { "dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.keyword rgb(86, 156, 214)", "light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.keyword rgb(0, 0, 255)", "dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.keyword rgb(86, 156, 214)", "light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.keyword rgb(0, 0, 255)", "hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.keyword rgb(86, 156, 214)" } }, { "c": " apt-get install -y nodejs", "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": "comment.definition.dockerfile.line.number-sign.punctuation", "r": { "dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.comment rgb(96, 139, 78)", "light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.comment rgb(0, 128, 0)", "dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.comment rgb(96, 139, 78)", "light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.comment rgb(0, 128, 0)", "hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.comment rgb(124, 166, 104)" } }, { "c": "RUN apt-get install -y nodejs=0.6.12~dfsg1-1ubuntu1", "t": "comment.dockerfile.line.number-sign", "r": { "dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.comment rgb(96, 139, 78)", "light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.comment rgb(0, 128, 0)", "dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.comment rgb(96, 139, 78)", "light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.comment rgb(0, 128, 0)", "hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.comment rgb(124, 166, 104)" } }, { "c": "RUN", "t": "dockerfile.keyword.other.special-method", "r": { "dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.keyword rgb(86, 156, 214)", "light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.keyword rgb(0, 0, 255)", "dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.keyword rgb(86, 156, 214)", "light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.keyword rgb(0, 0, 255)", "hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.keyword rgb(86, 156, 214)" } }, { "c": " mkdir /var/www", "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": "ADD", "t": "dockerfile.keyword.other.special-method", "r": { "dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.keyword rgb(86, 156, 214)", "light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.keyword rgb(0, 0, 255)", "dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.keyword rgb(86, 156, 214)", "light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.keyword rgb(0, 0, 255)", "hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.keyword rgb(86, 156, 214)" } }, { "c": " app.js /var/www/app.js", "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": "CMD", "t": "dockerfile.keyword.other.special-method", "r": { "dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.keyword rgb(86, 156, 214)", "light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.keyword rgb(0, 0, 255)", "dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.keyword rgb(86, 156, 214)", "light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.keyword rgb(0, 0, 255)", "hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.keyword 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": "\"/usr/bin/node\"", "t": "dockerfile.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": "", "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": "\"/var/www/app.js\"", "t": "dockerfile.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": "", "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)" } } ]
extensions/docker/test/colorize-results/Dockerfile.json
0
https://github.com/microsoft/vscode/commit/f632cf311d6e97dbffd778d35bd4d4e92a818123
[ 0.00017976161325350404, 0.0001737917773425579, 0.0001710211072349921, 0.00017384954844601452, 0.0000015658504253224237 ]
{ "id": 1, "code_window": [ "\n", "export interface ICommandService {\n", "\t_serviceBrand: any;\n", "\texecuteCommand<T>(commandId: string, ...args: any[]): TPromise<T>;\n", "\texecuteCommand(commandId: string, ...args: any[]): TPromise<any>;\n", "\tisKnownCommand(commandId: string): boolean;\n", "}\n", "\n", "export interface ICommandsMap {\n", "\t[id: string]: ICommand;\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/platform/commands/common/commands.ts", "type": "replace", "edit_start_line_idx": 16 }
/*--------------------------------------------------------------------------------------------- * 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 {IInstantiationService} from 'vs/platform/instantiation/common/instantiation'; import {ICommandService, CommandsRegistry} from 'vs/platform/commands/common/commands'; import {IExtensionService} from 'vs/platform/extensions/common/extensions'; export class CommandService implements ICommandService { _serviceBrand: any; constructor( @IInstantiationService private _instantiationService: IInstantiationService, @IExtensionService private _extensionService: IExtensionService ) { // } executeCommand<T>(id: string, ...args: any[]): TPromise<T> { return this._extensionService.activateByEvent(`onCommand:${id}`).then(_ => { const command = CommandsRegistry.getCommand(id); if (!command) { return TPromise.wrapError(new Error(`command '${id}' not found`)); } try { const result = this._instantiationService.invokeFunction.apply(this._instantiationService, [command.handler].concat(args)); return TPromise.as(result); } catch (err) { return TPromise.wrapError(err); } }); } isKnownCommand(commandId: string): boolean { const command = CommandsRegistry.getCommand(commandId); if (!command) { return false; } return true; } }
src/vs/platform/commands/common/commandService.ts
1
https://github.com/microsoft/vscode/commit/f632cf311d6e97dbffd778d35bd4d4e92a818123
[ 0.9992004036903381, 0.17030392587184906, 0.00017274376295972615, 0.004488829988986254, 0.37072423100471497 ]
{ "id": 1, "code_window": [ "\n", "export interface ICommandService {\n", "\t_serviceBrand: any;\n", "\texecuteCommand<T>(commandId: string, ...args: any[]): TPromise<T>;\n", "\texecuteCommand(commandId: string, ...args: any[]): TPromise<any>;\n", "\tisKnownCommand(commandId: string): boolean;\n", "}\n", "\n", "export interface ICommandsMap {\n", "\t[id: string]: ICommand;\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/platform/commands/common/commands.ts", "type": "replace", "edit_start_line_idx": 16 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import winjs = require('vs/base/common/winjs.base'); import {WorkbenchShell} from 'vs/workbench/electron-browser/shell'; import {IOptions, IGlobalSettings} from 'vs/workbench/common/options'; import errors = require('vs/base/common/errors'); import platform = require('vs/base/common/platform'); import paths = require('vs/base/common/paths'); import timer = require('vs/base/common/timer'); import {assign} from 'vs/base/common/objects'; import uri from 'vs/base/common/uri'; import strings = require('vs/base/common/strings'); import {IResourceInput} from 'vs/platform/editor/common/editor'; import {EventService} from 'vs/platform/event/common/eventService'; import {WorkspaceContextService} from 'vs/workbench/services/workspace/common/contextService'; import {IWorkspace, IConfiguration, IEnvironment} from 'vs/platform/workspace/common/workspace'; import {ConfigurationService} from 'vs/workbench/services/configuration/node/configurationService'; import path = require('path'); import fs = require('fs'); import gracefulFs = require('graceful-fs'); gracefulFs.gracefulify(fs); const timers = (<any>window).MonacoEnvironment.timers; function domContentLoaded(): winjs.Promise { return new winjs.Promise((c, e) => { var readyState = document.readyState; if (readyState === 'complete' || (document && document.body !== null)) { window.setImmediate(c); } else { window.addEventListener('DOMContentLoaded', c, false); } }); } export interface IPath { filePath: string; lineNumber?: number; columnNumber?: number; } export interface IMainEnvironment extends IEnvironment { workspacePath?: string; filesToOpen?: IPath[]; filesToCreate?: IPath[]; filesToDiff?: IPath[]; extensionsToInstall?: string[]; userEnv: { [key: string]: string; }; } export function startup(environment: IMainEnvironment, globalSettings: IGlobalSettings): winjs.TPromise<void> { // Inherit the user environment // TODO@Joao: this inheritance should **not** happen here! if (process.env['VSCODE_CLI'] !== '1') { assign(process.env, environment.userEnv); } // Shell Configuration let shellConfiguration: IConfiguration = { env: environment }; // Shell Options let filesToOpen = environment.filesToOpen && environment.filesToOpen.length ? toInputs(environment.filesToOpen) : null; let filesToCreate = environment.filesToCreate && environment.filesToCreate.length ? toInputs(environment.filesToCreate) : null; let filesToDiff = environment.filesToDiff && environment.filesToDiff.length ? toInputs(environment.filesToDiff) : null; let shellOptions: IOptions = { singleFileMode: !environment.workspacePath, filesToOpen: filesToOpen, filesToCreate: filesToCreate, filesToDiff: filesToDiff, extensionsToInstall: environment.extensionsToInstall, globalSettings: globalSettings }; if (environment.enablePerformance) { timer.ENABLE_TIMER = true; } // Open workbench return openWorkbench(getWorkspace(environment), shellConfiguration, shellOptions); } function toInputs(paths: IPath[]): IResourceInput[] { return paths.map(p => { let input = <IResourceInput>{ resource: uri.file(p.filePath) }; if (p.lineNumber) { input.options = { selection: { startLineNumber: p.lineNumber, startColumn: p.columnNumber } }; } return input; }); } function getWorkspace(environment: IMainEnvironment): IWorkspace { if (!environment.workspacePath) { return null; } let realWorkspacePath = path.normalize(fs.realpathSync(environment.workspacePath)); if (paths.isUNC(realWorkspacePath) && strings.endsWith(realWorkspacePath, paths.nativeSep)) { // for some weird reason, node adds a trailing slash to UNC paths // we never ever want trailing slashes as our workspace path unless // someone opens root ("/"). // See also https://github.com/nodejs/io.js/issues/1765 realWorkspacePath = strings.rtrim(realWorkspacePath, paths.nativeSep); } let workspaceResource = uri.file(realWorkspacePath); let folderName = path.basename(realWorkspacePath) || realWorkspacePath; let folderStat = fs.statSync(realWorkspacePath); let workspace: IWorkspace = { 'resource': workspaceResource, 'id': platform.isLinux ? realWorkspacePath : realWorkspacePath.toLowerCase(), 'name': folderName, 'uid': platform.isLinux ? folderStat.ino : folderStat.birthtime.getTime(), // On Linux, birthtime is ctime, so we cannot use it! We use the ino instead! 'mtime': folderStat.mtime.getTime() }; return workspace; } function openWorkbench(workspace: IWorkspace, configuration: IConfiguration, options: IOptions): winjs.TPromise<void> { let eventService = new EventService(); let contextService = new WorkspaceContextService(eventService, workspace, configuration, options); let configurationService = new ConfigurationService(contextService, eventService); // Since the configuration service is one of the core services that is used in so many places, we initialize it // right before startup of the workbench shell to have its data ready for consumers return configurationService.initialize().then(() => { timers.beforeReady = new Date(); return domContentLoaded().then(() => { timers.afterReady = new Date(); // Open Shell let beforeOpen = new Date(); let shell = new WorkbenchShell(document.body, workspace, { configurationService, eventService, contextService }, configuration, options); shell.open(); shell.joinCreation().then(() => { timer.start(timer.Topic.STARTUP, 'Open Shell, Viewlet & Editor', beforeOpen, 'Workbench has opened after this event with viewlet and editor restored').stop(); }); // Inform user about loading issues from the loader (<any>self).require.config({ onError: (err: any) => { if (err.errorCode === 'load') { shell.onUnexpectedError(errors.loaderError(err)); } } }); }); }); }
src/vs/workbench/electron-browser/main.ts
0
https://github.com/microsoft/vscode/commit/f632cf311d6e97dbffd778d35bd4d4e92a818123
[ 0.00027222727658227086, 0.00017877703066915274, 0.00016873156710062176, 0.0001737221027724445, 0.000022780355720897205 ]
{ "id": 1, "code_window": [ "\n", "export interface ICommandService {\n", "\t_serviceBrand: any;\n", "\texecuteCommand<T>(commandId: string, ...args: any[]): TPromise<T>;\n", "\texecuteCommand(commandId: string, ...args: any[]): TPromise<any>;\n", "\tisKnownCommand(commandId: string): boolean;\n", "}\n", "\n", "export interface ICommandsMap {\n", "\t[id: string]: ICommand;\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/platform/commands/common/commands.ts", "type": "replace", "edit_start_line_idx": 16 }
/*--------------------------------------------------------------------------------------------- * 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 assert = require('assert'); import model = require('vs/platform/configuration/common/model'); suite('ConfigurationService - Model', () => { test('simple merge', () => { let base = { 'a': 1, 'b': 2 }; model.merge(base, { 'a': 3, 'c': 4 }, true); assert.deepEqual(base, { 'a': 3, 'b': 2, 'c': 4 }); base = { 'a': 1, 'b': 2 }; model.merge(base, { 'a': 3, 'c': 4 }, false); assert.deepEqual(base, { 'a': 1, 'b': 2, 'c': 4 }); }); test('Recursive merge', () => { let base = { 'a': { 'b': 1 } }; model.merge(base, { 'a': { 'b': 2 } }, true); assert.deepEqual(base, { 'a': { 'b': 2 } }); }); test('Test consolidate (settings)', () => { let config1: model.IConfigFile = { contents: { awesome: true } }; let config2: model.IConfigFile = { contents: { awesome: false } }; let expected = { awesome: false }; assert.deepEqual(model.consolidate({ '.vscode/team.settings.json': config1, '.vscode/settings.json': config2 }).contents, expected); assert.deepEqual(model.consolidate({ 'settings.json': config2, 'team.settings.json': config1 }).contents, {}); assert.deepEqual(model.consolidate({ '.vscode/team.settings.json': config1, '.vscode/settings.json': config2, '.vscode/team2.settings.json': config1 }).contents, expected); }); test('Test consolidate (settings and tasks)', () => { let config1: model.IConfigFile = { contents: { awesome: true } }; let config2: model.IConfigFile = { contents: { awesome: false } }; let expected = { awesome: true, tasks: { awesome: false } }; assert.deepEqual(model.consolidate({ '.vscode/settings.json': config1, '.vscode/tasks.json': config2 }).contents, expected); }); });
src/vs/platform/configuration/test/common/model.test.ts
0
https://github.com/microsoft/vscode/commit/f632cf311d6e97dbffd778d35bd4d4e92a818123
[ 0.00017769123951438814, 0.00017570951604284346, 0.00017284938076045364, 0.00017609531641937792, 0.0000014511211929857382 ]
{ "id": 1, "code_window": [ "\n", "export interface ICommandService {\n", "\t_serviceBrand: any;\n", "\texecuteCommand<T>(commandId: string, ...args: any[]): TPromise<T>;\n", "\texecuteCommand(commandId: string, ...args: any[]): TPromise<any>;\n", "\tisKnownCommand(commandId: string): boolean;\n", "}\n", "\n", "export interface ICommandsMap {\n", "\t[id: string]: ICommand;\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/platform/commands/common/commands.ts", "type": "replace", "edit_start_line_idx": 16 }
/*--------------------------------------------------------------------------------------------- * 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. { "label": "기호 이동..." }
i18n/kor/src/vs/editor/contrib/quickOpen/browser/quickOutline.contribution.i18n.json
0
https://github.com/microsoft/vscode/commit/f632cf311d6e97dbffd778d35bd4d4e92a818123
[ 0.00017832672165241092, 0.00017832672165241092, 0.00017832672165241092, 0.00017832672165241092, 0 ]
{ "id": 2, "code_window": [ "\t_serviceBrand: undefined,\n", "\texecuteCommand() {\n", "\t\treturn TPromise.as(undefined);\n", "\t},\n", "\tisKnownCommand() {\n", "\t\treturn false;\n", "\t}\n", "};\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/platform/commands/common/commands.ts", "type": "replace", "edit_start_line_idx": 102 }
/*--------------------------------------------------------------------------------------------- * 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 {TypeConstraint, validateConstraints} from 'vs/base/common/types'; import {ServicesAccessor, createDecorator} from 'vs/platform/instantiation/common/instantiation'; export const ICommandService = createDecorator<ICommandService>('commandService'); export interface ICommandService { _serviceBrand: any; executeCommand<T>(commandId: string, ...args: any[]): TPromise<T>; executeCommand(commandId: string, ...args: any[]): TPromise<any>; isKnownCommand(commandId: string): boolean; } export interface ICommandsMap { [id: string]: ICommand; } export interface ICommandHandler { (accessor: ServicesAccessor, ...args: any[]): void; } export interface ICommand { handler: ICommandHandler; description?: ICommandHandlerDescription; } export interface ICommandHandlerDescription { description: string; args: { name: string; description?: string; constraint?: TypeConstraint; }[]; returns?: string; } export interface ICommandRegistry { registerCommand(id: string, command: ICommandHandler): void; registerCommand(id: string, command: ICommand): void; getCommand(id: string): ICommand; getCommands(): ICommandsMap; } function isCommand(thing: any): thing is ICommand { return typeof thing === 'object' && typeof (<ICommand>thing).handler === 'function' && (!(<ICommand>thing).description || typeof (<ICommand>thing).description === 'object'); } export const CommandsRegistry: ICommandRegistry = new class implements ICommandRegistry { private _commands: { [id: string]: ICommand } = Object.create(null); registerCommand(id: string, commandOrDesc: ICommandHandler | ICommand): void { // if (this._commands[id] !== void 0) { // throw new Error(`command already exists: '${id}'`); // } if (!commandOrDesc) { throw new Error(`invalid command`); } if (!isCommand(commandOrDesc)) { // simple handler this._commands[id] = { handler: commandOrDesc }; } else { const {handler, description} = commandOrDesc; if (description) { // add argument validation if rich command metadata is provided const constraints: TypeConstraint[] = []; for (let arg of description.args) { constraints.push(arg.constraint); } this._commands[id] = { description, handler(accessor, ...args: any[]) { validateConstraints(args, constraints); return handler(accessor, ...args); } }; } else { // add as simple handler this._commands[id] = { handler }; } } } getCommand(id: string): ICommand { return this._commands[id]; } getCommands(): ICommandsMap { return this._commands; } }; export const NullCommandService: ICommandService = { _serviceBrand: undefined, executeCommand() { return TPromise.as(undefined); }, isKnownCommand() { return false; } };
src/vs/platform/commands/common/commands.ts
1
https://github.com/microsoft/vscode/commit/f632cf311d6e97dbffd778d35bd4d4e92a818123
[ 0.04779055714607239, 0.005174107383936644, 0.00016800095909275115, 0.00047412377898581326, 0.013507259078323841 ]
{ "id": 2, "code_window": [ "\t_serviceBrand: undefined,\n", "\texecuteCommand() {\n", "\t\treturn TPromise.as(undefined);\n", "\t},\n", "\tisKnownCommand() {\n", "\t\treturn false;\n", "\t}\n", "};\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/platform/commands/common/commands.ts", "type": "replace", "edit_start_line_idx": 102 }
:root { --spacing-unit: 6px; --cell-padding: (4 * var(--spacing-unit)); } body { padding-left: calc(4 * var(--spacing-unit, 5px)); }
extensions/scss/test/colorize-fixtures/test-cssvariables.scss
0
https://github.com/microsoft/vscode/commit/f632cf311d6e97dbffd778d35bd4d4e92a818123
[ 0.00017423686222173274, 0.00017423686222173274, 0.00017423686222173274, 0.00017423686222173274, 0 ]
{ "id": 2, "code_window": [ "\t_serviceBrand: undefined,\n", "\texecuteCommand() {\n", "\t\treturn TPromise.as(undefined);\n", "\t},\n", "\tisKnownCommand() {\n", "\t\treturn false;\n", "\t}\n", "};\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/platform/commands/common/commands.ts", "type": "replace", "edit_start_line_idx": 102 }
/*--------------------------------------------------------------------------------------------- * 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 EditorCommon = require('vs/editor/common/editorCommon'); import Event, {Emitter} from 'vs/base/common/event'; import {IEditor} from 'vs/platform/editor/common/editor'; import {ICodeEditorService} from 'vs/editor/common/services/codeEditorService'; import {IModelService} from 'vs/editor/common/services/modelService'; import {IDisposable, dispose} from 'vs/base/common/lifecycle'; import {RunOnceScheduler} from 'vs/base/common/async'; import {IdGenerator} from 'vs/base/common/idGenerator'; import {Range} from 'vs/editor/common/core/range'; import {Selection} from 'vs/editor/common/core/selection'; import {EndOfLine} from 'vs/workbench/api/node/extHostTypes'; export interface ITextEditorConfigurationUpdate { tabSize?: number | string; insertSpaces?: boolean | string; cursorStyle?: EditorCommon.TextEditorCursorStyle; } export interface IResolvedTextEditorConfiguration { tabSize: number; insertSpaces: boolean; cursorStyle: EditorCommon.TextEditorCursorStyle; } function configurationsEqual(a:IResolvedTextEditorConfiguration, b:IResolvedTextEditorConfiguration) { if (a && !b || !a && b) { return false; } if (!a && !b) { return true; } return ( a.tabSize === b.tabSize && a.insertSpaces === b.insertSpaces ); } export interface IFocusTracker { onGainedFocus(): void; onLostFocus(): void; } export enum TextEditorRevealType { Default = 0, InCenter = 1, InCenterIfOutsideViewport = 2 } /** * Text Editor that is permanently bound to the same model. * It can be bound or not to a CodeEditor. */ export class MainThreadTextEditor { private _id: string; private _model: EditorCommon.IModel; private _modelService: IModelService; private _modelListeners: IDisposable[]; private _codeEditor: EditorCommon.ICommonCodeEditor; private _focusTracker: IFocusTracker; private _codeEditorListeners: IDisposable[]; private _lastSelection: Selection[]; private _configuration: IResolvedTextEditorConfiguration; private _onSelectionChanged: Emitter<Selection[]>; private _onConfigurationChanged: Emitter<IResolvedTextEditorConfiguration>; constructor( id: string, model:EditorCommon.IModel, codeEditor:EditorCommon.ICommonCodeEditor, focusTracker:IFocusTracker, modelService: IModelService ) { this._id = id; this._model = model; this._codeEditor = null; this._focusTracker = focusTracker; this._modelService = modelService; this._codeEditorListeners = []; this._onSelectionChanged = new Emitter<Selection[]>(); this._onConfigurationChanged = new Emitter<IResolvedTextEditorConfiguration>(); this._lastSelection = [ new Selection(1,1,1,1) ]; this._setConfiguration(this._readConfiguration(this._model, this._codeEditor)); this._modelListeners = []; this._modelListeners.push(this._model.onDidChangeOptions((e) => { this._setConfiguration(this._readConfiguration(this._model, this._codeEditor)); })); this.setCodeEditor(codeEditor); } public dispose(): void { this._model = null; this._modelListeners = dispose(this._modelListeners); this._codeEditor = null; this._codeEditorListeners = dispose(this._codeEditorListeners); } public getId(): string { return this._id; } public getModel(): EditorCommon.IModel { return this._model; } public hasCodeEditor(codeEditor:EditorCommon.ICommonCodeEditor): boolean { return (this._codeEditor === codeEditor); } public setCodeEditor(codeEditor:EditorCommon.ICommonCodeEditor): void { if (this.hasCodeEditor(codeEditor)) { // Nothing to do... return; } this._codeEditorListeners = dispose(this._codeEditorListeners); this._codeEditor = codeEditor; if (this._codeEditor) { // Catch early the case that this code editor gets a different model set and disassociate from this model this._codeEditorListeners.push(this._codeEditor.onDidChangeModel(() => { this.setCodeEditor(null); })); let forwardSelection = () => { this._lastSelection = this._codeEditor.getSelections(); this._onSelectionChanged.fire(this._lastSelection); }; this._codeEditorListeners.push(this._codeEditor.onDidChangeCursorSelection(forwardSelection)); if (!Selection.selectionsArrEqual(this._lastSelection, this._codeEditor.getSelections())) { forwardSelection(); } this._codeEditorListeners.push(this._codeEditor.onDidFocusEditor(() => { this._focusTracker.onGainedFocus(); })); this._codeEditorListeners.push(this._codeEditor.onDidBlurEditor(() => { this._focusTracker.onLostFocus(); })); this._codeEditorListeners.push(this._codeEditor.onDidChangeConfiguration(() => { this._setConfiguration(this._readConfiguration(this._model, this._codeEditor)); })); this._setConfiguration(this._readConfiguration(this._model, this._codeEditor)); } } public isVisible(): boolean { return !!this._codeEditor; } public get onSelectionChanged(): Event<Selection[]> { return this._onSelectionChanged.event; } public get onConfigurationChanged(): Event<IResolvedTextEditorConfiguration> { return this._onConfigurationChanged.event; } public getSelections(): Selection[] { if (this._codeEditor) { return this._codeEditor.getSelections(); } return this._lastSelection; } public setSelections(selections:EditorCommon.ISelection[]): void { if (this._codeEditor) { this._codeEditor.setSelections(selections); return; } this._lastSelection = selections.map(Selection.liftSelection); console.warn('setSelections on invisble editor'); } public getConfiguration(): IResolvedTextEditorConfiguration { return this._configuration; } private _setIndentConfiguration(newConfiguration:ITextEditorConfigurationUpdate): void { if (newConfiguration.tabSize === 'auto' || newConfiguration.insertSpaces === 'auto') { // one of the options was set to 'auto' => detect indentation let creationOpts = this._modelService.getCreationOptions(); let insertSpaces = creationOpts.insertSpaces; let tabSize = creationOpts.tabSize; if (newConfiguration.insertSpaces !== 'auto') { if (typeof newConfiguration.insertSpaces !== 'undefined') { insertSpaces = (newConfiguration.insertSpaces === 'false' ? false : Boolean(newConfiguration.insertSpaces)); } } if (newConfiguration.tabSize !== 'auto') { if (typeof newConfiguration.tabSize !== 'undefined') { let parsedTabSize = parseInt(<string>newConfiguration.tabSize, 10); if (!isNaN(parsedTabSize)) { tabSize = parsedTabSize; } } } this._model.detectIndentation(insertSpaces, tabSize); return; } let newOpts: EditorCommon.ITextModelUpdateOptions = {}; if (typeof newConfiguration.insertSpaces !== 'undefined') { newOpts.insertSpaces = (newConfiguration.insertSpaces === 'false' ? false : Boolean(newConfiguration.insertSpaces)); } if (typeof newConfiguration.tabSize !== 'undefined') { let parsedTabSize = parseInt(<string>newConfiguration.tabSize, 10); if (!isNaN(parsedTabSize)) { newOpts.tabSize = parsedTabSize; } } this._model.updateOptions(newOpts); } public setConfiguration(newConfiguration:ITextEditorConfigurationUpdate): void { this._setIndentConfiguration(newConfiguration); if (newConfiguration.cursorStyle) { let newCursorStyle = EditorCommon.cursorStyleToString(newConfiguration.cursorStyle); if (!this._codeEditor) { console.warn('setConfiguration on invisible editor'); return; } this._codeEditor.updateOptions({ cursorStyle: newCursorStyle }); } } public setDecorations(key: string, ranges:EditorCommon.IDecorationOptions[]): void { if (!this._codeEditor) { console.warn('setDecorations on invisible editor'); return; } this._codeEditor.setDecorations(key, ranges); } public revealRange(range:EditorCommon.IRange, revealType:TextEditorRevealType): void { if (!this._codeEditor) { console.warn('revealRange on invisible editor'); return; } if (revealType === TextEditorRevealType.Default) { this._codeEditor.revealRange(range); } else if (revealType === TextEditorRevealType.InCenter) { this._codeEditor.revealRangeInCenter(range); } else if (revealType === TextEditorRevealType.InCenterIfOutsideViewport) { this._codeEditor.revealRangeInCenterIfOutsideViewport(range); } else { console.warn('Unknown revealType'); } } private _readConfiguration(model:EditorCommon.IModel, codeEditor:EditorCommon.ICommonCodeEditor): IResolvedTextEditorConfiguration { if (model.isDisposed()) { // shutdown time return this._configuration; } let cursorStyle = this._configuration ? this._configuration.cursorStyle : EditorCommon.TextEditorCursorStyle.Line; if (codeEditor) { let codeEditorOpts = codeEditor.getConfiguration(); cursorStyle = codeEditorOpts.viewInfo.cursorStyle; } let indent = model.getOptions(); return { insertSpaces: indent.insertSpaces, tabSize: indent.tabSize, cursorStyle: cursorStyle }; } private _setConfiguration(newConfiguration:IResolvedTextEditorConfiguration): void { if (configurationsEqual(this._configuration, newConfiguration)) { return; } this._configuration = newConfiguration; this._onConfigurationChanged.fire(this._configuration); } public isFocused(): boolean { if (this._codeEditor) { return this._codeEditor.isFocused(); } return false; } public matches(editor: IEditor): boolean { if (!editor) { return false; } return editor.getControl() === this._codeEditor; } public applyEdits(versionIdCheck:number, edits:EditorCommon.ISingleEditOperation[], setEndOfLine:EndOfLine): boolean { if (this._model.getVersionId() !== versionIdCheck) { console.warn('Model has changed in the meantime!'); // throw new Error('Model has changed in the meantime!'); // model changed in the meantime return false; } if (this._codeEditor) { if (setEndOfLine === EndOfLine.CRLF) { this._model.setEOL(EditorCommon.EndOfLineSequence.CRLF); } else if (setEndOfLine === EndOfLine.LF) { this._model.setEOL(EditorCommon.EndOfLineSequence.LF); } let transformedEdits = edits.map((edit): EditorCommon.IIdentifiedSingleEditOperation => { return { identifier: null, range: Range.lift(edit.range), text: edit.text, forceMoveMarkers: edit.forceMoveMarkers }; }); this._codeEditor.pushUndoStop(); this._codeEditor.executeEdits('MainThreadTextEditor', transformedEdits); this._codeEditor.pushUndoStop(); return true; } console.warn('applyEdits on invisible editor'); return false; } } /** * Keeps track of what goes on in the main thread and maps models => text editors */ export class MainThreadEditorsTracker { private static _Ids = new IdGenerator(''); private _toDispose: IDisposable[]; private _codeEditorService: ICodeEditorService; private _modelService: IModelService; private _updateMapping: RunOnceScheduler; private _editorModelChangeListeners: {[editorId:string]:IDisposable;}; private _model2TextEditors: { [modelUri:string]: MainThreadTextEditor[]; }; private _focusedTextEditorId: string; private _visibleTextEditorIds: string[]; private _onTextEditorAdd: Emitter<MainThreadTextEditor>; private _onTextEditorRemove: Emitter<MainThreadTextEditor>; private _onDidChangeFocusedTextEditor: Emitter<string>; private _onDidUpdateTextEditors: Emitter<void>; private _focusTracker: IFocusTracker; constructor( editorService:ICodeEditorService, modelService:IModelService ) { this._codeEditorService = editorService; this._modelService = modelService; this._toDispose = []; this._focusedTextEditorId = null; this._visibleTextEditorIds = []; this._editorModelChangeListeners = Object.create(null); this._model2TextEditors = Object.create(null); this._onTextEditorAdd = new Emitter<MainThreadTextEditor>(); this._onTextEditorRemove = new Emitter<MainThreadTextEditor>(); this._onDidUpdateTextEditors = new Emitter<void>(); this._onDidChangeFocusedTextEditor = new Emitter<string>(); this._focusTracker = { onGainedFocus: () => this._updateFocusedTextEditor(), onLostFocus: () => this._updateFocusedTextEditor() }; this._modelService.onModelAdded(this._onModelAdded, this, this._toDispose); this._modelService.onModelRemoved(this._onModelRemoved, this, this._toDispose); this._codeEditorService.onCodeEditorAdd(this._onCodeEditorAdd, this, this._toDispose); this._codeEditorService.onCodeEditorRemove(this._onCodeEditorRemove, this, this._toDispose); this._updateMapping = new RunOnceScheduler(() => this._doUpdateMapping(), 0); this._toDispose.push(this._updateMapping); } public dispose(): void { this._toDispose = dispose(this._toDispose); } private _onModelAdded(model: EditorCommon.IModel): void { this._updateMapping.schedule(); } private _onModelRemoved(model: EditorCommon.IModel): void { this._updateMapping.schedule(); } private _onCodeEditorAdd(codeEditor: EditorCommon.ICommonCodeEditor): void { this._editorModelChangeListeners[codeEditor.getId()] = codeEditor.onDidChangeModel(_ => this._updateMapping.schedule()); this._updateMapping.schedule(); } private _onCodeEditorRemove(codeEditor: EditorCommon.ICommonCodeEditor): void { this._editorModelChangeListeners[codeEditor.getId()].dispose(); delete this._editorModelChangeListeners[codeEditor.getId()]; this._updateMapping.schedule(); } private _doUpdateMapping(): void { let allModels = this._modelService.getModels(); // Same filter as in extHostDocuments allModels = allModels.filter((model) => !model.isTooLargeForHavingARichMode()); let allModelsMap: { [modelUri:string]: EditorCommon.IModel; } = Object.create(null); allModels.forEach((model) => { allModelsMap[model.uri.toString()] = model; }); // Remove text editors for models that no longer exist Object.keys(this._model2TextEditors).forEach((modelUri) => { if (allModelsMap[modelUri]) { // model still exists, will be updated below return; } let textEditorsToRemove = this._model2TextEditors[modelUri]; delete this._model2TextEditors[modelUri]; for (let i = 0; i < textEditorsToRemove.length; i++) { this._onTextEditorRemove.fire(textEditorsToRemove[i]); textEditorsToRemove[i].dispose(); } }); // Handle all visible models let visibleModels = this._getVisibleModels(); Object.keys(visibleModels).forEach((modelUri) => { let model = visibleModels[modelUri].model; let codeEditors = visibleModels[modelUri].codeEditors; if (!this._model2TextEditors[modelUri]) { this._model2TextEditors[modelUri] = []; } let existingTextEditors = this._model2TextEditors[modelUri]; // Remove text editors if more exist while (existingTextEditors.length > codeEditors.length) { let removedTextEditor = existingTextEditors.pop(); this._onTextEditorRemove.fire(removedTextEditor); removedTextEditor.dispose(); } // Adjust remaining text editors for (let i = 0; i < existingTextEditors.length; i++) { existingTextEditors[i].setCodeEditor(codeEditors[i]); } // Create new editors as needed for (let i = existingTextEditors.length; i < codeEditors.length; i++) { let newTextEditor = new MainThreadTextEditor(MainThreadEditorsTracker._Ids.nextId(), model, codeEditors[i], this._focusTracker, this._modelService); existingTextEditors.push(newTextEditor); this._onTextEditorAdd.fire(newTextEditor); } }); // Handle all not visible models allModels.forEach((model) => { let modelUri = model.uri.toString(); if (visibleModels[modelUri]) { // model is visible, already handled above return; } if (!this._model2TextEditors[modelUri]) { this._model2TextEditors[modelUri] = []; } let existingTextEditors = this._model2TextEditors[modelUri]; // Remove extra text editors while (existingTextEditors.length > 1) { let removedTextEditor = existingTextEditors.pop(); this._onTextEditorRemove.fire(removedTextEditor); removedTextEditor.dispose(); } // Create new editor if needed or adjust it if (existingTextEditors.length === 0) { let newTextEditor = new MainThreadTextEditor(MainThreadEditorsTracker._Ids.nextId(), model, null, this._focusTracker, this._modelService); existingTextEditors.push(newTextEditor); this._onTextEditorAdd.fire(newTextEditor); } else { existingTextEditors[0].setCodeEditor(null); } }); this._printState(); this._visibleTextEditorIds = this._findVisibleTextEditorIds(); this._updateFocusedTextEditor(); // this is a sync event this._onDidUpdateTextEditors.fire(undefined); } private _updateFocusedTextEditor(): void { this._setFocusedTextEditorId(this._findFocusedTextEditorId()); } private _findFocusedTextEditorId(): string { let modelUris = Object.keys(this._model2TextEditors); for (let i = 0, len = modelUris.length; i < len; i++) { let editors = this._model2TextEditors[modelUris[i]]; for (let j = 0, lenJ = editors.length; j < lenJ; j++) { if (editors[j].isFocused()) { return editors[j].getId(); } } } return null; } private _findVisibleTextEditorIds(): string[] { let result = []; let modelUris = Object.keys(this._model2TextEditors); for (let i = 0, len = modelUris.length; i < len; i++) { let editors = this._model2TextEditors[modelUris[i]]; for (let j = 0, lenJ = editors.length; j < lenJ; j++) { if (editors[j].isVisible()) { result.push(editors[j].getId()); } } } result.sort(); return result; } private _setFocusedTextEditorId(focusedTextEditorId:string): void { if (this._focusedTextEditorId === focusedTextEditorId) { // no change return; } this._focusedTextEditorId = focusedTextEditorId; this._printState(); this._onDidChangeFocusedTextEditor.fire(this._focusedTextEditorId); } private _printState(): void { // console.log('----------------------'); // Object.keys(this._model2TextEditors).forEach((modelUri) => { // let editors = this._model2TextEditors[modelUri]; // console.log(editors.map((e) => { // return e.getId() + " (" + (e.getId() === this._focusedTextEditorId ? 'FOCUSED, ': '') + modelUri + ")"; // }).join('\n')); // }); } private _getVisibleModels(): IVisibleModels { let r: IVisibleModels = {}; let allCodeEditors = this._codeEditorService.listCodeEditors(); // Maintain a certain sorting such that the mapping doesn't change too much all the time allCodeEditors.sort((a, b) => strcmp(a.getId(), b.getId())); allCodeEditors.forEach((codeEditor) => { let model = codeEditor.getModel(); if (!model || model.isTooLargeForHavingARichMode()) { return; } let modelUri = model.uri.toString(); r[modelUri] = r[modelUri] || { model: model, codeEditors: [] }; r[modelUri].codeEditors.push(codeEditor); }); return r; } public getFocusedTextEditorId(): string { return this._focusedTextEditorId; } public getVisibleTextEditorIds(): string[] { return this._visibleTextEditorIds; } public get onTextEditorAdd(): Event<MainThreadTextEditor> { return this._onTextEditorAdd.event; } public get onTextEditorRemove(): Event<MainThreadTextEditor> { return this._onTextEditorRemove.event; } public get onDidUpdateTextEditors(): Event<void> { return this._onDidUpdateTextEditors.event; } public get onChangedFocusedTextEditor(): Event<string> { return this._onDidChangeFocusedTextEditor.event; } public findTextEditorIdFor(codeEditor:EditorCommon.ICommonCodeEditor): string { let modelUris = Object.keys(this._model2TextEditors); for (let i = 0, len = modelUris.length; i < len; i++) { let editors = this._model2TextEditors[modelUris[i]]; for (let j = 0, lenJ = editors.length; j < lenJ; j++) { if (editors[j].hasCodeEditor(codeEditor)) { return editors[j].getId(); } } } return null; } public registerTextEditorDecorationType(key:string, options: EditorCommon.IDecorationRenderOptions): void { this._codeEditorService.registerDecorationType(key, options); } public removeTextEditorDecorationType(key:string): void { this._codeEditorService.removeDecorationType(key); } } interface IVisibleModels { [modelUri:string]: { model: EditorCommon.IModel; codeEditors: EditorCommon.ICommonCodeEditor[]; }; } function strcmp(a:string, b:string): number { if (a < b) { return -1; } if (a > b) { return 1; } return 0; }
src/vs/workbench/api/node/mainThreadEditorsTracker.ts
0
https://github.com/microsoft/vscode/commit/f632cf311d6e97dbffd778d35bd4d4e92a818123
[ 0.00019773535314016044, 0.00017132420907728374, 0.00016481004422530532, 0.00017145134916063398, 0.0000041621406126068905 ]
{ "id": 2, "code_window": [ "\t_serviceBrand: undefined,\n", "\texecuteCommand() {\n", "\t\treturn TPromise.as(undefined);\n", "\t},\n", "\tisKnownCommand() {\n", "\t\treturn false;\n", "\t}\n", "};\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/platform/commands/common/commands.ts", "type": "replace", "edit_start_line_idx": 102 }
/*--------------------------------------------------------------------------------------------- * 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. { "conflict": "Estos archivos han cambiado durante el proceso: {0}" }
i18n/esn/src/vs/editor/common/services/bulkEdit.i18n.json
0
https://github.com/microsoft/vscode/commit/f632cf311d6e97dbffd778d35bd4d4e92a818123
[ 0.000176597575773485, 0.000176597575773485, 0.000176597575773485, 0.000176597575773485, 0 ]
{ "id": 3, "code_window": [ "\tprivate resolveKeybindings(actionIds: string[]): TPromise<{ id: string; binding: number; }[]> {\n", "\t\treturn this.partService.joinCreation().then(() => {\n", "\t\t\treturn arrays.coalesce(actionIds.map((id) => {\n", "\t\t\t\tif (!this.commandService.isKnownCommand(id)) {\n", "\t\t\t\t\tconsole.warn('Menu uses unknown command: ' + id);\n", "\t\t\t\t}\n", "\t\t\t\tlet bindings = this.keybindingService.lookupKeybindings(id);\n", "\n", "\t\t\t\t// return the first binding that can be represented by electron\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/electron-browser/integration.ts", "type": "replace", "edit_start_line_idx": 174 }
/*--------------------------------------------------------------------------------------------- * 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 {IInstantiationService} from 'vs/platform/instantiation/common/instantiation'; import {ICommandService, CommandsRegistry} from 'vs/platform/commands/common/commands'; import {IExtensionService} from 'vs/platform/extensions/common/extensions'; export class CommandService implements ICommandService { _serviceBrand: any; constructor( @IInstantiationService private _instantiationService: IInstantiationService, @IExtensionService private _extensionService: IExtensionService ) { // } executeCommand<T>(id: string, ...args: any[]): TPromise<T> { return this._extensionService.activateByEvent(`onCommand:${id}`).then(_ => { const command = CommandsRegistry.getCommand(id); if (!command) { return TPromise.wrapError(new Error(`command '${id}' not found`)); } try { const result = this._instantiationService.invokeFunction.apply(this._instantiationService, [command.handler].concat(args)); return TPromise.as(result); } catch (err) { return TPromise.wrapError(err); } }); } isKnownCommand(commandId: string): boolean { const command = CommandsRegistry.getCommand(commandId); if (!command) { return false; } return true; } }
src/vs/platform/commands/common/commandService.ts
1
https://github.com/microsoft/vscode/commit/f632cf311d6e97dbffd778d35bd4d4e92a818123
[ 0.0017181752482429147, 0.0006382225546985865, 0.00017006314010359347, 0.00025305841700173914, 0.0006184265948832035 ]
{ "id": 3, "code_window": [ "\tprivate resolveKeybindings(actionIds: string[]): TPromise<{ id: string; binding: number; }[]> {\n", "\t\treturn this.partService.joinCreation().then(() => {\n", "\t\t\treturn arrays.coalesce(actionIds.map((id) => {\n", "\t\t\t\tif (!this.commandService.isKnownCommand(id)) {\n", "\t\t\t\t\tconsole.warn('Menu uses unknown command: ' + id);\n", "\t\t\t\t}\n", "\t\t\t\tlet bindings = this.keybindingService.lookupKeybindings(id);\n", "\n", "\t\t\t\t// return the first binding that can be represented by electron\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/electron-browser/integration.ts", "type": "replace", "edit_start_line_idx": 174 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "sev.error": "Errore", "sev.info": "Informazioni", "sev.warning": "Avviso" }
i18n/ita/src/vs/base/common/severity.i18n.json
0
https://github.com/microsoft/vscode/commit/f632cf311d6e97dbffd778d35bd4d4e92a818123
[ 0.0001746690395521, 0.00017236609710380435, 0.00017006314010359347, 0.00017236609710380435, 0.000002302949724253267 ]
{ "id": 3, "code_window": [ "\tprivate resolveKeybindings(actionIds: string[]): TPromise<{ id: string; binding: number; }[]> {\n", "\t\treturn this.partService.joinCreation().then(() => {\n", "\t\t\treturn arrays.coalesce(actionIds.map((id) => {\n", "\t\t\t\tif (!this.commandService.isKnownCommand(id)) {\n", "\t\t\t\t\tconsole.warn('Menu uses unknown command: ' + id);\n", "\t\t\t\t}\n", "\t\t\t\tlet bindings = this.keybindingService.lookupKeybindings(id);\n", "\n", "\t\t\t\t// return the first binding that can be represented by electron\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/electron-browser/integration.ts", "type": "replace", "edit_start_line_idx": 174 }
/*--------------------------------------------------------------------------------------------- * 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. { "alreadyCheckedOut": "La branche {0} est déjà la branche active", "branchAriaLabel": "{0}, branche git", "checkoutBranch": "Branche sur {0}", "checkoutTag": "Balise sur {0}", "createBranch": "Créer une branche {0}", "noBranches": "Aucune autre branche", "notValidBranchName": "Fournissez un nom de branche valide", "refAriaLabel": "{0}, git" }
i18n/fra/src/vs/workbench/parts/git/browser/gitQuickOpen.i18n.json
0
https://github.com/microsoft/vscode/commit/f632cf311d6e97dbffd778d35bd4d4e92a818123
[ 0.00017340501653961837, 0.00017298111924901605, 0.00017255723651032895, 0.00017298111924901605, 4.238900146447122e-7 ]
{ "id": 3, "code_window": [ "\tprivate resolveKeybindings(actionIds: string[]): TPromise<{ id: string; binding: number; }[]> {\n", "\t\treturn this.partService.joinCreation().then(() => {\n", "\t\t\treturn arrays.coalesce(actionIds.map((id) => {\n", "\t\t\t\tif (!this.commandService.isKnownCommand(id)) {\n", "\t\t\t\t\tconsole.warn('Menu uses unknown command: ' + id);\n", "\t\t\t\t}\n", "\t\t\t\tlet bindings = this.keybindingService.lookupKeybindings(id);\n", "\n", "\t\t\t\t// return the first binding that can be represented by electron\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/electron-browser/integration.ts", "type": "replace", "edit_start_line_idx": 174 }
/*--------------------------------------------------------------------------------------------- * 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. { "QuickCommandAction.label": "命令選擇區", "quickCommandActionInput": "輸入您想要執行的動作名稱" }
i18n/cht/src/vs/editor/contrib/quickOpen/browser/quickCommand.i18n.json
0
https://github.com/microsoft/vscode/commit/f632cf311d6e97dbffd778d35bd4d4e92a818123
[ 0.00017179138376377523, 0.00017179138376377523, 0.00017179138376377523, 0.00017179138376377523, 0 ]
{ "id": 4, "code_window": [ "\t\tservices.set(ICommandService, {\n", "\t\t\t_serviceBrand: undefined,\n", "\t\t\texecuteCommand(id, args): any {\n", "\t\t\t\tlet {handler} = CommandsRegistry.getCommands()[id];\n", "\t\t\t\treturn TPromise.as(instantiationService.invokeFunction(handler, args));\n", "\t\t\t},\n", "\t\t\tisKnownCommand(id) {\n", "\t\t\t\treturn true;\n", "\t\t\t}\n", "\t\t});\n", "\t\tservices.set(IMarkerService, new MarkerService());\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/test/node/api/extHostApiCommands.test.ts", "type": "replace", "edit_start_line_idx": 66 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import {TPromise} from 'vs/base/common/winjs.base'; import {IInstantiationService} from 'vs/platform/instantiation/common/instantiation'; import {ICommandService, CommandsRegistry} from 'vs/platform/commands/common/commands'; import {IExtensionService} from 'vs/platform/extensions/common/extensions'; export class CommandService implements ICommandService { _serviceBrand: any; constructor( @IInstantiationService private _instantiationService: IInstantiationService, @IExtensionService private _extensionService: IExtensionService ) { // } executeCommand<T>(id: string, ...args: any[]): TPromise<T> { return this._extensionService.activateByEvent(`onCommand:${id}`).then(_ => { const command = CommandsRegistry.getCommand(id); if (!command) { return TPromise.wrapError(new Error(`command '${id}' not found`)); } try { const result = this._instantiationService.invokeFunction.apply(this._instantiationService, [command.handler].concat(args)); return TPromise.as(result); } catch (err) { return TPromise.wrapError(err); } }); } isKnownCommand(commandId: string): boolean { const command = CommandsRegistry.getCommand(commandId); if (!command) { return false; } return true; } }
src/vs/platform/commands/common/commandService.ts
1
https://github.com/microsoft/vscode/commit/f632cf311d6e97dbffd778d35bd4d4e92a818123
[ 0.0043135820887982845, 0.0015791066689416766, 0.00016738183330744505, 0.0012203613296151161, 0.001437681377865374 ]
{ "id": 4, "code_window": [ "\t\tservices.set(ICommandService, {\n", "\t\t\t_serviceBrand: undefined,\n", "\t\t\texecuteCommand(id, args): any {\n", "\t\t\t\tlet {handler} = CommandsRegistry.getCommands()[id];\n", "\t\t\t\treturn TPromise.as(instantiationService.invokeFunction(handler, args));\n", "\t\t\t},\n", "\t\t\tisKnownCommand(id) {\n", "\t\t\t\treturn true;\n", "\t\t\t}\n", "\t\t});\n", "\t\tservices.set(IMarkerService, new MarkerService());\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/test/node/api/extHostApiCommands.test.ts", "type": "replace", "edit_start_line_idx": 66 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as ts from 'typescript'; import * as Lint from 'tslint/lib/lint'; /** * Implementation of the no-unexternalized-strings rule. */ export class Rule extends Lint.Rules.AbstractRule { public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] { return this.applyWithWalker(new NoUnexternalizedStringsRuleWalker(sourceFile, this.getOptions())); } } interface Map<V> { [key: string]: V; } interface UnexternalizedStringsOptions { signatures?: string[]; messageIndex?: number; keyIndex?: number; ignores?: string[]; } function isStringLiteral(node: ts.Node): node is ts.StringLiteral { return node && node.kind === ts.SyntaxKind.StringLiteral; } function isObjectLiteral(node: ts.Node): node is ts.ObjectLiteralExpression { return node && node.kind === ts.SyntaxKind.ObjectLiteralExpression; } function isPropertyAssignment(node: ts.Node): node is ts.PropertyAssignment { return node && node.kind === ts.SyntaxKind.PropertyAssignment; } interface KeyMessagePair { key: ts.StringLiteral; message: ts.Node; } class NoUnexternalizedStringsRuleWalker extends Lint.RuleWalker { private static DOUBLE_QUOTE: string = '"'; private signatures: Map<boolean>; private messageIndex: number; private keyIndex: number; private ignores: Map<boolean>; private usedKeys: Map<KeyMessagePair[]>; constructor(file: ts.SourceFile, opts: Lint.IOptions) { super(file, opts); this.signatures = Object.create(null); this.ignores = Object.create(null); this.messageIndex = undefined; this.keyIndex = undefined; this.usedKeys = Object.create(null); let options: any[] = this.getOptions(); let first: UnexternalizedStringsOptions = options && options.length > 0 ? options[0] : null; if (first) { if (Array.isArray(first.signatures)) { first.signatures.forEach((signature: string) => this.signatures[signature] = true); } if (Array.isArray(first.ignores)) { first.ignores.forEach((ignore: string) => this.ignores[ignore] = true); } if (typeof first.messageIndex !== 'undefined') { this.messageIndex = first.messageIndex; } if (typeof first.keyIndex !== 'undefined') { this.keyIndex = first.keyIndex; } } } protected visitSourceFile(node: ts.SourceFile): void { super.visitSourceFile(node); Object.keys(this.usedKeys).forEach(key => { let occurences = this.usedKeys[key]; if (occurences.length > 1) { occurences.forEach(occurence => { this.addFailure((this.createFailure(occurence.key.getStart(), occurence.key.getWidth(), `Duplicate key ${occurence.key.getText()} with different message value.`))); }); } }); } protected visitStringLiteral(node: ts.StringLiteral): void { this.checkStringLiteral(node); super.visitStringLiteral(node); } private checkStringLiteral(node: ts.StringLiteral): void { let text = node.getText(); let doubleQuoted = text.length >= 2 && text[0] === NoUnexternalizedStringsRuleWalker.DOUBLE_QUOTE && text[text.length - 1] === NoUnexternalizedStringsRuleWalker.DOUBLE_QUOTE; let info = this.findDescribingParent(node); // Ignore strings in import and export nodes. if (info && info.ignoreUsage) { return; } let callInfo = info ? info.callInfo : null; let 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. let keyArg: ts.Expression = 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 (let i = 0; i < keyArg.properties.length; i++) { let property = keyArg.properties[i]; if (isPropertyAssignment(property)) { let name = property.name.getText(); if (name === 'key') { let initializer = property.initializer; if (isStringLiteral(initializer)) { this.recordKey(initializer, this.messageIndex ? callInfo.callExpression.arguments[this.messageIndex] : undefined); } break; } } } } } let messageArg: ts.Expression = 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; } } private recordKey(keyNode: ts.StringLiteral, messageNode: ts.Node) { let text = keyNode.getText(); let occurences: KeyMessagePair[] = this.usedKeys[text]; if (!occurences) { occurences = []; this.usedKeys[text] = occurences; } if (messageNode) { if (occurences.some(pair => pair.message ? pair.message.getText() === messageNode.getText() : false)) { return; } } occurences.push({ key: keyNode, message: messageNode }); } private findDescribingParent(node: ts.Node): { callInfo?: { callExpression: ts.CallExpression, argIndex: number }, ignoreUsage?: boolean; } { let parent: ts.Node; while ((parent = node.parent)) { let kind = parent.kind; if (kind === ts.SyntaxKind.CallExpression) { let callExpression = parent as ts.CallExpression; return { callInfo: { callExpression: callExpression, argIndex: callExpression.arguments.indexOf(<any>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; } } }
build/lib/tslint/noUnexternalizedStringsRule.ts
0
https://github.com/microsoft/vscode/commit/f632cf311d6e97dbffd778d35bd4d4e92a818123
[ 0.00017675626440905035, 0.00017202804156113416, 0.00016395578859373927, 0.00017364660743623972, 0.000003516475544529385 ]
{ "id": 4, "code_window": [ "\t\tservices.set(ICommandService, {\n", "\t\t\t_serviceBrand: undefined,\n", "\t\t\texecuteCommand(id, args): any {\n", "\t\t\t\tlet {handler} = CommandsRegistry.getCommands()[id];\n", "\t\t\t\treturn TPromise.as(instantiationService.invokeFunction(handler, args));\n", "\t\t\t},\n", "\t\t\tisKnownCommand(id) {\n", "\t\t\t\treturn true;\n", "\t\t\t}\n", "\t\t});\n", "\t\tservices.set(IMarkerService, new MarkerService());\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/test/node/api/extHostApiCommands.test.ts", "type": "replace", "edit_start_line_idx": 66 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "appCrashed": "La ventana se bloqueó", "appCrashedDetail": "Sentimos las molestias. Puede volver a abrir la ventana para continuar donde se detuvo.", "appStalled": "La ventana ha dejado de responder.", "appStalledDetail": "Puede volver a abrir la ventana, cerrarla o seguir esperando.", "close": "Cerrar", "hiddenMenuBar": "Para acceder a la barra de menús, también puede presionar la tecla **Alt**.", "ok": "Aceptar", "pathNotExistDetail": "Parece que la ruta '{0}' ya no existe en el disco.", "pathNotExistTitle": "La ruta no existe", "reopen": "Volver a abrir", "wait": "Siga esperando" }
i18n/esn/src/vs/code/electron-main/windows.i18n.json
0
https://github.com/microsoft/vscode/commit/f632cf311d6e97dbffd778d35bd4d4e92a818123
[ 0.00017224359908141196, 0.00017217645654454827, 0.00017210929945576936, 0.00017217645654454827, 6.714981282129884e-8 ]
{ "id": 4, "code_window": [ "\t\tservices.set(ICommandService, {\n", "\t\t\t_serviceBrand: undefined,\n", "\t\t\texecuteCommand(id, args): any {\n", "\t\t\t\tlet {handler} = CommandsRegistry.getCommands()[id];\n", "\t\t\t\treturn TPromise.as(instantiationService.invokeFunction(handler, args));\n", "\t\t\t},\n", "\t\t\tisKnownCommand(id) {\n", "\t\t\t\treturn true;\n", "\t\t\t}\n", "\t\t});\n", "\t\tservices.set(IMarkerService, new MarkerService());\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/test/node/api/extHostApiCommands.test.ts", "type": "replace", "edit_start_line_idx": 66 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "preview": "Vista previa de '{0}'" }
i18n/esn/src/vs/workbench/parts/markdown/common/markdownEditorInput.i18n.json
0
https://github.com/microsoft/vscode/commit/f632cf311d6e97dbffd778d35bd4d4e92a818123
[ 0.000175307912286371, 0.000175307912286371, 0.000175307912286371, 0.000175307912286371, 0 ]
{ "id": 0, "code_window": [ "\t\tstopOrDisconectAction\n", "\t];\n", "}\n", "\n", "\n", "class StopAction extends Action {\n", "\n", "\tconstructor(\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ "export class StopAction extends Action {\n" ], "file_path": "src/vs/workbench/contrib/debug/browser/callStackView.ts", "type": "replace", "edit_start_line_idx": 984 }
/*--------------------------------------------------------------------------------------------- * 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/debugViewlet'; import * as nls from 'vs/nls'; import { IAction, IActionViewItem } from 'vs/base/common/actions'; import * as DOM from 'vs/base/browser/dom'; import { IDebugService, VIEWLET_ID, State, BREAKPOINTS_VIEW_ID, IDebugConfiguration, CONTEXT_DEBUG_UX, CONTEXT_DEBUG_UX_KEY, REPL_VIEW_ID } from 'vs/workbench/contrib/debug/common/debug'; import { StartAction, ConfigureAction, SelectAndStartAction, FocusSessionAction } from 'vs/workbench/contrib/debug/browser/debugActions'; import { StartDebugActionViewItem, FocusSessionActionViewItem } from 'vs/workbench/contrib/debug/browser/debugActionViewItems'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions'; import { IProgressService } from 'vs/platform/progress/common/progress'; import { IWorkspaceContextService, WorkbenchState } from 'vs/platform/workspace/common/workspace'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IStorageService } from 'vs/platform/storage/common/storage'; import { IThemeService } from 'vs/platform/theme/common/themeService'; import { IContextMenuService, IContextViewService } from 'vs/platform/contextview/browser/contextView'; import { IDisposable, dispose } from 'vs/base/common/lifecycle'; import { IWorkbenchLayoutService } from 'vs/workbench/services/layout/browser/layoutService'; import { memoize } from 'vs/base/common/decorators'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { DebugToolBar } from 'vs/workbench/contrib/debug/browser/debugToolBar'; import { ViewPane, ViewPaneContainer } from 'vs/workbench/browser/parts/views/viewPaneContainer'; import { IMenu, MenuId, IMenuService, MenuItemAction, SubmenuItemAction } from 'vs/platform/actions/common/actions'; import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { MenuEntryActionViewItem, SubmenuEntryActionViewItem } from 'vs/platform/actions/browser/menuEntryActionViewItem'; import { IViewDescriptorService, IViewsService } from 'vs/workbench/common/views'; import { WelcomeView } from 'vs/workbench/contrib/debug/browser/welcomeView'; import { ToggleViewAction } from 'vs/workbench/browser/actions/layoutActions'; import { RunOnceScheduler } from 'vs/base/common/async'; import { ShowViewletAction } from 'vs/workbench/browser/viewlet'; import { IViewletService } from 'vs/workbench/services/viewlet/browser/viewlet'; import { IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService'; export class DebugViewPaneContainer extends ViewPaneContainer { private startDebugActionViewItem: StartDebugActionViewItem | undefined; private progressResolve: (() => void) | undefined; private breakpointView: ViewPane | undefined; private paneListeners = new Map<string, IDisposable>(); private debugToolBarMenu: IMenu | undefined; private disposeOnTitleUpdate: IDisposable | undefined; private updateToolBarScheduler: RunOnceScheduler; constructor( @IWorkbenchLayoutService layoutService: IWorkbenchLayoutService, @ITelemetryService telemetryService: ITelemetryService, @IProgressService private readonly progressService: IProgressService, @IDebugService private readonly debugService: IDebugService, @IInstantiationService instantiationService: IInstantiationService, @IWorkspaceContextService contextService: IWorkspaceContextService, @IStorageService storageService: IStorageService, @IThemeService themeService: IThemeService, @IContextMenuService contextMenuService: IContextMenuService, @IExtensionService extensionService: IExtensionService, @IConfigurationService configurationService: IConfigurationService, @IContextViewService private readonly contextViewService: IContextViewService, @IMenuService private readonly menuService: IMenuService, @IContextKeyService private readonly contextKeyService: IContextKeyService, @IViewDescriptorService viewDescriptorService: IViewDescriptorService ) { super(VIEWLET_ID, { mergeViewWithContainerWhenSingleView: true }, instantiationService, configurationService, layoutService, contextMenuService, telemetryService, extensionService, themeService, storageService, contextService, viewDescriptorService); this.updateToolBarScheduler = this._register(new RunOnceScheduler(() => { if (this.configurationService.getValue<IDebugConfiguration>('debug').toolBarLocation === 'docked') { this.updateTitleArea(); } }, 20)); // When there are potential updates to the docked debug toolbar we need to update it this._register(this.debugService.onDidChangeState(state => this.onDebugServiceStateChange(state))); this._register(this.debugService.onDidNewSession(() => this.updateToolBarScheduler.schedule())); this._register(this.debugService.getViewModel().onDidFocusSession(() => this.updateToolBarScheduler.schedule())); this._register(this.contextKeyService.onDidChangeContext(e => { if (e.affectsSome(new Set([CONTEXT_DEBUG_UX_KEY]))) { this.updateTitleArea(); } })); this._register(this.contextService.onDidChangeWorkbenchState(() => this.updateTitleArea())); this._register(this.configurationService.onDidChangeConfiguration(e => { if (e.affectsConfiguration('debug.toolBarLocation')) { this.updateTitleArea(); } })); } create(parent: HTMLElement): void { super.create(parent); DOM.addClass(parent, 'debug-viewlet'); } focus(): void { super.focus(); if (this.startDebugActionViewItem) { this.startDebugActionViewItem.focus(); } else { this.focusView(WelcomeView.ID); } } @memoize private get startAction(): StartAction { return this._register(this.instantiationService.createInstance(StartAction, StartAction.ID, StartAction.LABEL)); } @memoize private get configureAction(): ConfigureAction { return this._register(this.instantiationService.createInstance(ConfigureAction, ConfigureAction.ID, ConfigureAction.LABEL)); } @memoize private get toggleReplAction(): OpenDebugConsoleAction { return this._register(this.instantiationService.createInstance(OpenDebugConsoleAction, OpenDebugConsoleAction.ID, OpenDebugConsoleAction.LABEL)); } @memoize private get selectAndStartAction(): SelectAndStartAction { return this._register(this.instantiationService.createInstance(SelectAndStartAction, SelectAndStartAction.ID, nls.localize('startAdditionalSession', "Start Additional Session"))); } getActions(): IAction[] { if (CONTEXT_DEBUG_UX.getValue(this.contextKeyService) === 'simple') { return []; } if (!this.showInitialDebugActions) { if (!this.debugToolBarMenu) { this.debugToolBarMenu = this.menuService.createMenu(MenuId.DebugToolBar, this.contextKeyService); this._register(this.debugToolBarMenu); this._register(this.debugToolBarMenu.onDidChange(() => this.updateToolBarScheduler.schedule())); } const { actions, disposable } = DebugToolBar.getActions(this.debugToolBarMenu, this.debugService, this.instantiationService); if (this.disposeOnTitleUpdate) { dispose(this.disposeOnTitleUpdate); } this.disposeOnTitleUpdate = disposable; return actions; } if (this.contextService.getWorkbenchState() === WorkbenchState.EMPTY) { return [this.toggleReplAction]; } return [this.startAction, this.configureAction, this.toggleReplAction]; } get showInitialDebugActions(): boolean { const state = this.debugService.state; return state === State.Inactive || this.configurationService.getValue<IDebugConfiguration>('debug').toolBarLocation !== 'docked'; } getSecondaryActions(): IAction[] { if (this.showInitialDebugActions) { return []; } return [this.selectAndStartAction, this.configureAction, this.toggleReplAction]; } getActionViewItem(action: IAction): IActionViewItem | undefined { if (action.id === StartAction.ID) { this.startDebugActionViewItem = this.instantiationService.createInstance(StartDebugActionViewItem, null, action); return this.startDebugActionViewItem; } if (action.id === FocusSessionAction.ID) { return new FocusSessionActionViewItem(action, this.debugService, this.themeService, this.contextViewService, this.configurationService); } if (action instanceof MenuItemAction) { return this.instantiationService.createInstance(MenuEntryActionViewItem, action); } else if (action instanceof SubmenuItemAction) { return this.instantiationService.createInstance(SubmenuEntryActionViewItem, action); } return undefined; } focusView(id: string): void { const view = this.getView(id); if (view) { view.focus(); } } private onDebugServiceStateChange(state: State): void { if (this.progressResolve) { this.progressResolve(); this.progressResolve = undefined; } if (state === State.Initializing) { this.progressService.withProgress({ location: VIEWLET_ID, }, _progress => { return new Promise(resolve => this.progressResolve = resolve); }); } this.updateToolBarScheduler.schedule(); } addPanes(panes: { pane: ViewPane, size: number, index?: number }[]): void { super.addPanes(panes); for (const { pane: pane } of panes) { // attach event listener to if (pane.id === BREAKPOINTS_VIEW_ID) { this.breakpointView = pane; this.updateBreakpointsMaxSize(); } else { this.paneListeners.set(pane.id, pane.onDidChange(() => this.updateBreakpointsMaxSize())); } } } removePanes(panes: ViewPane[]): void { super.removePanes(panes); for (const pane of panes) { dispose(this.paneListeners.get(pane.id)); this.paneListeners.delete(pane.id); } } private updateBreakpointsMaxSize(): void { if (this.breakpointView) { // We need to update the breakpoints view since all other views are collapsed #25384 const allOtherCollapsed = this.panes.every(view => !view.isExpanded() || view === this.breakpointView); this.breakpointView.maximumBodySize = allOtherCollapsed ? Number.POSITIVE_INFINITY : this.breakpointView.minimumBodySize; } } } export class OpenDebugConsoleAction extends ToggleViewAction { public static readonly ID = 'workbench.debug.action.toggleRepl'; public static readonly LABEL = nls.localize('toggleDebugPanel', "Debug Console"); constructor( id: string, label: string, @IViewsService viewsService: IViewsService, @IViewDescriptorService viewDescriptorService: IViewDescriptorService, @IContextKeyService contextKeyService: IContextKeyService, @IWorkbenchLayoutService layoutService: IWorkbenchLayoutService ) { super(id, label, REPL_VIEW_ID, viewsService, viewDescriptorService, contextKeyService, layoutService, 'codicon-debug-console'); } } export class OpenDebugViewletAction extends ShowViewletAction { public static readonly ID = VIEWLET_ID; public static readonly LABEL = nls.localize('toggleDebugViewlet', "Show Run and Debug"); constructor( id: string, label: string, @IViewletService viewletService: IViewletService, @IEditorGroupsService editorGroupService: IEditorGroupsService, @IWorkbenchLayoutService layoutService: IWorkbenchLayoutService ) { super(id, label, VIEWLET_ID, viewletService, editorGroupService, layoutService); } }
src/vs/workbench/contrib/debug/browser/debugViewlet.ts
1
https://github.com/microsoft/vscode/commit/135b6da83746477b2983fee879122ceefa70014d
[ 0.9991389513015747, 0.03907713294029236, 0.0001623283460503444, 0.0001731051888782531, 0.18843169510364532 ]
{ "id": 0, "code_window": [ "\t\tstopOrDisconectAction\n", "\t];\n", "}\n", "\n", "\n", "class StopAction extends Action {\n", "\n", "\tconstructor(\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ "export class StopAction extends Action {\n" ], "file_path": "src/vs/workbench/contrib/debug/browser/callStackView.ts", "type": "replace", "edit_start_line_idx": 984 }
/*--------------------------------------------------------------------------------------------- * 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 { KeyMod, KeyChord, KeyCode } from 'vs/base/common/keyCodes'; import { Range } from 'vs/editor/common/core/range'; import { EditorContextKeys } from 'vs/editor/common/editorContextKeys'; import { ServicesAccessor, registerEditorAction, EditorAction, IActionOptions } from 'vs/editor/browser/editorExtensions'; import { ContextKeyExpr } from 'vs/platform/contextkey/common/contextkey'; import { IDebugService, CONTEXT_IN_DEBUG_MODE, CONTEXT_DEBUG_STATE, State, IDebugEditorContribution, EDITOR_CONTRIBUTION_ID, BreakpointWidgetContext, IBreakpoint, BREAKPOINT_EDITOR_CONTRIBUTION_ID, IBreakpointEditorContribution, REPL_VIEW_ID, CONTEXT_STEP_INTO_TARGETS_SUPPORTED, WATCH_VIEW_ID } from 'vs/workbench/contrib/debug/common/debug'; import { ICodeEditor } from 'vs/editor/browser/editorBrowser'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; import { openBreakpointSource } from 'vs/workbench/contrib/debug/browser/breakpointsView'; import { KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry'; import { PanelFocusContext } from 'vs/workbench/common/panel'; import { IViewsService } from 'vs/workbench/common/views'; import { IContextMenuService } from 'vs/platform/contextview/browser/contextView'; import { Action } from 'vs/base/common/actions'; import { getDomNodePagePosition } from 'vs/base/browser/dom'; export const TOGGLE_BREAKPOINT_ID = 'editor.debug.action.toggleBreakpoint'; class ToggleBreakpointAction extends EditorAction { constructor() { super({ id: TOGGLE_BREAKPOINT_ID, label: nls.localize('toggleBreakpointAction', "Debug: Toggle Breakpoint"), alias: 'Debug: Toggle Breakpoint', precondition: undefined, kbOpts: { kbExpr: EditorContextKeys.editorTextFocus, primary: KeyCode.F9, weight: KeybindingWeight.EditorContrib } }); } async run(accessor: ServicesAccessor, editor: ICodeEditor): Promise<any> { if (editor.hasModel()) { const debugService = accessor.get(IDebugService); const modelUri = editor.getModel().uri; const canSet = debugService.getConfigurationManager().canSetBreakpointsIn(editor.getModel()); // Does not account for multi line selections, Set to remove multiple cursor on the same line const lineNumbers = [...new Set(editor.getSelections().map(s => s.getPosition().lineNumber))]; return Promise.all(lineNumbers.map(line => { const bps = debugService.getModel().getBreakpoints({ lineNumber: line, uri: modelUri }); if (bps.length) { return Promise.all(bps.map(bp => debugService.removeBreakpoints(bp.getId()))); } else if (canSet) { return (debugService.addBreakpoints(modelUri, [{ lineNumber: line }], 'debugEditorActions.toggleBreakpointAction')); } else { return []; } })); } } } export const TOGGLE_CONDITIONAL_BREAKPOINT_ID = 'editor.debug.action.conditionalBreakpoint'; class ConditionalBreakpointAction extends EditorAction { constructor() { super({ id: TOGGLE_CONDITIONAL_BREAKPOINT_ID, label: nls.localize('conditionalBreakpointEditorAction', "Debug: Add Conditional Breakpoint..."), alias: 'Debug: Add Conditional Breakpoint...', precondition: undefined }); } public run(accessor: ServicesAccessor, editor: ICodeEditor): void { const debugService = accessor.get(IDebugService); const position = editor.getPosition(); if (position && editor.hasModel() && debugService.getConfigurationManager().canSetBreakpointsIn(editor.getModel())) { editor.getContribution<IBreakpointEditorContribution>(BREAKPOINT_EDITOR_CONTRIBUTION_ID).showBreakpointWidget(position.lineNumber, undefined, BreakpointWidgetContext.CONDITION); } } } export const ADD_LOG_POINT_ID = 'editor.debug.action.addLogPoint'; class LogPointAction extends EditorAction { constructor() { super({ id: ADD_LOG_POINT_ID, label: nls.localize('logPointEditorAction', "Debug: Add Logpoint..."), alias: 'Debug: Add Logpoint...', precondition: undefined }); } public run(accessor: ServicesAccessor, editor: ICodeEditor): void { const debugService = accessor.get(IDebugService); const position = editor.getPosition(); if (position && editor.hasModel() && debugService.getConfigurationManager().canSetBreakpointsIn(editor.getModel())) { editor.getContribution<IBreakpointEditorContribution>(BREAKPOINT_EDITOR_CONTRIBUTION_ID).showBreakpointWidget(position.lineNumber, position.column, BreakpointWidgetContext.LOG_MESSAGE); } } } export class RunToCursorAction extends EditorAction { public static readonly ID = 'editor.debug.action.runToCursor'; public static readonly LABEL = nls.localize('runToCursor', "Run to Cursor"); constructor() { super({ id: RunToCursorAction.ID, label: RunToCursorAction.LABEL, alias: 'Debug: Run to Cursor', precondition: ContextKeyExpr.and(CONTEXT_IN_DEBUG_MODE, PanelFocusContext.toNegated(), CONTEXT_DEBUG_STATE.isEqualTo('stopped'), EditorContextKeys.editorTextFocus), contextMenuOpts: { group: 'debug', order: 2 } }); } async run(accessor: ServicesAccessor, editor: ICodeEditor): Promise<void> { const debugService = accessor.get(IDebugService); const focusedSession = debugService.getViewModel().focusedSession; if (debugService.state !== State.Stopped || !focusedSession) { return; } let breakpointToRemove: IBreakpoint; const oneTimeListener = focusedSession.onDidChangeState(() => { const state = focusedSession.state; if (state === State.Stopped || state === State.Inactive) { if (breakpointToRemove) { debugService.removeBreakpoints(breakpointToRemove.getId()); } oneTimeListener.dispose(); } }); const position = editor.getPosition(); if (editor.hasModel() && position) { const uri = editor.getModel().uri; const bpExists = !!(debugService.getModel().getBreakpoints({ column: position.column, lineNumber: position.lineNumber, uri }).length); if (!bpExists) { let column = 0; const focusedStackFrame = debugService.getViewModel().focusedStackFrame; if (focusedStackFrame && focusedStackFrame.source.uri.toString() === uri.toString() && focusedStackFrame.range.startLineNumber === position.lineNumber) { // If the cursor is on a line different than the one the debugger is currently paused on, then send the breakpoint at column 0 on the line // otherwise set it at the precise column #102199 column = position.column; } const breakpoints = await debugService.addBreakpoints(uri, [{ lineNumber: position.lineNumber, column }], 'debugEditorActions.runToCursorAction'); if (breakpoints && breakpoints.length) { breakpointToRemove = breakpoints[0]; } } await debugService.getViewModel().focusedThread!.continue(); } } } class SelectionToReplAction extends EditorAction { constructor() { super({ id: 'editor.debug.action.selectionToRepl', label: nls.localize('evaluateInDebugConsole', "Evaluate in Debug Console"), alias: 'Evaluate', precondition: ContextKeyExpr.and(EditorContextKeys.hasNonEmptySelection, CONTEXT_IN_DEBUG_MODE, EditorContextKeys.editorTextFocus), contextMenuOpts: { group: 'debug', order: 0 } }); } async run(accessor: ServicesAccessor, editor: ICodeEditor): Promise<void> { const debugService = accessor.get(IDebugService); const viewsService = accessor.get(IViewsService); const viewModel = debugService.getViewModel(); const session = viewModel.focusedSession; if (!editor.hasModel() || !session) { return; } const text = editor.getModel().getValueInRange(editor.getSelection()); await session.addReplExpression(viewModel.focusedStackFrame!, text); await viewsService.openView(REPL_VIEW_ID, false); } } class SelectionToWatchExpressionsAction extends EditorAction { constructor() { super({ id: 'editor.debug.action.selectionToWatch', label: nls.localize('addToWatch', "Add to Watch"), alias: 'Add to Watch', precondition: ContextKeyExpr.and(EditorContextKeys.hasNonEmptySelection, CONTEXT_IN_DEBUG_MODE, EditorContextKeys.editorTextFocus), contextMenuOpts: { group: 'debug', order: 1 } }); } async run(accessor: ServicesAccessor, editor: ICodeEditor): Promise<void> { const debugService = accessor.get(IDebugService); const viewsService = accessor.get(IViewsService); if (!editor.hasModel()) { return; } const text = editor.getModel().getValueInRange(editor.getSelection()); await viewsService.openView(WATCH_VIEW_ID); debugService.addWatchExpression(text); } } class ShowDebugHoverAction extends EditorAction { constructor() { super({ id: 'editor.debug.action.showDebugHover', label: nls.localize('showDebugHover', "Debug: Show Hover"), alias: 'Debug: Show Hover', precondition: CONTEXT_IN_DEBUG_MODE, kbOpts: { kbExpr: EditorContextKeys.editorTextFocus, primary: KeyChord(KeyMod.CtrlCmd | KeyCode.KEY_K, KeyMod.CtrlCmd | KeyCode.KEY_I), weight: KeybindingWeight.EditorContrib } }); } async run(accessor: ServicesAccessor, editor: ICodeEditor): Promise<void> { const position = editor.getPosition(); if (!position || !editor.hasModel()) { return; } const word = editor.getModel().getWordAtPosition(position); if (!word) { return; } const range = new Range(position.lineNumber, position.column, position.lineNumber, word.endColumn); return editor.getContribution<IDebugEditorContribution>(EDITOR_CONTRIBUTION_ID).showHover(range, true); } } class StepIntoTargetsAction extends EditorAction { public static readonly ID = 'editor.debug.action.stepIntoTargets'; public static readonly LABEL = nls.localize({ key: 'stepIntoTargets', comment: ['Step Into Targets lets the user step into an exact function he or she is interested in.'] }, "Step Into Targets..."); constructor() { super({ id: StepIntoTargetsAction.ID, label: StepIntoTargetsAction.LABEL, alias: 'Debug: Step Into Targets...', precondition: ContextKeyExpr.and(CONTEXT_STEP_INTO_TARGETS_SUPPORTED, CONTEXT_IN_DEBUG_MODE, CONTEXT_DEBUG_STATE.isEqualTo('stopped'), EditorContextKeys.editorTextFocus), contextMenuOpts: { group: 'debug', order: 1.5 } }); } async run(accessor: ServicesAccessor, editor: ICodeEditor): Promise<void> { const debugService = accessor.get(IDebugService); const contextMenuService = accessor.get(IContextMenuService); const session = debugService.getViewModel().focusedSession; const frame = debugService.getViewModel().focusedStackFrame; if (session && frame && editor.hasModel() && editor.getModel().uri.toString() === frame.source.uri.toString()) { const targets = await session.stepInTargets(frame.frameId); editor.revealLineInCenterIfOutsideViewport(frame.range.startLineNumber); const cursorCoords = editor.getScrolledVisiblePosition({ lineNumber: frame.range.startLineNumber, column: frame.range.startColumn }); const editorCoords = getDomNodePagePosition(editor.getDomNode()); const x = editorCoords.left + cursorCoords.left; const y = editorCoords.top + cursorCoords.top + cursorCoords.height; contextMenuService.showContextMenu({ getAnchor: () => ({ x, y }), getActions: () => { return targets.map(t => new Action(`stepIntoTarget:${t.id}`, t.label, undefined, true, () => session.stepIn(frame.thread.threadId, t.id))); } }); } } } class GoToBreakpointAction extends EditorAction { constructor(private isNext: boolean, opts: IActionOptions) { super(opts); } async run(accessor: ServicesAccessor, editor: ICodeEditor): Promise<any> { const debugService = accessor.get(IDebugService); const editorService = accessor.get(IEditorService); if (editor.hasModel()) { const currentUri = editor.getModel().uri; const currentLine = editor.getPosition().lineNumber; //Breakpoints returned from `getBreakpoints` are already sorted. const allEnabledBreakpoints = debugService.getModel().getBreakpoints({ enabledOnly: true }); //Try to find breakpoint in current file let moveBreakpoint = this.isNext ? allEnabledBreakpoints.filter(bp => bp.uri.toString() === currentUri.toString() && bp.lineNumber > currentLine).shift() : allEnabledBreakpoints.filter(bp => bp.uri.toString() === currentUri.toString() && bp.lineNumber < currentLine).pop(); //Try to find breakpoints in following files if (!moveBreakpoint) { moveBreakpoint = this.isNext ? allEnabledBreakpoints.filter(bp => bp.uri.toString() > currentUri.toString()).shift() : allEnabledBreakpoints.filter(bp => bp.uri.toString() < currentUri.toString()).pop(); } //Move to first or last possible breakpoint if (!moveBreakpoint && allEnabledBreakpoints.length) { moveBreakpoint = this.isNext ? allEnabledBreakpoints[0] : allEnabledBreakpoints[allEnabledBreakpoints.length - 1]; } if (moveBreakpoint) { return openBreakpointSource(moveBreakpoint, false, true, debugService, editorService); } } } } class GoToNextBreakpointAction extends GoToBreakpointAction { constructor() { super(true, { id: 'editor.debug.action.goToNextBreakpoint', label: nls.localize('goToNextBreakpoint', "Debug: Go To Next Breakpoint"), alias: 'Debug: Go To Next Breakpoint', precondition: undefined }); } } class GoToPreviousBreakpointAction extends GoToBreakpointAction { constructor() { super(false, { id: 'editor.debug.action.goToPreviousBreakpoint', label: nls.localize('goToPreviousBreakpoint', "Debug: Go To Previous Breakpoint"), alias: 'Debug: Go To Previous Breakpoint', precondition: undefined }); } } export function registerEditorActions(): void { registerEditorAction(ToggleBreakpointAction); registerEditorAction(ConditionalBreakpointAction); registerEditorAction(LogPointAction); registerEditorAction(RunToCursorAction); registerEditorAction(StepIntoTargetsAction); registerEditorAction(SelectionToReplAction); registerEditorAction(SelectionToWatchExpressionsAction); registerEditorAction(ShowDebugHoverAction); registerEditorAction(GoToNextBreakpointAction); registerEditorAction(GoToPreviousBreakpointAction); }
src/vs/workbench/contrib/debug/browser/debugEditorActions.ts
0
https://github.com/microsoft/vscode/commit/135b6da83746477b2983fee879122ceefa70014d
[ 0.023036394268274307, 0.0025485826190561056, 0.00016641696856822819, 0.0002416966890450567, 0.004744826816022396 ]
{ "id": 0, "code_window": [ "\t\tstopOrDisconectAction\n", "\t];\n", "}\n", "\n", "\n", "class StopAction extends Action {\n", "\n", "\tconstructor(\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ "export class StopAction extends Action {\n" ], "file_path": "src/vs/workbench/contrib/debug/browser/callStackView.ts", "type": "replace", "edit_start_line_idx": 984 }
/*--------------------------------------------------------------------------------------------- * 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!./selectBoxCustom'; import { IDisposable, dispose, Disposable } from 'vs/base/common/lifecycle'; import { Event, Emitter } from 'vs/base/common/event'; import { KeyCode, KeyCodeUtils } from 'vs/base/common/keyCodes'; import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent'; import * as dom from 'vs/base/browser/dom'; import * as arrays from 'vs/base/common/arrays'; import { IContextViewProvider, AnchorPosition } from 'vs/base/browser/ui/contextview/contextview'; import { List } from 'vs/base/browser/ui/list/listWidget'; import { IListVirtualDelegate, IListRenderer, IListEvent } from 'vs/base/browser/ui/list/list'; import { domEvent } from 'vs/base/browser/event'; import { ScrollbarVisibility } from 'vs/base/common/scrollable'; import { ISelectBoxDelegate, ISelectOptionItem, ISelectBoxOptions, ISelectBoxStyles, ISelectData } from 'vs/base/browser/ui/selectBox/selectBox'; import { isMacintosh } from 'vs/base/common/platform'; import { renderMarkdown } from 'vs/base/browser/markdownRenderer'; import { IContentActionHandler } from 'vs/base/browser/formattedTextRenderer'; import { localize } from 'vs/nls'; const $ = dom.$; const SELECT_OPTION_ENTRY_TEMPLATE_ID = 'selectOption.entry.template'; interface ISelectListTemplateData { root: HTMLElement; text: HTMLElement; itemDescription: HTMLElement; decoratorRight: HTMLElement; disposables: IDisposable[]; } class SelectListRenderer implements IListRenderer<ISelectOptionItem, ISelectListTemplateData> { get templateId(): string { return SELECT_OPTION_ENTRY_TEMPLATE_ID; } renderTemplate(container: HTMLElement): ISelectListTemplateData { const data: ISelectListTemplateData = Object.create(null); data.disposables = []; data.root = container; data.text = dom.append(container, $('.option-text')); data.decoratorRight = dom.append(container, $('.option-decorator-right')); data.itemDescription = dom.append(container, $('.option-text-description')); dom.addClass(data.itemDescription, 'visually-hidden'); return data; } renderElement(element: ISelectOptionItem, index: number, templateData: ISelectListTemplateData): void { const data: ISelectListTemplateData = templateData; const text = element.text; const decoratorRight = element.decoratorRight; const isDisabled = element.isDisabled; data.text.textContent = text; data.decoratorRight.innerText = (!!decoratorRight ? decoratorRight : ''); if (typeof element.description === 'string') { const itemDescriptionId = (text.replace(/ /g, '_').toLowerCase() + '_description_' + data.root.id); data.text.setAttribute('aria-describedby', itemDescriptionId); data.itemDescription.id = itemDescriptionId; data.itemDescription.innerText = element.description; } // pseudo-select disabled option if (isDisabled) { dom.addClass(data.root, 'option-disabled'); } else { // Make sure we do class removal from prior template rendering dom.removeClass(data.root, 'option-disabled'); } } disposeTemplate(templateData: ISelectListTemplateData): void { templateData.disposables = dispose(templateData.disposables); } } export class SelectBoxList extends Disposable implements ISelectBoxDelegate, IListVirtualDelegate<ISelectOptionItem> { private static readonly DEFAULT_DROPDOWN_MINIMUM_BOTTOM_MARGIN = 32; private static readonly DEFAULT_DROPDOWN_MINIMUM_TOP_MARGIN = 2; private static readonly DEFAULT_MINIMUM_VISIBLE_OPTIONS = 3; private _isVisible: boolean; private selectBoxOptions: ISelectBoxOptions; private selectElement: HTMLSelectElement; private container?: HTMLElement; private options: ISelectOptionItem[] = []; private selected: number; private readonly _onDidSelect: Emitter<ISelectData>; private styles: ISelectBoxStyles; private listRenderer!: SelectListRenderer; private contextViewProvider!: IContextViewProvider; private selectDropDownContainer!: HTMLElement; private styleElement!: HTMLStyleElement; private selectList!: List<ISelectOptionItem>; private selectDropDownListContainer!: HTMLElement; private widthControlElement!: HTMLElement; private _currentSelection = 0; private _dropDownPosition!: AnchorPosition; private _hasDetails: boolean = false; private selectionDetailsPane!: HTMLElement; private _skipLayout: boolean = false; private _sticky: boolean = false; // for dev purposes only constructor(options: ISelectOptionItem[], selected: number, contextViewProvider: IContextViewProvider, styles: ISelectBoxStyles, selectBoxOptions?: ISelectBoxOptions) { super(); this._isVisible = false; this.selectBoxOptions = selectBoxOptions || Object.create(null); if (typeof this.selectBoxOptions.minBottomMargin !== 'number') { this.selectBoxOptions.minBottomMargin = SelectBoxList.DEFAULT_DROPDOWN_MINIMUM_BOTTOM_MARGIN; } else if (this.selectBoxOptions.minBottomMargin < 0) { this.selectBoxOptions.minBottomMargin = 0; } this.selectElement = document.createElement('select'); // Use custom CSS vars for padding calculation this.selectElement.className = 'monaco-select-box monaco-select-box-dropdown-padding'; if (typeof this.selectBoxOptions.ariaLabel === 'string') { this.selectElement.setAttribute('aria-label', this.selectBoxOptions.ariaLabel); } this._onDidSelect = new Emitter<ISelectData>(); this._register(this._onDidSelect); this.styles = styles; this.registerListeners(); this.constructSelectDropDown(contextViewProvider); this.selected = selected || 0; if (options) { this.setOptions(options, selected); } } // IDelegate - List renderer getHeight(): number { return 18; } getTemplateId(): string { return SELECT_OPTION_ENTRY_TEMPLATE_ID; } private constructSelectDropDown(contextViewProvider: IContextViewProvider) { // SetUp ContextView container to hold select Dropdown this.contextViewProvider = contextViewProvider; this.selectDropDownContainer = dom.$('.monaco-select-box-dropdown-container'); // Use custom CSS vars for padding calculation (shared with parent select) dom.addClass(this.selectDropDownContainer, 'monaco-select-box-dropdown-padding'); // Setup container for select option details this.selectionDetailsPane = dom.append(this.selectDropDownContainer, $('.select-box-details-pane')); // Create span flex box item/div we can measure and control let widthControlOuterDiv = dom.append(this.selectDropDownContainer, $('.select-box-dropdown-container-width-control')); let widthControlInnerDiv = dom.append(widthControlOuterDiv, $('.width-control-div')); this.widthControlElement = document.createElement('span'); this.widthControlElement.className = 'option-text-width-control'; dom.append(widthControlInnerDiv, this.widthControlElement); // Always default to below position this._dropDownPosition = AnchorPosition.BELOW; // Inline stylesheet for themes this.styleElement = dom.createStyleSheet(this.selectDropDownContainer); } private registerListeners() { // Parent native select keyboard listeners this._register(dom.addStandardDisposableListener(this.selectElement, 'change', (e) => { this.selected = e.target.selectedIndex; this._onDidSelect.fire({ index: e.target.selectedIndex, selected: e.target.value }); if (!!this.options[this.selected] && !!this.options[this.selected].text) { this.selectElement.title = this.options[this.selected].text; } })); // Have to implement both keyboard and mouse controllers to handle disabled options // Intercept mouse events to override normal select actions on parents this._register(dom.addDisposableListener(this.selectElement, dom.EventType.CLICK, (e) => { dom.EventHelper.stop(e); if (this._isVisible) { this.hideSelectDropDown(true); } else { this.showSelectDropDown(); } })); this._register(dom.addDisposableListener(this.selectElement, dom.EventType.MOUSE_DOWN, (e) => { dom.EventHelper.stop(e); })); // Intercept keyboard handling this._register(dom.addDisposableListener(this.selectElement, dom.EventType.KEY_DOWN, (e: KeyboardEvent) => { const event = new StandardKeyboardEvent(e); let showDropDown = false; // Create and drop down select list on keyboard select if (isMacintosh) { if (event.keyCode === KeyCode.DownArrow || event.keyCode === KeyCode.UpArrow || event.keyCode === KeyCode.Space || event.keyCode === KeyCode.Enter) { showDropDown = true; } } else { if (event.keyCode === KeyCode.DownArrow && event.altKey || event.keyCode === KeyCode.UpArrow && event.altKey || event.keyCode === KeyCode.Space || event.keyCode === KeyCode.Enter) { showDropDown = true; } } if (showDropDown) { this.showSelectDropDown(); dom.EventHelper.stop(e); } })); } public get onDidSelect(): Event<ISelectData> { return this._onDidSelect.event; } public setOptions(options: ISelectOptionItem[], selected?: number): void { if (!arrays.equals(this.options, options)) { this.options = options; this.selectElement.options.length = 0; this._hasDetails = false; this.options.forEach((option, index) => { this.selectElement.add(this.createOption(option.text, index, option.isDisabled)); if (typeof option.description === 'string') { this._hasDetails = true; } }); } if (selected !== undefined) { this.select(selected); // Set current = selected since this is not necessarily a user exit this._currentSelection = this.selected; } } private setOptionsList() { // Mirror options in drop-down // Populate select list for non-native select mode if (this.selectList) { this.selectList.splice(0, this.selectList.length, this.options); } } public select(index: number): void { if (index >= 0 && index < this.options.length) { this.selected = index; } else if (index > this.options.length - 1) { // Adjust index to end of list // This could make client out of sync with the select this.select(this.options.length - 1); } else if (this.selected < 0) { this.selected = 0; } this.selectElement.selectedIndex = this.selected; if (!!this.options[this.selected] && !!this.options[this.selected].text) { this.selectElement.title = this.options[this.selected].text; } } public setAriaLabel(label: string): void { this.selectBoxOptions.ariaLabel = label; this.selectElement.setAttribute('aria-label', this.selectBoxOptions.ariaLabel); } public focus(): void { if (this.selectElement) { this.selectElement.focus(); } } public blur(): void { if (this.selectElement) { this.selectElement.blur(); } } public render(container: HTMLElement): void { this.container = container; dom.addClass(container, 'select-container'); container.appendChild(this.selectElement); this.applyStyles(); } public style(styles: ISelectBoxStyles): void { const content: string[] = []; this.styles = styles; // Style non-native select mode if (this.styles.listFocusBackground) { content.push(`.monaco-select-box-dropdown-container > .select-box-dropdown-list-container .monaco-list .monaco-list-row.focused { background-color: ${this.styles.listFocusBackground} !important; }`); } if (this.styles.listFocusForeground) { content.push(`.monaco-select-box-dropdown-container > .select-box-dropdown-list-container .monaco-list .monaco-list-row.focused:not(:hover) { color: ${this.styles.listFocusForeground} !important; }`); } if (this.styles.decoratorRightForeground) { content.push(`.monaco-select-box-dropdown-container > .select-box-dropdown-list-container .monaco-list .monaco-list-row .option-decorator-right { color: ${this.styles.decoratorRightForeground} !important; }`); } if (this.styles.selectBackground && this.styles.selectBorder && !this.styles.selectBorder.equals(this.styles.selectBackground)) { content.push(`.monaco-select-box-dropdown-container { border: 1px solid ${this.styles.selectBorder} } `); content.push(`.monaco-select-box-dropdown-container > .select-box-details-pane.border-top { border-top: 1px solid ${this.styles.selectBorder} } `); content.push(`.monaco-select-box-dropdown-container > .select-box-details-pane.border-bottom { border-bottom: 1px solid ${this.styles.selectBorder} } `); } else if (this.styles.selectListBorder) { content.push(`.monaco-select-box-dropdown-container > .select-box-details-pane.border-top { border-top: 1px solid ${this.styles.selectListBorder} } `); content.push(`.monaco-select-box-dropdown-container > .select-box-details-pane.border-bottom { border-bottom: 1px solid ${this.styles.selectListBorder} } `); } // Hover foreground - ignore for disabled options if (this.styles.listHoverForeground) { content.push(`.monaco-select-box-dropdown-container > .select-box-dropdown-list-container .monaco-list .monaco-list-row:hover { color: ${this.styles.listHoverForeground} !important; }`); content.push(`.monaco-select-box-dropdown-container > .select-box-dropdown-list-container .monaco-list .monaco-list-row.option-disabled:hover { background-color: ${this.styles.listActiveSelectionForeground} !important; }`); } // Hover background - ignore for disabled options if (this.styles.listHoverBackground) { content.push(`.monaco-select-box-dropdown-container > .select-box-dropdown-list-container .monaco-list .monaco-list-row:not(.option-disabled):not(.focused):hover { background-color: ${this.styles.listHoverBackground} !important; }`); content.push(`.monaco-select-box-dropdown-container > .select-box-dropdown-list-container .monaco-list .monaco-list-row.option-disabled:hover { background-color: ${this.styles.selectBackground} !important; }`); } // Match quick input outline styles - ignore for disabled options if (this.styles.listFocusOutline) { content.push(`.monaco-select-box-dropdown-container > .select-box-dropdown-list-container .monaco-list .monaco-list-row.focused { outline: 1.6px dotted ${this.styles.listFocusOutline} !important; outline-offset: -1.6px !important; }`); } if (this.styles.listHoverOutline) { content.push(`.monaco-select-box-dropdown-container > .select-box-dropdown-list-container .monaco-list .monaco-list-row:hover:not(.focused) { outline: 1.6px dashed ${this.styles.listHoverOutline} !important; outline-offset: -1.6px !important; }`); content.push(`.monaco-select-box-dropdown-container > .select-box-dropdown-list-container .monaco-list .monaco-list-row.option-disabled:hover { outline: none !important; }`); } this.styleElement.innerHTML = content.join('\n'); this.applyStyles(); } public applyStyles(): void { // Style parent select if (this.selectElement) { const background = this.styles.selectBackground ? this.styles.selectBackground.toString() : ''; const foreground = this.styles.selectForeground ? this.styles.selectForeground.toString() : ''; const border = this.styles.selectBorder ? this.styles.selectBorder.toString() : ''; this.selectElement.style.backgroundColor = background; this.selectElement.style.color = foreground; this.selectElement.style.borderColor = border; } // Style drop down select list (non-native mode only) if (this.selectList) { this.styleList(); } } private styleList() { if (this.selectList) { const background = this.styles.selectBackground ? this.styles.selectBackground.toString() : ''; this.selectList.style({}); const listBackground = this.styles.selectListBackground ? this.styles.selectListBackground.toString() : background; this.selectDropDownListContainer.style.backgroundColor = listBackground; this.selectionDetailsPane.style.backgroundColor = listBackground; const optionsBorder = this.styles.focusBorder ? this.styles.focusBorder.toString() : ''; this.selectDropDownContainer.style.outlineColor = optionsBorder; this.selectDropDownContainer.style.outlineOffset = '-1px'; } } private createOption(value: string, index: number, disabled?: boolean): HTMLOptionElement { let option = document.createElement('option'); option.value = value; option.text = value; option.disabled = !!disabled; return option; } // ContextView dropdown methods private showSelectDropDown() { this.selectionDetailsPane.innerText = ''; if (!this.contextViewProvider || this._isVisible) { return; } // Lazily create and populate list only at open, moved from constructor this.createSelectList(this.selectDropDownContainer); this.setOptionsList(); // This allows us to flip the position based on measurement // Set drop-down position above/below from required height and margins // If pre-layout cannot fit at least one option do not show drop-down this.contextViewProvider.showContextView({ getAnchor: () => this.selectElement, render: (container: HTMLElement) => this.renderSelectDropDown(container, true), layout: () => { this.layoutSelectDropDown(); }, onHide: () => { dom.toggleClass(this.selectDropDownContainer, 'visible', false); dom.toggleClass(this.selectElement, 'synthetic-focus', false); }, anchorPosition: this._dropDownPosition }, this.selectBoxOptions.optionsAsChildren ? this.container : undefined); // Hide so we can relay out this._isVisible = true; this.hideSelectDropDown(false); this.contextViewProvider.showContextView({ getAnchor: () => this.selectElement, render: (container: HTMLElement) => this.renderSelectDropDown(container), layout: () => this.layoutSelectDropDown(), onHide: () => { dom.toggleClass(this.selectDropDownContainer, 'visible', false); dom.toggleClass(this.selectElement, 'synthetic-focus', false); }, anchorPosition: this._dropDownPosition }, this.selectBoxOptions.optionsAsChildren ? this.container : undefined); // Track initial selection the case user escape, blur this._currentSelection = this.selected; this._isVisible = true; this.selectElement.setAttribute('aria-expanded', 'true'); } private hideSelectDropDown(focusSelect: boolean) { if (!this.contextViewProvider || !this._isVisible) { return; } this._isVisible = false; this.selectElement.setAttribute('aria-expanded', 'false'); if (focusSelect) { this.selectElement.focus(); } this.contextViewProvider.hideContextView(); } private renderSelectDropDown(container: HTMLElement, preLayoutPosition?: boolean): IDisposable { container.appendChild(this.selectDropDownContainer); // Pre-Layout allows us to change position this.layoutSelectDropDown(preLayoutPosition); return { dispose: () => { // contextView will dispose itself if moving from one View to another try { container.removeChild(this.selectDropDownContainer); // remove to take out the CSS rules we add } catch (error) { // Ignore, removed already by change of focus } } }; } // Iterate over detailed descriptions, find max height private measureMaxDetailsHeight(): number { let maxDetailsPaneHeight = 0; this.options.forEach((option, index) => { this.selectionDetailsPane.innerText = ''; if (option.description) { if (option.descriptionIsMarkdown) { this.selectionDetailsPane.appendChild(this.renderDescriptionMarkdown(option.description)); } else { this.selectionDetailsPane.innerText = option.description; } this.selectionDetailsPane.style.display = 'block'; } else { this.selectionDetailsPane.style.display = 'none'; } if (this.selectionDetailsPane.offsetHeight > maxDetailsPaneHeight) { maxDetailsPaneHeight = this.selectionDetailsPane.offsetHeight; } }); // Reset description to selected this.selectionDetailsPane.innerText = ''; const description = this.options[this.selected].description || null; const descriptionIsMarkdown = this.options[this.selected].descriptionIsMarkdown || null; if (description) { if (descriptionIsMarkdown) { this.selectionDetailsPane.appendChild(this.renderDescriptionMarkdown(description)); } else { this.selectionDetailsPane.innerText = description; } this.selectionDetailsPane.style.display = 'block'; } return maxDetailsPaneHeight; } private layoutSelectDropDown(preLayoutPosition?: boolean): boolean { // Avoid recursion from layout called in onListFocus if (this._skipLayout) { return false; } // Layout ContextView drop down select list and container // Have to manage our vertical overflow, sizing, position below or above // Position has to be determined and set prior to contextView instantiation if (this.selectList) { // Make visible to enable measurements dom.toggleClass(this.selectDropDownContainer, 'visible', true); const selectPosition = dom.getDomNodePagePosition(this.selectElement); const styles = getComputedStyle(this.selectElement); const verticalPadding = parseFloat(styles.getPropertyValue('--dropdown-padding-top')) + parseFloat(styles.getPropertyValue('--dropdown-padding-bottom')); const maxSelectDropDownHeightBelow = (window.innerHeight - selectPosition.top - selectPosition.height - (this.selectBoxOptions.minBottomMargin || 0)); const maxSelectDropDownHeightAbove = (selectPosition.top - SelectBoxList.DEFAULT_DROPDOWN_MINIMUM_TOP_MARGIN); // Determine optimal width - min(longest option), opt(parent select, excluding margins), max(ContextView controlled) const selectWidth = this.selectElement.offsetWidth; const selectMinWidth = this.setWidthControlElement(this.widthControlElement); const selectOptimalWidth = Math.max(selectMinWidth, Math.round(selectWidth)).toString() + 'px'; this.selectDropDownContainer.style.width = selectOptimalWidth; // Get initial list height and determine space above and below this.selectList.getHTMLElement().style.height = ''; this.selectList.layout(); let listHeight = this.selectList.contentHeight; const maxDetailsPaneHeight = this._hasDetails ? this.measureMaxDetailsHeight() : 0; const minRequiredDropDownHeight = listHeight + verticalPadding + maxDetailsPaneHeight; const maxVisibleOptionsBelow = ((Math.floor((maxSelectDropDownHeightBelow - verticalPadding - maxDetailsPaneHeight) / this.getHeight()))); const maxVisibleOptionsAbove = ((Math.floor((maxSelectDropDownHeightAbove - verticalPadding - maxDetailsPaneHeight) / this.getHeight()))); // If we are only doing pre-layout check/adjust position only // Calculate vertical space available, flip up if insufficient // Use reflected padding on parent select, ContextView style // properties not available before DOM attachment if (preLayoutPosition) { // Check if select moved out of viewport , do not open // If at least one option cannot be shown, don't open the drop-down or hide/remove if open if ((selectPosition.top + selectPosition.height) > (window.innerHeight - 22) || selectPosition.top < SelectBoxList.DEFAULT_DROPDOWN_MINIMUM_TOP_MARGIN || ((maxVisibleOptionsBelow < 1) && (maxVisibleOptionsAbove < 1))) { // Indicate we cannot open return false; } // Determine if we have to flip up // Always show complete list items - never more than Max available vertical height if (maxVisibleOptionsBelow < SelectBoxList.DEFAULT_MINIMUM_VISIBLE_OPTIONS && maxVisibleOptionsAbove > maxVisibleOptionsBelow && this.options.length > maxVisibleOptionsBelow ) { this._dropDownPosition = AnchorPosition.ABOVE; this.selectDropDownContainer.removeChild(this.selectDropDownListContainer); this.selectDropDownContainer.removeChild(this.selectionDetailsPane); this.selectDropDownContainer.appendChild(this.selectionDetailsPane); this.selectDropDownContainer.appendChild(this.selectDropDownListContainer); dom.removeClass(this.selectionDetailsPane, 'border-top'); dom.addClass(this.selectionDetailsPane, 'border-bottom'); } else { this._dropDownPosition = AnchorPosition.BELOW; this.selectDropDownContainer.removeChild(this.selectDropDownListContainer); this.selectDropDownContainer.removeChild(this.selectionDetailsPane); this.selectDropDownContainer.appendChild(this.selectDropDownListContainer); this.selectDropDownContainer.appendChild(this.selectionDetailsPane); dom.removeClass(this.selectionDetailsPane, 'border-bottom'); dom.addClass(this.selectionDetailsPane, 'border-top'); } // Do full layout on showSelectDropDown only return true; } // Check if select out of viewport or cutting into status bar if ((selectPosition.top + selectPosition.height) > (window.innerHeight - 22) || selectPosition.top < SelectBoxList.DEFAULT_DROPDOWN_MINIMUM_TOP_MARGIN || (this._dropDownPosition === AnchorPosition.BELOW && maxVisibleOptionsBelow < 1) || (this._dropDownPosition === AnchorPosition.ABOVE && maxVisibleOptionsAbove < 1)) { // Cannot properly layout, close and hide this.hideSelectDropDown(true); return false; } // SetUp list dimensions and layout - account for container padding // Use position to check above or below available space if (this._dropDownPosition === AnchorPosition.BELOW) { if (this._isVisible && maxVisibleOptionsBelow + maxVisibleOptionsAbove < 1) { // If drop-down is visible, must be doing a DOM re-layout, hide since we don't fit // Hide drop-down, hide contextview, focus on parent select this.hideSelectDropDown(true); return false; } // Adjust list height to max from select bottom to margin (default/minBottomMargin) if (minRequiredDropDownHeight > maxSelectDropDownHeightBelow) { listHeight = (maxVisibleOptionsBelow * this.getHeight()); } } else { if (minRequiredDropDownHeight > maxSelectDropDownHeightAbove) { listHeight = (maxVisibleOptionsAbove * this.getHeight()); } } // Set adjusted list height and relayout this.selectList.layout(listHeight); this.selectList.domFocus(); // Finally set focus on selected item if (this.selectList.length > 0) { this.selectList.setFocus([this.selected || 0]); this.selectList.reveal(this.selectList.getFocus()[0] || 0); } if (this._hasDetails) { // Leave the selectDropDownContainer to size itself according to children (list + details) - #57447 this.selectList.getHTMLElement().style.height = (listHeight + verticalPadding) + 'px'; this.selectDropDownContainer.style.height = ''; } else { this.selectDropDownContainer.style.height = (listHeight + verticalPadding) + 'px'; } this.selectDropDownContainer.style.width = selectOptimalWidth; // Maintain focus outline on parent select as well as list container - tabindex for focus this.selectDropDownListContainer.setAttribute('tabindex', '0'); dom.toggleClass(this.selectElement, 'synthetic-focus', true); dom.toggleClass(this.selectDropDownContainer, 'synthetic-focus', true); return true; } else { return false; } } private setWidthControlElement(container: HTMLElement): number { let elementWidth = 0; if (container) { let longest = 0; let longestLength = 0; this.options.forEach((option, index) => { const len = option.text.length + (!!option.decoratorRight ? option.decoratorRight.length : 0); if (len > longestLength) { longest = index; longestLength = len; } }); container.innerHTML = this.options[longest].text + (!!this.options[longest].decoratorRight ? (this.options[longest].decoratorRight + ' ') : ''); elementWidth = dom.getTotalWidth(container); } return elementWidth; } private createSelectList(parent: HTMLElement): void { // If we have already constructive list on open, skip if (this.selectList) { return; } // SetUp container for list this.selectDropDownListContainer = dom.append(parent, $('.select-box-dropdown-list-container')); this.listRenderer = new SelectListRenderer(); this.selectList = new List('SelectBoxCustom', this.selectDropDownListContainer, this, [this.listRenderer], { useShadows: false, verticalScrollMode: ScrollbarVisibility.Visible, keyboardSupport: false, mouseSupport: false, accessibilityProvider: { getAriaLabel: (element) => element.text, getWidgetAriaLabel: () => localize({ key: 'selectBox', comment: ['Behave like native select dropdown element.'] }, "Select Box"), getRole: () => 'option', getWidgetRole: () => 'listbox' } }); if (this.selectBoxOptions.ariaLabel) { this.selectList.ariaLabel = this.selectBoxOptions.ariaLabel; } // SetUp list keyboard controller - control navigation, disabled items, focus const onSelectDropDownKeyDown = Event.chain(domEvent(this.selectDropDownListContainer, 'keydown')) .filter(() => this.selectList.length > 0) .map(e => new StandardKeyboardEvent(e)); this._register(onSelectDropDownKeyDown.filter(e => e.keyCode === KeyCode.Enter).on(e => this.onEnter(e), this)); this._register(onSelectDropDownKeyDown.filter(e => e.keyCode === KeyCode.Escape).on(e => this.onEscape(e), this)); this._register(onSelectDropDownKeyDown.filter(e => e.keyCode === KeyCode.UpArrow).on(this.onUpArrow, this)); this._register(onSelectDropDownKeyDown.filter(e => e.keyCode === KeyCode.DownArrow).on(this.onDownArrow, this)); this._register(onSelectDropDownKeyDown.filter(e => e.keyCode === KeyCode.PageDown).on(this.onPageDown, this)); this._register(onSelectDropDownKeyDown.filter(e => e.keyCode === KeyCode.PageUp).on(this.onPageUp, this)); this._register(onSelectDropDownKeyDown.filter(e => e.keyCode === KeyCode.Home).on(this.onHome, this)); this._register(onSelectDropDownKeyDown.filter(e => e.keyCode === KeyCode.End).on(this.onEnd, this)); this._register(onSelectDropDownKeyDown.filter(e => (e.keyCode >= KeyCode.KEY_0 && e.keyCode <= KeyCode.KEY_Z) || (e.keyCode >= KeyCode.US_SEMICOLON && e.keyCode <= KeyCode.NUMPAD_DIVIDE)).on(this.onCharacter, this)); // SetUp list mouse controller - control navigation, disabled items, focus this._register(Event.chain(domEvent(this.selectList.getHTMLElement(), 'mouseup')) .filter(() => this.selectList.length > 0) .on(e => this.onMouseUp(e), this)); this._register(this.selectList.onMouseOver(e => typeof e.index !== 'undefined' && this.selectList.setFocus([e.index]))); this._register(this.selectList.onDidChangeFocus(e => this.onListFocus(e))); this._register(dom.addDisposableListener(this.selectDropDownContainer, dom.EventType.FOCUS_OUT, e => { if (!this._isVisible || dom.isAncestor(e.relatedTarget as HTMLElement, this.selectDropDownContainer)) { return; } this.onListBlur(); })); this.selectList.getHTMLElement().setAttribute('aria-label', this.selectBoxOptions.ariaLabel || ''); this.selectList.getHTMLElement().setAttribute('aria-expanded', 'true'); this.styleList(); } // List methods // List mouse controller - active exit, select option, fire onDidSelect if change, return focus to parent select private onMouseUp(e: MouseEvent): void { dom.EventHelper.stop(e); const target = <Element>e.target; if (!target) { return; } // Check our mouse event is on an option (not scrollbar) if (!!target.classList.contains('slider')) { return; } const listRowElement = target.closest('.monaco-list-row'); if (!listRowElement) { return; } const index = Number(listRowElement.getAttribute('data-index')); const disabled = listRowElement.classList.contains('option-disabled'); // Ignore mouse selection of disabled options if (index >= 0 && index < this.options.length && !disabled) { this.selected = index; this.select(this.selected); this.selectList.setFocus([this.selected]); this.selectList.reveal(this.selectList.getFocus()[0]); // Only fire if selection change if (this.selected !== this._currentSelection) { // Set current = selected this._currentSelection = this.selected; this._onDidSelect.fire({ index: this.selectElement.selectedIndex, selected: this.options[this.selected].text }); if (!!this.options[this.selected] && !!this.options[this.selected].text) { this.selectElement.title = this.options[this.selected].text; } } this.hideSelectDropDown(true); } } // List Exit - passive - implicit no selection change, hide drop-down private onListBlur(): void { if (this._sticky) { return; } if (this.selected !== this._currentSelection) { // Reset selected to current if no change this.select(this._currentSelection); } this.hideSelectDropDown(false); } private renderDescriptionMarkdown(text: string, actionHandler?: IContentActionHandler): HTMLElement { const cleanRenderedMarkdown = (element: Node) => { for (let i = 0; i < element.childNodes.length; i++) { const child = <Element>element.childNodes.item(i); const tagName = child.tagName && child.tagName.toLowerCase(); if (tagName === 'img') { element.removeChild(child); } else { cleanRenderedMarkdown(child); } } }; const renderedMarkdown = renderMarkdown({ value: text }, { actionHandler }); renderedMarkdown.classList.add('select-box-description-markdown'); cleanRenderedMarkdown(renderedMarkdown); return renderedMarkdown; } // List Focus Change - passive - update details pane with newly focused element's data private onListFocus(e: IListEvent<ISelectOptionItem>) { // Skip during initial layout if (!this._isVisible || !this._hasDetails) { return; } this.selectionDetailsPane.innerText = ''; const selectedIndex = e.indexes[0]; const description = this.options[selectedIndex].description; const descriptionIsMarkdown = this.options[selectedIndex].descriptionIsMarkdown; if (description) { if (descriptionIsMarkdown) { const actionHandler = this.options[selectedIndex].descriptionMarkdownActionHandler; this.selectionDetailsPane.appendChild(this.renderDescriptionMarkdown(description, actionHandler)); } else { this.selectionDetailsPane.innerText = description; } this.selectionDetailsPane.style.display = 'block'; } else { this.selectionDetailsPane.style.display = 'none'; } // Avoid recursion this._skipLayout = true; this.contextViewProvider.layout(); this._skipLayout = false; } // List keyboard controller // List exit - active - hide ContextView dropdown, reset selection, return focus to parent select private onEscape(e: StandardKeyboardEvent): void { dom.EventHelper.stop(e); // Reset selection to value when opened this.select(this._currentSelection); this.hideSelectDropDown(true); } // List exit - active - hide ContextView dropdown, return focus to parent select, fire onDidSelect if change private onEnter(e: StandardKeyboardEvent): void { dom.EventHelper.stop(e); // Only fire if selection change if (this.selected !== this._currentSelection) { this._currentSelection = this.selected; this._onDidSelect.fire({ index: this.selectElement.selectedIndex, selected: this.options[this.selected].text }); if (!!this.options[this.selected] && !!this.options[this.selected].text) { this.selectElement.title = this.options[this.selected].text; } } this.hideSelectDropDown(true); } // List navigation - have to handle a disabled option (jump over) private onDownArrow(): void { if (this.selected < this.options.length - 1) { // Skip disabled options const nextOptionDisabled = this.options[this.selected + 1].isDisabled; if (nextOptionDisabled && this.options.length > this.selected + 2) { this.selected += 2; } else if (nextOptionDisabled) { return; } else { this.selected++; } // Set focus/selection - only fire event when closing drop-down or on blur this.select(this.selected); this.selectList.setFocus([this.selected]); this.selectList.reveal(this.selectList.getFocus()[0]); } } private onUpArrow(): void { if (this.selected > 0) { // Skip disabled options const previousOptionDisabled = this.options[this.selected - 1].isDisabled; if (previousOptionDisabled && this.selected > 1) { this.selected -= 2; } else { this.selected--; } // Set focus/selection - only fire event when closing drop-down or on blur this.select(this.selected); this.selectList.setFocus([this.selected]); this.selectList.reveal(this.selectList.getFocus()[0]); } } private onPageUp(e: StandardKeyboardEvent): void { dom.EventHelper.stop(e); this.selectList.focusPreviousPage(); // Allow scrolling to settle setTimeout(() => { this.selected = this.selectList.getFocus()[0]; // Shift selection down if we land on a disabled option if (this.options[this.selected].isDisabled && this.selected < this.options.length - 1) { this.selected++; this.selectList.setFocus([this.selected]); } this.selectList.reveal(this.selected); this.select(this.selected); }, 1); } private onPageDown(e: StandardKeyboardEvent): void { dom.EventHelper.stop(e); this.selectList.focusNextPage(); // Allow scrolling to settle setTimeout(() => { this.selected = this.selectList.getFocus()[0]; // Shift selection up if we land on a disabled option if (this.options[this.selected].isDisabled && this.selected > 0) { this.selected--; this.selectList.setFocus([this.selected]); } this.selectList.reveal(this.selected); this.select(this.selected); }, 1); } private onHome(e: StandardKeyboardEvent): void { dom.EventHelper.stop(e); if (this.options.length < 2) { return; } this.selected = 0; if (this.options[this.selected].isDisabled && this.selected > 1) { this.selected++; } this.selectList.setFocus([this.selected]); this.selectList.reveal(this.selected); this.select(this.selected); } private onEnd(e: StandardKeyboardEvent): void { dom.EventHelper.stop(e); if (this.options.length < 2) { return; } this.selected = this.options.length - 1; if (this.options[this.selected].isDisabled && this.selected > 1) { this.selected--; } this.selectList.setFocus([this.selected]); this.selectList.reveal(this.selected); this.select(this.selected); } // Mimic option first character navigation of native select private onCharacter(e: StandardKeyboardEvent): void { const ch = KeyCodeUtils.toString(e.keyCode); let optionIndex = -1; for (let i = 0; i < this.options.length - 1; i++) { optionIndex = (i + this.selected + 1) % this.options.length; if (this.options[optionIndex].text.charAt(0).toUpperCase() === ch && !this.options[optionIndex].isDisabled) { this.select(optionIndex); this.selectList.setFocus([optionIndex]); this.selectList.reveal(this.selectList.getFocus()[0]); dom.EventHelper.stop(e); break; } } } public dispose(): void { this.hideSelectDropDown(false); super.dispose(); } }
src/vs/base/browser/ui/selectBox/selectBoxCustom.ts
0
https://github.com/microsoft/vscode/commit/135b6da83746477b2983fee879122ceefa70014d
[ 0.00036341368104331195, 0.0001713021338218823, 0.0001587297156220302, 0.0001685547613305971, 0.0000202952232939424 ]
{ "id": 0, "code_window": [ "\t\tstopOrDisconectAction\n", "\t];\n", "}\n", "\n", "\n", "class StopAction extends Action {\n", "\n", "\tconstructor(\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ "export class StopAction extends Action {\n" ], "file_path": "src/vs/workbench/contrib/debug/browser/callStackView.ts", "type": "replace", "edit_start_line_idx": 984 }
// lss is mor
src/vs/workbench/services/search/test/node/fixtures/site.less
0
https://github.com/microsoft/vscode/commit/135b6da83746477b2983fee879122ceefa70014d
[ 0.00017510527686681598, 0.00017510527686681598, 0.00017510527686681598, 0.00017510527686681598, 0 ]
{ "id": 1, "code_window": [ "\n", "\tconstructor(\n", "\t\tprivate readonly session: IDebugSession,\n", "\t\t@ICommandService private readonly commandService: ICommandService\n", "\t) {\n", "\t\tsuper(`action.${STOP_ID}`, STOP_LABEL, 'debug-action codicon-debug-stop');\n", "\t}\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tprivate readonly session: IDebugSession | null,\n" ], "file_path": "src/vs/workbench/contrib/debug/browser/callStackView.ts", "type": "replace", "edit_start_line_idx": 987 }
/*--------------------------------------------------------------------------------------------- * 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 { RunOnceScheduler } from 'vs/base/common/async'; import * as dom from 'vs/base/browser/dom'; import { IViewletViewOptions } from 'vs/workbench/browser/parts/views/viewsViewlet'; import { IDebugService, State, IStackFrame, IDebugSession, IThread, CONTEXT_CALLSTACK_ITEM_TYPE, IDebugModel } from 'vs/workbench/contrib/debug/common/debug'; import { Thread, StackFrame, ThreadAndSessionIds } from 'vs/workbench/contrib/debug/common/debugModel'; import { IContextMenuService } from 'vs/platform/contextview/browser/contextView'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { MenuId, IMenu, IMenuService, MenuItemAction, SubmenuItemAction } from 'vs/platform/actions/common/actions'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; import { renderViewTree } from 'vs/workbench/contrib/debug/browser/baseDebugView'; import { IAction, Action } from 'vs/base/common/actions'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IContextKey, IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { ViewPane } from 'vs/workbench/browser/parts/views/viewPaneContainer'; import { ILabelService } from 'vs/platform/label/common/label'; import { IListAccessibilityProvider } from 'vs/base/browser/ui/list/listWidget'; import { createAndFillInContextMenuActions, createAndFillInActionBarActions, MenuEntryActionViewItem, SubmenuEntryActionViewItem } from 'vs/platform/actions/browser/menuEntryActionViewItem'; import { IListVirtualDelegate } from 'vs/base/browser/ui/list/list'; import { ITreeNode, ITreeContextMenuEvent, IAsyncDataSource } from 'vs/base/browser/ui/tree/tree'; import { WorkbenchCompressibleAsyncDataTree } from 'vs/platform/list/browser/listService'; import { HighlightedLabel } from 'vs/base/browser/ui/highlightedlabel/highlightedLabel'; import { createMatches, FuzzyScore, IMatch } from 'vs/base/common/filters'; import { Event } from 'vs/base/common/event'; import { dispose, IDisposable } from 'vs/base/common/lifecycle'; import { ActionBar } from 'vs/base/browser/ui/actionbar/actionbar'; import { isSessionAttach } from 'vs/workbench/contrib/debug/common/debugUtils'; import { STOP_ID, STOP_LABEL, DISCONNECT_ID, DISCONNECT_LABEL, RESTART_SESSION_ID, RESTART_LABEL, STEP_OVER_ID, STEP_OVER_LABEL, STEP_INTO_LABEL, STEP_INTO_ID, STEP_OUT_LABEL, STEP_OUT_ID, PAUSE_ID, PAUSE_LABEL, CONTINUE_ID, CONTINUE_LABEL } from 'vs/workbench/contrib/debug/browser/debugCommands'; import { ICommandService } from 'vs/platform/commands/common/commands'; import { CollapseAction } from 'vs/workbench/browser/viewlet'; import { IViewDescriptorService } from 'vs/workbench/common/views'; import { textLinkForeground } from 'vs/platform/theme/common/colorRegistry'; import { IThemeService } from 'vs/platform/theme/common/themeService'; import { IOpenerService } from 'vs/platform/opener/common/opener'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { attachStylerCallback } from 'vs/platform/theme/common/styler'; import { INotificationService } from 'vs/platform/notification/common/notification'; import { commonSuffixLength } from 'vs/base/common/strings'; import { posix } from 'vs/base/common/path'; import { ITreeCompressionDelegate } from 'vs/base/browser/ui/tree/asyncDataTree'; import { ICompressibleTreeRenderer } from 'vs/base/browser/ui/tree/objectTree'; import { ICompressedTreeNode } from 'vs/base/browser/ui/tree/compressedObjectTreeModel'; const $ = dom.$; type CallStackItem = IStackFrame | IThread | IDebugSession | string | ThreadAndSessionIds | IStackFrame[]; export function getContext(element: CallStackItem | null): any { return element instanceof StackFrame ? { sessionId: element.thread.session.getId(), threadId: element.thread.getId(), frameId: element.getId() } : element instanceof Thread ? { sessionId: element.session.getId(), threadId: element.getId() } : isDebugSession(element) ? { sessionId: element.getId() } : undefined; } // Extensions depend on this context, should not be changed even though it is not fully deterministic export function getContextForContributedActions(element: CallStackItem | null): string | number { if (element instanceof StackFrame) { if (element.source.inMemory) { return element.source.raw.path || element.source.reference || element.source.name; } return element.source.uri.toString(); } if (element instanceof Thread) { return element.threadId; } if (isDebugSession(element)) { return element.getId(); } return ''; } export function getSpecificSourceName(stackFrame: IStackFrame): string { // To reduce flashing of the path name and the way we fetch stack frames // We need to compute the source name based on the other frames in the stale call stack let callStack = (<Thread>stackFrame.thread).getStaleCallStack(); callStack = callStack.length > 0 ? callStack : stackFrame.thread.getCallStack(); const otherSources = callStack.map(sf => sf.source).filter(s => s !== stackFrame.source); let suffixLength = 0; otherSources.forEach(s => { if (s.name === stackFrame.source.name) { suffixLength = Math.max(suffixLength, commonSuffixLength(stackFrame.source.uri.path, s.uri.path)); } }); if (suffixLength === 0) { return stackFrame.source.name; } const from = Math.max(0, stackFrame.source.uri.path.lastIndexOf(posix.sep, stackFrame.source.uri.path.length - suffixLength - 1)); return (from > 0 ? '...' : '') + stackFrame.source.uri.path.substr(from); } async function expandTo(session: IDebugSession, tree: WorkbenchCompressibleAsyncDataTree<IDebugModel, CallStackItem, FuzzyScore>): Promise<void> { if (session.parentSession) { await expandTo(session.parentSession, tree); } await tree.expand(session); } export class CallStackView extends ViewPane { private pauseMessage!: HTMLSpanElement; private pauseMessageLabel!: HTMLSpanElement; private onCallStackChangeScheduler: RunOnceScheduler; private needsRefresh = false; private ignoreSelectionChangedEvent = false; private ignoreFocusStackFrameEvent = false; private callStackItemType: IContextKey<string>; private dataSource!: CallStackDataSource; private tree!: WorkbenchCompressibleAsyncDataTree<IDebugModel, CallStackItem, FuzzyScore>; private menu: IMenu; private autoExpandedSessions = new Set<IDebugSession>(); private selectionNeedsUpdate = false; constructor( private options: IViewletViewOptions, @IContextMenuService contextMenuService: IContextMenuService, @IDebugService private readonly debugService: IDebugService, @IKeybindingService keybindingService: IKeybindingService, @IInstantiationService instantiationService: IInstantiationService, @IViewDescriptorService viewDescriptorService: IViewDescriptorService, @IEditorService private readonly editorService: IEditorService, @IConfigurationService configurationService: IConfigurationService, @IMenuService menuService: IMenuService, @IContextKeyService readonly contextKeyService: IContextKeyService, @IOpenerService openerService: IOpenerService, @IThemeService themeService: IThemeService, @ITelemetryService telemetryService: ITelemetryService, ) { super(options, keybindingService, contextMenuService, configurationService, contextKeyService, viewDescriptorService, instantiationService, openerService, themeService, telemetryService); this.callStackItemType = CONTEXT_CALLSTACK_ITEM_TYPE.bindTo(contextKeyService); this.menu = menuService.createMenu(MenuId.DebugCallStackContext, contextKeyService); this._register(this.menu); // Create scheduler to prevent unnecessary flashing of tree when reacting to changes this.onCallStackChangeScheduler = new RunOnceScheduler(async () => { // Only show the global pause message if we do not display threads. // Otherwise there will be a pause message per thread and there is no need for a global one. const sessions = this.debugService.getModel().getSessions(); if (sessions.length === 0) { this.autoExpandedSessions.clear(); } const thread = sessions.length === 1 && sessions[0].getAllThreads().length === 1 ? sessions[0].getAllThreads()[0] : undefined; if (thread && thread.stoppedDetails) { this.pauseMessageLabel.textContent = thread.stoppedDetails.description || nls.localize('debugStopped', "Paused on {0}", thread.stoppedDetails.reason || ''); this.pauseMessageLabel.title = thread.stoppedDetails.text || ''; dom.toggleClass(this.pauseMessageLabel, 'exception', thread.stoppedDetails.reason === 'exception'); this.pauseMessage.hidden = false; this.updateActions(); } else { this.pauseMessage.hidden = true; this.updateActions(); } this.needsRefresh = false; this.dataSource.deemphasizedStackFramesToShow = []; await this.tree.updateChildren(); try { const toExpand = new Set<IDebugSession>(); sessions.forEach(s => { // Automatically expand sessions that have children, but only do this once. if (s.parentSession && !this.autoExpandedSessions.has(s.parentSession)) { toExpand.add(s.parentSession); } }); for (let session of toExpand) { await expandTo(session, this.tree); this.autoExpandedSessions.add(session); } } catch (e) { // Ignore tree expand errors if element no longer present } if (this.selectionNeedsUpdate) { this.selectionNeedsUpdate = false; await this.updateTreeSelection(); } }, 50); } protected renderHeaderTitle(container: HTMLElement): void { const titleContainer = dom.append(container, $('.debug-call-stack-title')); super.renderHeaderTitle(titleContainer, this.options.title); this.pauseMessage = dom.append(titleContainer, $('span.pause-message')); this.pauseMessage.hidden = true; this.pauseMessageLabel = dom.append(this.pauseMessage, $('span.label')); } getActions(): IAction[] { if (this.pauseMessage.hidden) { return [new CollapseAction(() => this.tree, true, 'explorer-action codicon-collapse-all')]; } return []; } renderBody(container: HTMLElement): void { super.renderBody(container); dom.addClass(this.element, 'debug-pane'); dom.addClass(container, 'debug-call-stack'); const treeContainer = renderViewTree(container); this.dataSource = new CallStackDataSource(this.debugService); const sessionsRenderer = this.instantiationService.createInstance(SessionsRenderer, this.menu); this.tree = <WorkbenchCompressibleAsyncDataTree<IDebugModel, CallStackItem, FuzzyScore>>this.instantiationService.createInstance(WorkbenchCompressibleAsyncDataTree, 'CallStackView', treeContainer, new CallStackDelegate(), new CallStackCompressionDelegate(this.debugService), [ sessionsRenderer, new ThreadsRenderer(this.instantiationService), this.instantiationService.createInstance(StackFramesRenderer), new ErrorsRenderer(), new LoadAllRenderer(this.themeService), new ShowMoreRenderer(this.themeService) ], this.dataSource, { accessibilityProvider: new CallStackAccessibilityProvider(), compressionEnabled: true, autoExpandSingleChildren: true, identityProvider: { getId: (element: CallStackItem) => { if (typeof element === 'string') { return element; } if (element instanceof Array) { return `showMore ${element[0].getId()}`; } return element.getId(); } }, keyboardNavigationLabelProvider: { getKeyboardNavigationLabel: (e: CallStackItem) => { if (isDebugSession(e)) { return e.getLabel(); } if (e instanceof Thread) { return `${e.name} ${e.stateLabel}`; } if (e instanceof StackFrame || typeof e === 'string') { return e; } if (e instanceof ThreadAndSessionIds) { return LoadAllRenderer.LABEL; } return nls.localize('showMoreStackFrames2', "Show More Stack Frames"); }, getCompressedNodeKeyboardNavigationLabel: (e: CallStackItem[]) => { const firstItem = e[0]; if (isDebugSession(firstItem)) { return firstItem.getLabel(); } return ''; } }, expandOnlyOnTwistieClick: true, overrideStyles: { listBackground: this.getBackgroundColor() } }); this.tree.setInput(this.debugService.getModel()); this._register(this.tree.onDidOpen(async e => { if (this.ignoreSelectionChangedEvent) { return; } const focusStackFrame = (stackFrame: IStackFrame | undefined, thread: IThread | undefined, session: IDebugSession) => { this.ignoreFocusStackFrameEvent = true; try { this.debugService.focusStackFrame(stackFrame, thread, session, true); } finally { this.ignoreFocusStackFrameEvent = false; } }; const element = e.element; if (element instanceof StackFrame) { focusStackFrame(element, element.thread, element.thread.session); element.openInEditor(this.editorService, e.editorOptions.preserveFocus, e.sideBySide, e.editorOptions.pinned); } if (element instanceof Thread) { focusStackFrame(undefined, element, element.session); } if (isDebugSession(element)) { focusStackFrame(undefined, undefined, element); } if (element instanceof ThreadAndSessionIds) { const session = this.debugService.getModel().getSession(element.sessionId); const thread = session && session.getThread(element.threadId); if (thread) { const totalFrames = thread.stoppedDetails?.totalFrames; const remainingFramesCount = typeof totalFrames === 'number' ? (totalFrames - thread.getCallStack().length) : undefined; // Get all the remaining frames await (<Thread>thread).fetchCallStack(remainingFramesCount); await this.tree.updateChildren(); } } if (element instanceof Array) { this.dataSource.deemphasizedStackFramesToShow.push(...element); this.tree.updateChildren(); } })); this._register(this.debugService.getModel().onDidChangeCallStack(() => { if (!this.isBodyVisible()) { this.needsRefresh = true; return; } if (!this.onCallStackChangeScheduler.isScheduled()) { this.onCallStackChangeScheduler.schedule(); } })); const onFocusChange = Event.any<any>(this.debugService.getViewModel().onDidFocusStackFrame, this.debugService.getViewModel().onDidFocusSession); this._register(onFocusChange(async () => { if (this.ignoreFocusStackFrameEvent) { return; } if (!this.isBodyVisible()) { this.needsRefresh = true; return; } if (this.onCallStackChangeScheduler.isScheduled()) { this.selectionNeedsUpdate = true; return; } await this.updateTreeSelection(); })); this._register(this.tree.onContextMenu(e => this.onContextMenu(e))); // Schedule the update of the call stack tree if the viewlet is opened after a session started #14684 if (this.debugService.state === State.Stopped) { this.onCallStackChangeScheduler.schedule(0); } this._register(this.onDidChangeBodyVisibility(visible => { if (visible && this.needsRefresh) { this.onCallStackChangeScheduler.schedule(); } })); this._register(this.debugService.onDidNewSession(s => { const sessionListeners: IDisposable[] = []; sessionListeners.push(s.onDidChangeName(() => this.tree.rerender(s))); sessionListeners.push(s.onDidEndAdapter(() => dispose(sessionListeners))); if (s.parentSession) { // A session we already expanded has a new child session, allow to expand it again. this.autoExpandedSessions.delete(s.parentSession); } })); } layoutBody(height: number, width: number): void { super.layoutBody(height, width); this.tree.layout(height, width); } focus(): void { this.tree.domFocus(); } private async updateTreeSelection(): Promise<void> { if (!this.tree || !this.tree.getInput()) { // Tree not initialized yet return; } const updateSelectionAndReveal = (element: IStackFrame | IDebugSession) => { this.ignoreSelectionChangedEvent = true; try { this.tree.setSelection([element]); // If the element is outside of the screen bounds, // position it in the middle if (this.tree.getRelativeTop(element) === null) { this.tree.reveal(element, 0.5); } else { this.tree.reveal(element); } } catch (e) { } finally { this.ignoreSelectionChangedEvent = false; } }; const thread = this.debugService.getViewModel().focusedThread; const session = this.debugService.getViewModel().focusedSession; const stackFrame = this.debugService.getViewModel().focusedStackFrame; if (!thread) { if (!session) { this.tree.setSelection([]); } else { updateSelectionAndReveal(session); } } else { // Ignore errors from this expansions because we are not aware if we rendered the threads and sessions or we hide them to declutter the view try { await expandTo(thread.session, this.tree); } catch (e) { } try { await this.tree.expand(thread); } catch (e) { } const toReveal = stackFrame || session; if (toReveal) { updateSelectionAndReveal(toReveal); } } } private onContextMenu(e: ITreeContextMenuEvent<CallStackItem>): void { const element = e.element; if (isDebugSession(element)) { this.callStackItemType.set('session'); } else if (element instanceof Thread) { this.callStackItemType.set('thread'); } else if (element instanceof StackFrame) { this.callStackItemType.set('stackFrame'); } else { this.callStackItemType.reset(); } const primary: IAction[] = []; const secondary: IAction[] = []; const result = { primary, secondary }; const actionsDisposable = createAndFillInContextMenuActions(this.menu, { arg: getContextForContributedActions(element), shouldForwardArgs: true }, result, this.contextMenuService, g => /^inline/.test(g)); this.contextMenuService.showContextMenu({ getAnchor: () => e.anchor, getActions: () => result.secondary, getActionsContext: () => getContext(element), onHide: () => dispose(actionsDisposable) }); } } interface IThreadTemplateData { thread: HTMLElement; name: HTMLElement; stateLabel: HTMLSpanElement; label: HighlightedLabel; actionBar: ActionBar; } interface ISessionTemplateData { session: HTMLElement; name: HTMLElement; stateLabel: HTMLSpanElement; label: HighlightedLabel; actionBar: ActionBar; elementDisposable: IDisposable[]; } interface IErrorTemplateData { label: HTMLElement; } interface ILabelTemplateData { label: HTMLElement; toDispose: IDisposable; } interface IStackFrameTemplateData { stackFrame: HTMLElement; file: HTMLElement; fileName: HTMLElement; lineNumber: HTMLElement; label: HighlightedLabel; actionBar: ActionBar; } class SessionsRenderer implements ICompressibleTreeRenderer<IDebugSession, FuzzyScore, ISessionTemplateData> { static readonly ID = 'session'; constructor( private menu: IMenu, @IInstantiationService private readonly instantiationService: IInstantiationService ) { } get templateId(): string { return SessionsRenderer.ID; } renderTemplate(container: HTMLElement): ISessionTemplateData { const session = dom.append(container, $('.session')); dom.append(session, $('.codicon.codicon-bug')); const name = dom.append(session, $('.name')); const stateLabel = dom.append(session, $('span.state.label.monaco-count-badge.long')); const label = new HighlightedLabel(name, false); const actionBar = new ActionBar(session, { actionViewItemProvider: action => { if (action instanceof MenuItemAction) { return this.instantiationService.createInstance(MenuEntryActionViewItem, action); } else if (action instanceof SubmenuItemAction) { return this.instantiationService.createInstance(SubmenuEntryActionViewItem, action); } return undefined; } }); return { session, name, stateLabel, label, actionBar, elementDisposable: [] }; } renderElement(element: ITreeNode<IDebugSession, FuzzyScore>, _: number, data: ISessionTemplateData): void { this.doRenderElement(element.element, createMatches(element.filterData), data); } renderCompressedElements(node: ITreeNode<ICompressedTreeNode<IDebugSession>, FuzzyScore>, index: number, templateData: ISessionTemplateData, height: number | undefined): void { const lastElement = node.element.elements[node.element.elements.length - 1]; const matches = createMatches(node.filterData); this.doRenderElement(lastElement, matches, templateData); } private doRenderElement(session: IDebugSession, matches: IMatch[], data: ISessionTemplateData): void { data.session.title = nls.localize({ key: 'session', comment: ['Session is a noun'] }, "Session"); data.label.set(session.getLabel(), matches); const thread = session.getAllThreads().find(t => t.stopped); const setActionBar = () => { const actions = getActions(this.instantiationService, session); const primary: IAction[] = actions; const secondary: IAction[] = []; const result = { primary, secondary }; data.elementDisposable.push(createAndFillInActionBarActions(this.menu, { arg: getContextForContributedActions(session), shouldForwardArgs: true }, result, g => /^inline/.test(g))); data.actionBar.clear(); data.actionBar.push(primary, { icon: true, label: false }); }; setActionBar(); data.elementDisposable.push(this.menu.onDidChange(() => setActionBar())); data.stateLabel.style.display = ''; if (thread && thread.stoppedDetails) { data.stateLabel.textContent = thread.stoppedDetails.description || nls.localize('debugStopped', "Paused on {0}", thread.stoppedDetails.reason || ''); if (thread.stoppedDetails.text) { data.session.title = thread.stoppedDetails.text; } } else { data.stateLabel.textContent = nls.localize({ key: 'running', comment: ['indicates state'] }, "Running"); } } disposeTemplate(templateData: ISessionTemplateData): void { templateData.actionBar.dispose(); } disposeElement(_element: ITreeNode<IDebugSession, FuzzyScore>, _: number, templateData: ISessionTemplateData): void { dispose(templateData.elementDisposable); } } class ThreadsRenderer implements ICompressibleTreeRenderer<IThread, FuzzyScore, IThreadTemplateData> { static readonly ID = 'thread'; constructor(private readonly instantiationService: IInstantiationService) { } get templateId(): string { return ThreadsRenderer.ID; } renderTemplate(container: HTMLElement): IThreadTemplateData { const thread = dom.append(container, $('.thread')); const name = dom.append(thread, $('.name')); const stateLabel = dom.append(thread, $('span.state.label')); const label = new HighlightedLabel(name, false); const actionBar = new ActionBar(thread); return { thread, name, stateLabel, label, actionBar }; } renderElement(element: ITreeNode<IThread, FuzzyScore>, index: number, data: IThreadTemplateData): void { const thread = element.element; data.thread.title = nls.localize('thread', "Thread"); data.label.set(thread.name, createMatches(element.filterData)); data.stateLabel.textContent = thread.stateLabel; data.actionBar.clear(); const actions = getActions(this.instantiationService, thread); data.actionBar.push(actions, { icon: true, label: false }); } renderCompressedElements(node: ITreeNode<ICompressedTreeNode<IThread>, FuzzyScore>, index: number, templateData: IThreadTemplateData, height: number | undefined): void { throw new Error('Method not implemented.'); } disposeTemplate(templateData: IThreadTemplateData): void { templateData.actionBar.dispose(); } } class StackFramesRenderer implements ICompressibleTreeRenderer<IStackFrame, FuzzyScore, IStackFrameTemplateData> { static readonly ID = 'stackFrame'; constructor( @ILabelService private readonly labelService: ILabelService, @INotificationService private readonly notificationService: INotificationService ) { } get templateId(): string { return StackFramesRenderer.ID; } renderTemplate(container: HTMLElement): IStackFrameTemplateData { const stackFrame = dom.append(container, $('.stack-frame')); const labelDiv = dom.append(stackFrame, $('span.label.expression')); const file = dom.append(stackFrame, $('.file')); const fileName = dom.append(file, $('span.file-name')); const wrapper = dom.append(file, $('span.line-number-wrapper')); const lineNumber = dom.append(wrapper, $('span.line-number.monaco-count-badge')); const label = new HighlightedLabel(labelDiv, false); const actionBar = new ActionBar(stackFrame); return { file, fileName, label, lineNumber, stackFrame, actionBar }; } renderElement(element: ITreeNode<IStackFrame, FuzzyScore>, index: number, data: IStackFrameTemplateData): void { const stackFrame = element.element; dom.toggleClass(data.stackFrame, 'disabled', !stackFrame.source || !stackFrame.source.available || isDeemphasized(stackFrame)); dom.toggleClass(data.stackFrame, 'label', stackFrame.presentationHint === 'label'); dom.toggleClass(data.stackFrame, 'subtle', stackFrame.presentationHint === 'subtle'); const hasActions = !!stackFrame.thread.session.capabilities.supportsRestartFrame && stackFrame.presentationHint !== 'label' && stackFrame.presentationHint !== 'subtle'; dom.toggleClass(data.stackFrame, 'has-actions', hasActions); data.file.title = stackFrame.source.inMemory ? stackFrame.source.uri.path : this.labelService.getUriLabel(stackFrame.source.uri); if (stackFrame.source.raw.origin) { data.file.title += `\n${stackFrame.source.raw.origin}`; } data.label.set(stackFrame.name, createMatches(element.filterData), stackFrame.name); data.fileName.textContent = getSpecificSourceName(stackFrame); if (stackFrame.range.startLineNumber !== undefined) { data.lineNumber.textContent = `${stackFrame.range.startLineNumber}`; if (stackFrame.range.startColumn) { data.lineNumber.textContent += `:${stackFrame.range.startColumn}`; } dom.removeClass(data.lineNumber, 'unavailable'); } else { dom.addClass(data.lineNumber, 'unavailable'); } data.actionBar.clear(); if (hasActions) { const action = new Action('debug.callStack.restartFrame', nls.localize('restartFrame', "Restart Frame"), 'codicon-debug-restart-frame', true, async () => { try { await stackFrame.restart(); } catch (e) { this.notificationService.error(e); } }); data.actionBar.push(action, { icon: true, label: false }); } } renderCompressedElements(node: ITreeNode<ICompressedTreeNode<IStackFrame>, FuzzyScore>, index: number, templateData: IStackFrameTemplateData, height: number | undefined): void { throw new Error('Method not implemented.'); } disposeTemplate(templateData: IStackFrameTemplateData): void { templateData.actionBar.dispose(); } } class ErrorsRenderer implements ICompressibleTreeRenderer<string, FuzzyScore, IErrorTemplateData> { static readonly ID = 'error'; get templateId(): string { return ErrorsRenderer.ID; } renderTemplate(container: HTMLElement): IErrorTemplateData { const label = dom.append(container, $('.error')); return { label }; } renderElement(element: ITreeNode<string, FuzzyScore>, index: number, data: IErrorTemplateData): void { const error = element.element; data.label.textContent = error; data.label.title = error; } renderCompressedElements(node: ITreeNode<ICompressedTreeNode<string>, FuzzyScore>, index: number, templateData: IErrorTemplateData, height: number | undefined): void { throw new Error('Method not implemented.'); } disposeTemplate(templateData: IErrorTemplateData): void { // noop } } class LoadAllRenderer implements ICompressibleTreeRenderer<ThreadAndSessionIds, FuzzyScore, ILabelTemplateData> { static readonly ID = 'loadAll'; static readonly LABEL = nls.localize('loadAllStackFrames', "Load All Stack Frames"); constructor(private readonly themeService: IThemeService) { } get templateId(): string { return LoadAllRenderer.ID; } renderTemplate(container: HTMLElement): ILabelTemplateData { const label = dom.append(container, $('.load-all')); const toDispose = attachStylerCallback(this.themeService, { textLinkForeground }, colors => { if (colors.textLinkForeground) { label.style.color = colors.textLinkForeground.toString(); } }); return { label, toDispose }; } renderElement(element: ITreeNode<ThreadAndSessionIds, FuzzyScore>, index: number, data: ILabelTemplateData): void { data.label.textContent = LoadAllRenderer.LABEL; } renderCompressedElements(node: ITreeNode<ICompressedTreeNode<ThreadAndSessionIds>, FuzzyScore>, index: number, templateData: ILabelTemplateData, height: number | undefined): void { throw new Error('Method not implemented.'); } disposeTemplate(templateData: ILabelTemplateData): void { templateData.toDispose.dispose(); } } class ShowMoreRenderer implements ICompressibleTreeRenderer<IStackFrame[], FuzzyScore, ILabelTemplateData> { static readonly ID = 'showMore'; constructor(private readonly themeService: IThemeService) { } get templateId(): string { return ShowMoreRenderer.ID; } renderTemplate(container: HTMLElement): ILabelTemplateData { const label = dom.append(container, $('.show-more')); const toDispose = attachStylerCallback(this.themeService, { textLinkForeground }, colors => { if (colors.textLinkForeground) { label.style.color = colors.textLinkForeground.toString(); } }); return { label, toDispose }; } renderElement(element: ITreeNode<IStackFrame[], FuzzyScore>, index: number, data: ILabelTemplateData): void { const stackFrames = element.element; if (stackFrames.every(sf => !!(sf.source && sf.source.origin && sf.source.origin === stackFrames[0].source.origin))) { data.label.textContent = nls.localize('showMoreAndOrigin', "Show {0} More: {1}", stackFrames.length, stackFrames[0].source.origin); } else { data.label.textContent = nls.localize('showMoreStackFrames', "Show {0} More Stack Frames", stackFrames.length); } } renderCompressedElements(node: ITreeNode<ICompressedTreeNode<IStackFrame[]>, FuzzyScore>, index: number, templateData: ILabelTemplateData, height: number | undefined): void { throw new Error('Method not implemented.'); } disposeTemplate(templateData: ILabelTemplateData): void { templateData.toDispose.dispose(); } } class CallStackDelegate implements IListVirtualDelegate<CallStackItem> { getHeight(element: CallStackItem): number { if (element instanceof StackFrame && element.presentationHint === 'label') { return 16; } if (element instanceof ThreadAndSessionIds || element instanceof Array) { return 16; } return 22; } getTemplateId(element: CallStackItem): string { if (isDebugSession(element)) { return SessionsRenderer.ID; } if (element instanceof Thread) { return ThreadsRenderer.ID; } if (element instanceof StackFrame) { return StackFramesRenderer.ID; } if (typeof element === 'string') { return ErrorsRenderer.ID; } if (element instanceof ThreadAndSessionIds) { return LoadAllRenderer.ID; } // element instanceof Array return ShowMoreRenderer.ID; } } function isDebugModel(obj: any): obj is IDebugModel { return typeof obj.getSessions === 'function'; } function isDebugSession(obj: any): obj is IDebugSession { return obj && typeof obj.getAllThreads === 'function'; } function isDeemphasized(frame: IStackFrame): boolean { return frame.source.presentationHint === 'deemphasize' || frame.presentationHint === 'deemphasize'; } class CallStackDataSource implements IAsyncDataSource<IDebugModel, CallStackItem> { deemphasizedStackFramesToShow: IStackFrame[] = []; constructor(private debugService: IDebugService) { } hasChildren(element: IDebugModel | CallStackItem): boolean { if (isDebugSession(element)) { const threads = element.getAllThreads(); return (threads.length > 1) || (threads.length === 1 && threads[0].stopped) || !!(this.debugService.getModel().getSessions().find(s => s.parentSession === element)); } return isDebugModel(element) || (element instanceof Thread && element.stopped); } async getChildren(element: IDebugModel | CallStackItem): Promise<CallStackItem[]> { if (isDebugModel(element)) { const sessions = element.getSessions(); if (sessions.length === 0) { return Promise.resolve([]); } if (sessions.length > 1 || this.debugService.getViewModel().isMultiSessionView()) { return Promise.resolve(sessions.filter(s => !s.parentSession)); } const threads = sessions[0].getAllThreads(); // Only show the threads in the call stack if there is more than 1 thread. return threads.length === 1 ? this.getThreadChildren(<Thread>threads[0]) : Promise.resolve(threads); } else if (isDebugSession(element)) { const childSessions = this.debugService.getModel().getSessions().filter(s => s.parentSession === element); const threads: CallStackItem[] = element.getAllThreads(); if (threads.length === 1) { // Do not show thread when there is only one to be compact. const children = await this.getThreadChildren(<Thread>threads[0]); return children.concat(childSessions); } return Promise.resolve(threads.concat(childSessions)); } else { return this.getThreadChildren(<Thread>element); } } private getThreadChildren(thread: Thread): Promise<CallStackItem[]> { return this.getThreadCallstack(thread).then(children => { // Check if some stack frames should be hidden under a parent element since they are deemphasized const result: CallStackItem[] = []; children.forEach((child, index) => { if (child instanceof StackFrame && child.source && isDeemphasized(child)) { // Check if the user clicked to show the deemphasized source if (this.deemphasizedStackFramesToShow.indexOf(child) === -1) { if (result.length) { const last = result[result.length - 1]; if (last instanceof Array) { // Collect all the stackframes that will be "collapsed" last.push(child); return; } } const nextChild = index < children.length - 1 ? children[index + 1] : undefined; if (nextChild instanceof StackFrame && nextChild.source && isDeemphasized(nextChild)) { // Start collecting stackframes that will be "collapsed" result.push([child]); return; } } } result.push(child); }); return result; }); } private async getThreadCallstack(thread: Thread): Promise<Array<IStackFrame | string | ThreadAndSessionIds>> { let callStack: any[] = thread.getCallStack(); if (!callStack || !callStack.length) { await thread.fetchCallStack(); callStack = thread.getCallStack(); } if (callStack.length === 1 && thread.session.capabilities.supportsDelayedStackTraceLoading && thread.stoppedDetails && thread.stoppedDetails.totalFrames && thread.stoppedDetails.totalFrames > 1) { // To reduce flashing of the call stack view simply append the stale call stack // once we have the correct data the tree will refresh and we will no longer display it. callStack = callStack.concat(thread.getStaleCallStack().slice(1)); } if (thread.stoppedDetails && thread.stoppedDetails.framesErrorMessage) { callStack = callStack.concat([thread.stoppedDetails.framesErrorMessage]); } if (thread.stoppedDetails && thread.stoppedDetails.totalFrames && thread.stoppedDetails.totalFrames > callStack.length && callStack.length > 1) { callStack = callStack.concat([new ThreadAndSessionIds(thread.session.getId(), thread.threadId)]); } return callStack; } } class CallStackAccessibilityProvider implements IListAccessibilityProvider<CallStackItem> { getWidgetAriaLabel(): string { return nls.localize({ comment: ['Debug is a noun in this context, not a verb.'], key: 'callStackAriaLabel' }, "Debug Call Stack"); } getAriaLabel(element: CallStackItem): string { if (element instanceof Thread) { return nls.localize('threadAriaLabel', "Thread {0}, callstack, debug", (<Thread>element).name); } if (element instanceof StackFrame) { return nls.localize('stackFrameAriaLabel', "Stack Frame {0}, line {1}, {2}, callstack, debug", element.name, element.range.startLineNumber, getSpecificSourceName(element)); } if (isDebugSession(element)) { return nls.localize('sessionLabel', "Debug Session {0}", element.getLabel()); } if (typeof element === 'string') { return element; } if (element instanceof Array) { return nls.localize('showMoreStackFrames', "Show {0} More Stack Frames", element.length); } // element instanceof ThreadAndSessionIds return LoadAllRenderer.LABEL; } } function getActions(instantiationService: IInstantiationService, element: IDebugSession | IThread): IAction[] { const getThreadActions = (thread: IThread): IAction[] => { return [ thread.stopped ? instantiationService.createInstance(ContinueAction, thread) : instantiationService.createInstance(PauseAction, thread), instantiationService.createInstance(StepOverAction, thread), instantiationService.createInstance(StepIntoAction, thread), instantiationService.createInstance(StepOutAction, thread) ]; }; if (element instanceof Thread) { return getThreadActions(element); } const session = <IDebugSession>element; const stopOrDisconectAction = isSessionAttach(session) ? instantiationService.createInstance(DisconnectAction, session) : instantiationService.createInstance(StopAction, session); const restartAction = instantiationService.createInstance(RestartAction, session); const threads = session.getAllThreads(); if (threads.length === 1) { return getThreadActions(threads[0]).concat([ restartAction, stopOrDisconectAction ]); } return [ restartAction, stopOrDisconectAction ]; } class StopAction extends Action { constructor( private readonly session: IDebugSession, @ICommandService private readonly commandService: ICommandService ) { super(`action.${STOP_ID}`, STOP_LABEL, 'debug-action codicon-debug-stop'); } public run(): Promise<any> { return this.commandService.executeCommand(STOP_ID, undefined, getContext(this.session)); } } class DisconnectAction extends Action { constructor( private readonly session: IDebugSession, @ICommandService private readonly commandService: ICommandService ) { super(`action.${DISCONNECT_ID}`, DISCONNECT_LABEL, 'debug-action codicon-debug-disconnect'); } public run(): Promise<any> { return this.commandService.executeCommand(DISCONNECT_ID, undefined, getContext(this.session)); } } class RestartAction extends Action { constructor( private readonly session: IDebugSession, @ICommandService private readonly commandService: ICommandService ) { super(`action.${RESTART_SESSION_ID}`, RESTART_LABEL, 'debug-action codicon-debug-restart'); } public run(): Promise<any> { return this.commandService.executeCommand(RESTART_SESSION_ID, undefined, getContext(this.session)); } } class StepOverAction extends Action { constructor( private readonly thread: IThread, @ICommandService private readonly commandService: ICommandService ) { super(`action.${STEP_OVER_ID}`, STEP_OVER_LABEL, 'debug-action codicon-debug-step-over', thread.stopped); } public run(): Promise<any> { return this.commandService.executeCommand(STEP_OVER_ID, undefined, getContext(this.thread)); } } class StepIntoAction extends Action { constructor( private readonly thread: IThread, @ICommandService private readonly commandService: ICommandService ) { super(`action.${STEP_INTO_ID}`, STEP_INTO_LABEL, 'debug-action codicon-debug-step-into', thread.stopped); } public run(): Promise<any> { return this.commandService.executeCommand(STEP_INTO_ID, undefined, getContext(this.thread)); } } class StepOutAction extends Action { constructor( private readonly thread: IThread, @ICommandService private readonly commandService: ICommandService ) { super(`action.${STEP_OUT_ID}`, STEP_OUT_LABEL, 'debug-action codicon-debug-step-out', thread.stopped); } public run(): Promise<any> { return this.commandService.executeCommand(STEP_OUT_ID, undefined, getContext(this.thread)); } } class PauseAction extends Action { constructor( private readonly thread: IThread, @ICommandService private readonly commandService: ICommandService ) { super(`action.${PAUSE_ID}`, PAUSE_LABEL, 'debug-action codicon-debug-pause', !thread.stopped); } public run(): Promise<any> { return this.commandService.executeCommand(PAUSE_ID, undefined, getContext(this.thread)); } } class ContinueAction extends Action { constructor( private readonly thread: IThread, @ICommandService private readonly commandService: ICommandService ) { super(`action.${CONTINUE_ID}`, CONTINUE_LABEL, 'debug-action codicon-debug-continue', thread.stopped); } public run(): Promise<any> { return this.commandService.executeCommand(CONTINUE_ID, undefined, getContext(this.thread)); } } class CallStackCompressionDelegate implements ITreeCompressionDelegate<CallStackItem> { constructor(private readonly debugService: IDebugService) { } isIncompressible(stat: CallStackItem): boolean { if (isDebugSession(stat)) { if (stat.compact) { return false; } const sessions = this.debugService.getModel().getSessions(); if (sessions.some(s => s.parentSession === stat && s.compact)) { return false; } return true; } return true; } }
src/vs/workbench/contrib/debug/browser/callStackView.ts
1
https://github.com/microsoft/vscode/commit/135b6da83746477b2983fee879122ceefa70014d
[ 0.24097368121147156, 0.0037887003272771835, 0.000163244127179496, 0.00017131929052993655, 0.022979555651545525 ]
{ "id": 1, "code_window": [ "\n", "\tconstructor(\n", "\t\tprivate readonly session: IDebugSession,\n", "\t\t@ICommandService private readonly commandService: ICommandService\n", "\t) {\n", "\t\tsuper(`action.${STOP_ID}`, STOP_LABEL, 'debug-action codicon-debug-stop');\n", "\t}\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tprivate readonly session: IDebugSession | null,\n" ], "file_path": "src/vs/workbench/contrib/debug/browser/callStackView.ts", "type": "replace", "edit_start_line_idx": 987 }
/*--------------------------------------------------------------------------------------------- * 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 { extractRangeFromFilter } from 'vs/workbench/contrib/search/common/search'; suite('extractRangeFromFilter', () => { test('basics', async function () { assert.ok(!extractRangeFromFilter('')); assert.ok(!extractRangeFromFilter('/some/path')); assert.ok(!extractRangeFromFilter('/some/path/file.txt')); for (const lineSep of [':', '#', '(', ':line ']) { for (const colSep of [':', '#', ',']) { const base = '/some/path/file.txt'; let res = extractRangeFromFilter(`${base}${lineSep}20`); assert.equal(res?.filter, base); assert.equal(res?.range.startLineNumber, 20); assert.equal(res?.range.startColumn, 1); res = extractRangeFromFilter(`${base}${lineSep}20${colSep}`); assert.equal(res?.filter, base); assert.equal(res?.range.startLineNumber, 20); assert.equal(res?.range.startColumn, 1); res = extractRangeFromFilter(`${base}${lineSep}20${colSep}3`); assert.equal(res?.filter, base); assert.equal(res?.range.startLineNumber, 20); assert.equal(res?.range.startColumn, 3); } } }); test('allow space after path', async function () { const res = extractRangeFromFilter('/some/path/file.txt (19,20)'); assert.equal(res?.filter, '/some/path/file.txt'); assert.equal(res?.range.startLineNumber, 19); assert.equal(res?.range.startColumn, 20); }); test('unless', async function () { const res = extractRangeFromFilter('/some/path/file.txt@ (19,20)', ['@']); assert.ok(!res); }); });
src/vs/workbench/contrib/search/test/common/extractRange.test.ts
0
https://github.com/microsoft/vscode/commit/135b6da83746477b2983fee879122ceefa70014d
[ 0.00017452138126827776, 0.00017281003238167614, 0.00016995469923131168, 0.00017290936375502497, 0.0000014611981669077068 ]
{ "id": 1, "code_window": [ "\n", "\tconstructor(\n", "\t\tprivate readonly session: IDebugSession,\n", "\t\t@ICommandService private readonly commandService: ICommandService\n", "\t) {\n", "\t\tsuper(`action.${STOP_ID}`, STOP_LABEL, 'debug-action codicon-debug-stop');\n", "\t}\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tprivate readonly session: IDebugSession | null,\n" ], "file_path": "src/vs/workbench/contrib/debug/browser/callStackView.ts", "type": "replace", "edit_start_line_idx": 987 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { toDisposable } from 'vs/base/common/lifecycle'; import { globals } from 'vs/base/common/platform'; import BaseErrorTelemetry, { ErrorEvent } from '../common/errorTelemetry'; export default class ErrorTelemetry extends BaseErrorTelemetry { protected installErrorListeners(): void { let oldOnError: Function; let that = this; if (typeof globals.onerror === 'function') { oldOnError = globals.onerror; } globals.onerror = function (message: string, filename: string, line: number, column?: number, e?: any) { that._onUncaughtError(message, filename, line, column, e); if (oldOnError) { oldOnError.apply(this, arguments); } }; this._disposables.add(toDisposable(() => { if (oldOnError) { globals.onerror = oldOnError; } })); } private _onUncaughtError(msg: string, file: string, line: number, column?: number, err?: any): void { let data: ErrorEvent = { callstack: msg, msg, file, line, column }; if (err) { let { name, message, stack } = err; data.uncaught_error_name = name; if (message) { data.uncaught_error_msg = message; } if (stack) { data.callstack = Array.isArray(err.stack) ? err.stack = err.stack.join('\n') : err.stack; } } this._enqueue(data); } }
src/vs/platform/telemetry/browser/errorTelemetry.ts
0
https://github.com/microsoft/vscode/commit/135b6da83746477b2983fee879122ceefa70014d
[ 0.00017435055633541197, 0.0001693273225100711, 0.00016565751866437495, 0.00016880423936527222, 0.0000026974198590323795 ]
{ "id": 1, "code_window": [ "\n", "\tconstructor(\n", "\t\tprivate readonly session: IDebugSession,\n", "\t\t@ICommandService private readonly commandService: ICommandService\n", "\t) {\n", "\t\tsuper(`action.${STOP_ID}`, STOP_LABEL, 'debug-action codicon-debug-stop');\n", "\t}\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tprivate readonly session: IDebugSession | null,\n" ], "file_path": "src/vs/workbench/contrib/debug/browser/callStackView.ts", "type": "replace", "edit_start_line_idx": 987 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as nls from 'vs/nls'; import { ICodeEditor } from 'vs/editor/browser/editorBrowser'; import { EditorAction, ServicesAccessor, registerEditorAction } from 'vs/editor/browser/editorExtensions'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; import { Registry } from 'vs/platform/registry/common/platform'; import { Extensions as ActionExtensions, IWorkbenchActionRegistry } from 'vs/workbench/common/actions'; import { SyncActionDescriptor } from 'vs/platform/actions/common/actions'; import { Action } from 'vs/base/common/actions'; class InspectKeyMap extends EditorAction { constructor() { super({ id: 'workbench.action.inspectKeyMappings', label: nls.localize('workbench.action.inspectKeyMap', "Developer: Inspect Key Mappings"), alias: 'Developer: Inspect Key Mappings', precondition: undefined }); } public run(accessor: ServicesAccessor, editor: ICodeEditor): void { const keybindingService = accessor.get(IKeybindingService); const editorService = accessor.get(IEditorService); editorService.openEditor({ contents: keybindingService._dumpDebugInfo(), options: { pinned: true } }); } } registerEditorAction(InspectKeyMap); class InspectKeyMapJSON extends Action { public static readonly ID = 'workbench.action.inspectKeyMappingsJSON'; public static readonly LABEL = nls.localize('workbench.action.inspectKeyMapJSON', "Inspect Key Mappings (JSON)"); constructor( id: string, label: string, @IKeybindingService private readonly _keybindingService: IKeybindingService, @IEditorService private readonly _editorService: IEditorService ) { super(id, label); } public run(): Promise<any> { return this._editorService.openEditor({ contents: this._keybindingService._dumpDebugInfoJSON(), options: { pinned: true } }); } } const registry = Registry.as<IWorkbenchActionRegistry>(ActionExtensions.WorkbenchActions); registry.registerWorkbenchAction(SyncActionDescriptor.from(InspectKeyMapJSON), 'Developer: Inspect Key Mappings (JSON)', nls.localize({ key: 'developer', comment: ['A developer on Code itself or someone diagnosing issues in Code'] }, "Developer"));
src/vs/workbench/contrib/codeEditor/browser/inspectKeybindings.ts
0
https://github.com/microsoft/vscode/commit/135b6da83746477b2983fee879122ceefa70014d
[ 0.00035406264942139387, 0.00021689482673536986, 0.0001655823434703052, 0.0001965845440281555, 0.0000651006048428826 ]
{ "id": 2, "code_window": [ "\t\tthis.updateScheduler = this._register(new RunOnceScheduler(() => {\n", "\t\t\tconst state = this.debugService.state;\n", "\t\t\tconst toolBarLocation = this.configurationService.getValue<IDebugConfiguration>('debug').toolBarLocation;\n", "\t\t\tif (state === State.Inactive || toolBarLocation === 'docked' || toolBarLocation === 'hidden') {\n", "\t\t\t\treturn this.hide();\n", "\t\t\t}\n", "\n", "\t\t\tconst { actions, disposable } = DebugToolBar.getActions(this.debugToolBarMenu, this.debugService, this.instantiationService);\n", "\t\t\tif (!arrays.equals(actions, this.activeActions, (first, second) => first.id === second.id)) {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tif (state === State.Inactive || state === State.Initializing || toolBarLocation === 'docked' || toolBarLocation === 'hidden') {\n" ], "file_path": "src/vs/workbench/contrib/debug/browser/debugToolBar.ts", "type": "replace", "edit_start_line_idx": 93 }
/*--------------------------------------------------------------------------------------------- * 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 { RunOnceScheduler } from 'vs/base/common/async'; import * as dom from 'vs/base/browser/dom'; import { IViewletViewOptions } from 'vs/workbench/browser/parts/views/viewsViewlet'; import { IDebugService, State, IStackFrame, IDebugSession, IThread, CONTEXT_CALLSTACK_ITEM_TYPE, IDebugModel } from 'vs/workbench/contrib/debug/common/debug'; import { Thread, StackFrame, ThreadAndSessionIds } from 'vs/workbench/contrib/debug/common/debugModel'; import { IContextMenuService } from 'vs/platform/contextview/browser/contextView'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { MenuId, IMenu, IMenuService, MenuItemAction, SubmenuItemAction } from 'vs/platform/actions/common/actions'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; import { renderViewTree } from 'vs/workbench/contrib/debug/browser/baseDebugView'; import { IAction, Action } from 'vs/base/common/actions'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IContextKey, IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { ViewPane } from 'vs/workbench/browser/parts/views/viewPaneContainer'; import { ILabelService } from 'vs/platform/label/common/label'; import { IListAccessibilityProvider } from 'vs/base/browser/ui/list/listWidget'; import { createAndFillInContextMenuActions, createAndFillInActionBarActions, MenuEntryActionViewItem, SubmenuEntryActionViewItem } from 'vs/platform/actions/browser/menuEntryActionViewItem'; import { IListVirtualDelegate } from 'vs/base/browser/ui/list/list'; import { ITreeNode, ITreeContextMenuEvent, IAsyncDataSource } from 'vs/base/browser/ui/tree/tree'; import { WorkbenchCompressibleAsyncDataTree } from 'vs/platform/list/browser/listService'; import { HighlightedLabel } from 'vs/base/browser/ui/highlightedlabel/highlightedLabel'; import { createMatches, FuzzyScore, IMatch } from 'vs/base/common/filters'; import { Event } from 'vs/base/common/event'; import { dispose, IDisposable } from 'vs/base/common/lifecycle'; import { ActionBar } from 'vs/base/browser/ui/actionbar/actionbar'; import { isSessionAttach } from 'vs/workbench/contrib/debug/common/debugUtils'; import { STOP_ID, STOP_LABEL, DISCONNECT_ID, DISCONNECT_LABEL, RESTART_SESSION_ID, RESTART_LABEL, STEP_OVER_ID, STEP_OVER_LABEL, STEP_INTO_LABEL, STEP_INTO_ID, STEP_OUT_LABEL, STEP_OUT_ID, PAUSE_ID, PAUSE_LABEL, CONTINUE_ID, CONTINUE_LABEL } from 'vs/workbench/contrib/debug/browser/debugCommands'; import { ICommandService } from 'vs/platform/commands/common/commands'; import { CollapseAction } from 'vs/workbench/browser/viewlet'; import { IViewDescriptorService } from 'vs/workbench/common/views'; import { textLinkForeground } from 'vs/platform/theme/common/colorRegistry'; import { IThemeService } from 'vs/platform/theme/common/themeService'; import { IOpenerService } from 'vs/platform/opener/common/opener'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { attachStylerCallback } from 'vs/platform/theme/common/styler'; import { INotificationService } from 'vs/platform/notification/common/notification'; import { commonSuffixLength } from 'vs/base/common/strings'; import { posix } from 'vs/base/common/path'; import { ITreeCompressionDelegate } from 'vs/base/browser/ui/tree/asyncDataTree'; import { ICompressibleTreeRenderer } from 'vs/base/browser/ui/tree/objectTree'; import { ICompressedTreeNode } from 'vs/base/browser/ui/tree/compressedObjectTreeModel'; const $ = dom.$; type CallStackItem = IStackFrame | IThread | IDebugSession | string | ThreadAndSessionIds | IStackFrame[]; export function getContext(element: CallStackItem | null): any { return element instanceof StackFrame ? { sessionId: element.thread.session.getId(), threadId: element.thread.getId(), frameId: element.getId() } : element instanceof Thread ? { sessionId: element.session.getId(), threadId: element.getId() } : isDebugSession(element) ? { sessionId: element.getId() } : undefined; } // Extensions depend on this context, should not be changed even though it is not fully deterministic export function getContextForContributedActions(element: CallStackItem | null): string | number { if (element instanceof StackFrame) { if (element.source.inMemory) { return element.source.raw.path || element.source.reference || element.source.name; } return element.source.uri.toString(); } if (element instanceof Thread) { return element.threadId; } if (isDebugSession(element)) { return element.getId(); } return ''; } export function getSpecificSourceName(stackFrame: IStackFrame): string { // To reduce flashing of the path name and the way we fetch stack frames // We need to compute the source name based on the other frames in the stale call stack let callStack = (<Thread>stackFrame.thread).getStaleCallStack(); callStack = callStack.length > 0 ? callStack : stackFrame.thread.getCallStack(); const otherSources = callStack.map(sf => sf.source).filter(s => s !== stackFrame.source); let suffixLength = 0; otherSources.forEach(s => { if (s.name === stackFrame.source.name) { suffixLength = Math.max(suffixLength, commonSuffixLength(stackFrame.source.uri.path, s.uri.path)); } }); if (suffixLength === 0) { return stackFrame.source.name; } const from = Math.max(0, stackFrame.source.uri.path.lastIndexOf(posix.sep, stackFrame.source.uri.path.length - suffixLength - 1)); return (from > 0 ? '...' : '') + stackFrame.source.uri.path.substr(from); } async function expandTo(session: IDebugSession, tree: WorkbenchCompressibleAsyncDataTree<IDebugModel, CallStackItem, FuzzyScore>): Promise<void> { if (session.parentSession) { await expandTo(session.parentSession, tree); } await tree.expand(session); } export class CallStackView extends ViewPane { private pauseMessage!: HTMLSpanElement; private pauseMessageLabel!: HTMLSpanElement; private onCallStackChangeScheduler: RunOnceScheduler; private needsRefresh = false; private ignoreSelectionChangedEvent = false; private ignoreFocusStackFrameEvent = false; private callStackItemType: IContextKey<string>; private dataSource!: CallStackDataSource; private tree!: WorkbenchCompressibleAsyncDataTree<IDebugModel, CallStackItem, FuzzyScore>; private menu: IMenu; private autoExpandedSessions = new Set<IDebugSession>(); private selectionNeedsUpdate = false; constructor( private options: IViewletViewOptions, @IContextMenuService contextMenuService: IContextMenuService, @IDebugService private readonly debugService: IDebugService, @IKeybindingService keybindingService: IKeybindingService, @IInstantiationService instantiationService: IInstantiationService, @IViewDescriptorService viewDescriptorService: IViewDescriptorService, @IEditorService private readonly editorService: IEditorService, @IConfigurationService configurationService: IConfigurationService, @IMenuService menuService: IMenuService, @IContextKeyService readonly contextKeyService: IContextKeyService, @IOpenerService openerService: IOpenerService, @IThemeService themeService: IThemeService, @ITelemetryService telemetryService: ITelemetryService, ) { super(options, keybindingService, contextMenuService, configurationService, contextKeyService, viewDescriptorService, instantiationService, openerService, themeService, telemetryService); this.callStackItemType = CONTEXT_CALLSTACK_ITEM_TYPE.bindTo(contextKeyService); this.menu = menuService.createMenu(MenuId.DebugCallStackContext, contextKeyService); this._register(this.menu); // Create scheduler to prevent unnecessary flashing of tree when reacting to changes this.onCallStackChangeScheduler = new RunOnceScheduler(async () => { // Only show the global pause message if we do not display threads. // Otherwise there will be a pause message per thread and there is no need for a global one. const sessions = this.debugService.getModel().getSessions(); if (sessions.length === 0) { this.autoExpandedSessions.clear(); } const thread = sessions.length === 1 && sessions[0].getAllThreads().length === 1 ? sessions[0].getAllThreads()[0] : undefined; if (thread && thread.stoppedDetails) { this.pauseMessageLabel.textContent = thread.stoppedDetails.description || nls.localize('debugStopped', "Paused on {0}", thread.stoppedDetails.reason || ''); this.pauseMessageLabel.title = thread.stoppedDetails.text || ''; dom.toggleClass(this.pauseMessageLabel, 'exception', thread.stoppedDetails.reason === 'exception'); this.pauseMessage.hidden = false; this.updateActions(); } else { this.pauseMessage.hidden = true; this.updateActions(); } this.needsRefresh = false; this.dataSource.deemphasizedStackFramesToShow = []; await this.tree.updateChildren(); try { const toExpand = new Set<IDebugSession>(); sessions.forEach(s => { // Automatically expand sessions that have children, but only do this once. if (s.parentSession && !this.autoExpandedSessions.has(s.parentSession)) { toExpand.add(s.parentSession); } }); for (let session of toExpand) { await expandTo(session, this.tree); this.autoExpandedSessions.add(session); } } catch (e) { // Ignore tree expand errors if element no longer present } if (this.selectionNeedsUpdate) { this.selectionNeedsUpdate = false; await this.updateTreeSelection(); } }, 50); } protected renderHeaderTitle(container: HTMLElement): void { const titleContainer = dom.append(container, $('.debug-call-stack-title')); super.renderHeaderTitle(titleContainer, this.options.title); this.pauseMessage = dom.append(titleContainer, $('span.pause-message')); this.pauseMessage.hidden = true; this.pauseMessageLabel = dom.append(this.pauseMessage, $('span.label')); } getActions(): IAction[] { if (this.pauseMessage.hidden) { return [new CollapseAction(() => this.tree, true, 'explorer-action codicon-collapse-all')]; } return []; } renderBody(container: HTMLElement): void { super.renderBody(container); dom.addClass(this.element, 'debug-pane'); dom.addClass(container, 'debug-call-stack'); const treeContainer = renderViewTree(container); this.dataSource = new CallStackDataSource(this.debugService); const sessionsRenderer = this.instantiationService.createInstance(SessionsRenderer, this.menu); this.tree = <WorkbenchCompressibleAsyncDataTree<IDebugModel, CallStackItem, FuzzyScore>>this.instantiationService.createInstance(WorkbenchCompressibleAsyncDataTree, 'CallStackView', treeContainer, new CallStackDelegate(), new CallStackCompressionDelegate(this.debugService), [ sessionsRenderer, new ThreadsRenderer(this.instantiationService), this.instantiationService.createInstance(StackFramesRenderer), new ErrorsRenderer(), new LoadAllRenderer(this.themeService), new ShowMoreRenderer(this.themeService) ], this.dataSource, { accessibilityProvider: new CallStackAccessibilityProvider(), compressionEnabled: true, autoExpandSingleChildren: true, identityProvider: { getId: (element: CallStackItem) => { if (typeof element === 'string') { return element; } if (element instanceof Array) { return `showMore ${element[0].getId()}`; } return element.getId(); } }, keyboardNavigationLabelProvider: { getKeyboardNavigationLabel: (e: CallStackItem) => { if (isDebugSession(e)) { return e.getLabel(); } if (e instanceof Thread) { return `${e.name} ${e.stateLabel}`; } if (e instanceof StackFrame || typeof e === 'string') { return e; } if (e instanceof ThreadAndSessionIds) { return LoadAllRenderer.LABEL; } return nls.localize('showMoreStackFrames2', "Show More Stack Frames"); }, getCompressedNodeKeyboardNavigationLabel: (e: CallStackItem[]) => { const firstItem = e[0]; if (isDebugSession(firstItem)) { return firstItem.getLabel(); } return ''; } }, expandOnlyOnTwistieClick: true, overrideStyles: { listBackground: this.getBackgroundColor() } }); this.tree.setInput(this.debugService.getModel()); this._register(this.tree.onDidOpen(async e => { if (this.ignoreSelectionChangedEvent) { return; } const focusStackFrame = (stackFrame: IStackFrame | undefined, thread: IThread | undefined, session: IDebugSession) => { this.ignoreFocusStackFrameEvent = true; try { this.debugService.focusStackFrame(stackFrame, thread, session, true); } finally { this.ignoreFocusStackFrameEvent = false; } }; const element = e.element; if (element instanceof StackFrame) { focusStackFrame(element, element.thread, element.thread.session); element.openInEditor(this.editorService, e.editorOptions.preserveFocus, e.sideBySide, e.editorOptions.pinned); } if (element instanceof Thread) { focusStackFrame(undefined, element, element.session); } if (isDebugSession(element)) { focusStackFrame(undefined, undefined, element); } if (element instanceof ThreadAndSessionIds) { const session = this.debugService.getModel().getSession(element.sessionId); const thread = session && session.getThread(element.threadId); if (thread) { const totalFrames = thread.stoppedDetails?.totalFrames; const remainingFramesCount = typeof totalFrames === 'number' ? (totalFrames - thread.getCallStack().length) : undefined; // Get all the remaining frames await (<Thread>thread).fetchCallStack(remainingFramesCount); await this.tree.updateChildren(); } } if (element instanceof Array) { this.dataSource.deemphasizedStackFramesToShow.push(...element); this.tree.updateChildren(); } })); this._register(this.debugService.getModel().onDidChangeCallStack(() => { if (!this.isBodyVisible()) { this.needsRefresh = true; return; } if (!this.onCallStackChangeScheduler.isScheduled()) { this.onCallStackChangeScheduler.schedule(); } })); const onFocusChange = Event.any<any>(this.debugService.getViewModel().onDidFocusStackFrame, this.debugService.getViewModel().onDidFocusSession); this._register(onFocusChange(async () => { if (this.ignoreFocusStackFrameEvent) { return; } if (!this.isBodyVisible()) { this.needsRefresh = true; return; } if (this.onCallStackChangeScheduler.isScheduled()) { this.selectionNeedsUpdate = true; return; } await this.updateTreeSelection(); })); this._register(this.tree.onContextMenu(e => this.onContextMenu(e))); // Schedule the update of the call stack tree if the viewlet is opened after a session started #14684 if (this.debugService.state === State.Stopped) { this.onCallStackChangeScheduler.schedule(0); } this._register(this.onDidChangeBodyVisibility(visible => { if (visible && this.needsRefresh) { this.onCallStackChangeScheduler.schedule(); } })); this._register(this.debugService.onDidNewSession(s => { const sessionListeners: IDisposable[] = []; sessionListeners.push(s.onDidChangeName(() => this.tree.rerender(s))); sessionListeners.push(s.onDidEndAdapter(() => dispose(sessionListeners))); if (s.parentSession) { // A session we already expanded has a new child session, allow to expand it again. this.autoExpandedSessions.delete(s.parentSession); } })); } layoutBody(height: number, width: number): void { super.layoutBody(height, width); this.tree.layout(height, width); } focus(): void { this.tree.domFocus(); } private async updateTreeSelection(): Promise<void> { if (!this.tree || !this.tree.getInput()) { // Tree not initialized yet return; } const updateSelectionAndReveal = (element: IStackFrame | IDebugSession) => { this.ignoreSelectionChangedEvent = true; try { this.tree.setSelection([element]); // If the element is outside of the screen bounds, // position it in the middle if (this.tree.getRelativeTop(element) === null) { this.tree.reveal(element, 0.5); } else { this.tree.reveal(element); } } catch (e) { } finally { this.ignoreSelectionChangedEvent = false; } }; const thread = this.debugService.getViewModel().focusedThread; const session = this.debugService.getViewModel().focusedSession; const stackFrame = this.debugService.getViewModel().focusedStackFrame; if (!thread) { if (!session) { this.tree.setSelection([]); } else { updateSelectionAndReveal(session); } } else { // Ignore errors from this expansions because we are not aware if we rendered the threads and sessions or we hide them to declutter the view try { await expandTo(thread.session, this.tree); } catch (e) { } try { await this.tree.expand(thread); } catch (e) { } const toReveal = stackFrame || session; if (toReveal) { updateSelectionAndReveal(toReveal); } } } private onContextMenu(e: ITreeContextMenuEvent<CallStackItem>): void { const element = e.element; if (isDebugSession(element)) { this.callStackItemType.set('session'); } else if (element instanceof Thread) { this.callStackItemType.set('thread'); } else if (element instanceof StackFrame) { this.callStackItemType.set('stackFrame'); } else { this.callStackItemType.reset(); } const primary: IAction[] = []; const secondary: IAction[] = []; const result = { primary, secondary }; const actionsDisposable = createAndFillInContextMenuActions(this.menu, { arg: getContextForContributedActions(element), shouldForwardArgs: true }, result, this.contextMenuService, g => /^inline/.test(g)); this.contextMenuService.showContextMenu({ getAnchor: () => e.anchor, getActions: () => result.secondary, getActionsContext: () => getContext(element), onHide: () => dispose(actionsDisposable) }); } } interface IThreadTemplateData { thread: HTMLElement; name: HTMLElement; stateLabel: HTMLSpanElement; label: HighlightedLabel; actionBar: ActionBar; } interface ISessionTemplateData { session: HTMLElement; name: HTMLElement; stateLabel: HTMLSpanElement; label: HighlightedLabel; actionBar: ActionBar; elementDisposable: IDisposable[]; } interface IErrorTemplateData { label: HTMLElement; } interface ILabelTemplateData { label: HTMLElement; toDispose: IDisposable; } interface IStackFrameTemplateData { stackFrame: HTMLElement; file: HTMLElement; fileName: HTMLElement; lineNumber: HTMLElement; label: HighlightedLabel; actionBar: ActionBar; } class SessionsRenderer implements ICompressibleTreeRenderer<IDebugSession, FuzzyScore, ISessionTemplateData> { static readonly ID = 'session'; constructor( private menu: IMenu, @IInstantiationService private readonly instantiationService: IInstantiationService ) { } get templateId(): string { return SessionsRenderer.ID; } renderTemplate(container: HTMLElement): ISessionTemplateData { const session = dom.append(container, $('.session')); dom.append(session, $('.codicon.codicon-bug')); const name = dom.append(session, $('.name')); const stateLabel = dom.append(session, $('span.state.label.monaco-count-badge.long')); const label = new HighlightedLabel(name, false); const actionBar = new ActionBar(session, { actionViewItemProvider: action => { if (action instanceof MenuItemAction) { return this.instantiationService.createInstance(MenuEntryActionViewItem, action); } else if (action instanceof SubmenuItemAction) { return this.instantiationService.createInstance(SubmenuEntryActionViewItem, action); } return undefined; } }); return { session, name, stateLabel, label, actionBar, elementDisposable: [] }; } renderElement(element: ITreeNode<IDebugSession, FuzzyScore>, _: number, data: ISessionTemplateData): void { this.doRenderElement(element.element, createMatches(element.filterData), data); } renderCompressedElements(node: ITreeNode<ICompressedTreeNode<IDebugSession>, FuzzyScore>, index: number, templateData: ISessionTemplateData, height: number | undefined): void { const lastElement = node.element.elements[node.element.elements.length - 1]; const matches = createMatches(node.filterData); this.doRenderElement(lastElement, matches, templateData); } private doRenderElement(session: IDebugSession, matches: IMatch[], data: ISessionTemplateData): void { data.session.title = nls.localize({ key: 'session', comment: ['Session is a noun'] }, "Session"); data.label.set(session.getLabel(), matches); const thread = session.getAllThreads().find(t => t.stopped); const setActionBar = () => { const actions = getActions(this.instantiationService, session); const primary: IAction[] = actions; const secondary: IAction[] = []; const result = { primary, secondary }; data.elementDisposable.push(createAndFillInActionBarActions(this.menu, { arg: getContextForContributedActions(session), shouldForwardArgs: true }, result, g => /^inline/.test(g))); data.actionBar.clear(); data.actionBar.push(primary, { icon: true, label: false }); }; setActionBar(); data.elementDisposable.push(this.menu.onDidChange(() => setActionBar())); data.stateLabel.style.display = ''; if (thread && thread.stoppedDetails) { data.stateLabel.textContent = thread.stoppedDetails.description || nls.localize('debugStopped', "Paused on {0}", thread.stoppedDetails.reason || ''); if (thread.stoppedDetails.text) { data.session.title = thread.stoppedDetails.text; } } else { data.stateLabel.textContent = nls.localize({ key: 'running', comment: ['indicates state'] }, "Running"); } } disposeTemplate(templateData: ISessionTemplateData): void { templateData.actionBar.dispose(); } disposeElement(_element: ITreeNode<IDebugSession, FuzzyScore>, _: number, templateData: ISessionTemplateData): void { dispose(templateData.elementDisposable); } } class ThreadsRenderer implements ICompressibleTreeRenderer<IThread, FuzzyScore, IThreadTemplateData> { static readonly ID = 'thread'; constructor(private readonly instantiationService: IInstantiationService) { } get templateId(): string { return ThreadsRenderer.ID; } renderTemplate(container: HTMLElement): IThreadTemplateData { const thread = dom.append(container, $('.thread')); const name = dom.append(thread, $('.name')); const stateLabel = dom.append(thread, $('span.state.label')); const label = new HighlightedLabel(name, false); const actionBar = new ActionBar(thread); return { thread, name, stateLabel, label, actionBar }; } renderElement(element: ITreeNode<IThread, FuzzyScore>, index: number, data: IThreadTemplateData): void { const thread = element.element; data.thread.title = nls.localize('thread', "Thread"); data.label.set(thread.name, createMatches(element.filterData)); data.stateLabel.textContent = thread.stateLabel; data.actionBar.clear(); const actions = getActions(this.instantiationService, thread); data.actionBar.push(actions, { icon: true, label: false }); } renderCompressedElements(node: ITreeNode<ICompressedTreeNode<IThread>, FuzzyScore>, index: number, templateData: IThreadTemplateData, height: number | undefined): void { throw new Error('Method not implemented.'); } disposeTemplate(templateData: IThreadTemplateData): void { templateData.actionBar.dispose(); } } class StackFramesRenderer implements ICompressibleTreeRenderer<IStackFrame, FuzzyScore, IStackFrameTemplateData> { static readonly ID = 'stackFrame'; constructor( @ILabelService private readonly labelService: ILabelService, @INotificationService private readonly notificationService: INotificationService ) { } get templateId(): string { return StackFramesRenderer.ID; } renderTemplate(container: HTMLElement): IStackFrameTemplateData { const stackFrame = dom.append(container, $('.stack-frame')); const labelDiv = dom.append(stackFrame, $('span.label.expression')); const file = dom.append(stackFrame, $('.file')); const fileName = dom.append(file, $('span.file-name')); const wrapper = dom.append(file, $('span.line-number-wrapper')); const lineNumber = dom.append(wrapper, $('span.line-number.monaco-count-badge')); const label = new HighlightedLabel(labelDiv, false); const actionBar = new ActionBar(stackFrame); return { file, fileName, label, lineNumber, stackFrame, actionBar }; } renderElement(element: ITreeNode<IStackFrame, FuzzyScore>, index: number, data: IStackFrameTemplateData): void { const stackFrame = element.element; dom.toggleClass(data.stackFrame, 'disabled', !stackFrame.source || !stackFrame.source.available || isDeemphasized(stackFrame)); dom.toggleClass(data.stackFrame, 'label', stackFrame.presentationHint === 'label'); dom.toggleClass(data.stackFrame, 'subtle', stackFrame.presentationHint === 'subtle'); const hasActions = !!stackFrame.thread.session.capabilities.supportsRestartFrame && stackFrame.presentationHint !== 'label' && stackFrame.presentationHint !== 'subtle'; dom.toggleClass(data.stackFrame, 'has-actions', hasActions); data.file.title = stackFrame.source.inMemory ? stackFrame.source.uri.path : this.labelService.getUriLabel(stackFrame.source.uri); if (stackFrame.source.raw.origin) { data.file.title += `\n${stackFrame.source.raw.origin}`; } data.label.set(stackFrame.name, createMatches(element.filterData), stackFrame.name); data.fileName.textContent = getSpecificSourceName(stackFrame); if (stackFrame.range.startLineNumber !== undefined) { data.lineNumber.textContent = `${stackFrame.range.startLineNumber}`; if (stackFrame.range.startColumn) { data.lineNumber.textContent += `:${stackFrame.range.startColumn}`; } dom.removeClass(data.lineNumber, 'unavailable'); } else { dom.addClass(data.lineNumber, 'unavailable'); } data.actionBar.clear(); if (hasActions) { const action = new Action('debug.callStack.restartFrame', nls.localize('restartFrame', "Restart Frame"), 'codicon-debug-restart-frame', true, async () => { try { await stackFrame.restart(); } catch (e) { this.notificationService.error(e); } }); data.actionBar.push(action, { icon: true, label: false }); } } renderCompressedElements(node: ITreeNode<ICompressedTreeNode<IStackFrame>, FuzzyScore>, index: number, templateData: IStackFrameTemplateData, height: number | undefined): void { throw new Error('Method not implemented.'); } disposeTemplate(templateData: IStackFrameTemplateData): void { templateData.actionBar.dispose(); } } class ErrorsRenderer implements ICompressibleTreeRenderer<string, FuzzyScore, IErrorTemplateData> { static readonly ID = 'error'; get templateId(): string { return ErrorsRenderer.ID; } renderTemplate(container: HTMLElement): IErrorTemplateData { const label = dom.append(container, $('.error')); return { label }; } renderElement(element: ITreeNode<string, FuzzyScore>, index: number, data: IErrorTemplateData): void { const error = element.element; data.label.textContent = error; data.label.title = error; } renderCompressedElements(node: ITreeNode<ICompressedTreeNode<string>, FuzzyScore>, index: number, templateData: IErrorTemplateData, height: number | undefined): void { throw new Error('Method not implemented.'); } disposeTemplate(templateData: IErrorTemplateData): void { // noop } } class LoadAllRenderer implements ICompressibleTreeRenderer<ThreadAndSessionIds, FuzzyScore, ILabelTemplateData> { static readonly ID = 'loadAll'; static readonly LABEL = nls.localize('loadAllStackFrames', "Load All Stack Frames"); constructor(private readonly themeService: IThemeService) { } get templateId(): string { return LoadAllRenderer.ID; } renderTemplate(container: HTMLElement): ILabelTemplateData { const label = dom.append(container, $('.load-all')); const toDispose = attachStylerCallback(this.themeService, { textLinkForeground }, colors => { if (colors.textLinkForeground) { label.style.color = colors.textLinkForeground.toString(); } }); return { label, toDispose }; } renderElement(element: ITreeNode<ThreadAndSessionIds, FuzzyScore>, index: number, data: ILabelTemplateData): void { data.label.textContent = LoadAllRenderer.LABEL; } renderCompressedElements(node: ITreeNode<ICompressedTreeNode<ThreadAndSessionIds>, FuzzyScore>, index: number, templateData: ILabelTemplateData, height: number | undefined): void { throw new Error('Method not implemented.'); } disposeTemplate(templateData: ILabelTemplateData): void { templateData.toDispose.dispose(); } } class ShowMoreRenderer implements ICompressibleTreeRenderer<IStackFrame[], FuzzyScore, ILabelTemplateData> { static readonly ID = 'showMore'; constructor(private readonly themeService: IThemeService) { } get templateId(): string { return ShowMoreRenderer.ID; } renderTemplate(container: HTMLElement): ILabelTemplateData { const label = dom.append(container, $('.show-more')); const toDispose = attachStylerCallback(this.themeService, { textLinkForeground }, colors => { if (colors.textLinkForeground) { label.style.color = colors.textLinkForeground.toString(); } }); return { label, toDispose }; } renderElement(element: ITreeNode<IStackFrame[], FuzzyScore>, index: number, data: ILabelTemplateData): void { const stackFrames = element.element; if (stackFrames.every(sf => !!(sf.source && sf.source.origin && sf.source.origin === stackFrames[0].source.origin))) { data.label.textContent = nls.localize('showMoreAndOrigin', "Show {0} More: {1}", stackFrames.length, stackFrames[0].source.origin); } else { data.label.textContent = nls.localize('showMoreStackFrames', "Show {0} More Stack Frames", stackFrames.length); } } renderCompressedElements(node: ITreeNode<ICompressedTreeNode<IStackFrame[]>, FuzzyScore>, index: number, templateData: ILabelTemplateData, height: number | undefined): void { throw new Error('Method not implemented.'); } disposeTemplate(templateData: ILabelTemplateData): void { templateData.toDispose.dispose(); } } class CallStackDelegate implements IListVirtualDelegate<CallStackItem> { getHeight(element: CallStackItem): number { if (element instanceof StackFrame && element.presentationHint === 'label') { return 16; } if (element instanceof ThreadAndSessionIds || element instanceof Array) { return 16; } return 22; } getTemplateId(element: CallStackItem): string { if (isDebugSession(element)) { return SessionsRenderer.ID; } if (element instanceof Thread) { return ThreadsRenderer.ID; } if (element instanceof StackFrame) { return StackFramesRenderer.ID; } if (typeof element === 'string') { return ErrorsRenderer.ID; } if (element instanceof ThreadAndSessionIds) { return LoadAllRenderer.ID; } // element instanceof Array return ShowMoreRenderer.ID; } } function isDebugModel(obj: any): obj is IDebugModel { return typeof obj.getSessions === 'function'; } function isDebugSession(obj: any): obj is IDebugSession { return obj && typeof obj.getAllThreads === 'function'; } function isDeemphasized(frame: IStackFrame): boolean { return frame.source.presentationHint === 'deemphasize' || frame.presentationHint === 'deemphasize'; } class CallStackDataSource implements IAsyncDataSource<IDebugModel, CallStackItem> { deemphasizedStackFramesToShow: IStackFrame[] = []; constructor(private debugService: IDebugService) { } hasChildren(element: IDebugModel | CallStackItem): boolean { if (isDebugSession(element)) { const threads = element.getAllThreads(); return (threads.length > 1) || (threads.length === 1 && threads[0].stopped) || !!(this.debugService.getModel().getSessions().find(s => s.parentSession === element)); } return isDebugModel(element) || (element instanceof Thread && element.stopped); } async getChildren(element: IDebugModel | CallStackItem): Promise<CallStackItem[]> { if (isDebugModel(element)) { const sessions = element.getSessions(); if (sessions.length === 0) { return Promise.resolve([]); } if (sessions.length > 1 || this.debugService.getViewModel().isMultiSessionView()) { return Promise.resolve(sessions.filter(s => !s.parentSession)); } const threads = sessions[0].getAllThreads(); // Only show the threads in the call stack if there is more than 1 thread. return threads.length === 1 ? this.getThreadChildren(<Thread>threads[0]) : Promise.resolve(threads); } else if (isDebugSession(element)) { const childSessions = this.debugService.getModel().getSessions().filter(s => s.parentSession === element); const threads: CallStackItem[] = element.getAllThreads(); if (threads.length === 1) { // Do not show thread when there is only one to be compact. const children = await this.getThreadChildren(<Thread>threads[0]); return children.concat(childSessions); } return Promise.resolve(threads.concat(childSessions)); } else { return this.getThreadChildren(<Thread>element); } } private getThreadChildren(thread: Thread): Promise<CallStackItem[]> { return this.getThreadCallstack(thread).then(children => { // Check if some stack frames should be hidden under a parent element since they are deemphasized const result: CallStackItem[] = []; children.forEach((child, index) => { if (child instanceof StackFrame && child.source && isDeemphasized(child)) { // Check if the user clicked to show the deemphasized source if (this.deemphasizedStackFramesToShow.indexOf(child) === -1) { if (result.length) { const last = result[result.length - 1]; if (last instanceof Array) { // Collect all the stackframes that will be "collapsed" last.push(child); return; } } const nextChild = index < children.length - 1 ? children[index + 1] : undefined; if (nextChild instanceof StackFrame && nextChild.source && isDeemphasized(nextChild)) { // Start collecting stackframes that will be "collapsed" result.push([child]); return; } } } result.push(child); }); return result; }); } private async getThreadCallstack(thread: Thread): Promise<Array<IStackFrame | string | ThreadAndSessionIds>> { let callStack: any[] = thread.getCallStack(); if (!callStack || !callStack.length) { await thread.fetchCallStack(); callStack = thread.getCallStack(); } if (callStack.length === 1 && thread.session.capabilities.supportsDelayedStackTraceLoading && thread.stoppedDetails && thread.stoppedDetails.totalFrames && thread.stoppedDetails.totalFrames > 1) { // To reduce flashing of the call stack view simply append the stale call stack // once we have the correct data the tree will refresh and we will no longer display it. callStack = callStack.concat(thread.getStaleCallStack().slice(1)); } if (thread.stoppedDetails && thread.stoppedDetails.framesErrorMessage) { callStack = callStack.concat([thread.stoppedDetails.framesErrorMessage]); } if (thread.stoppedDetails && thread.stoppedDetails.totalFrames && thread.stoppedDetails.totalFrames > callStack.length && callStack.length > 1) { callStack = callStack.concat([new ThreadAndSessionIds(thread.session.getId(), thread.threadId)]); } return callStack; } } class CallStackAccessibilityProvider implements IListAccessibilityProvider<CallStackItem> { getWidgetAriaLabel(): string { return nls.localize({ comment: ['Debug is a noun in this context, not a verb.'], key: 'callStackAriaLabel' }, "Debug Call Stack"); } getAriaLabel(element: CallStackItem): string { if (element instanceof Thread) { return nls.localize('threadAriaLabel', "Thread {0}, callstack, debug", (<Thread>element).name); } if (element instanceof StackFrame) { return nls.localize('stackFrameAriaLabel', "Stack Frame {0}, line {1}, {2}, callstack, debug", element.name, element.range.startLineNumber, getSpecificSourceName(element)); } if (isDebugSession(element)) { return nls.localize('sessionLabel', "Debug Session {0}", element.getLabel()); } if (typeof element === 'string') { return element; } if (element instanceof Array) { return nls.localize('showMoreStackFrames', "Show {0} More Stack Frames", element.length); } // element instanceof ThreadAndSessionIds return LoadAllRenderer.LABEL; } } function getActions(instantiationService: IInstantiationService, element: IDebugSession | IThread): IAction[] { const getThreadActions = (thread: IThread): IAction[] => { return [ thread.stopped ? instantiationService.createInstance(ContinueAction, thread) : instantiationService.createInstance(PauseAction, thread), instantiationService.createInstance(StepOverAction, thread), instantiationService.createInstance(StepIntoAction, thread), instantiationService.createInstance(StepOutAction, thread) ]; }; if (element instanceof Thread) { return getThreadActions(element); } const session = <IDebugSession>element; const stopOrDisconectAction = isSessionAttach(session) ? instantiationService.createInstance(DisconnectAction, session) : instantiationService.createInstance(StopAction, session); const restartAction = instantiationService.createInstance(RestartAction, session); const threads = session.getAllThreads(); if (threads.length === 1) { return getThreadActions(threads[0]).concat([ restartAction, stopOrDisconectAction ]); } return [ restartAction, stopOrDisconectAction ]; } class StopAction extends Action { constructor( private readonly session: IDebugSession, @ICommandService private readonly commandService: ICommandService ) { super(`action.${STOP_ID}`, STOP_LABEL, 'debug-action codicon-debug-stop'); } public run(): Promise<any> { return this.commandService.executeCommand(STOP_ID, undefined, getContext(this.session)); } } class DisconnectAction extends Action { constructor( private readonly session: IDebugSession, @ICommandService private readonly commandService: ICommandService ) { super(`action.${DISCONNECT_ID}`, DISCONNECT_LABEL, 'debug-action codicon-debug-disconnect'); } public run(): Promise<any> { return this.commandService.executeCommand(DISCONNECT_ID, undefined, getContext(this.session)); } } class RestartAction extends Action { constructor( private readonly session: IDebugSession, @ICommandService private readonly commandService: ICommandService ) { super(`action.${RESTART_SESSION_ID}`, RESTART_LABEL, 'debug-action codicon-debug-restart'); } public run(): Promise<any> { return this.commandService.executeCommand(RESTART_SESSION_ID, undefined, getContext(this.session)); } } class StepOverAction extends Action { constructor( private readonly thread: IThread, @ICommandService private readonly commandService: ICommandService ) { super(`action.${STEP_OVER_ID}`, STEP_OVER_LABEL, 'debug-action codicon-debug-step-over', thread.stopped); } public run(): Promise<any> { return this.commandService.executeCommand(STEP_OVER_ID, undefined, getContext(this.thread)); } } class StepIntoAction extends Action { constructor( private readonly thread: IThread, @ICommandService private readonly commandService: ICommandService ) { super(`action.${STEP_INTO_ID}`, STEP_INTO_LABEL, 'debug-action codicon-debug-step-into', thread.stopped); } public run(): Promise<any> { return this.commandService.executeCommand(STEP_INTO_ID, undefined, getContext(this.thread)); } } class StepOutAction extends Action { constructor( private readonly thread: IThread, @ICommandService private readonly commandService: ICommandService ) { super(`action.${STEP_OUT_ID}`, STEP_OUT_LABEL, 'debug-action codicon-debug-step-out', thread.stopped); } public run(): Promise<any> { return this.commandService.executeCommand(STEP_OUT_ID, undefined, getContext(this.thread)); } } class PauseAction extends Action { constructor( private readonly thread: IThread, @ICommandService private readonly commandService: ICommandService ) { super(`action.${PAUSE_ID}`, PAUSE_LABEL, 'debug-action codicon-debug-pause', !thread.stopped); } public run(): Promise<any> { return this.commandService.executeCommand(PAUSE_ID, undefined, getContext(this.thread)); } } class ContinueAction extends Action { constructor( private readonly thread: IThread, @ICommandService private readonly commandService: ICommandService ) { super(`action.${CONTINUE_ID}`, CONTINUE_LABEL, 'debug-action codicon-debug-continue', thread.stopped); } public run(): Promise<any> { return this.commandService.executeCommand(CONTINUE_ID, undefined, getContext(this.thread)); } } class CallStackCompressionDelegate implements ITreeCompressionDelegate<CallStackItem> { constructor(private readonly debugService: IDebugService) { } isIncompressible(stat: CallStackItem): boolean { if (isDebugSession(stat)) { if (stat.compact) { return false; } const sessions = this.debugService.getModel().getSessions(); if (sessions.some(s => s.parentSession === stat && s.compact)) { return false; } return true; } return true; } }
src/vs/workbench/contrib/debug/browser/callStackView.ts
1
https://github.com/microsoft/vscode/commit/135b6da83746477b2983fee879122ceefa70014d
[ 0.9709445834159851, 0.009075373411178589, 0.00015976607392076403, 0.00017267733346670866, 0.0913170576095581 ]
{ "id": 2, "code_window": [ "\t\tthis.updateScheduler = this._register(new RunOnceScheduler(() => {\n", "\t\t\tconst state = this.debugService.state;\n", "\t\t\tconst toolBarLocation = this.configurationService.getValue<IDebugConfiguration>('debug').toolBarLocation;\n", "\t\t\tif (state === State.Inactive || toolBarLocation === 'docked' || toolBarLocation === 'hidden') {\n", "\t\t\t\treturn this.hide();\n", "\t\t\t}\n", "\n", "\t\t\tconst { actions, disposable } = DebugToolBar.getActions(this.debugToolBarMenu, this.debugService, this.instantiationService);\n", "\t\t\tif (!arrays.equals(actions, this.activeActions, (first, second) => first.id === second.id)) {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tif (state === State.Inactive || state === State.Initializing || toolBarLocation === 'docked' || toolBarLocation === 'hidden') {\n" ], "file_path": "src/vs/workbench/contrib/debug/browser/debugToolBar.ts", "type": "replace", "edit_start_line_idx": 93 }
Small File
src/vs/platform/files/test/electron-browser/fixtures/service/small.txt
0
https://github.com/microsoft/vscode/commit/135b6da83746477b2983fee879122ceefa70014d
[ 0.00017313522403128445, 0.00017313522403128445, 0.00017313522403128445, 0.00017313522403128445, 0 ]
{ "id": 2, "code_window": [ "\t\tthis.updateScheduler = this._register(new RunOnceScheduler(() => {\n", "\t\t\tconst state = this.debugService.state;\n", "\t\t\tconst toolBarLocation = this.configurationService.getValue<IDebugConfiguration>('debug').toolBarLocation;\n", "\t\t\tif (state === State.Inactive || toolBarLocation === 'docked' || toolBarLocation === 'hidden') {\n", "\t\t\t\treturn this.hide();\n", "\t\t\t}\n", "\n", "\t\t\tconst { actions, disposable } = DebugToolBar.getActions(this.debugToolBarMenu, this.debugService, this.instantiationService);\n", "\t\t\tif (!arrays.equals(actions, this.activeActions, (first, second) => first.id === second.id)) {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tif (state === State.Inactive || state === State.Initializing || toolBarLocation === 'docked' || toolBarLocation === 'hidden') {\n" ], "file_path": "src/vs/workbench/contrib/debug/browser/debugToolBar.ts", "type": "replace", "edit_start_line_idx": 93 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { createDecorator } from 'vs/platform/instantiation/common/instantiation'; import { Emitter, Event } from 'vs/base/common/event'; import { Disposable } from 'vs/base/common/lifecycle'; import { IUserDataSyncStoreService } from 'vs/platform/userDataSync/common/userDataSync'; export interface IUserDataSyncAccount { readonly authenticationProviderId: string; readonly token: string; } export const IUserDataSyncAccountService = createDecorator<IUserDataSyncAccountService>('IUserDataSyncAccountService'); export interface IUserDataSyncAccountService { readonly _serviceBrand: undefined; readonly onTokenFailed: Event<boolean>; readonly account: IUserDataSyncAccount | undefined; readonly onDidChangeAccount: Event<IUserDataSyncAccount | undefined>; updateAccount(account: IUserDataSyncAccount | undefined): Promise<void>; } export class UserDataSyncAccountService extends Disposable implements IUserDataSyncAccountService { _serviceBrand: any; private _account: IUserDataSyncAccount | undefined; get account(): IUserDataSyncAccount | undefined { return this._account; } private _onDidChangeAccount = this._register(new Emitter<IUserDataSyncAccount | undefined>()); readonly onDidChangeAccount = this._onDidChangeAccount.event; private _onTokenFailed: Emitter<boolean> = this._register(new Emitter<boolean>()); readonly onTokenFailed: Event<boolean> = this._onTokenFailed.event; private wasTokenFailed: boolean = false; constructor( @IUserDataSyncStoreService private readonly userDataSyncStoreService: IUserDataSyncStoreService ) { super(); this._register(userDataSyncStoreService.onTokenFailed(() => { this.updateAccount(undefined); this._onTokenFailed.fire(this.wasTokenFailed); this.wasTokenFailed = true; })); this._register(userDataSyncStoreService.onTokenSucceed(() => this.wasTokenFailed = false)); } async updateAccount(account: IUserDataSyncAccount | undefined): Promise<void> { if (account && this._account ? account.token !== this._account.token || account.authenticationProviderId !== this._account.authenticationProviderId : account !== this._account) { this._account = account; if (this._account) { this.userDataSyncStoreService.setAuthToken(this._account.token, this._account.authenticationProviderId); } this._onDidChangeAccount.fire(account); } } }
src/vs/platform/userDataSync/common/userDataSyncAccount.ts
0
https://github.com/microsoft/vscode/commit/135b6da83746477b2983fee879122ceefa70014d
[ 0.00017378789198119193, 0.00017016087076626718, 0.00016594459884800017, 0.00017078709788620472, 0.000002651406930453959 ]
{ "id": 2, "code_window": [ "\t\tthis.updateScheduler = this._register(new RunOnceScheduler(() => {\n", "\t\t\tconst state = this.debugService.state;\n", "\t\t\tconst toolBarLocation = this.configurationService.getValue<IDebugConfiguration>('debug').toolBarLocation;\n", "\t\t\tif (state === State.Inactive || toolBarLocation === 'docked' || toolBarLocation === 'hidden') {\n", "\t\t\t\treturn this.hide();\n", "\t\t\t}\n", "\n", "\t\t\tconst { actions, disposable } = DebugToolBar.getActions(this.debugToolBarMenu, this.debugService, this.instantiationService);\n", "\t\t\tif (!arrays.equals(actions, this.activeActions, (first, second) => first.id === second.id)) {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tif (state === State.Inactive || state === State.Initializing || toolBarLocation === 'docked' || toolBarLocation === 'hidden') {\n" ], "file_path": "src/vs/workbench/contrib/debug/browser/debugToolBar.ts", "type": "replace", "edit_start_line_idx": 93 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { ISyncExtension } from 'vs/platform/userDataSync/common/userDataSync'; import { IExtensionIdentifier } from 'vs/platform/extensions/common/extensions'; import { deepClone } from 'vs/base/common/objects'; import { ILocalExtension } from 'vs/platform/extensionManagement/common/extensionManagement'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { distinct } from 'vs/base/common/arrays'; export interface IMergeResult { added: ISyncExtension[]; removed: IExtensionIdentifier[]; updated: ISyncExtension[]; remote: ISyncExtension[] | null; } export function merge(localExtensions: ISyncExtension[], remoteExtensions: ISyncExtension[] | null, lastSyncExtensions: ISyncExtension[] | null, skippedExtensions: ISyncExtension[], ignoredExtensions: string[]): IMergeResult { const added: ISyncExtension[] = []; const removed: IExtensionIdentifier[] = []; const updated: ISyncExtension[] = []; if (!remoteExtensions) { const remote = localExtensions.filter(({ identifier }) => ignoredExtensions.every(id => id.toLowerCase() !== identifier.id.toLowerCase())); return { added, removed, updated, remote: remote.length > 0 ? remote : null }; } localExtensions = localExtensions.map(massageIncomingExtension); remoteExtensions = remoteExtensions.map(massageIncomingExtension); lastSyncExtensions = lastSyncExtensions ? lastSyncExtensions.map(massageIncomingExtension) : null; const uuids: Map<string, string> = new Map<string, string>(); const addUUID = (identifier: IExtensionIdentifier) => { if (identifier.uuid) { uuids.set(identifier.id.toLowerCase(), identifier.uuid); } }; localExtensions.forEach(({ identifier }) => addUUID(identifier)); remoteExtensions.forEach(({ identifier }) => addUUID(identifier)); if (lastSyncExtensions) { lastSyncExtensions.forEach(({ identifier }) => addUUID(identifier)); } const getKey = (extension: ISyncExtension): string => { const uuid = extension.identifier.uuid || uuids.get(extension.identifier.id.toLowerCase()); return uuid ? `uuid:${uuid}` : `id:${extension.identifier.id.toLowerCase()}`; }; const addExtensionToMap = (map: Map<string, ISyncExtension>, extension: ISyncExtension) => { map.set(getKey(extension), extension); return map; }; const localExtensionsMap = localExtensions.reduce(addExtensionToMap, new Map<string, ISyncExtension>()); const remoteExtensionsMap = remoteExtensions.reduce(addExtensionToMap, new Map<string, ISyncExtension>()); const newRemoteExtensionsMap = remoteExtensions.reduce((map: Map<string, ISyncExtension>, extension: ISyncExtension) => { const key = getKey(extension); extension = deepClone(extension); if (localExtensionsMap.get(key)?.installed) { extension.installed = true; } return addExtensionToMap(map, extension); }, new Map<string, ISyncExtension>()); const lastSyncExtensionsMap = lastSyncExtensions ? lastSyncExtensions.reduce(addExtensionToMap, new Map<string, ISyncExtension>()) : null; const skippedExtensionsMap = skippedExtensions.reduce(addExtensionToMap, new Map<string, ISyncExtension>()); const ignoredExtensionsSet = ignoredExtensions.reduce((set, id) => { const uuid = uuids.get(id.toLowerCase()); return set.add(uuid ? `uuid:${uuid}` : `id:${id.toLowerCase()}`); }, new Set<string>()); const localToRemote = compare(localExtensionsMap, remoteExtensionsMap, ignoredExtensionsSet); if (localToRemote.added.size > 0 || localToRemote.removed.size > 0 || localToRemote.updated.size > 0) { const baseToLocal = compare(lastSyncExtensionsMap, localExtensionsMap, ignoredExtensionsSet); const baseToRemote = compare(lastSyncExtensionsMap, remoteExtensionsMap, ignoredExtensionsSet); // Remotely removed extension. for (const key of baseToRemote.removed.values()) { const e = localExtensionsMap.get(key); if (e) { removed.push(e.identifier); } } // Remotely added extension for (const key of baseToRemote.added.values()) { // Got added in local if (baseToLocal.added.has(key)) { // Is different from local to remote if (localToRemote.updated.has(key)) { updated.push(massageOutgoingExtension(remoteExtensionsMap.get(key)!, key)); } } else { // Add only installed extension to local const remoteExtension = remoteExtensionsMap.get(key)!; if (remoteExtension.installed) { added.push(massageOutgoingExtension(remoteExtension, key)); } } } // Remotely updated extensions for (const key of baseToRemote.updated.values()) { // Update in local always updated.push(massageOutgoingExtension(remoteExtensionsMap.get(key)!, key)); } // Locally added extensions for (const key of baseToLocal.added.values()) { // Not there in remote if (!baseToRemote.added.has(key)) { newRemoteExtensionsMap.set(key, localExtensionsMap.get(key)!); } } // Locally updated extensions for (const key of baseToLocal.updated.values()) { // If removed in remote if (baseToRemote.removed.has(key)) { continue; } // If not updated in remote if (!baseToRemote.updated.has(key)) { const extension = deepClone(localExtensionsMap.get(key)!); // Retain installed property if (newRemoteExtensionsMap.get(key)?.installed) { extension.installed = true; } newRemoteExtensionsMap.set(key, extension); } } // Locally removed extensions for (const key of baseToLocal.removed.values()) { // If not skipped and not updated in remote if (!skippedExtensionsMap.has(key) && !baseToRemote.updated.has(key)) { // Remove only if it is an installed extension if (lastSyncExtensionsMap?.get(key)?.installed) { newRemoteExtensionsMap.delete(key); } } } } const remote: ISyncExtension[] = []; const remoteChanges = compare(remoteExtensionsMap, newRemoteExtensionsMap, new Set<string>(), { checkInstalledProperty: true }); if (remoteChanges.added.size > 0 || remoteChanges.updated.size > 0 || remoteChanges.removed.size > 0) { newRemoteExtensionsMap.forEach((value, key) => remote.push(massageOutgoingExtension(value, key))); } return { added, removed, updated, remote: remote.length ? remote : null }; } function compare(from: Map<string, ISyncExtension> | null, to: Map<string, ISyncExtension>, ignoredExtensions: Set<string>, { checkInstalledProperty }: { checkInstalledProperty: boolean } = { checkInstalledProperty: false }): { added: Set<string>, removed: Set<string>, updated: Set<string> } { const fromKeys = from ? [...from.keys()].filter(key => !ignoredExtensions.has(key)) : []; const toKeys = [...to.keys()].filter(key => !ignoredExtensions.has(key)); const added = toKeys.filter(key => fromKeys.indexOf(key) === -1).reduce((r, key) => { r.add(key); return r; }, new Set<string>()); const removed = fromKeys.filter(key => toKeys.indexOf(key) === -1).reduce((r, key) => { r.add(key); return r; }, new Set<string>()); const updated: Set<string> = new Set<string>(); for (const key of fromKeys) { if (removed.has(key)) { continue; } const fromExtension = from!.get(key)!; const toExtension = to.get(key); if (!toExtension || fromExtension.disabled !== toExtension.disabled || fromExtension.version !== toExtension.version || (checkInstalledProperty && fromExtension.installed !== toExtension.installed) ) { updated.add(key); } } return { added, removed, updated }; } // massage incoming extension - add optional properties function massageIncomingExtension(extension: ISyncExtension): ISyncExtension { return { ...extension, ...{ disabled: !!extension.disabled, installed: !!extension.installed } }; } // massage outgoing extension - remove optional properties function massageOutgoingExtension(extension: ISyncExtension, key: string): ISyncExtension { const massagedExtension: ISyncExtension = { identifier: { id: extension.identifier.id, uuid: key.startsWith('uuid:') ? key.substring('uuid:'.length) : undefined }, }; if (extension.disabled) { massagedExtension.disabled = true; } if (extension.installed) { massagedExtension.installed = true; } if (extension.version) { massagedExtension.version = extension.version; } return massagedExtension; } export function getIgnoredExtensions(installed: ILocalExtension[], configurationService: IConfigurationService): string[] { const defaultIgnoredExtensions = installed.filter(i => i.isMachineScoped).map(i => i.identifier.id.toLowerCase()); const value = getConfiguredIgnoredExtensions(configurationService).map(id => id.toLowerCase()); const added: string[] = [], removed: string[] = []; if (Array.isArray(value)) { for (const key of value) { if (key.startsWith('-')) { removed.push(key.substring(1)); } else { added.push(key); } } } return distinct([...defaultIgnoredExtensions, ...added,].filter(setting => removed.indexOf(setting) === -1)); } function getConfiguredIgnoredExtensions(configurationService: IConfigurationService): string[] { let userValue = configurationService.inspect<string[]>('settingsSync.ignoredExtensions').userValue; if (userValue !== undefined) { return userValue; } userValue = configurationService.inspect<string[]>('sync.ignoredExtensions').userValue; if (userValue !== undefined) { return userValue; } return configurationService.getValue<string[]>('settingsSync.ignoredExtensions') || []; }
src/vs/platform/userDataSync/common/extensionsMerge.ts
0
https://github.com/microsoft/vscode/commit/135b6da83746477b2983fee879122ceefa70014d
[ 0.0002292259014211595, 0.00017682091856840998, 0.00016770182992331684, 0.0001728275528876111, 0.000012827945283788722 ]
{ "id": 3, "code_window": [ "import { ToggleViewAction } from 'vs/workbench/browser/actions/layoutActions';\n", "import { RunOnceScheduler } from 'vs/base/common/async';\n", "import { ShowViewletAction } from 'vs/workbench/browser/viewlet';\n", "import { IViewletService } from 'vs/workbench/services/viewlet/browser/viewlet';\n", "import { IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService';\n", "\n", "export class DebugViewPaneContainer extends ViewPaneContainer {\n", "\n", "\tprivate startDebugActionViewItem: StartDebugActionViewItem | undefined;\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { StopAction } from 'vs/workbench/contrib/debug/browser/callStackView';\n" ], "file_path": "src/vs/workbench/contrib/debug/browser/debugViewlet.ts", "type": "add", "edit_start_line_idx": 36 }
/*--------------------------------------------------------------------------------------------- * 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/debugViewlet'; import * as nls from 'vs/nls'; import { IAction, IActionViewItem } from 'vs/base/common/actions'; import * as DOM from 'vs/base/browser/dom'; import { IDebugService, VIEWLET_ID, State, BREAKPOINTS_VIEW_ID, IDebugConfiguration, CONTEXT_DEBUG_UX, CONTEXT_DEBUG_UX_KEY, REPL_VIEW_ID } from 'vs/workbench/contrib/debug/common/debug'; import { StartAction, ConfigureAction, SelectAndStartAction, FocusSessionAction } from 'vs/workbench/contrib/debug/browser/debugActions'; import { StartDebugActionViewItem, FocusSessionActionViewItem } from 'vs/workbench/contrib/debug/browser/debugActionViewItems'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions'; import { IProgressService } from 'vs/platform/progress/common/progress'; import { IWorkspaceContextService, WorkbenchState } from 'vs/platform/workspace/common/workspace'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IStorageService } from 'vs/platform/storage/common/storage'; import { IThemeService } from 'vs/platform/theme/common/themeService'; import { IContextMenuService, IContextViewService } from 'vs/platform/contextview/browser/contextView'; import { IDisposable, dispose } from 'vs/base/common/lifecycle'; import { IWorkbenchLayoutService } from 'vs/workbench/services/layout/browser/layoutService'; import { memoize } from 'vs/base/common/decorators'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { DebugToolBar } from 'vs/workbench/contrib/debug/browser/debugToolBar'; import { ViewPane, ViewPaneContainer } from 'vs/workbench/browser/parts/views/viewPaneContainer'; import { IMenu, MenuId, IMenuService, MenuItemAction, SubmenuItemAction } from 'vs/platform/actions/common/actions'; import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { MenuEntryActionViewItem, SubmenuEntryActionViewItem } from 'vs/platform/actions/browser/menuEntryActionViewItem'; import { IViewDescriptorService, IViewsService } from 'vs/workbench/common/views'; import { WelcomeView } from 'vs/workbench/contrib/debug/browser/welcomeView'; import { ToggleViewAction } from 'vs/workbench/browser/actions/layoutActions'; import { RunOnceScheduler } from 'vs/base/common/async'; import { ShowViewletAction } from 'vs/workbench/browser/viewlet'; import { IViewletService } from 'vs/workbench/services/viewlet/browser/viewlet'; import { IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService'; export class DebugViewPaneContainer extends ViewPaneContainer { private startDebugActionViewItem: StartDebugActionViewItem | undefined; private progressResolve: (() => void) | undefined; private breakpointView: ViewPane | undefined; private paneListeners = new Map<string, IDisposable>(); private debugToolBarMenu: IMenu | undefined; private disposeOnTitleUpdate: IDisposable | undefined; private updateToolBarScheduler: RunOnceScheduler; constructor( @IWorkbenchLayoutService layoutService: IWorkbenchLayoutService, @ITelemetryService telemetryService: ITelemetryService, @IProgressService private readonly progressService: IProgressService, @IDebugService private readonly debugService: IDebugService, @IInstantiationService instantiationService: IInstantiationService, @IWorkspaceContextService contextService: IWorkspaceContextService, @IStorageService storageService: IStorageService, @IThemeService themeService: IThemeService, @IContextMenuService contextMenuService: IContextMenuService, @IExtensionService extensionService: IExtensionService, @IConfigurationService configurationService: IConfigurationService, @IContextViewService private readonly contextViewService: IContextViewService, @IMenuService private readonly menuService: IMenuService, @IContextKeyService private readonly contextKeyService: IContextKeyService, @IViewDescriptorService viewDescriptorService: IViewDescriptorService ) { super(VIEWLET_ID, { mergeViewWithContainerWhenSingleView: true }, instantiationService, configurationService, layoutService, contextMenuService, telemetryService, extensionService, themeService, storageService, contextService, viewDescriptorService); this.updateToolBarScheduler = this._register(new RunOnceScheduler(() => { if (this.configurationService.getValue<IDebugConfiguration>('debug').toolBarLocation === 'docked') { this.updateTitleArea(); } }, 20)); // When there are potential updates to the docked debug toolbar we need to update it this._register(this.debugService.onDidChangeState(state => this.onDebugServiceStateChange(state))); this._register(this.debugService.onDidNewSession(() => this.updateToolBarScheduler.schedule())); this._register(this.debugService.getViewModel().onDidFocusSession(() => this.updateToolBarScheduler.schedule())); this._register(this.contextKeyService.onDidChangeContext(e => { if (e.affectsSome(new Set([CONTEXT_DEBUG_UX_KEY]))) { this.updateTitleArea(); } })); this._register(this.contextService.onDidChangeWorkbenchState(() => this.updateTitleArea())); this._register(this.configurationService.onDidChangeConfiguration(e => { if (e.affectsConfiguration('debug.toolBarLocation')) { this.updateTitleArea(); } })); } create(parent: HTMLElement): void { super.create(parent); DOM.addClass(parent, 'debug-viewlet'); } focus(): void { super.focus(); if (this.startDebugActionViewItem) { this.startDebugActionViewItem.focus(); } else { this.focusView(WelcomeView.ID); } } @memoize private get startAction(): StartAction { return this._register(this.instantiationService.createInstance(StartAction, StartAction.ID, StartAction.LABEL)); } @memoize private get configureAction(): ConfigureAction { return this._register(this.instantiationService.createInstance(ConfigureAction, ConfigureAction.ID, ConfigureAction.LABEL)); } @memoize private get toggleReplAction(): OpenDebugConsoleAction { return this._register(this.instantiationService.createInstance(OpenDebugConsoleAction, OpenDebugConsoleAction.ID, OpenDebugConsoleAction.LABEL)); } @memoize private get selectAndStartAction(): SelectAndStartAction { return this._register(this.instantiationService.createInstance(SelectAndStartAction, SelectAndStartAction.ID, nls.localize('startAdditionalSession', "Start Additional Session"))); } getActions(): IAction[] { if (CONTEXT_DEBUG_UX.getValue(this.contextKeyService) === 'simple') { return []; } if (!this.showInitialDebugActions) { if (!this.debugToolBarMenu) { this.debugToolBarMenu = this.menuService.createMenu(MenuId.DebugToolBar, this.contextKeyService); this._register(this.debugToolBarMenu); this._register(this.debugToolBarMenu.onDidChange(() => this.updateToolBarScheduler.schedule())); } const { actions, disposable } = DebugToolBar.getActions(this.debugToolBarMenu, this.debugService, this.instantiationService); if (this.disposeOnTitleUpdate) { dispose(this.disposeOnTitleUpdate); } this.disposeOnTitleUpdate = disposable; return actions; } if (this.contextService.getWorkbenchState() === WorkbenchState.EMPTY) { return [this.toggleReplAction]; } return [this.startAction, this.configureAction, this.toggleReplAction]; } get showInitialDebugActions(): boolean { const state = this.debugService.state; return state === State.Inactive || this.configurationService.getValue<IDebugConfiguration>('debug').toolBarLocation !== 'docked'; } getSecondaryActions(): IAction[] { if (this.showInitialDebugActions) { return []; } return [this.selectAndStartAction, this.configureAction, this.toggleReplAction]; } getActionViewItem(action: IAction): IActionViewItem | undefined { if (action.id === StartAction.ID) { this.startDebugActionViewItem = this.instantiationService.createInstance(StartDebugActionViewItem, null, action); return this.startDebugActionViewItem; } if (action.id === FocusSessionAction.ID) { return new FocusSessionActionViewItem(action, this.debugService, this.themeService, this.contextViewService, this.configurationService); } if (action instanceof MenuItemAction) { return this.instantiationService.createInstance(MenuEntryActionViewItem, action); } else if (action instanceof SubmenuItemAction) { return this.instantiationService.createInstance(SubmenuEntryActionViewItem, action); } return undefined; } focusView(id: string): void { const view = this.getView(id); if (view) { view.focus(); } } private onDebugServiceStateChange(state: State): void { if (this.progressResolve) { this.progressResolve(); this.progressResolve = undefined; } if (state === State.Initializing) { this.progressService.withProgress({ location: VIEWLET_ID, }, _progress => { return new Promise(resolve => this.progressResolve = resolve); }); } this.updateToolBarScheduler.schedule(); } addPanes(panes: { pane: ViewPane, size: number, index?: number }[]): void { super.addPanes(panes); for (const { pane: pane } of panes) { // attach event listener to if (pane.id === BREAKPOINTS_VIEW_ID) { this.breakpointView = pane; this.updateBreakpointsMaxSize(); } else { this.paneListeners.set(pane.id, pane.onDidChange(() => this.updateBreakpointsMaxSize())); } } } removePanes(panes: ViewPane[]): void { super.removePanes(panes); for (const pane of panes) { dispose(this.paneListeners.get(pane.id)); this.paneListeners.delete(pane.id); } } private updateBreakpointsMaxSize(): void { if (this.breakpointView) { // We need to update the breakpoints view since all other views are collapsed #25384 const allOtherCollapsed = this.panes.every(view => !view.isExpanded() || view === this.breakpointView); this.breakpointView.maximumBodySize = allOtherCollapsed ? Number.POSITIVE_INFINITY : this.breakpointView.minimumBodySize; } } } export class OpenDebugConsoleAction extends ToggleViewAction { public static readonly ID = 'workbench.debug.action.toggleRepl'; public static readonly LABEL = nls.localize('toggleDebugPanel', "Debug Console"); constructor( id: string, label: string, @IViewsService viewsService: IViewsService, @IViewDescriptorService viewDescriptorService: IViewDescriptorService, @IContextKeyService contextKeyService: IContextKeyService, @IWorkbenchLayoutService layoutService: IWorkbenchLayoutService ) { super(id, label, REPL_VIEW_ID, viewsService, viewDescriptorService, contextKeyService, layoutService, 'codicon-debug-console'); } } export class OpenDebugViewletAction extends ShowViewletAction { public static readonly ID = VIEWLET_ID; public static readonly LABEL = nls.localize('toggleDebugViewlet', "Show Run and Debug"); constructor( id: string, label: string, @IViewletService viewletService: IViewletService, @IEditorGroupsService editorGroupService: IEditorGroupsService, @IWorkbenchLayoutService layoutService: IWorkbenchLayoutService ) { super(id, label, VIEWLET_ID, viewletService, editorGroupService, layoutService); } }
src/vs/workbench/contrib/debug/browser/debugViewlet.ts
1
https://github.com/microsoft/vscode/commit/135b6da83746477b2983fee879122ceefa70014d
[ 0.9972116351127625, 0.1132885068655014, 0.00016333040548488498, 0.00020446635608095676, 0.30391576886177063 ]
{ "id": 3, "code_window": [ "import { ToggleViewAction } from 'vs/workbench/browser/actions/layoutActions';\n", "import { RunOnceScheduler } from 'vs/base/common/async';\n", "import { ShowViewletAction } from 'vs/workbench/browser/viewlet';\n", "import { IViewletService } from 'vs/workbench/services/viewlet/browser/viewlet';\n", "import { IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService';\n", "\n", "export class DebugViewPaneContainer extends ViewPaneContainer {\n", "\n", "\tprivate startDebugActionViewItem: StartDebugActionViewItem | undefined;\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { StopAction } from 'vs/workbench/contrib/debug/browser/callStackView';\n" ], "file_path": "src/vs/workbench/contrib/debug/browser/debugViewlet.ts", "type": "add", "edit_start_line_idx": 36 }
/*--------------------------------------------------------------------------------------------- * 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 { SnippetCompletionProvider } from 'vs/workbench/contrib/snippets/browser/snippetCompletionProvider'; import { Position } from 'vs/editor/common/core/position'; import { ModesRegistry } from 'vs/editor/common/modes/modesRegistry'; import { ModeServiceImpl } from 'vs/editor/common/services/modeServiceImpl'; import { createTextModel } from 'vs/editor/test/common/editorTestUtils'; import { ISnippetsService } from 'vs/workbench/contrib/snippets/browser/snippets.contribution'; import { Snippet, SnippetSource } from 'vs/workbench/contrib/snippets/browser/snippetsFile'; import { LanguageConfigurationRegistry } from 'vs/editor/common/modes/languageConfigurationRegistry'; import { CompletionContext, CompletionTriggerKind } from 'vs/editor/common/modes'; class SimpleSnippetService implements ISnippetsService { declare readonly _serviceBrand: undefined; constructor(readonly snippets: Snippet[]) { } getSnippets() { return Promise.resolve(this.getSnippetsSync()); } getSnippetsSync(): Snippet[] { return this.snippets; } getSnippetFiles(): any { throw new Error(); } } suite('SnippetsService', function () { suiteSetup(function () { ModesRegistry.registerLanguage({ id: 'fooLang', extensions: ['.fooLang',] }); }); let modeService: ModeServiceImpl; let snippetService: ISnippetsService; let context: CompletionContext = { triggerKind: CompletionTriggerKind.Invoke }; setup(function () { modeService = new ModeServiceImpl(); snippetService = new SimpleSnippetService([new Snippet( ['fooLang'], 'barTest', 'bar', '', 'barCodeSnippet', '', SnippetSource.User ), new Snippet( ['fooLang'], 'bazzTest', 'bazz', '', 'bazzCodeSnippet', '', SnippetSource.User )]); }); test('snippet completions - simple', function () { const provider = new SnippetCompletionProvider(modeService, snippetService); const model = createTextModel('', undefined, modeService.getLanguageIdentifier('fooLang')); return provider.provideCompletionItems(model, new Position(1, 1), context)!.then(result => { assert.equal(result.incomplete, undefined); assert.equal(result.suggestions.length, 2); }); }); test('snippet completions - with prefix', function () { const provider = new SnippetCompletionProvider(modeService, snippetService); const model = createTextModel('bar', undefined, modeService.getLanguageIdentifier('fooLang')); return provider.provideCompletionItems(model, new Position(1, 4), context)!.then(result => { assert.equal(result.incomplete, undefined); assert.equal(result.suggestions.length, 1); assert.deepEqual(result.suggestions[0].label, { name: 'bar', type: 'barTest ()' }); assert.equal((result.suggestions[0].range as any).insert.startColumn, 1); assert.equal(result.suggestions[0].insertText, 'barCodeSnippet'); }); }); test('snippet completions - with different prefixes', async function () { snippetService = new SimpleSnippetService([new Snippet( ['fooLang'], 'barTest', 'bar', '', 's1', '', SnippetSource.User ), new Snippet( ['fooLang'], 'name', 'bar-bar', '', 's2', '', SnippetSource.User )]); const provider = new SnippetCompletionProvider(modeService, snippetService); const model = createTextModel('bar-bar', undefined, modeService.getLanguageIdentifier('fooLang')); await provider.provideCompletionItems(model, new Position(1, 3), context)!.then(result => { assert.equal(result.incomplete, undefined); assert.equal(result.suggestions.length, 2); assert.deepEqual(result.suggestions[0].label, { name: 'bar', type: 'barTest ()' }); assert.equal(result.suggestions[0].insertText, 's1'); assert.equal((result.suggestions[0].range as any).insert.startColumn, 1); assert.deepEqual(result.suggestions[1].label, { name: 'bar-bar', type: 'name ()' }); assert.equal(result.suggestions[1].insertText, 's2'); assert.equal((result.suggestions[1].range as any).insert.startColumn, 1); }); await provider.provideCompletionItems(model, new Position(1, 5), context)!.then(result => { assert.equal(result.incomplete, undefined); assert.equal(result.suggestions.length, 1); assert.deepEqual(result.suggestions[0].label, { name: 'bar-bar', type: 'name ()' }); assert.equal(result.suggestions[0].insertText, 's2'); assert.equal((result.suggestions[0].range as any).insert.startColumn, 1); }); await provider.provideCompletionItems(model, new Position(1, 6), context)!.then(result => { assert.equal(result.incomplete, undefined); assert.equal(result.suggestions.length, 2); assert.deepEqual(result.suggestions[0].label, { name: 'bar', type: 'barTest ()' }); assert.equal(result.suggestions[0].insertText, 's1'); assert.equal((result.suggestions[0].range as any).insert.startColumn, 5); assert.deepEqual(result.suggestions[1].label, { name: 'bar-bar', type: 'name ()' }); assert.equal(result.suggestions[1].insertText, 's2'); assert.equal((result.suggestions[1].range as any).insert.startColumn, 1); }); }); test('Cannot use "<?php" as user snippet prefix anymore, #26275', function () { snippetService = new SimpleSnippetService([new Snippet( ['fooLang'], '', '<?php', '', 'insert me', '', SnippetSource.User )]); const provider = new SnippetCompletionProvider(modeService, snippetService); let model = createTextModel('\t<?php', undefined, modeService.getLanguageIdentifier('fooLang')); return provider.provideCompletionItems(model, new Position(1, 7), context)!.then(result => { assert.equal(result.suggestions.length, 1); model.dispose(); model = createTextModel('\t<?', undefined, modeService.getLanguageIdentifier('fooLang')); return provider.provideCompletionItems(model, new Position(1, 4), context)!; }).then(result => { assert.equal(result.suggestions.length, 1); assert.equal((result.suggestions[0].range as any).insert.startColumn, 2); model.dispose(); model = createTextModel('a<?', undefined, modeService.getLanguageIdentifier('fooLang')); return provider.provideCompletionItems(model, new Position(1, 4), context)!; }).then(result => { assert.equal(result.suggestions.length, 1); assert.equal((result.suggestions[0].range as any).insert.startColumn, 2); model.dispose(); }); }); test('No user snippets in suggestions, when inside the code, #30508', function () { snippetService = new SimpleSnippetService([new Snippet( ['fooLang'], '', 'foo', '', '<foo>$0</foo>', '', SnippetSource.User )]); const provider = new SnippetCompletionProvider(modeService, snippetService); let model = createTextModel('<head>\n\t\n>/head>', undefined, modeService.getLanguageIdentifier('fooLang')); return provider.provideCompletionItems(model, new Position(1, 1), context)!.then(result => { assert.equal(result.suggestions.length, 1); return provider.provideCompletionItems(model, new Position(2, 2), context)!; }).then(result => { assert.equal(result.suggestions.length, 1); }); }); test('SnippetSuggest - ensure extension snippets come last ', function () { snippetService = new SimpleSnippetService([new Snippet( ['fooLang'], 'second', 'second', '', 'second', '', SnippetSource.Extension ), new Snippet( ['fooLang'], 'first', 'first', '', 'first', '', SnippetSource.User )]); const provider = new SnippetCompletionProvider(modeService, snippetService); let model = createTextModel('', undefined, modeService.getLanguageIdentifier('fooLang')); return provider.provideCompletionItems(model, new Position(1, 1), context)!.then(result => { assert.equal(result.suggestions.length, 2); let [first, second] = result.suggestions; assert.deepEqual(first.label, { name: 'first', type: 'first ()' }); assert.deepEqual(second.label, { name: 'second', type: 'second ()' }); }); }); test('Dash in snippets prefix broken #53945', async function () { snippetService = new SimpleSnippetService([new Snippet( ['fooLang'], 'p-a', 'p-a', '', 'second', '', SnippetSource.User )]); const provider = new SnippetCompletionProvider(modeService, snippetService); let model = createTextModel('p-', undefined, modeService.getLanguageIdentifier('fooLang')); let result = await provider.provideCompletionItems(model, new Position(1, 2), context)!; assert.equal(result.suggestions.length, 1); result = await provider.provideCompletionItems(model, new Position(1, 3), context)!; assert.equal(result.suggestions.length, 1); result = await provider.provideCompletionItems(model, new Position(1, 3), context)!; assert.equal(result.suggestions.length, 1); }); test('No snippets suggestion on long lines beyond character 100 #58807', async function () { snippetService = new SimpleSnippetService([new Snippet( ['fooLang'], 'bug', 'bug', '', 'second', '', SnippetSource.User )]); const provider = new SnippetCompletionProvider(modeService, snippetService); let model = createTextModel('Thisisaverylonglinegoingwithmore100bcharactersandthismakesintellisensebecomea Thisisaverylonglinegoingwithmore100bcharactersandthismakesintellisensebecomea b', undefined, modeService.getLanguageIdentifier('fooLang')); let result = await provider.provideCompletionItems(model, new Position(1, 158), context)!; assert.equal(result.suggestions.length, 1); }); test('Type colon will trigger snippet #60746', async function () { snippetService = new SimpleSnippetService([new Snippet( ['fooLang'], 'bug', 'bug', '', 'second', '', SnippetSource.User )]); const provider = new SnippetCompletionProvider(modeService, snippetService); let model = createTextModel(':', undefined, modeService.getLanguageIdentifier('fooLang')); let result = await provider.provideCompletionItems(model, new Position(1, 2), context)!; assert.equal(result.suggestions.length, 0); }); test('substring of prefix can\'t trigger snippet #60737', async function () { snippetService = new SimpleSnippetService([new Snippet( ['fooLang'], 'mytemplate', 'mytemplate', '', 'second', '', SnippetSource.User )]); const provider = new SnippetCompletionProvider(modeService, snippetService); let model = createTextModel('template', undefined, modeService.getLanguageIdentifier('fooLang')); let result = await provider.provideCompletionItems(model, new Position(1, 9), context)!; assert.equal(result.suggestions.length, 1); assert.deepEqual(result.suggestions[0].label, { name: 'mytemplate', type: 'mytemplate ()' }); }); test('No snippets suggestion beyond character 100 if not at end of line #60247', async function () { snippetService = new SimpleSnippetService([new Snippet( ['fooLang'], 'bug', 'bug', '', 'second', '', SnippetSource.User )]); const provider = new SnippetCompletionProvider(modeService, snippetService); let model = createTextModel('Thisisaverylonglinegoingwithmore100bcharactersandthismakesintellisensebecomea Thisisaverylonglinegoingwithmore100bcharactersandthismakesintellisensebecomea b text_after_b', undefined, modeService.getLanguageIdentifier('fooLang')); let result = await provider.provideCompletionItems(model, new Position(1, 158), context)!; assert.equal(result.suggestions.length, 1); }); test('issue #61296: VS code freezes when editing CSS file with emoji', async function () { let toDispose = LanguageConfigurationRegistry.register(modeService.getLanguageIdentifier('fooLang')!, { wordPattern: /(#?-?\d*\.\d\w*%?)|(::?[\w-]*(?=[^,{;]*[,{]))|(([@#.!])?[\w-?]+%?|[@#!.])/g }); snippetService = new SimpleSnippetService([new Snippet( ['fooLang'], 'bug', '-a-bug', '', 'second', '', SnippetSource.User )]); const provider = new SnippetCompletionProvider(modeService, snippetService); let model = createTextModel('.🐷-a-b', undefined, modeService.getLanguageIdentifier('fooLang')); let result = await provider.provideCompletionItems(model, new Position(1, 8), context)!; assert.equal(result.suggestions.length, 1); toDispose.dispose(); }); test('No snippets shown when triggering completions at whitespace on line that already has text #62335', async function () { snippetService = new SimpleSnippetService([new Snippet( ['fooLang'], 'bug', 'bug', '', 'second', '', SnippetSource.User )]); const provider = new SnippetCompletionProvider(modeService, snippetService); let model = createTextModel('a ', undefined, modeService.getLanguageIdentifier('fooLang')); let result = await provider.provideCompletionItems(model, new Position(1, 3), context)!; assert.equal(result.suggestions.length, 1); }); test('Snippet prefix with special chars and numbers does not work #62906', async function () { snippetService = new SimpleSnippetService([new Snippet( ['fooLang'], 'noblockwdelay', '<<', '', '<= #dly"', '', SnippetSource.User ), new Snippet( ['fooLang'], 'noblockwdelay', '11', '', 'eleven', '', SnippetSource.User )]); const provider = new SnippetCompletionProvider(modeService, snippetService); let model = createTextModel(' <', undefined, modeService.getLanguageIdentifier('fooLang')); let result = await provider.provideCompletionItems(model, new Position(1, 3), context)!; assert.equal(result.suggestions.length, 1); let [first] = result.suggestions; assert.equal((first.range as any).insert.startColumn, 2); model = createTextModel('1', undefined, modeService.getLanguageIdentifier('fooLang')); result = await provider.provideCompletionItems(model, new Position(1, 2), context)!; assert.equal(result.suggestions.length, 1); [first] = result.suggestions; assert.equal((first.range as any).insert.startColumn, 1); }); test('Snippet replace range', async function () { snippetService = new SimpleSnippetService([new Snippet( ['fooLang'], 'notWordTest', 'not word', '', 'not word snippet', '', SnippetSource.User )]); const provider = new SnippetCompletionProvider(modeService, snippetService); let model = createTextModel('not wordFoo bar', undefined, modeService.getLanguageIdentifier('fooLang')); let result = await provider.provideCompletionItems(model, new Position(1, 3), context)!; assert.equal(result.suggestions.length, 1); let [first] = result.suggestions; assert.equal((first.range as any).insert.endColumn, 3); assert.equal((first.range as any).replace.endColumn, 9); model = createTextModel('not woFoo bar', undefined, modeService.getLanguageIdentifier('fooLang')); result = await provider.provideCompletionItems(model, new Position(1, 3), context)!; assert.equal(result.suggestions.length, 1); [first] = result.suggestions; assert.equal((first.range as any).insert.endColumn, 3); assert.equal((first.range as any).replace.endColumn, 3); model = createTextModel('not word', undefined, modeService.getLanguageIdentifier('fooLang')); result = await provider.provideCompletionItems(model, new Position(1, 1), context)!; assert.equal(result.suggestions.length, 1); [first] = result.suggestions; assert.equal((first.range as any).insert.endColumn, 1); assert.equal((first.range as any).replace.endColumn, 9); }); });
src/vs/workbench/contrib/snippets/test/browser/snippetsService.test.ts
0
https://github.com/microsoft/vscode/commit/135b6da83746477b2983fee879122ceefa70014d
[ 0.0001858984469436109, 0.000173429143615067, 0.0001693550293566659, 0.00017333534196950495, 0.000002422900706733344 ]
{ "id": 3, "code_window": [ "import { ToggleViewAction } from 'vs/workbench/browser/actions/layoutActions';\n", "import { RunOnceScheduler } from 'vs/base/common/async';\n", "import { ShowViewletAction } from 'vs/workbench/browser/viewlet';\n", "import { IViewletService } from 'vs/workbench/services/viewlet/browser/viewlet';\n", "import { IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService';\n", "\n", "export class DebugViewPaneContainer extends ViewPaneContainer {\n", "\n", "\tprivate startDebugActionViewItem: StartDebugActionViewItem | undefined;\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { StopAction } from 'vs/workbench/contrib/debug/browser/callStackView';\n" ], "file_path": "src/vs/workbench/contrib/debug/browser/debugViewlet.ts", "type": "add", "edit_start_line_idx": 36 }
/*--------------------------------------------------------------------------------------------- * 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 { joinPath } from 'vs/base/common/resources'; import { URI } from 'vs/base/common/uri'; import { fixRegexNewline, IRgMatch, IRgMessage, RipgrepParser, unicodeEscapesToPCRE2, fixNewline } from 'vs/workbench/services/search/node/ripgrepTextSearchEngine'; import { Range, TextSearchResult } from 'vs/workbench/services/search/common/searchExtTypes'; suite('RipgrepTextSearchEngine', () => { test('unicodeEscapesToPCRE2', async () => { assert.equal(unicodeEscapesToPCRE2('\\u1234'), '\\x{1234}'); assert.equal(unicodeEscapesToPCRE2('\\u1234\\u0001'), '\\x{1234}\\x{0001}'); assert.equal(unicodeEscapesToPCRE2('foo\\u1234bar'), 'foo\\x{1234}bar'); assert.equal(unicodeEscapesToPCRE2('\\\\\\u1234'), '\\\\\\x{1234}'); assert.equal(unicodeEscapesToPCRE2('foo\\\\\\u1234'), 'foo\\\\\\x{1234}'); assert.equal(unicodeEscapesToPCRE2('\\u{1234}'), '\\x{1234}'); assert.equal(unicodeEscapesToPCRE2('\\u{1234}\\u{0001}'), '\\x{1234}\\x{0001}'); assert.equal(unicodeEscapesToPCRE2('foo\\u{1234}bar'), 'foo\\x{1234}bar'); assert.equal(unicodeEscapesToPCRE2('foo\\u{123456}7bar'), 'foo\\u{123456}7bar'); assert.equal(unicodeEscapesToPCRE2('\\u123'), '\\u123'); assert.equal(unicodeEscapesToPCRE2('foo'), 'foo'); assert.equal(unicodeEscapesToPCRE2(''), ''); }); test('fixRegexNewline', () => { function testFixRegexNewline([inputReg, testStr, shouldMatch]: readonly [string, string, boolean]): void { const fixed = fixRegexNewline(inputReg); const reg = new RegExp(fixed); assert.equal(reg.test(testStr), shouldMatch, `${inputReg} => ${reg}, ${testStr}, ${shouldMatch}`); } ([ ['foo', 'foo', true], ['foo\\n', 'foo\r\n', true], ['foo\\n\\n', 'foo\n\n', true], ['foo\\n\\n', 'foo\r\n\r\n', true], ['foo\\n', 'foo\n', true], ['foo\\nabc', 'foo\r\nabc', true], ['foo\\nabc', 'foo\nabc', true], ['foo\\r\\n', 'foo\r\n', true], ['foo\\n+abc', 'foo\r\nabc', true], ['foo\\n+abc', 'foo\n\n\nabc', true], ] as const).forEach(testFixRegexNewline); }); test('fixNewline', () => { function testFixNewline([inputReg, testStr, shouldMatch = true]: readonly [string, string, boolean?]): void { const fixed = fixNewline(inputReg); const reg = new RegExp(fixed); assert.equal(reg.test(testStr), shouldMatch, `${inputReg} => ${reg}, ${testStr}, ${shouldMatch}`); } ([ ['foo', 'foo'], ['foo\n', 'foo\r\n'], ['foo\n', 'foo\n'], ['foo\nabc', 'foo\r\nabc'], ['foo\nabc', 'foo\nabc'], ['foo\r\n', 'foo\r\n'], ['foo\nbarc', 'foobar', false], ['foobar', 'foo\nbar', false], ] as const).forEach(testFixNewline); }); suite('RipgrepParser', () => { const TEST_FOLDER = URI.file('/foo/bar'); function testParser(inputData: string[], expectedResults: TextSearchResult[]): void { const testParser = new RipgrepParser(1000, TEST_FOLDER.fsPath); const actualResults: TextSearchResult[] = []; testParser.on('result', r => { actualResults.push(r); }); inputData.forEach(d => testParser.handleData(d)); testParser.flush(); assert.deepEqual(actualResults, expectedResults); } function makeRgMatch(relativePath: string, text: string, lineNumber: number, matchRanges: { start: number, end: number }[]): string { return JSON.stringify(<IRgMessage>{ type: 'match', data: <IRgMatch>{ path: { text: relativePath }, lines: { text }, line_number: lineNumber, absolute_offset: 0, // unused submatches: matchRanges.map(mr => { return { ...mr, match: { text: text.substring(mr.start, mr.end) } }; }) } }) + '\n'; } test('single result', () => { testParser( [ makeRgMatch('file1.js', 'foobar', 4, [{ start: 3, end: 6 }]) ], [ { preview: { text: 'foobar', matches: [new Range(0, 3, 0, 6)] }, uri: joinPath(TEST_FOLDER, 'file1.js'), ranges: [new Range(3, 3, 3, 6)] } ]); }); test('multiple results', () => { testParser( [ makeRgMatch('file1.js', 'foobar', 4, [{ start: 3, end: 6 }]), makeRgMatch('app/file2.js', 'foobar', 4, [{ start: 3, end: 6 }]), makeRgMatch('app2/file3.js', 'foobar', 4, [{ start: 3, end: 6 }]), ], [ { preview: { text: 'foobar', matches: [new Range(0, 3, 0, 6)] }, uri: joinPath(TEST_FOLDER, 'file1.js'), ranges: [new Range(3, 3, 3, 6)] }, { preview: { text: 'foobar', matches: [new Range(0, 3, 0, 6)] }, uri: joinPath(TEST_FOLDER, 'app/file2.js'), ranges: [new Range(3, 3, 3, 6)] }, { preview: { text: 'foobar', matches: [new Range(0, 3, 0, 6)] }, uri: joinPath(TEST_FOLDER, 'app2/file3.js'), ranges: [new Range(3, 3, 3, 6)] } ]); }); test('chopped-up input chunks', () => { const dataStrs = [ makeRgMatch('file1.js', 'foo bar', 4, [{ start: 3, end: 7 }]), makeRgMatch('app/file2.js', 'foobar', 4, [{ start: 3, end: 6 }]), makeRgMatch('app2/file3.js', 'foobar', 4, [{ start: 3, end: 6 }]), ]; const dataStr0Space = dataStrs[0].indexOf(' '); testParser( [ dataStrs[0].substring(0, dataStr0Space + 1), dataStrs[0].substring(dataStr0Space + 1), '\n', dataStrs[1].trim(), '\n' + dataStrs[2].substring(0, 25), dataStrs[2].substring(25) ], [ { preview: { text: 'foo bar', matches: [new Range(0, 3, 0, 7)] }, uri: joinPath(TEST_FOLDER, 'file1.js'), ranges: [new Range(3, 3, 3, 7)] }, { preview: { text: 'foobar', matches: [new Range(0, 3, 0, 6)] }, uri: joinPath(TEST_FOLDER, 'app/file2.js'), ranges: [new Range(3, 3, 3, 6)] }, { preview: { text: 'foobar', matches: [new Range(0, 3, 0, 6)] }, uri: joinPath(TEST_FOLDER, 'app2/file3.js'), ranges: [new Range(3, 3, 3, 6)] } ]); }); }); });
src/vs/workbench/services/search/test/node/ripgrepTextSearchEngine.test.ts
0
https://github.com/microsoft/vscode/commit/135b6da83746477b2983fee879122ceefa70014d
[ 0.00017649252549745142, 0.0001727430644677952, 0.0001670933561399579, 0.00017313795979134738, 0.0000022853073460282758 ]
{ "id": 3, "code_window": [ "import { ToggleViewAction } from 'vs/workbench/browser/actions/layoutActions';\n", "import { RunOnceScheduler } from 'vs/base/common/async';\n", "import { ShowViewletAction } from 'vs/workbench/browser/viewlet';\n", "import { IViewletService } from 'vs/workbench/services/viewlet/browser/viewlet';\n", "import { IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService';\n", "\n", "export class DebugViewPaneContainer extends ViewPaneContainer {\n", "\n", "\tprivate startDebugActionViewItem: StartDebugActionViewItem | undefined;\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { StopAction } from 'vs/workbench/contrib/debug/browser/callStackView';\n" ], "file_path": "src/vs/workbench/contrib/debug/browser/debugViewlet.ts", "type": "add", "edit_start_line_idx": 36 }
/*--------------------------------------------------------------------------------------------- * 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 nls from 'vscode-nls'; import { PreviewStatusBarEntry } from './ownedStatusBarEntry'; const localize = nls.loadMessageBundle(); class BinarySize { static readonly KB = 1024; static readonly MB = BinarySize.KB * BinarySize.KB; static readonly GB = BinarySize.MB * BinarySize.KB; static readonly TB = BinarySize.GB * BinarySize.KB; static formatSize(size: number): string { if (size < BinarySize.KB) { return localize('sizeB', "{0}B", size); } if (size < BinarySize.MB) { return localize('sizeKB', "{0}KB", (size / BinarySize.KB).toFixed(2)); } if (size < BinarySize.GB) { return localize('sizeMB', "{0}MB", (size / BinarySize.MB).toFixed(2)); } if (size < BinarySize.TB) { return localize('sizeGB', "{0}GB", (size / BinarySize.GB).toFixed(2)); } return localize('sizeTB', "{0}TB", (size / BinarySize.TB).toFixed(2)); } } export class BinarySizeStatusBarEntry extends PreviewStatusBarEntry { constructor() { super({ id: 'imagePreview.binarySize', name: localize('sizeStatusBar.name', "Image Binary Size"), alignment: vscode.StatusBarAlignment.Right, priority: 100, }); } public show(owner: string, size: number | undefined) { if (typeof size === 'number') { super.showItem(owner, BinarySize.formatSize(size)); } else { this.hide(owner); } } }
extensions/image-preview/src/binarySizeStatusBarEntry.ts
0
https://github.com/microsoft/vscode/commit/135b6da83746477b2983fee879122ceefa70014d
[ 0.0001769498485373333, 0.00017043208936229348, 0.00016172241885215044, 0.0001708601921563968, 0.000004655690190702444 ]
{ "id": 4, "code_window": [ "\t) {\n", "\t\tsuper(VIEWLET_ID, { mergeViewWithContainerWhenSingleView: true }, instantiationService, configurationService, layoutService, contextMenuService, telemetryService, extensionService, themeService, storageService, contextService, viewDescriptorService);\n", "\n", "\t\tthis.updateToolBarScheduler = this._register(new RunOnceScheduler(() => {\n", "\t\t\tif (this.configurationService.getValue<IDebugConfiguration>('debug').toolBarLocation === 'docked') {\n", "\t\t\t\tthis.updateTitleArea();\n", "\t\t\t}\n", "\t\t}, 20));\n", "\n", "\t\t// When there are potential updates to the docked debug toolbar we need to update it\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tthis.updateTitleArea();\n" ], "file_path": "src/vs/workbench/contrib/debug/browser/debugViewlet.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 nls from 'vs/nls'; import { RunOnceScheduler } from 'vs/base/common/async'; import * as dom from 'vs/base/browser/dom'; import { IViewletViewOptions } from 'vs/workbench/browser/parts/views/viewsViewlet'; import { IDebugService, State, IStackFrame, IDebugSession, IThread, CONTEXT_CALLSTACK_ITEM_TYPE, IDebugModel } from 'vs/workbench/contrib/debug/common/debug'; import { Thread, StackFrame, ThreadAndSessionIds } from 'vs/workbench/contrib/debug/common/debugModel'; import { IContextMenuService } from 'vs/platform/contextview/browser/contextView'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { MenuId, IMenu, IMenuService, MenuItemAction, SubmenuItemAction } from 'vs/platform/actions/common/actions'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; import { renderViewTree } from 'vs/workbench/contrib/debug/browser/baseDebugView'; import { IAction, Action } from 'vs/base/common/actions'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IContextKey, IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { ViewPane } from 'vs/workbench/browser/parts/views/viewPaneContainer'; import { ILabelService } from 'vs/platform/label/common/label'; import { IListAccessibilityProvider } from 'vs/base/browser/ui/list/listWidget'; import { createAndFillInContextMenuActions, createAndFillInActionBarActions, MenuEntryActionViewItem, SubmenuEntryActionViewItem } from 'vs/platform/actions/browser/menuEntryActionViewItem'; import { IListVirtualDelegate } from 'vs/base/browser/ui/list/list'; import { ITreeNode, ITreeContextMenuEvent, IAsyncDataSource } from 'vs/base/browser/ui/tree/tree'; import { WorkbenchCompressibleAsyncDataTree } from 'vs/platform/list/browser/listService'; import { HighlightedLabel } from 'vs/base/browser/ui/highlightedlabel/highlightedLabel'; import { createMatches, FuzzyScore, IMatch } from 'vs/base/common/filters'; import { Event } from 'vs/base/common/event'; import { dispose, IDisposable } from 'vs/base/common/lifecycle'; import { ActionBar } from 'vs/base/browser/ui/actionbar/actionbar'; import { isSessionAttach } from 'vs/workbench/contrib/debug/common/debugUtils'; import { STOP_ID, STOP_LABEL, DISCONNECT_ID, DISCONNECT_LABEL, RESTART_SESSION_ID, RESTART_LABEL, STEP_OVER_ID, STEP_OVER_LABEL, STEP_INTO_LABEL, STEP_INTO_ID, STEP_OUT_LABEL, STEP_OUT_ID, PAUSE_ID, PAUSE_LABEL, CONTINUE_ID, CONTINUE_LABEL } from 'vs/workbench/contrib/debug/browser/debugCommands'; import { ICommandService } from 'vs/platform/commands/common/commands'; import { CollapseAction } from 'vs/workbench/browser/viewlet'; import { IViewDescriptorService } from 'vs/workbench/common/views'; import { textLinkForeground } from 'vs/platform/theme/common/colorRegistry'; import { IThemeService } from 'vs/platform/theme/common/themeService'; import { IOpenerService } from 'vs/platform/opener/common/opener'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { attachStylerCallback } from 'vs/platform/theme/common/styler'; import { INotificationService } from 'vs/platform/notification/common/notification'; import { commonSuffixLength } from 'vs/base/common/strings'; import { posix } from 'vs/base/common/path'; import { ITreeCompressionDelegate } from 'vs/base/browser/ui/tree/asyncDataTree'; import { ICompressibleTreeRenderer } from 'vs/base/browser/ui/tree/objectTree'; import { ICompressedTreeNode } from 'vs/base/browser/ui/tree/compressedObjectTreeModel'; const $ = dom.$; type CallStackItem = IStackFrame | IThread | IDebugSession | string | ThreadAndSessionIds | IStackFrame[]; export function getContext(element: CallStackItem | null): any { return element instanceof StackFrame ? { sessionId: element.thread.session.getId(), threadId: element.thread.getId(), frameId: element.getId() } : element instanceof Thread ? { sessionId: element.session.getId(), threadId: element.getId() } : isDebugSession(element) ? { sessionId: element.getId() } : undefined; } // Extensions depend on this context, should not be changed even though it is not fully deterministic export function getContextForContributedActions(element: CallStackItem | null): string | number { if (element instanceof StackFrame) { if (element.source.inMemory) { return element.source.raw.path || element.source.reference || element.source.name; } return element.source.uri.toString(); } if (element instanceof Thread) { return element.threadId; } if (isDebugSession(element)) { return element.getId(); } return ''; } export function getSpecificSourceName(stackFrame: IStackFrame): string { // To reduce flashing of the path name and the way we fetch stack frames // We need to compute the source name based on the other frames in the stale call stack let callStack = (<Thread>stackFrame.thread).getStaleCallStack(); callStack = callStack.length > 0 ? callStack : stackFrame.thread.getCallStack(); const otherSources = callStack.map(sf => sf.source).filter(s => s !== stackFrame.source); let suffixLength = 0; otherSources.forEach(s => { if (s.name === stackFrame.source.name) { suffixLength = Math.max(suffixLength, commonSuffixLength(stackFrame.source.uri.path, s.uri.path)); } }); if (suffixLength === 0) { return stackFrame.source.name; } const from = Math.max(0, stackFrame.source.uri.path.lastIndexOf(posix.sep, stackFrame.source.uri.path.length - suffixLength - 1)); return (from > 0 ? '...' : '') + stackFrame.source.uri.path.substr(from); } async function expandTo(session: IDebugSession, tree: WorkbenchCompressibleAsyncDataTree<IDebugModel, CallStackItem, FuzzyScore>): Promise<void> { if (session.parentSession) { await expandTo(session.parentSession, tree); } await tree.expand(session); } export class CallStackView extends ViewPane { private pauseMessage!: HTMLSpanElement; private pauseMessageLabel!: HTMLSpanElement; private onCallStackChangeScheduler: RunOnceScheduler; private needsRefresh = false; private ignoreSelectionChangedEvent = false; private ignoreFocusStackFrameEvent = false; private callStackItemType: IContextKey<string>; private dataSource!: CallStackDataSource; private tree!: WorkbenchCompressibleAsyncDataTree<IDebugModel, CallStackItem, FuzzyScore>; private menu: IMenu; private autoExpandedSessions = new Set<IDebugSession>(); private selectionNeedsUpdate = false; constructor( private options: IViewletViewOptions, @IContextMenuService contextMenuService: IContextMenuService, @IDebugService private readonly debugService: IDebugService, @IKeybindingService keybindingService: IKeybindingService, @IInstantiationService instantiationService: IInstantiationService, @IViewDescriptorService viewDescriptorService: IViewDescriptorService, @IEditorService private readonly editorService: IEditorService, @IConfigurationService configurationService: IConfigurationService, @IMenuService menuService: IMenuService, @IContextKeyService readonly contextKeyService: IContextKeyService, @IOpenerService openerService: IOpenerService, @IThemeService themeService: IThemeService, @ITelemetryService telemetryService: ITelemetryService, ) { super(options, keybindingService, contextMenuService, configurationService, contextKeyService, viewDescriptorService, instantiationService, openerService, themeService, telemetryService); this.callStackItemType = CONTEXT_CALLSTACK_ITEM_TYPE.bindTo(contextKeyService); this.menu = menuService.createMenu(MenuId.DebugCallStackContext, contextKeyService); this._register(this.menu); // Create scheduler to prevent unnecessary flashing of tree when reacting to changes this.onCallStackChangeScheduler = new RunOnceScheduler(async () => { // Only show the global pause message if we do not display threads. // Otherwise there will be a pause message per thread and there is no need for a global one. const sessions = this.debugService.getModel().getSessions(); if (sessions.length === 0) { this.autoExpandedSessions.clear(); } const thread = sessions.length === 1 && sessions[0].getAllThreads().length === 1 ? sessions[0].getAllThreads()[0] : undefined; if (thread && thread.stoppedDetails) { this.pauseMessageLabel.textContent = thread.stoppedDetails.description || nls.localize('debugStopped', "Paused on {0}", thread.stoppedDetails.reason || ''); this.pauseMessageLabel.title = thread.stoppedDetails.text || ''; dom.toggleClass(this.pauseMessageLabel, 'exception', thread.stoppedDetails.reason === 'exception'); this.pauseMessage.hidden = false; this.updateActions(); } else { this.pauseMessage.hidden = true; this.updateActions(); } this.needsRefresh = false; this.dataSource.deemphasizedStackFramesToShow = []; await this.tree.updateChildren(); try { const toExpand = new Set<IDebugSession>(); sessions.forEach(s => { // Automatically expand sessions that have children, but only do this once. if (s.parentSession && !this.autoExpandedSessions.has(s.parentSession)) { toExpand.add(s.parentSession); } }); for (let session of toExpand) { await expandTo(session, this.tree); this.autoExpandedSessions.add(session); } } catch (e) { // Ignore tree expand errors if element no longer present } if (this.selectionNeedsUpdate) { this.selectionNeedsUpdate = false; await this.updateTreeSelection(); } }, 50); } protected renderHeaderTitle(container: HTMLElement): void { const titleContainer = dom.append(container, $('.debug-call-stack-title')); super.renderHeaderTitle(titleContainer, this.options.title); this.pauseMessage = dom.append(titleContainer, $('span.pause-message')); this.pauseMessage.hidden = true; this.pauseMessageLabel = dom.append(this.pauseMessage, $('span.label')); } getActions(): IAction[] { if (this.pauseMessage.hidden) { return [new CollapseAction(() => this.tree, true, 'explorer-action codicon-collapse-all')]; } return []; } renderBody(container: HTMLElement): void { super.renderBody(container); dom.addClass(this.element, 'debug-pane'); dom.addClass(container, 'debug-call-stack'); const treeContainer = renderViewTree(container); this.dataSource = new CallStackDataSource(this.debugService); const sessionsRenderer = this.instantiationService.createInstance(SessionsRenderer, this.menu); this.tree = <WorkbenchCompressibleAsyncDataTree<IDebugModel, CallStackItem, FuzzyScore>>this.instantiationService.createInstance(WorkbenchCompressibleAsyncDataTree, 'CallStackView', treeContainer, new CallStackDelegate(), new CallStackCompressionDelegate(this.debugService), [ sessionsRenderer, new ThreadsRenderer(this.instantiationService), this.instantiationService.createInstance(StackFramesRenderer), new ErrorsRenderer(), new LoadAllRenderer(this.themeService), new ShowMoreRenderer(this.themeService) ], this.dataSource, { accessibilityProvider: new CallStackAccessibilityProvider(), compressionEnabled: true, autoExpandSingleChildren: true, identityProvider: { getId: (element: CallStackItem) => { if (typeof element === 'string') { return element; } if (element instanceof Array) { return `showMore ${element[0].getId()}`; } return element.getId(); } }, keyboardNavigationLabelProvider: { getKeyboardNavigationLabel: (e: CallStackItem) => { if (isDebugSession(e)) { return e.getLabel(); } if (e instanceof Thread) { return `${e.name} ${e.stateLabel}`; } if (e instanceof StackFrame || typeof e === 'string') { return e; } if (e instanceof ThreadAndSessionIds) { return LoadAllRenderer.LABEL; } return nls.localize('showMoreStackFrames2', "Show More Stack Frames"); }, getCompressedNodeKeyboardNavigationLabel: (e: CallStackItem[]) => { const firstItem = e[0]; if (isDebugSession(firstItem)) { return firstItem.getLabel(); } return ''; } }, expandOnlyOnTwistieClick: true, overrideStyles: { listBackground: this.getBackgroundColor() } }); this.tree.setInput(this.debugService.getModel()); this._register(this.tree.onDidOpen(async e => { if (this.ignoreSelectionChangedEvent) { return; } const focusStackFrame = (stackFrame: IStackFrame | undefined, thread: IThread | undefined, session: IDebugSession) => { this.ignoreFocusStackFrameEvent = true; try { this.debugService.focusStackFrame(stackFrame, thread, session, true); } finally { this.ignoreFocusStackFrameEvent = false; } }; const element = e.element; if (element instanceof StackFrame) { focusStackFrame(element, element.thread, element.thread.session); element.openInEditor(this.editorService, e.editorOptions.preserveFocus, e.sideBySide, e.editorOptions.pinned); } if (element instanceof Thread) { focusStackFrame(undefined, element, element.session); } if (isDebugSession(element)) { focusStackFrame(undefined, undefined, element); } if (element instanceof ThreadAndSessionIds) { const session = this.debugService.getModel().getSession(element.sessionId); const thread = session && session.getThread(element.threadId); if (thread) { const totalFrames = thread.stoppedDetails?.totalFrames; const remainingFramesCount = typeof totalFrames === 'number' ? (totalFrames - thread.getCallStack().length) : undefined; // Get all the remaining frames await (<Thread>thread).fetchCallStack(remainingFramesCount); await this.tree.updateChildren(); } } if (element instanceof Array) { this.dataSource.deemphasizedStackFramesToShow.push(...element); this.tree.updateChildren(); } })); this._register(this.debugService.getModel().onDidChangeCallStack(() => { if (!this.isBodyVisible()) { this.needsRefresh = true; return; } if (!this.onCallStackChangeScheduler.isScheduled()) { this.onCallStackChangeScheduler.schedule(); } })); const onFocusChange = Event.any<any>(this.debugService.getViewModel().onDidFocusStackFrame, this.debugService.getViewModel().onDidFocusSession); this._register(onFocusChange(async () => { if (this.ignoreFocusStackFrameEvent) { return; } if (!this.isBodyVisible()) { this.needsRefresh = true; return; } if (this.onCallStackChangeScheduler.isScheduled()) { this.selectionNeedsUpdate = true; return; } await this.updateTreeSelection(); })); this._register(this.tree.onContextMenu(e => this.onContextMenu(e))); // Schedule the update of the call stack tree if the viewlet is opened after a session started #14684 if (this.debugService.state === State.Stopped) { this.onCallStackChangeScheduler.schedule(0); } this._register(this.onDidChangeBodyVisibility(visible => { if (visible && this.needsRefresh) { this.onCallStackChangeScheduler.schedule(); } })); this._register(this.debugService.onDidNewSession(s => { const sessionListeners: IDisposable[] = []; sessionListeners.push(s.onDidChangeName(() => this.tree.rerender(s))); sessionListeners.push(s.onDidEndAdapter(() => dispose(sessionListeners))); if (s.parentSession) { // A session we already expanded has a new child session, allow to expand it again. this.autoExpandedSessions.delete(s.parentSession); } })); } layoutBody(height: number, width: number): void { super.layoutBody(height, width); this.tree.layout(height, width); } focus(): void { this.tree.domFocus(); } private async updateTreeSelection(): Promise<void> { if (!this.tree || !this.tree.getInput()) { // Tree not initialized yet return; } const updateSelectionAndReveal = (element: IStackFrame | IDebugSession) => { this.ignoreSelectionChangedEvent = true; try { this.tree.setSelection([element]); // If the element is outside of the screen bounds, // position it in the middle if (this.tree.getRelativeTop(element) === null) { this.tree.reveal(element, 0.5); } else { this.tree.reveal(element); } } catch (e) { } finally { this.ignoreSelectionChangedEvent = false; } }; const thread = this.debugService.getViewModel().focusedThread; const session = this.debugService.getViewModel().focusedSession; const stackFrame = this.debugService.getViewModel().focusedStackFrame; if (!thread) { if (!session) { this.tree.setSelection([]); } else { updateSelectionAndReveal(session); } } else { // Ignore errors from this expansions because we are not aware if we rendered the threads and sessions or we hide them to declutter the view try { await expandTo(thread.session, this.tree); } catch (e) { } try { await this.tree.expand(thread); } catch (e) { } const toReveal = stackFrame || session; if (toReveal) { updateSelectionAndReveal(toReveal); } } } private onContextMenu(e: ITreeContextMenuEvent<CallStackItem>): void { const element = e.element; if (isDebugSession(element)) { this.callStackItemType.set('session'); } else if (element instanceof Thread) { this.callStackItemType.set('thread'); } else if (element instanceof StackFrame) { this.callStackItemType.set('stackFrame'); } else { this.callStackItemType.reset(); } const primary: IAction[] = []; const secondary: IAction[] = []; const result = { primary, secondary }; const actionsDisposable = createAndFillInContextMenuActions(this.menu, { arg: getContextForContributedActions(element), shouldForwardArgs: true }, result, this.contextMenuService, g => /^inline/.test(g)); this.contextMenuService.showContextMenu({ getAnchor: () => e.anchor, getActions: () => result.secondary, getActionsContext: () => getContext(element), onHide: () => dispose(actionsDisposable) }); } } interface IThreadTemplateData { thread: HTMLElement; name: HTMLElement; stateLabel: HTMLSpanElement; label: HighlightedLabel; actionBar: ActionBar; } interface ISessionTemplateData { session: HTMLElement; name: HTMLElement; stateLabel: HTMLSpanElement; label: HighlightedLabel; actionBar: ActionBar; elementDisposable: IDisposable[]; } interface IErrorTemplateData { label: HTMLElement; } interface ILabelTemplateData { label: HTMLElement; toDispose: IDisposable; } interface IStackFrameTemplateData { stackFrame: HTMLElement; file: HTMLElement; fileName: HTMLElement; lineNumber: HTMLElement; label: HighlightedLabel; actionBar: ActionBar; } class SessionsRenderer implements ICompressibleTreeRenderer<IDebugSession, FuzzyScore, ISessionTemplateData> { static readonly ID = 'session'; constructor( private menu: IMenu, @IInstantiationService private readonly instantiationService: IInstantiationService ) { } get templateId(): string { return SessionsRenderer.ID; } renderTemplate(container: HTMLElement): ISessionTemplateData { const session = dom.append(container, $('.session')); dom.append(session, $('.codicon.codicon-bug')); const name = dom.append(session, $('.name')); const stateLabel = dom.append(session, $('span.state.label.monaco-count-badge.long')); const label = new HighlightedLabel(name, false); const actionBar = new ActionBar(session, { actionViewItemProvider: action => { if (action instanceof MenuItemAction) { return this.instantiationService.createInstance(MenuEntryActionViewItem, action); } else if (action instanceof SubmenuItemAction) { return this.instantiationService.createInstance(SubmenuEntryActionViewItem, action); } return undefined; } }); return { session, name, stateLabel, label, actionBar, elementDisposable: [] }; } renderElement(element: ITreeNode<IDebugSession, FuzzyScore>, _: number, data: ISessionTemplateData): void { this.doRenderElement(element.element, createMatches(element.filterData), data); } renderCompressedElements(node: ITreeNode<ICompressedTreeNode<IDebugSession>, FuzzyScore>, index: number, templateData: ISessionTemplateData, height: number | undefined): void { const lastElement = node.element.elements[node.element.elements.length - 1]; const matches = createMatches(node.filterData); this.doRenderElement(lastElement, matches, templateData); } private doRenderElement(session: IDebugSession, matches: IMatch[], data: ISessionTemplateData): void { data.session.title = nls.localize({ key: 'session', comment: ['Session is a noun'] }, "Session"); data.label.set(session.getLabel(), matches); const thread = session.getAllThreads().find(t => t.stopped); const setActionBar = () => { const actions = getActions(this.instantiationService, session); const primary: IAction[] = actions; const secondary: IAction[] = []; const result = { primary, secondary }; data.elementDisposable.push(createAndFillInActionBarActions(this.menu, { arg: getContextForContributedActions(session), shouldForwardArgs: true }, result, g => /^inline/.test(g))); data.actionBar.clear(); data.actionBar.push(primary, { icon: true, label: false }); }; setActionBar(); data.elementDisposable.push(this.menu.onDidChange(() => setActionBar())); data.stateLabel.style.display = ''; if (thread && thread.stoppedDetails) { data.stateLabel.textContent = thread.stoppedDetails.description || nls.localize('debugStopped', "Paused on {0}", thread.stoppedDetails.reason || ''); if (thread.stoppedDetails.text) { data.session.title = thread.stoppedDetails.text; } } else { data.stateLabel.textContent = nls.localize({ key: 'running', comment: ['indicates state'] }, "Running"); } } disposeTemplate(templateData: ISessionTemplateData): void { templateData.actionBar.dispose(); } disposeElement(_element: ITreeNode<IDebugSession, FuzzyScore>, _: number, templateData: ISessionTemplateData): void { dispose(templateData.elementDisposable); } } class ThreadsRenderer implements ICompressibleTreeRenderer<IThread, FuzzyScore, IThreadTemplateData> { static readonly ID = 'thread'; constructor(private readonly instantiationService: IInstantiationService) { } get templateId(): string { return ThreadsRenderer.ID; } renderTemplate(container: HTMLElement): IThreadTemplateData { const thread = dom.append(container, $('.thread')); const name = dom.append(thread, $('.name')); const stateLabel = dom.append(thread, $('span.state.label')); const label = new HighlightedLabel(name, false); const actionBar = new ActionBar(thread); return { thread, name, stateLabel, label, actionBar }; } renderElement(element: ITreeNode<IThread, FuzzyScore>, index: number, data: IThreadTemplateData): void { const thread = element.element; data.thread.title = nls.localize('thread', "Thread"); data.label.set(thread.name, createMatches(element.filterData)); data.stateLabel.textContent = thread.stateLabel; data.actionBar.clear(); const actions = getActions(this.instantiationService, thread); data.actionBar.push(actions, { icon: true, label: false }); } renderCompressedElements(node: ITreeNode<ICompressedTreeNode<IThread>, FuzzyScore>, index: number, templateData: IThreadTemplateData, height: number | undefined): void { throw new Error('Method not implemented.'); } disposeTemplate(templateData: IThreadTemplateData): void { templateData.actionBar.dispose(); } } class StackFramesRenderer implements ICompressibleTreeRenderer<IStackFrame, FuzzyScore, IStackFrameTemplateData> { static readonly ID = 'stackFrame'; constructor( @ILabelService private readonly labelService: ILabelService, @INotificationService private readonly notificationService: INotificationService ) { } get templateId(): string { return StackFramesRenderer.ID; } renderTemplate(container: HTMLElement): IStackFrameTemplateData { const stackFrame = dom.append(container, $('.stack-frame')); const labelDiv = dom.append(stackFrame, $('span.label.expression')); const file = dom.append(stackFrame, $('.file')); const fileName = dom.append(file, $('span.file-name')); const wrapper = dom.append(file, $('span.line-number-wrapper')); const lineNumber = dom.append(wrapper, $('span.line-number.monaco-count-badge')); const label = new HighlightedLabel(labelDiv, false); const actionBar = new ActionBar(stackFrame); return { file, fileName, label, lineNumber, stackFrame, actionBar }; } renderElement(element: ITreeNode<IStackFrame, FuzzyScore>, index: number, data: IStackFrameTemplateData): void { const stackFrame = element.element; dom.toggleClass(data.stackFrame, 'disabled', !stackFrame.source || !stackFrame.source.available || isDeemphasized(stackFrame)); dom.toggleClass(data.stackFrame, 'label', stackFrame.presentationHint === 'label'); dom.toggleClass(data.stackFrame, 'subtle', stackFrame.presentationHint === 'subtle'); const hasActions = !!stackFrame.thread.session.capabilities.supportsRestartFrame && stackFrame.presentationHint !== 'label' && stackFrame.presentationHint !== 'subtle'; dom.toggleClass(data.stackFrame, 'has-actions', hasActions); data.file.title = stackFrame.source.inMemory ? stackFrame.source.uri.path : this.labelService.getUriLabel(stackFrame.source.uri); if (stackFrame.source.raw.origin) { data.file.title += `\n${stackFrame.source.raw.origin}`; } data.label.set(stackFrame.name, createMatches(element.filterData), stackFrame.name); data.fileName.textContent = getSpecificSourceName(stackFrame); if (stackFrame.range.startLineNumber !== undefined) { data.lineNumber.textContent = `${stackFrame.range.startLineNumber}`; if (stackFrame.range.startColumn) { data.lineNumber.textContent += `:${stackFrame.range.startColumn}`; } dom.removeClass(data.lineNumber, 'unavailable'); } else { dom.addClass(data.lineNumber, 'unavailable'); } data.actionBar.clear(); if (hasActions) { const action = new Action('debug.callStack.restartFrame', nls.localize('restartFrame', "Restart Frame"), 'codicon-debug-restart-frame', true, async () => { try { await stackFrame.restart(); } catch (e) { this.notificationService.error(e); } }); data.actionBar.push(action, { icon: true, label: false }); } } renderCompressedElements(node: ITreeNode<ICompressedTreeNode<IStackFrame>, FuzzyScore>, index: number, templateData: IStackFrameTemplateData, height: number | undefined): void { throw new Error('Method not implemented.'); } disposeTemplate(templateData: IStackFrameTemplateData): void { templateData.actionBar.dispose(); } } class ErrorsRenderer implements ICompressibleTreeRenderer<string, FuzzyScore, IErrorTemplateData> { static readonly ID = 'error'; get templateId(): string { return ErrorsRenderer.ID; } renderTemplate(container: HTMLElement): IErrorTemplateData { const label = dom.append(container, $('.error')); return { label }; } renderElement(element: ITreeNode<string, FuzzyScore>, index: number, data: IErrorTemplateData): void { const error = element.element; data.label.textContent = error; data.label.title = error; } renderCompressedElements(node: ITreeNode<ICompressedTreeNode<string>, FuzzyScore>, index: number, templateData: IErrorTemplateData, height: number | undefined): void { throw new Error('Method not implemented.'); } disposeTemplate(templateData: IErrorTemplateData): void { // noop } } class LoadAllRenderer implements ICompressibleTreeRenderer<ThreadAndSessionIds, FuzzyScore, ILabelTemplateData> { static readonly ID = 'loadAll'; static readonly LABEL = nls.localize('loadAllStackFrames', "Load All Stack Frames"); constructor(private readonly themeService: IThemeService) { } get templateId(): string { return LoadAllRenderer.ID; } renderTemplate(container: HTMLElement): ILabelTemplateData { const label = dom.append(container, $('.load-all')); const toDispose = attachStylerCallback(this.themeService, { textLinkForeground }, colors => { if (colors.textLinkForeground) { label.style.color = colors.textLinkForeground.toString(); } }); return { label, toDispose }; } renderElement(element: ITreeNode<ThreadAndSessionIds, FuzzyScore>, index: number, data: ILabelTemplateData): void { data.label.textContent = LoadAllRenderer.LABEL; } renderCompressedElements(node: ITreeNode<ICompressedTreeNode<ThreadAndSessionIds>, FuzzyScore>, index: number, templateData: ILabelTemplateData, height: number | undefined): void { throw new Error('Method not implemented.'); } disposeTemplate(templateData: ILabelTemplateData): void { templateData.toDispose.dispose(); } } class ShowMoreRenderer implements ICompressibleTreeRenderer<IStackFrame[], FuzzyScore, ILabelTemplateData> { static readonly ID = 'showMore'; constructor(private readonly themeService: IThemeService) { } get templateId(): string { return ShowMoreRenderer.ID; } renderTemplate(container: HTMLElement): ILabelTemplateData { const label = dom.append(container, $('.show-more')); const toDispose = attachStylerCallback(this.themeService, { textLinkForeground }, colors => { if (colors.textLinkForeground) { label.style.color = colors.textLinkForeground.toString(); } }); return { label, toDispose }; } renderElement(element: ITreeNode<IStackFrame[], FuzzyScore>, index: number, data: ILabelTemplateData): void { const stackFrames = element.element; if (stackFrames.every(sf => !!(sf.source && sf.source.origin && sf.source.origin === stackFrames[0].source.origin))) { data.label.textContent = nls.localize('showMoreAndOrigin', "Show {0} More: {1}", stackFrames.length, stackFrames[0].source.origin); } else { data.label.textContent = nls.localize('showMoreStackFrames', "Show {0} More Stack Frames", stackFrames.length); } } renderCompressedElements(node: ITreeNode<ICompressedTreeNode<IStackFrame[]>, FuzzyScore>, index: number, templateData: ILabelTemplateData, height: number | undefined): void { throw new Error('Method not implemented.'); } disposeTemplate(templateData: ILabelTemplateData): void { templateData.toDispose.dispose(); } } class CallStackDelegate implements IListVirtualDelegate<CallStackItem> { getHeight(element: CallStackItem): number { if (element instanceof StackFrame && element.presentationHint === 'label') { return 16; } if (element instanceof ThreadAndSessionIds || element instanceof Array) { return 16; } return 22; } getTemplateId(element: CallStackItem): string { if (isDebugSession(element)) { return SessionsRenderer.ID; } if (element instanceof Thread) { return ThreadsRenderer.ID; } if (element instanceof StackFrame) { return StackFramesRenderer.ID; } if (typeof element === 'string') { return ErrorsRenderer.ID; } if (element instanceof ThreadAndSessionIds) { return LoadAllRenderer.ID; } // element instanceof Array return ShowMoreRenderer.ID; } } function isDebugModel(obj: any): obj is IDebugModel { return typeof obj.getSessions === 'function'; } function isDebugSession(obj: any): obj is IDebugSession { return obj && typeof obj.getAllThreads === 'function'; } function isDeemphasized(frame: IStackFrame): boolean { return frame.source.presentationHint === 'deemphasize' || frame.presentationHint === 'deemphasize'; } class CallStackDataSource implements IAsyncDataSource<IDebugModel, CallStackItem> { deemphasizedStackFramesToShow: IStackFrame[] = []; constructor(private debugService: IDebugService) { } hasChildren(element: IDebugModel | CallStackItem): boolean { if (isDebugSession(element)) { const threads = element.getAllThreads(); return (threads.length > 1) || (threads.length === 1 && threads[0].stopped) || !!(this.debugService.getModel().getSessions().find(s => s.parentSession === element)); } return isDebugModel(element) || (element instanceof Thread && element.stopped); } async getChildren(element: IDebugModel | CallStackItem): Promise<CallStackItem[]> { if (isDebugModel(element)) { const sessions = element.getSessions(); if (sessions.length === 0) { return Promise.resolve([]); } if (sessions.length > 1 || this.debugService.getViewModel().isMultiSessionView()) { return Promise.resolve(sessions.filter(s => !s.parentSession)); } const threads = sessions[0].getAllThreads(); // Only show the threads in the call stack if there is more than 1 thread. return threads.length === 1 ? this.getThreadChildren(<Thread>threads[0]) : Promise.resolve(threads); } else if (isDebugSession(element)) { const childSessions = this.debugService.getModel().getSessions().filter(s => s.parentSession === element); const threads: CallStackItem[] = element.getAllThreads(); if (threads.length === 1) { // Do not show thread when there is only one to be compact. const children = await this.getThreadChildren(<Thread>threads[0]); return children.concat(childSessions); } return Promise.resolve(threads.concat(childSessions)); } else { return this.getThreadChildren(<Thread>element); } } private getThreadChildren(thread: Thread): Promise<CallStackItem[]> { return this.getThreadCallstack(thread).then(children => { // Check if some stack frames should be hidden under a parent element since they are deemphasized const result: CallStackItem[] = []; children.forEach((child, index) => { if (child instanceof StackFrame && child.source && isDeemphasized(child)) { // Check if the user clicked to show the deemphasized source if (this.deemphasizedStackFramesToShow.indexOf(child) === -1) { if (result.length) { const last = result[result.length - 1]; if (last instanceof Array) { // Collect all the stackframes that will be "collapsed" last.push(child); return; } } const nextChild = index < children.length - 1 ? children[index + 1] : undefined; if (nextChild instanceof StackFrame && nextChild.source && isDeemphasized(nextChild)) { // Start collecting stackframes that will be "collapsed" result.push([child]); return; } } } result.push(child); }); return result; }); } private async getThreadCallstack(thread: Thread): Promise<Array<IStackFrame | string | ThreadAndSessionIds>> { let callStack: any[] = thread.getCallStack(); if (!callStack || !callStack.length) { await thread.fetchCallStack(); callStack = thread.getCallStack(); } if (callStack.length === 1 && thread.session.capabilities.supportsDelayedStackTraceLoading && thread.stoppedDetails && thread.stoppedDetails.totalFrames && thread.stoppedDetails.totalFrames > 1) { // To reduce flashing of the call stack view simply append the stale call stack // once we have the correct data the tree will refresh and we will no longer display it. callStack = callStack.concat(thread.getStaleCallStack().slice(1)); } if (thread.stoppedDetails && thread.stoppedDetails.framesErrorMessage) { callStack = callStack.concat([thread.stoppedDetails.framesErrorMessage]); } if (thread.stoppedDetails && thread.stoppedDetails.totalFrames && thread.stoppedDetails.totalFrames > callStack.length && callStack.length > 1) { callStack = callStack.concat([new ThreadAndSessionIds(thread.session.getId(), thread.threadId)]); } return callStack; } } class CallStackAccessibilityProvider implements IListAccessibilityProvider<CallStackItem> { getWidgetAriaLabel(): string { return nls.localize({ comment: ['Debug is a noun in this context, not a verb.'], key: 'callStackAriaLabel' }, "Debug Call Stack"); } getAriaLabel(element: CallStackItem): string { if (element instanceof Thread) { return nls.localize('threadAriaLabel', "Thread {0}, callstack, debug", (<Thread>element).name); } if (element instanceof StackFrame) { return nls.localize('stackFrameAriaLabel', "Stack Frame {0}, line {1}, {2}, callstack, debug", element.name, element.range.startLineNumber, getSpecificSourceName(element)); } if (isDebugSession(element)) { return nls.localize('sessionLabel', "Debug Session {0}", element.getLabel()); } if (typeof element === 'string') { return element; } if (element instanceof Array) { return nls.localize('showMoreStackFrames', "Show {0} More Stack Frames", element.length); } // element instanceof ThreadAndSessionIds return LoadAllRenderer.LABEL; } } function getActions(instantiationService: IInstantiationService, element: IDebugSession | IThread): IAction[] { const getThreadActions = (thread: IThread): IAction[] => { return [ thread.stopped ? instantiationService.createInstance(ContinueAction, thread) : instantiationService.createInstance(PauseAction, thread), instantiationService.createInstance(StepOverAction, thread), instantiationService.createInstance(StepIntoAction, thread), instantiationService.createInstance(StepOutAction, thread) ]; }; if (element instanceof Thread) { return getThreadActions(element); } const session = <IDebugSession>element; const stopOrDisconectAction = isSessionAttach(session) ? instantiationService.createInstance(DisconnectAction, session) : instantiationService.createInstance(StopAction, session); const restartAction = instantiationService.createInstance(RestartAction, session); const threads = session.getAllThreads(); if (threads.length === 1) { return getThreadActions(threads[0]).concat([ restartAction, stopOrDisconectAction ]); } return [ restartAction, stopOrDisconectAction ]; } class StopAction extends Action { constructor( private readonly session: IDebugSession, @ICommandService private readonly commandService: ICommandService ) { super(`action.${STOP_ID}`, STOP_LABEL, 'debug-action codicon-debug-stop'); } public run(): Promise<any> { return this.commandService.executeCommand(STOP_ID, undefined, getContext(this.session)); } } class DisconnectAction extends Action { constructor( private readonly session: IDebugSession, @ICommandService private readonly commandService: ICommandService ) { super(`action.${DISCONNECT_ID}`, DISCONNECT_LABEL, 'debug-action codicon-debug-disconnect'); } public run(): Promise<any> { return this.commandService.executeCommand(DISCONNECT_ID, undefined, getContext(this.session)); } } class RestartAction extends Action { constructor( private readonly session: IDebugSession, @ICommandService private readonly commandService: ICommandService ) { super(`action.${RESTART_SESSION_ID}`, RESTART_LABEL, 'debug-action codicon-debug-restart'); } public run(): Promise<any> { return this.commandService.executeCommand(RESTART_SESSION_ID, undefined, getContext(this.session)); } } class StepOverAction extends Action { constructor( private readonly thread: IThread, @ICommandService private readonly commandService: ICommandService ) { super(`action.${STEP_OVER_ID}`, STEP_OVER_LABEL, 'debug-action codicon-debug-step-over', thread.stopped); } public run(): Promise<any> { return this.commandService.executeCommand(STEP_OVER_ID, undefined, getContext(this.thread)); } } class StepIntoAction extends Action { constructor( private readonly thread: IThread, @ICommandService private readonly commandService: ICommandService ) { super(`action.${STEP_INTO_ID}`, STEP_INTO_LABEL, 'debug-action codicon-debug-step-into', thread.stopped); } public run(): Promise<any> { return this.commandService.executeCommand(STEP_INTO_ID, undefined, getContext(this.thread)); } } class StepOutAction extends Action { constructor( private readonly thread: IThread, @ICommandService private readonly commandService: ICommandService ) { super(`action.${STEP_OUT_ID}`, STEP_OUT_LABEL, 'debug-action codicon-debug-step-out', thread.stopped); } public run(): Promise<any> { return this.commandService.executeCommand(STEP_OUT_ID, undefined, getContext(this.thread)); } } class PauseAction extends Action { constructor( private readonly thread: IThread, @ICommandService private readonly commandService: ICommandService ) { super(`action.${PAUSE_ID}`, PAUSE_LABEL, 'debug-action codicon-debug-pause', !thread.stopped); } public run(): Promise<any> { return this.commandService.executeCommand(PAUSE_ID, undefined, getContext(this.thread)); } } class ContinueAction extends Action { constructor( private readonly thread: IThread, @ICommandService private readonly commandService: ICommandService ) { super(`action.${CONTINUE_ID}`, CONTINUE_LABEL, 'debug-action codicon-debug-continue', thread.stopped); } public run(): Promise<any> { return this.commandService.executeCommand(CONTINUE_ID, undefined, getContext(this.thread)); } } class CallStackCompressionDelegate implements ITreeCompressionDelegate<CallStackItem> { constructor(private readonly debugService: IDebugService) { } isIncompressible(stat: CallStackItem): boolean { if (isDebugSession(stat)) { if (stat.compact) { return false; } const sessions = this.debugService.getModel().getSessions(); if (sessions.some(s => s.parentSession === stat && s.compact)) { return false; } return true; } return true; } }
src/vs/workbench/contrib/debug/browser/callStackView.ts
1
https://github.com/microsoft/vscode/commit/135b6da83746477b2983fee879122ceefa70014d
[ 0.0014734138967469335, 0.0002027237496804446, 0.00016306072939187288, 0.00017051617032848299, 0.00018410751363262534 ]
{ "id": 4, "code_window": [ "\t) {\n", "\t\tsuper(VIEWLET_ID, { mergeViewWithContainerWhenSingleView: true }, instantiationService, configurationService, layoutService, contextMenuService, telemetryService, extensionService, themeService, storageService, contextService, viewDescriptorService);\n", "\n", "\t\tthis.updateToolBarScheduler = this._register(new RunOnceScheduler(() => {\n", "\t\t\tif (this.configurationService.getValue<IDebugConfiguration>('debug').toolBarLocation === 'docked') {\n", "\t\t\t\tthis.updateTitleArea();\n", "\t\t\t}\n", "\t\t}, 20));\n", "\n", "\t\t// When there are potential updates to the docked debug toolbar we need to update it\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tthis.updateTitleArea();\n" ], "file_path": "src/vs/workbench/contrib/debug/browser/debugViewlet.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 { IStatusbarService, StatusbarAlignment as MainThreadStatusBarAlignment, IStatusbarEntryAccessor, IStatusbarEntry } from 'vs/workbench/services/statusbar/common/statusbar'; import { MainThreadStatusBarShape, MainContext, IExtHostContext } from '../common/extHost.protocol'; import { ThemeColor } from 'vs/platform/theme/common/themeService'; import { extHostNamedCustomer } from 'vs/workbench/api/common/extHostCustomers'; import { dispose } from 'vs/base/common/lifecycle'; import { Command } from 'vs/editor/common/modes'; import { IAccessibilityInformation } from 'vs/platform/accessibility/common/accessibility'; @extHostNamedCustomer(MainContext.MainThreadStatusBar) export class MainThreadStatusBar implements MainThreadStatusBarShape { private readonly entries: Map<number, { accessor: IStatusbarEntryAccessor, alignment: MainThreadStatusBarAlignment, priority: number }> = new Map(); static readonly CODICON_REGEXP = /\$\((.*?)\)/g; constructor( _extHostContext: IExtHostContext, @IStatusbarService private readonly statusbarService: IStatusbarService ) { } dispose(): void { this.entries.forEach(entry => entry.accessor.dispose()); this.entries.clear(); } $setEntry(id: number, statusId: string, statusName: string, text: string, tooltip: string | undefined, command: Command | undefined, color: string | ThemeColor | undefined, alignment: MainThreadStatusBarAlignment, priority: number | undefined, accessibilityInformation: IAccessibilityInformation): void { // if there are icons in the text use the tooltip for the aria label let ariaLabel: string; let role: string | undefined = undefined; if (accessibilityInformation) { ariaLabel = accessibilityInformation.label; role = accessibilityInformation.role; } else { ariaLabel = text ? text.replace(MainThreadStatusBar.CODICON_REGEXP, (_match, codiconName) => codiconName) : ''; } const entry: IStatusbarEntry = { text, tooltip, command, color, ariaLabel, role }; if (typeof priority === 'undefined') { priority = 0; } // Reset existing entry if alignment or priority changed let existingEntry = this.entries.get(id); if (existingEntry && (existingEntry.alignment !== alignment || existingEntry.priority !== priority)) { dispose(existingEntry.accessor); this.entries.delete(id); existingEntry = undefined; } // Create new entry if not existing if (!existingEntry) { this.entries.set(id, { accessor: this.statusbarService.addEntry(entry, statusId, statusName, alignment, priority), alignment, priority }); } // Otherwise update else { existingEntry.accessor.update(entry); } } $dispose(id: number) { const entry = this.entries.get(id); if (entry) { dispose(entry.accessor); this.entries.delete(id); } } }
src/vs/workbench/api/browser/mainThreadStatusBar.ts
0
https://github.com/microsoft/vscode/commit/135b6da83746477b2983fee879122ceefa70014d
[ 0.00017258817388210446, 0.00017076848598662764, 0.00016405728820245713, 0.00017203716561198235, 0.0000027080620839115 ]
{ "id": 4, "code_window": [ "\t) {\n", "\t\tsuper(VIEWLET_ID, { mergeViewWithContainerWhenSingleView: true }, instantiationService, configurationService, layoutService, contextMenuService, telemetryService, extensionService, themeService, storageService, contextService, viewDescriptorService);\n", "\n", "\t\tthis.updateToolBarScheduler = this._register(new RunOnceScheduler(() => {\n", "\t\t\tif (this.configurationService.getValue<IDebugConfiguration>('debug').toolBarLocation === 'docked') {\n", "\t\t\t\tthis.updateTitleArea();\n", "\t\t\t}\n", "\t\t}, 20));\n", "\n", "\t\t// When there are potential updates to the docked debug toolbar we need to update it\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tthis.updateTitleArea();\n" ], "file_path": "src/vs/workbench/contrib/debug/browser/debugViewlet.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 .call-hierarchy .results, .monaco-workbench .call-hierarchy .message { display: none; } .monaco-workbench .call-hierarchy[data-state="data"] .results { display: inherit; height: 100%; } .monaco-workbench .call-hierarchy[data-state="message"] .message { display: flex; align-items: center; justify-content: center; height: 100%; } .monaco-workbench .call-hierarchy .editor, .monaco-workbench .call-hierarchy .tree { height: 100%; } .monaco-workbench .call-hierarchy .tree .callhierarchy-element { display: flex; flex: 1; flex-flow: row nowrap; align-items: center; } .monaco-workbench .call-hierarchy .tree .callhierarchy-element .monaco-icon-label { padding-left: 4px; }
src/vs/workbench/contrib/callHierarchy/browser/media/callHierarchy.css
0
https://github.com/microsoft/vscode/commit/135b6da83746477b2983fee879122ceefa70014d
[ 0.00017402849334757775, 0.0001723416498862207, 0.00017087734886445105, 0.0001722303859423846, 0.0000011323254511808045 ]
{ "id": 4, "code_window": [ "\t) {\n", "\t\tsuper(VIEWLET_ID, { mergeViewWithContainerWhenSingleView: true }, instantiationService, configurationService, layoutService, contextMenuService, telemetryService, extensionService, themeService, storageService, contextService, viewDescriptorService);\n", "\n", "\t\tthis.updateToolBarScheduler = this._register(new RunOnceScheduler(() => {\n", "\t\t\tif (this.configurationService.getValue<IDebugConfiguration>('debug').toolBarLocation === 'docked') {\n", "\t\t\t\tthis.updateTitleArea();\n", "\t\t\t}\n", "\t\t}, 20));\n", "\n", "\t\t// When there are potential updates to the docked debug toolbar we need to update it\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tthis.updateTitleArea();\n" ], "file_path": "src/vs/workbench/contrib/debug/browser/debugViewlet.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 { FastDomNode, createFastDomNode } from 'vs/base/browser/fastDomNode'; import * as strings from 'vs/base/common/strings'; import { Configuration } from 'vs/editor/browser/config/configuration'; import { TextEditorCursorStyle, EditorOption } from 'vs/editor/common/config/editorOptions'; import { Position } from 'vs/editor/common/core/position'; import { Range } from 'vs/editor/common/core/range'; import { RenderingContext, RestrictedRenderingContext } from 'vs/editor/common/view/renderingContext'; import { ViewContext } from 'vs/editor/common/view/viewContext'; import * as viewEvents from 'vs/editor/common/view/viewEvents'; import { MOUSE_CURSOR_TEXT_CSS_CLASS_NAME } from 'vs/base/browser/ui/mouseCursor/mouseCursor'; export interface IViewCursorRenderData { domNode: HTMLElement; position: Position; contentLeft: number; width: number; height: number; } class ViewCursorRenderData { constructor( public readonly top: number, public readonly left: number, public readonly width: number, public readonly height: number, public readonly textContent: string, public readonly textContentClassName: string ) { } } export class ViewCursor { private readonly _context: ViewContext; private readonly _domNode: FastDomNode<HTMLElement>; private _cursorStyle: TextEditorCursorStyle; private _lineCursorWidth: number; private _lineHeight: number; private _typicalHalfwidthCharacterWidth: number; private _isVisible: boolean; private _position: Position; private _lastRenderedContent: string; private _renderData: ViewCursorRenderData | null; constructor(context: ViewContext) { this._context = context; const options = this._context.configuration.options; const fontInfo = options.get(EditorOption.fontInfo); this._cursorStyle = options.get(EditorOption.cursorStyle); this._lineHeight = options.get(EditorOption.lineHeight); this._typicalHalfwidthCharacterWidth = fontInfo.typicalHalfwidthCharacterWidth; this._lineCursorWidth = Math.min(options.get(EditorOption.cursorWidth), this._typicalHalfwidthCharacterWidth); this._isVisible = true; // Create the dom node this._domNode = createFastDomNode(document.createElement('div')); this._domNode.setClassName(`cursor ${MOUSE_CURSOR_TEXT_CSS_CLASS_NAME}`); this._domNode.setHeight(this._lineHeight); this._domNode.setTop(0); this._domNode.setLeft(0); Configuration.applyFontInfo(this._domNode, fontInfo); this._domNode.setDisplay('none'); this._position = new Position(1, 1); this._lastRenderedContent = ''; this._renderData = null; } public getDomNode(): FastDomNode<HTMLElement> { return this._domNode; } public getPosition(): Position { return this._position; } public show(): void { if (!this._isVisible) { this._domNode.setVisibility('inherit'); this._isVisible = true; } } public hide(): void { if (this._isVisible) { this._domNode.setVisibility('hidden'); this._isVisible = false; } } public onConfigurationChanged(e: viewEvents.ViewConfigurationChangedEvent): boolean { const options = this._context.configuration.options; const fontInfo = options.get(EditorOption.fontInfo); this._cursorStyle = options.get(EditorOption.cursorStyle); this._lineHeight = options.get(EditorOption.lineHeight); this._typicalHalfwidthCharacterWidth = fontInfo.typicalHalfwidthCharacterWidth; this._lineCursorWidth = Math.min(options.get(EditorOption.cursorWidth), this._typicalHalfwidthCharacterWidth); Configuration.applyFontInfo(this._domNode, fontInfo); return true; } public onCursorPositionChanged(position: Position): boolean { this._position = position; return true; } private _prepareRender(ctx: RenderingContext): ViewCursorRenderData | null { let textContent = ''; if (this._cursorStyle === TextEditorCursorStyle.Line || this._cursorStyle === TextEditorCursorStyle.LineThin) { const visibleRange = ctx.visibleRangeForPosition(this._position); if (!visibleRange || visibleRange.outsideRenderedLine) { // Outside viewport return null; } let width: number; if (this._cursorStyle === TextEditorCursorStyle.Line) { width = dom.computeScreenAwareSize(this._lineCursorWidth > 0 ? this._lineCursorWidth : 2); if (width > 2) { const lineContent = this._context.model.getLineContent(this._position.lineNumber); const nextCharLength = strings.nextCharLength(lineContent, this._position.column - 1); textContent = lineContent.substr(this._position.column - 1, nextCharLength); } } else { width = dom.computeScreenAwareSize(1); } let left = visibleRange.left; if (width >= 2 && left >= 1) { // try to center cursor left -= 1; } const top = ctx.getVerticalOffsetForLineNumber(this._position.lineNumber) - ctx.bigNumbersDelta; return new ViewCursorRenderData(top, left, width, this._lineHeight, textContent, ''); } const lineContent = this._context.model.getLineContent(this._position.lineNumber); const nextCharLength = strings.nextCharLength(lineContent, this._position.column - 1); const visibleRangeForCharacter = ctx.linesVisibleRangesForRange(new Range(this._position.lineNumber, this._position.column, this._position.lineNumber, this._position.column + nextCharLength), false); if (!visibleRangeForCharacter || visibleRangeForCharacter.length === 0) { // Outside viewport return null; } const firstVisibleRangeForCharacter = visibleRangeForCharacter[0]; if (firstVisibleRangeForCharacter.outsideRenderedLine || firstVisibleRangeForCharacter.ranges.length === 0) { // Outside viewport return null; } const range = firstVisibleRangeForCharacter.ranges[0]; const width = range.width < 1 ? this._typicalHalfwidthCharacterWidth : range.width; let textContentClassName = ''; if (this._cursorStyle === TextEditorCursorStyle.Block) { const lineData = this._context.model.getViewLineData(this._position.lineNumber); textContent = lineContent.substr(this._position.column - 1, nextCharLength); const tokenIndex = lineData.tokens.findTokenIndexAtOffset(this._position.column - 1); textContentClassName = lineData.tokens.getClassName(tokenIndex); } let top = ctx.getVerticalOffsetForLineNumber(this._position.lineNumber) - ctx.bigNumbersDelta; let height = this._lineHeight; // Underline might interfere with clicking if (this._cursorStyle === TextEditorCursorStyle.Underline || this._cursorStyle === TextEditorCursorStyle.UnderlineThin) { top += this._lineHeight - 2; height = 2; } return new ViewCursorRenderData(top, range.left, width, height, textContent, textContentClassName); } public prepareRender(ctx: RenderingContext): void { this._renderData = this._prepareRender(ctx); } public render(ctx: RestrictedRenderingContext): IViewCursorRenderData | null { if (!this._renderData) { this._domNode.setDisplay('none'); return null; } if (this._lastRenderedContent !== this._renderData.textContent) { this._lastRenderedContent = this._renderData.textContent; this._domNode.domNode.textContent = this._lastRenderedContent; } this._domNode.setClassName(`cursor ${MOUSE_CURSOR_TEXT_CSS_CLASS_NAME} ${this._renderData.textContentClassName}`); this._domNode.setDisplay('block'); this._domNode.setTop(this._renderData.top); this._domNode.setLeft(this._renderData.left); this._domNode.setWidth(this._renderData.width); this._domNode.setLineHeight(this._renderData.height); this._domNode.setHeight(this._renderData.height); return { domNode: this._domNode.domNode, position: this._position, contentLeft: this._renderData.left, height: this._renderData.height, width: 2 }; } }
src/vs/editor/browser/viewParts/viewCursors/viewCursor.ts
0
https://github.com/microsoft/vscode/commit/135b6da83746477b2983fee879122ceefa70014d
[ 0.00025891399127431214, 0.00017632762319408357, 0.00016567013517487794, 0.00017123976431321353, 0.000018701068256632425 ]
{ "id": 5, "code_window": [ "\tprivate get toggleReplAction(): OpenDebugConsoleAction {\n", "\t\treturn this._register(this.instantiationService.createInstance(OpenDebugConsoleAction, OpenDebugConsoleAction.ID, OpenDebugConsoleAction.LABEL));\n", "\t}\n", "\n", "\t@memoize\n", "\tprivate get selectAndStartAction(): SelectAndStartAction {\n", "\t\treturn this._register(this.instantiationService.createInstance(SelectAndStartAction, SelectAndStartAction.ID, nls.localize('startAdditionalSession', \"Start Additional Session\")));\n", "\t}\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t@memoize\n", "\tprivate get stopAction(): StopAction {\n", "\t\treturn this._register(this.instantiationService.createInstance(StopAction, null));\n", "\t}\n", "\n" ], "file_path": "src/vs/workbench/contrib/debug/browser/debugViewlet.ts", "type": "add", "edit_start_line_idx": 121 }
/*--------------------------------------------------------------------------------------------- * 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 { RunOnceScheduler } from 'vs/base/common/async'; import * as dom from 'vs/base/browser/dom'; import { IViewletViewOptions } from 'vs/workbench/browser/parts/views/viewsViewlet'; import { IDebugService, State, IStackFrame, IDebugSession, IThread, CONTEXT_CALLSTACK_ITEM_TYPE, IDebugModel } from 'vs/workbench/contrib/debug/common/debug'; import { Thread, StackFrame, ThreadAndSessionIds } from 'vs/workbench/contrib/debug/common/debugModel'; import { IContextMenuService } from 'vs/platform/contextview/browser/contextView'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { MenuId, IMenu, IMenuService, MenuItemAction, SubmenuItemAction } from 'vs/platform/actions/common/actions'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; import { renderViewTree } from 'vs/workbench/contrib/debug/browser/baseDebugView'; import { IAction, Action } from 'vs/base/common/actions'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IContextKey, IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { ViewPane } from 'vs/workbench/browser/parts/views/viewPaneContainer'; import { ILabelService } from 'vs/platform/label/common/label'; import { IListAccessibilityProvider } from 'vs/base/browser/ui/list/listWidget'; import { createAndFillInContextMenuActions, createAndFillInActionBarActions, MenuEntryActionViewItem, SubmenuEntryActionViewItem } from 'vs/platform/actions/browser/menuEntryActionViewItem'; import { IListVirtualDelegate } from 'vs/base/browser/ui/list/list'; import { ITreeNode, ITreeContextMenuEvent, IAsyncDataSource } from 'vs/base/browser/ui/tree/tree'; import { WorkbenchCompressibleAsyncDataTree } from 'vs/platform/list/browser/listService'; import { HighlightedLabel } from 'vs/base/browser/ui/highlightedlabel/highlightedLabel'; import { createMatches, FuzzyScore, IMatch } from 'vs/base/common/filters'; import { Event } from 'vs/base/common/event'; import { dispose, IDisposable } from 'vs/base/common/lifecycle'; import { ActionBar } from 'vs/base/browser/ui/actionbar/actionbar'; import { isSessionAttach } from 'vs/workbench/contrib/debug/common/debugUtils'; import { STOP_ID, STOP_LABEL, DISCONNECT_ID, DISCONNECT_LABEL, RESTART_SESSION_ID, RESTART_LABEL, STEP_OVER_ID, STEP_OVER_LABEL, STEP_INTO_LABEL, STEP_INTO_ID, STEP_OUT_LABEL, STEP_OUT_ID, PAUSE_ID, PAUSE_LABEL, CONTINUE_ID, CONTINUE_LABEL } from 'vs/workbench/contrib/debug/browser/debugCommands'; import { ICommandService } from 'vs/platform/commands/common/commands'; import { CollapseAction } from 'vs/workbench/browser/viewlet'; import { IViewDescriptorService } from 'vs/workbench/common/views'; import { textLinkForeground } from 'vs/platform/theme/common/colorRegistry'; import { IThemeService } from 'vs/platform/theme/common/themeService'; import { IOpenerService } from 'vs/platform/opener/common/opener'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { attachStylerCallback } from 'vs/platform/theme/common/styler'; import { INotificationService } from 'vs/platform/notification/common/notification'; import { commonSuffixLength } from 'vs/base/common/strings'; import { posix } from 'vs/base/common/path'; import { ITreeCompressionDelegate } from 'vs/base/browser/ui/tree/asyncDataTree'; import { ICompressibleTreeRenderer } from 'vs/base/browser/ui/tree/objectTree'; import { ICompressedTreeNode } from 'vs/base/browser/ui/tree/compressedObjectTreeModel'; const $ = dom.$; type CallStackItem = IStackFrame | IThread | IDebugSession | string | ThreadAndSessionIds | IStackFrame[]; export function getContext(element: CallStackItem | null): any { return element instanceof StackFrame ? { sessionId: element.thread.session.getId(), threadId: element.thread.getId(), frameId: element.getId() } : element instanceof Thread ? { sessionId: element.session.getId(), threadId: element.getId() } : isDebugSession(element) ? { sessionId: element.getId() } : undefined; } // Extensions depend on this context, should not be changed even though it is not fully deterministic export function getContextForContributedActions(element: CallStackItem | null): string | number { if (element instanceof StackFrame) { if (element.source.inMemory) { return element.source.raw.path || element.source.reference || element.source.name; } return element.source.uri.toString(); } if (element instanceof Thread) { return element.threadId; } if (isDebugSession(element)) { return element.getId(); } return ''; } export function getSpecificSourceName(stackFrame: IStackFrame): string { // To reduce flashing of the path name and the way we fetch stack frames // We need to compute the source name based on the other frames in the stale call stack let callStack = (<Thread>stackFrame.thread).getStaleCallStack(); callStack = callStack.length > 0 ? callStack : stackFrame.thread.getCallStack(); const otherSources = callStack.map(sf => sf.source).filter(s => s !== stackFrame.source); let suffixLength = 0; otherSources.forEach(s => { if (s.name === stackFrame.source.name) { suffixLength = Math.max(suffixLength, commonSuffixLength(stackFrame.source.uri.path, s.uri.path)); } }); if (suffixLength === 0) { return stackFrame.source.name; } const from = Math.max(0, stackFrame.source.uri.path.lastIndexOf(posix.sep, stackFrame.source.uri.path.length - suffixLength - 1)); return (from > 0 ? '...' : '') + stackFrame.source.uri.path.substr(from); } async function expandTo(session: IDebugSession, tree: WorkbenchCompressibleAsyncDataTree<IDebugModel, CallStackItem, FuzzyScore>): Promise<void> { if (session.parentSession) { await expandTo(session.parentSession, tree); } await tree.expand(session); } export class CallStackView extends ViewPane { private pauseMessage!: HTMLSpanElement; private pauseMessageLabel!: HTMLSpanElement; private onCallStackChangeScheduler: RunOnceScheduler; private needsRefresh = false; private ignoreSelectionChangedEvent = false; private ignoreFocusStackFrameEvent = false; private callStackItemType: IContextKey<string>; private dataSource!: CallStackDataSource; private tree!: WorkbenchCompressibleAsyncDataTree<IDebugModel, CallStackItem, FuzzyScore>; private menu: IMenu; private autoExpandedSessions = new Set<IDebugSession>(); private selectionNeedsUpdate = false; constructor( private options: IViewletViewOptions, @IContextMenuService contextMenuService: IContextMenuService, @IDebugService private readonly debugService: IDebugService, @IKeybindingService keybindingService: IKeybindingService, @IInstantiationService instantiationService: IInstantiationService, @IViewDescriptorService viewDescriptorService: IViewDescriptorService, @IEditorService private readonly editorService: IEditorService, @IConfigurationService configurationService: IConfigurationService, @IMenuService menuService: IMenuService, @IContextKeyService readonly contextKeyService: IContextKeyService, @IOpenerService openerService: IOpenerService, @IThemeService themeService: IThemeService, @ITelemetryService telemetryService: ITelemetryService, ) { super(options, keybindingService, contextMenuService, configurationService, contextKeyService, viewDescriptorService, instantiationService, openerService, themeService, telemetryService); this.callStackItemType = CONTEXT_CALLSTACK_ITEM_TYPE.bindTo(contextKeyService); this.menu = menuService.createMenu(MenuId.DebugCallStackContext, contextKeyService); this._register(this.menu); // Create scheduler to prevent unnecessary flashing of tree when reacting to changes this.onCallStackChangeScheduler = new RunOnceScheduler(async () => { // Only show the global pause message if we do not display threads. // Otherwise there will be a pause message per thread and there is no need for a global one. const sessions = this.debugService.getModel().getSessions(); if (sessions.length === 0) { this.autoExpandedSessions.clear(); } const thread = sessions.length === 1 && sessions[0].getAllThreads().length === 1 ? sessions[0].getAllThreads()[0] : undefined; if (thread && thread.stoppedDetails) { this.pauseMessageLabel.textContent = thread.stoppedDetails.description || nls.localize('debugStopped', "Paused on {0}", thread.stoppedDetails.reason || ''); this.pauseMessageLabel.title = thread.stoppedDetails.text || ''; dom.toggleClass(this.pauseMessageLabel, 'exception', thread.stoppedDetails.reason === 'exception'); this.pauseMessage.hidden = false; this.updateActions(); } else { this.pauseMessage.hidden = true; this.updateActions(); } this.needsRefresh = false; this.dataSource.deemphasizedStackFramesToShow = []; await this.tree.updateChildren(); try { const toExpand = new Set<IDebugSession>(); sessions.forEach(s => { // Automatically expand sessions that have children, but only do this once. if (s.parentSession && !this.autoExpandedSessions.has(s.parentSession)) { toExpand.add(s.parentSession); } }); for (let session of toExpand) { await expandTo(session, this.tree); this.autoExpandedSessions.add(session); } } catch (e) { // Ignore tree expand errors if element no longer present } if (this.selectionNeedsUpdate) { this.selectionNeedsUpdate = false; await this.updateTreeSelection(); } }, 50); } protected renderHeaderTitle(container: HTMLElement): void { const titleContainer = dom.append(container, $('.debug-call-stack-title')); super.renderHeaderTitle(titleContainer, this.options.title); this.pauseMessage = dom.append(titleContainer, $('span.pause-message')); this.pauseMessage.hidden = true; this.pauseMessageLabel = dom.append(this.pauseMessage, $('span.label')); } getActions(): IAction[] { if (this.pauseMessage.hidden) { return [new CollapseAction(() => this.tree, true, 'explorer-action codicon-collapse-all')]; } return []; } renderBody(container: HTMLElement): void { super.renderBody(container); dom.addClass(this.element, 'debug-pane'); dom.addClass(container, 'debug-call-stack'); const treeContainer = renderViewTree(container); this.dataSource = new CallStackDataSource(this.debugService); const sessionsRenderer = this.instantiationService.createInstance(SessionsRenderer, this.menu); this.tree = <WorkbenchCompressibleAsyncDataTree<IDebugModel, CallStackItem, FuzzyScore>>this.instantiationService.createInstance(WorkbenchCompressibleAsyncDataTree, 'CallStackView', treeContainer, new CallStackDelegate(), new CallStackCompressionDelegate(this.debugService), [ sessionsRenderer, new ThreadsRenderer(this.instantiationService), this.instantiationService.createInstance(StackFramesRenderer), new ErrorsRenderer(), new LoadAllRenderer(this.themeService), new ShowMoreRenderer(this.themeService) ], this.dataSource, { accessibilityProvider: new CallStackAccessibilityProvider(), compressionEnabled: true, autoExpandSingleChildren: true, identityProvider: { getId: (element: CallStackItem) => { if (typeof element === 'string') { return element; } if (element instanceof Array) { return `showMore ${element[0].getId()}`; } return element.getId(); } }, keyboardNavigationLabelProvider: { getKeyboardNavigationLabel: (e: CallStackItem) => { if (isDebugSession(e)) { return e.getLabel(); } if (e instanceof Thread) { return `${e.name} ${e.stateLabel}`; } if (e instanceof StackFrame || typeof e === 'string') { return e; } if (e instanceof ThreadAndSessionIds) { return LoadAllRenderer.LABEL; } return nls.localize('showMoreStackFrames2', "Show More Stack Frames"); }, getCompressedNodeKeyboardNavigationLabel: (e: CallStackItem[]) => { const firstItem = e[0]; if (isDebugSession(firstItem)) { return firstItem.getLabel(); } return ''; } }, expandOnlyOnTwistieClick: true, overrideStyles: { listBackground: this.getBackgroundColor() } }); this.tree.setInput(this.debugService.getModel()); this._register(this.tree.onDidOpen(async e => { if (this.ignoreSelectionChangedEvent) { return; } const focusStackFrame = (stackFrame: IStackFrame | undefined, thread: IThread | undefined, session: IDebugSession) => { this.ignoreFocusStackFrameEvent = true; try { this.debugService.focusStackFrame(stackFrame, thread, session, true); } finally { this.ignoreFocusStackFrameEvent = false; } }; const element = e.element; if (element instanceof StackFrame) { focusStackFrame(element, element.thread, element.thread.session); element.openInEditor(this.editorService, e.editorOptions.preserveFocus, e.sideBySide, e.editorOptions.pinned); } if (element instanceof Thread) { focusStackFrame(undefined, element, element.session); } if (isDebugSession(element)) { focusStackFrame(undefined, undefined, element); } if (element instanceof ThreadAndSessionIds) { const session = this.debugService.getModel().getSession(element.sessionId); const thread = session && session.getThread(element.threadId); if (thread) { const totalFrames = thread.stoppedDetails?.totalFrames; const remainingFramesCount = typeof totalFrames === 'number' ? (totalFrames - thread.getCallStack().length) : undefined; // Get all the remaining frames await (<Thread>thread).fetchCallStack(remainingFramesCount); await this.tree.updateChildren(); } } if (element instanceof Array) { this.dataSource.deemphasizedStackFramesToShow.push(...element); this.tree.updateChildren(); } })); this._register(this.debugService.getModel().onDidChangeCallStack(() => { if (!this.isBodyVisible()) { this.needsRefresh = true; return; } if (!this.onCallStackChangeScheduler.isScheduled()) { this.onCallStackChangeScheduler.schedule(); } })); const onFocusChange = Event.any<any>(this.debugService.getViewModel().onDidFocusStackFrame, this.debugService.getViewModel().onDidFocusSession); this._register(onFocusChange(async () => { if (this.ignoreFocusStackFrameEvent) { return; } if (!this.isBodyVisible()) { this.needsRefresh = true; return; } if (this.onCallStackChangeScheduler.isScheduled()) { this.selectionNeedsUpdate = true; return; } await this.updateTreeSelection(); })); this._register(this.tree.onContextMenu(e => this.onContextMenu(e))); // Schedule the update of the call stack tree if the viewlet is opened after a session started #14684 if (this.debugService.state === State.Stopped) { this.onCallStackChangeScheduler.schedule(0); } this._register(this.onDidChangeBodyVisibility(visible => { if (visible && this.needsRefresh) { this.onCallStackChangeScheduler.schedule(); } })); this._register(this.debugService.onDidNewSession(s => { const sessionListeners: IDisposable[] = []; sessionListeners.push(s.onDidChangeName(() => this.tree.rerender(s))); sessionListeners.push(s.onDidEndAdapter(() => dispose(sessionListeners))); if (s.parentSession) { // A session we already expanded has a new child session, allow to expand it again. this.autoExpandedSessions.delete(s.parentSession); } })); } layoutBody(height: number, width: number): void { super.layoutBody(height, width); this.tree.layout(height, width); } focus(): void { this.tree.domFocus(); } private async updateTreeSelection(): Promise<void> { if (!this.tree || !this.tree.getInput()) { // Tree not initialized yet return; } const updateSelectionAndReveal = (element: IStackFrame | IDebugSession) => { this.ignoreSelectionChangedEvent = true; try { this.tree.setSelection([element]); // If the element is outside of the screen bounds, // position it in the middle if (this.tree.getRelativeTop(element) === null) { this.tree.reveal(element, 0.5); } else { this.tree.reveal(element); } } catch (e) { } finally { this.ignoreSelectionChangedEvent = false; } }; const thread = this.debugService.getViewModel().focusedThread; const session = this.debugService.getViewModel().focusedSession; const stackFrame = this.debugService.getViewModel().focusedStackFrame; if (!thread) { if (!session) { this.tree.setSelection([]); } else { updateSelectionAndReveal(session); } } else { // Ignore errors from this expansions because we are not aware if we rendered the threads and sessions or we hide them to declutter the view try { await expandTo(thread.session, this.tree); } catch (e) { } try { await this.tree.expand(thread); } catch (e) { } const toReveal = stackFrame || session; if (toReveal) { updateSelectionAndReveal(toReveal); } } } private onContextMenu(e: ITreeContextMenuEvent<CallStackItem>): void { const element = e.element; if (isDebugSession(element)) { this.callStackItemType.set('session'); } else if (element instanceof Thread) { this.callStackItemType.set('thread'); } else if (element instanceof StackFrame) { this.callStackItemType.set('stackFrame'); } else { this.callStackItemType.reset(); } const primary: IAction[] = []; const secondary: IAction[] = []; const result = { primary, secondary }; const actionsDisposable = createAndFillInContextMenuActions(this.menu, { arg: getContextForContributedActions(element), shouldForwardArgs: true }, result, this.contextMenuService, g => /^inline/.test(g)); this.contextMenuService.showContextMenu({ getAnchor: () => e.anchor, getActions: () => result.secondary, getActionsContext: () => getContext(element), onHide: () => dispose(actionsDisposable) }); } } interface IThreadTemplateData { thread: HTMLElement; name: HTMLElement; stateLabel: HTMLSpanElement; label: HighlightedLabel; actionBar: ActionBar; } interface ISessionTemplateData { session: HTMLElement; name: HTMLElement; stateLabel: HTMLSpanElement; label: HighlightedLabel; actionBar: ActionBar; elementDisposable: IDisposable[]; } interface IErrorTemplateData { label: HTMLElement; } interface ILabelTemplateData { label: HTMLElement; toDispose: IDisposable; } interface IStackFrameTemplateData { stackFrame: HTMLElement; file: HTMLElement; fileName: HTMLElement; lineNumber: HTMLElement; label: HighlightedLabel; actionBar: ActionBar; } class SessionsRenderer implements ICompressibleTreeRenderer<IDebugSession, FuzzyScore, ISessionTemplateData> { static readonly ID = 'session'; constructor( private menu: IMenu, @IInstantiationService private readonly instantiationService: IInstantiationService ) { } get templateId(): string { return SessionsRenderer.ID; } renderTemplate(container: HTMLElement): ISessionTemplateData { const session = dom.append(container, $('.session')); dom.append(session, $('.codicon.codicon-bug')); const name = dom.append(session, $('.name')); const stateLabel = dom.append(session, $('span.state.label.monaco-count-badge.long')); const label = new HighlightedLabel(name, false); const actionBar = new ActionBar(session, { actionViewItemProvider: action => { if (action instanceof MenuItemAction) { return this.instantiationService.createInstance(MenuEntryActionViewItem, action); } else if (action instanceof SubmenuItemAction) { return this.instantiationService.createInstance(SubmenuEntryActionViewItem, action); } return undefined; } }); return { session, name, stateLabel, label, actionBar, elementDisposable: [] }; } renderElement(element: ITreeNode<IDebugSession, FuzzyScore>, _: number, data: ISessionTemplateData): void { this.doRenderElement(element.element, createMatches(element.filterData), data); } renderCompressedElements(node: ITreeNode<ICompressedTreeNode<IDebugSession>, FuzzyScore>, index: number, templateData: ISessionTemplateData, height: number | undefined): void { const lastElement = node.element.elements[node.element.elements.length - 1]; const matches = createMatches(node.filterData); this.doRenderElement(lastElement, matches, templateData); } private doRenderElement(session: IDebugSession, matches: IMatch[], data: ISessionTemplateData): void { data.session.title = nls.localize({ key: 'session', comment: ['Session is a noun'] }, "Session"); data.label.set(session.getLabel(), matches); const thread = session.getAllThreads().find(t => t.stopped); const setActionBar = () => { const actions = getActions(this.instantiationService, session); const primary: IAction[] = actions; const secondary: IAction[] = []; const result = { primary, secondary }; data.elementDisposable.push(createAndFillInActionBarActions(this.menu, { arg: getContextForContributedActions(session), shouldForwardArgs: true }, result, g => /^inline/.test(g))); data.actionBar.clear(); data.actionBar.push(primary, { icon: true, label: false }); }; setActionBar(); data.elementDisposable.push(this.menu.onDidChange(() => setActionBar())); data.stateLabel.style.display = ''; if (thread && thread.stoppedDetails) { data.stateLabel.textContent = thread.stoppedDetails.description || nls.localize('debugStopped', "Paused on {0}", thread.stoppedDetails.reason || ''); if (thread.stoppedDetails.text) { data.session.title = thread.stoppedDetails.text; } } else { data.stateLabel.textContent = nls.localize({ key: 'running', comment: ['indicates state'] }, "Running"); } } disposeTemplate(templateData: ISessionTemplateData): void { templateData.actionBar.dispose(); } disposeElement(_element: ITreeNode<IDebugSession, FuzzyScore>, _: number, templateData: ISessionTemplateData): void { dispose(templateData.elementDisposable); } } class ThreadsRenderer implements ICompressibleTreeRenderer<IThread, FuzzyScore, IThreadTemplateData> { static readonly ID = 'thread'; constructor(private readonly instantiationService: IInstantiationService) { } get templateId(): string { return ThreadsRenderer.ID; } renderTemplate(container: HTMLElement): IThreadTemplateData { const thread = dom.append(container, $('.thread')); const name = dom.append(thread, $('.name')); const stateLabel = dom.append(thread, $('span.state.label')); const label = new HighlightedLabel(name, false); const actionBar = new ActionBar(thread); return { thread, name, stateLabel, label, actionBar }; } renderElement(element: ITreeNode<IThread, FuzzyScore>, index: number, data: IThreadTemplateData): void { const thread = element.element; data.thread.title = nls.localize('thread', "Thread"); data.label.set(thread.name, createMatches(element.filterData)); data.stateLabel.textContent = thread.stateLabel; data.actionBar.clear(); const actions = getActions(this.instantiationService, thread); data.actionBar.push(actions, { icon: true, label: false }); } renderCompressedElements(node: ITreeNode<ICompressedTreeNode<IThread>, FuzzyScore>, index: number, templateData: IThreadTemplateData, height: number | undefined): void { throw new Error('Method not implemented.'); } disposeTemplate(templateData: IThreadTemplateData): void { templateData.actionBar.dispose(); } } class StackFramesRenderer implements ICompressibleTreeRenderer<IStackFrame, FuzzyScore, IStackFrameTemplateData> { static readonly ID = 'stackFrame'; constructor( @ILabelService private readonly labelService: ILabelService, @INotificationService private readonly notificationService: INotificationService ) { } get templateId(): string { return StackFramesRenderer.ID; } renderTemplate(container: HTMLElement): IStackFrameTemplateData { const stackFrame = dom.append(container, $('.stack-frame')); const labelDiv = dom.append(stackFrame, $('span.label.expression')); const file = dom.append(stackFrame, $('.file')); const fileName = dom.append(file, $('span.file-name')); const wrapper = dom.append(file, $('span.line-number-wrapper')); const lineNumber = dom.append(wrapper, $('span.line-number.monaco-count-badge')); const label = new HighlightedLabel(labelDiv, false); const actionBar = new ActionBar(stackFrame); return { file, fileName, label, lineNumber, stackFrame, actionBar }; } renderElement(element: ITreeNode<IStackFrame, FuzzyScore>, index: number, data: IStackFrameTemplateData): void { const stackFrame = element.element; dom.toggleClass(data.stackFrame, 'disabled', !stackFrame.source || !stackFrame.source.available || isDeemphasized(stackFrame)); dom.toggleClass(data.stackFrame, 'label', stackFrame.presentationHint === 'label'); dom.toggleClass(data.stackFrame, 'subtle', stackFrame.presentationHint === 'subtle'); const hasActions = !!stackFrame.thread.session.capabilities.supportsRestartFrame && stackFrame.presentationHint !== 'label' && stackFrame.presentationHint !== 'subtle'; dom.toggleClass(data.stackFrame, 'has-actions', hasActions); data.file.title = stackFrame.source.inMemory ? stackFrame.source.uri.path : this.labelService.getUriLabel(stackFrame.source.uri); if (stackFrame.source.raw.origin) { data.file.title += `\n${stackFrame.source.raw.origin}`; } data.label.set(stackFrame.name, createMatches(element.filterData), stackFrame.name); data.fileName.textContent = getSpecificSourceName(stackFrame); if (stackFrame.range.startLineNumber !== undefined) { data.lineNumber.textContent = `${stackFrame.range.startLineNumber}`; if (stackFrame.range.startColumn) { data.lineNumber.textContent += `:${stackFrame.range.startColumn}`; } dom.removeClass(data.lineNumber, 'unavailable'); } else { dom.addClass(data.lineNumber, 'unavailable'); } data.actionBar.clear(); if (hasActions) { const action = new Action('debug.callStack.restartFrame', nls.localize('restartFrame', "Restart Frame"), 'codicon-debug-restart-frame', true, async () => { try { await stackFrame.restart(); } catch (e) { this.notificationService.error(e); } }); data.actionBar.push(action, { icon: true, label: false }); } } renderCompressedElements(node: ITreeNode<ICompressedTreeNode<IStackFrame>, FuzzyScore>, index: number, templateData: IStackFrameTemplateData, height: number | undefined): void { throw new Error('Method not implemented.'); } disposeTemplate(templateData: IStackFrameTemplateData): void { templateData.actionBar.dispose(); } } class ErrorsRenderer implements ICompressibleTreeRenderer<string, FuzzyScore, IErrorTemplateData> { static readonly ID = 'error'; get templateId(): string { return ErrorsRenderer.ID; } renderTemplate(container: HTMLElement): IErrorTemplateData { const label = dom.append(container, $('.error')); return { label }; } renderElement(element: ITreeNode<string, FuzzyScore>, index: number, data: IErrorTemplateData): void { const error = element.element; data.label.textContent = error; data.label.title = error; } renderCompressedElements(node: ITreeNode<ICompressedTreeNode<string>, FuzzyScore>, index: number, templateData: IErrorTemplateData, height: number | undefined): void { throw new Error('Method not implemented.'); } disposeTemplate(templateData: IErrorTemplateData): void { // noop } } class LoadAllRenderer implements ICompressibleTreeRenderer<ThreadAndSessionIds, FuzzyScore, ILabelTemplateData> { static readonly ID = 'loadAll'; static readonly LABEL = nls.localize('loadAllStackFrames', "Load All Stack Frames"); constructor(private readonly themeService: IThemeService) { } get templateId(): string { return LoadAllRenderer.ID; } renderTemplate(container: HTMLElement): ILabelTemplateData { const label = dom.append(container, $('.load-all')); const toDispose = attachStylerCallback(this.themeService, { textLinkForeground }, colors => { if (colors.textLinkForeground) { label.style.color = colors.textLinkForeground.toString(); } }); return { label, toDispose }; } renderElement(element: ITreeNode<ThreadAndSessionIds, FuzzyScore>, index: number, data: ILabelTemplateData): void { data.label.textContent = LoadAllRenderer.LABEL; } renderCompressedElements(node: ITreeNode<ICompressedTreeNode<ThreadAndSessionIds>, FuzzyScore>, index: number, templateData: ILabelTemplateData, height: number | undefined): void { throw new Error('Method not implemented.'); } disposeTemplate(templateData: ILabelTemplateData): void { templateData.toDispose.dispose(); } } class ShowMoreRenderer implements ICompressibleTreeRenderer<IStackFrame[], FuzzyScore, ILabelTemplateData> { static readonly ID = 'showMore'; constructor(private readonly themeService: IThemeService) { } get templateId(): string { return ShowMoreRenderer.ID; } renderTemplate(container: HTMLElement): ILabelTemplateData { const label = dom.append(container, $('.show-more')); const toDispose = attachStylerCallback(this.themeService, { textLinkForeground }, colors => { if (colors.textLinkForeground) { label.style.color = colors.textLinkForeground.toString(); } }); return { label, toDispose }; } renderElement(element: ITreeNode<IStackFrame[], FuzzyScore>, index: number, data: ILabelTemplateData): void { const stackFrames = element.element; if (stackFrames.every(sf => !!(sf.source && sf.source.origin && sf.source.origin === stackFrames[0].source.origin))) { data.label.textContent = nls.localize('showMoreAndOrigin', "Show {0} More: {1}", stackFrames.length, stackFrames[0].source.origin); } else { data.label.textContent = nls.localize('showMoreStackFrames', "Show {0} More Stack Frames", stackFrames.length); } } renderCompressedElements(node: ITreeNode<ICompressedTreeNode<IStackFrame[]>, FuzzyScore>, index: number, templateData: ILabelTemplateData, height: number | undefined): void { throw new Error('Method not implemented.'); } disposeTemplate(templateData: ILabelTemplateData): void { templateData.toDispose.dispose(); } } class CallStackDelegate implements IListVirtualDelegate<CallStackItem> { getHeight(element: CallStackItem): number { if (element instanceof StackFrame && element.presentationHint === 'label') { return 16; } if (element instanceof ThreadAndSessionIds || element instanceof Array) { return 16; } return 22; } getTemplateId(element: CallStackItem): string { if (isDebugSession(element)) { return SessionsRenderer.ID; } if (element instanceof Thread) { return ThreadsRenderer.ID; } if (element instanceof StackFrame) { return StackFramesRenderer.ID; } if (typeof element === 'string') { return ErrorsRenderer.ID; } if (element instanceof ThreadAndSessionIds) { return LoadAllRenderer.ID; } // element instanceof Array return ShowMoreRenderer.ID; } } function isDebugModel(obj: any): obj is IDebugModel { return typeof obj.getSessions === 'function'; } function isDebugSession(obj: any): obj is IDebugSession { return obj && typeof obj.getAllThreads === 'function'; } function isDeemphasized(frame: IStackFrame): boolean { return frame.source.presentationHint === 'deemphasize' || frame.presentationHint === 'deemphasize'; } class CallStackDataSource implements IAsyncDataSource<IDebugModel, CallStackItem> { deemphasizedStackFramesToShow: IStackFrame[] = []; constructor(private debugService: IDebugService) { } hasChildren(element: IDebugModel | CallStackItem): boolean { if (isDebugSession(element)) { const threads = element.getAllThreads(); return (threads.length > 1) || (threads.length === 1 && threads[0].stopped) || !!(this.debugService.getModel().getSessions().find(s => s.parentSession === element)); } return isDebugModel(element) || (element instanceof Thread && element.stopped); } async getChildren(element: IDebugModel | CallStackItem): Promise<CallStackItem[]> { if (isDebugModel(element)) { const sessions = element.getSessions(); if (sessions.length === 0) { return Promise.resolve([]); } if (sessions.length > 1 || this.debugService.getViewModel().isMultiSessionView()) { return Promise.resolve(sessions.filter(s => !s.parentSession)); } const threads = sessions[0].getAllThreads(); // Only show the threads in the call stack if there is more than 1 thread. return threads.length === 1 ? this.getThreadChildren(<Thread>threads[0]) : Promise.resolve(threads); } else if (isDebugSession(element)) { const childSessions = this.debugService.getModel().getSessions().filter(s => s.parentSession === element); const threads: CallStackItem[] = element.getAllThreads(); if (threads.length === 1) { // Do not show thread when there is only one to be compact. const children = await this.getThreadChildren(<Thread>threads[0]); return children.concat(childSessions); } return Promise.resolve(threads.concat(childSessions)); } else { return this.getThreadChildren(<Thread>element); } } private getThreadChildren(thread: Thread): Promise<CallStackItem[]> { return this.getThreadCallstack(thread).then(children => { // Check if some stack frames should be hidden under a parent element since they are deemphasized const result: CallStackItem[] = []; children.forEach((child, index) => { if (child instanceof StackFrame && child.source && isDeemphasized(child)) { // Check if the user clicked to show the deemphasized source if (this.deemphasizedStackFramesToShow.indexOf(child) === -1) { if (result.length) { const last = result[result.length - 1]; if (last instanceof Array) { // Collect all the stackframes that will be "collapsed" last.push(child); return; } } const nextChild = index < children.length - 1 ? children[index + 1] : undefined; if (nextChild instanceof StackFrame && nextChild.source && isDeemphasized(nextChild)) { // Start collecting stackframes that will be "collapsed" result.push([child]); return; } } } result.push(child); }); return result; }); } private async getThreadCallstack(thread: Thread): Promise<Array<IStackFrame | string | ThreadAndSessionIds>> { let callStack: any[] = thread.getCallStack(); if (!callStack || !callStack.length) { await thread.fetchCallStack(); callStack = thread.getCallStack(); } if (callStack.length === 1 && thread.session.capabilities.supportsDelayedStackTraceLoading && thread.stoppedDetails && thread.stoppedDetails.totalFrames && thread.stoppedDetails.totalFrames > 1) { // To reduce flashing of the call stack view simply append the stale call stack // once we have the correct data the tree will refresh and we will no longer display it. callStack = callStack.concat(thread.getStaleCallStack().slice(1)); } if (thread.stoppedDetails && thread.stoppedDetails.framesErrorMessage) { callStack = callStack.concat([thread.stoppedDetails.framesErrorMessage]); } if (thread.stoppedDetails && thread.stoppedDetails.totalFrames && thread.stoppedDetails.totalFrames > callStack.length && callStack.length > 1) { callStack = callStack.concat([new ThreadAndSessionIds(thread.session.getId(), thread.threadId)]); } return callStack; } } class CallStackAccessibilityProvider implements IListAccessibilityProvider<CallStackItem> { getWidgetAriaLabel(): string { return nls.localize({ comment: ['Debug is a noun in this context, not a verb.'], key: 'callStackAriaLabel' }, "Debug Call Stack"); } getAriaLabel(element: CallStackItem): string { if (element instanceof Thread) { return nls.localize('threadAriaLabel', "Thread {0}, callstack, debug", (<Thread>element).name); } if (element instanceof StackFrame) { return nls.localize('stackFrameAriaLabel', "Stack Frame {0}, line {1}, {2}, callstack, debug", element.name, element.range.startLineNumber, getSpecificSourceName(element)); } if (isDebugSession(element)) { return nls.localize('sessionLabel', "Debug Session {0}", element.getLabel()); } if (typeof element === 'string') { return element; } if (element instanceof Array) { return nls.localize('showMoreStackFrames', "Show {0} More Stack Frames", element.length); } // element instanceof ThreadAndSessionIds return LoadAllRenderer.LABEL; } } function getActions(instantiationService: IInstantiationService, element: IDebugSession | IThread): IAction[] { const getThreadActions = (thread: IThread): IAction[] => { return [ thread.stopped ? instantiationService.createInstance(ContinueAction, thread) : instantiationService.createInstance(PauseAction, thread), instantiationService.createInstance(StepOverAction, thread), instantiationService.createInstance(StepIntoAction, thread), instantiationService.createInstance(StepOutAction, thread) ]; }; if (element instanceof Thread) { return getThreadActions(element); } const session = <IDebugSession>element; const stopOrDisconectAction = isSessionAttach(session) ? instantiationService.createInstance(DisconnectAction, session) : instantiationService.createInstance(StopAction, session); const restartAction = instantiationService.createInstance(RestartAction, session); const threads = session.getAllThreads(); if (threads.length === 1) { return getThreadActions(threads[0]).concat([ restartAction, stopOrDisconectAction ]); } return [ restartAction, stopOrDisconectAction ]; } class StopAction extends Action { constructor( private readonly session: IDebugSession, @ICommandService private readonly commandService: ICommandService ) { super(`action.${STOP_ID}`, STOP_LABEL, 'debug-action codicon-debug-stop'); } public run(): Promise<any> { return this.commandService.executeCommand(STOP_ID, undefined, getContext(this.session)); } } class DisconnectAction extends Action { constructor( private readonly session: IDebugSession, @ICommandService private readonly commandService: ICommandService ) { super(`action.${DISCONNECT_ID}`, DISCONNECT_LABEL, 'debug-action codicon-debug-disconnect'); } public run(): Promise<any> { return this.commandService.executeCommand(DISCONNECT_ID, undefined, getContext(this.session)); } } class RestartAction extends Action { constructor( private readonly session: IDebugSession, @ICommandService private readonly commandService: ICommandService ) { super(`action.${RESTART_SESSION_ID}`, RESTART_LABEL, 'debug-action codicon-debug-restart'); } public run(): Promise<any> { return this.commandService.executeCommand(RESTART_SESSION_ID, undefined, getContext(this.session)); } } class StepOverAction extends Action { constructor( private readonly thread: IThread, @ICommandService private readonly commandService: ICommandService ) { super(`action.${STEP_OVER_ID}`, STEP_OVER_LABEL, 'debug-action codicon-debug-step-over', thread.stopped); } public run(): Promise<any> { return this.commandService.executeCommand(STEP_OVER_ID, undefined, getContext(this.thread)); } } class StepIntoAction extends Action { constructor( private readonly thread: IThread, @ICommandService private readonly commandService: ICommandService ) { super(`action.${STEP_INTO_ID}`, STEP_INTO_LABEL, 'debug-action codicon-debug-step-into', thread.stopped); } public run(): Promise<any> { return this.commandService.executeCommand(STEP_INTO_ID, undefined, getContext(this.thread)); } } class StepOutAction extends Action { constructor( private readonly thread: IThread, @ICommandService private readonly commandService: ICommandService ) { super(`action.${STEP_OUT_ID}`, STEP_OUT_LABEL, 'debug-action codicon-debug-step-out', thread.stopped); } public run(): Promise<any> { return this.commandService.executeCommand(STEP_OUT_ID, undefined, getContext(this.thread)); } } class PauseAction extends Action { constructor( private readonly thread: IThread, @ICommandService private readonly commandService: ICommandService ) { super(`action.${PAUSE_ID}`, PAUSE_LABEL, 'debug-action codicon-debug-pause', !thread.stopped); } public run(): Promise<any> { return this.commandService.executeCommand(PAUSE_ID, undefined, getContext(this.thread)); } } class ContinueAction extends Action { constructor( private readonly thread: IThread, @ICommandService private readonly commandService: ICommandService ) { super(`action.${CONTINUE_ID}`, CONTINUE_LABEL, 'debug-action codicon-debug-continue', thread.stopped); } public run(): Promise<any> { return this.commandService.executeCommand(CONTINUE_ID, undefined, getContext(this.thread)); } } class CallStackCompressionDelegate implements ITreeCompressionDelegate<CallStackItem> { constructor(private readonly debugService: IDebugService) { } isIncompressible(stat: CallStackItem): boolean { if (isDebugSession(stat)) { if (stat.compact) { return false; } const sessions = this.debugService.getModel().getSessions(); if (sessions.some(s => s.parentSession === stat && s.compact)) { return false; } return true; } return true; } }
src/vs/workbench/contrib/debug/browser/callStackView.ts
1
https://github.com/microsoft/vscode/commit/135b6da83746477b2983fee879122ceefa70014d
[ 0.0004936440382152796, 0.0001846667000791058, 0.00016408560622949153, 0.0001726405171211809, 0.00004665731466957368 ]
{ "id": 5, "code_window": [ "\tprivate get toggleReplAction(): OpenDebugConsoleAction {\n", "\t\treturn this._register(this.instantiationService.createInstance(OpenDebugConsoleAction, OpenDebugConsoleAction.ID, OpenDebugConsoleAction.LABEL));\n", "\t}\n", "\n", "\t@memoize\n", "\tprivate get selectAndStartAction(): SelectAndStartAction {\n", "\t\treturn this._register(this.instantiationService.createInstance(SelectAndStartAction, SelectAndStartAction.ID, nls.localize('startAdditionalSession', \"Start Additional Session\")));\n", "\t}\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t@memoize\n", "\tprivate get stopAction(): StopAction {\n", "\t\treturn this._register(this.instantiationService.createInstance(StopAction, null));\n", "\t}\n", "\n" ], "file_path": "src/vs/workbench/contrib/debug/browser/debugViewlet.ts", "type": "add", "edit_start_line_idx": 121 }
function bar(): void { var a = 1; a = 1; a = 1; a = 1; a = 1; a = 1; a = 1; a = 1; a = 1; a = 1; a = 1; a = 1; a = 1; a = 1; a = 1; a = 1; a = 1; a = 1; a = 1; a = 1; a = 1; a = 1; a = 1; a = 1; a = 1; a = 1; a = 1; a = 1; }
extensions/vscode-api-tests/testWorkspace/30linefile.ts
0
https://github.com/microsoft/vscode/commit/135b6da83746477b2983fee879122ceefa70014d
[ 0.0001770906092133373, 0.00017658215074334294, 0.000176362314959988, 0.00017643783940002322, 2.9632096243403794e-7 ]
{ "id": 5, "code_window": [ "\tprivate get toggleReplAction(): OpenDebugConsoleAction {\n", "\t\treturn this._register(this.instantiationService.createInstance(OpenDebugConsoleAction, OpenDebugConsoleAction.ID, OpenDebugConsoleAction.LABEL));\n", "\t}\n", "\n", "\t@memoize\n", "\tprivate get selectAndStartAction(): SelectAndStartAction {\n", "\t\treturn this._register(this.instantiationService.createInstance(SelectAndStartAction, SelectAndStartAction.ID, nls.localize('startAdditionalSession', \"Start Additional Session\")));\n", "\t}\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t@memoize\n", "\tprivate get stopAction(): StopAction {\n", "\t\treturn this._register(this.instantiationService.createInstance(StopAction, null));\n", "\t}\n", "\n" ], "file_path": "src/vs/workbench/contrib/debug/browser/debugViewlet.ts", "type": "add", "edit_start_line_idx": 121 }
/*--------------------------------------------------------------------------------------------- * 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 { IDisposable } from 'vs/base/common/lifecycle'; import { EditOperation } from 'vs/editor/common/core/editOperation'; import { Position } from 'vs/editor/common/core/position'; import { Range } from 'vs/editor/common/core/range'; import { TokenizationResult2 } from 'vs/editor/common/core/token'; import { TextModel } from 'vs/editor/common/model/textModel'; import * as modes from 'vs/editor/common/modes'; import { NULL_STATE } from 'vs/editor/common/modes/nullMode'; import { createTextModel } from 'vs/editor/test/common/editorTestUtils'; // --------- utils suite('Editor Model - Model Modes 1', () => { let calledFor: string[] = []; function checkAndClear(arr: string[]) { assert.deepEqual(calledFor, arr); calledFor = []; } const tokenizationSupport: modes.ITokenizationSupport = { getInitialState: () => NULL_STATE, tokenize: undefined!, tokenize2: (line: string, state: modes.IState): TokenizationResult2 => { calledFor.push(line.charAt(0)); return new TokenizationResult2(new Uint32Array(0), state); } }; let thisModel: TextModel; let languageRegistration: IDisposable; setup(() => { const TEXT = '1\r\n' + '2\n' + '3\n' + '4\r\n' + '5'; const LANGUAGE_ID = 'modelModeTest1'; calledFor = []; languageRegistration = modes.TokenizationRegistry.register(LANGUAGE_ID, tokenizationSupport); thisModel = createTextModel(TEXT, undefined, new modes.LanguageIdentifier(LANGUAGE_ID, 0)); }); teardown(() => { thisModel.dispose(); languageRegistration.dispose(); calledFor = []; }); test('model calls syntax highlighter 1', () => { thisModel.forceTokenization(1); checkAndClear(['1']); }); test('model calls syntax highlighter 2', () => { thisModel.forceTokenization(2); checkAndClear(['1', '2']); thisModel.forceTokenization(2); checkAndClear([]); }); test('model caches states', () => { thisModel.forceTokenization(1); checkAndClear(['1']); thisModel.forceTokenization(2); checkAndClear(['2']); thisModel.forceTokenization(3); checkAndClear(['3']); thisModel.forceTokenization(4); checkAndClear(['4']); thisModel.forceTokenization(5); checkAndClear(['5']); thisModel.forceTokenization(5); checkAndClear([]); }); test('model invalidates states for one line insert', () => { thisModel.forceTokenization(5); checkAndClear(['1', '2', '3', '4', '5']); thisModel.applyEdits([EditOperation.insert(new Position(1, 1), '-')]); thisModel.forceTokenization(5); checkAndClear(['-']); thisModel.forceTokenization(5); checkAndClear([]); }); test('model invalidates states for many lines insert', () => { thisModel.forceTokenization(5); checkAndClear(['1', '2', '3', '4', '5']); thisModel.applyEdits([EditOperation.insert(new Position(1, 1), '0\n-\n+')]); assert.equal(thisModel.getLineCount(), 7); thisModel.forceTokenization(7); checkAndClear(['0', '-', '+']); thisModel.forceTokenization(7); checkAndClear([]); }); test('model invalidates states for one new line', () => { thisModel.forceTokenization(5); checkAndClear(['1', '2', '3', '4', '5']); thisModel.applyEdits([EditOperation.insert(new Position(1, 2), '\n')]); thisModel.applyEdits([EditOperation.insert(new Position(2, 1), 'a')]); thisModel.forceTokenization(6); checkAndClear(['1', 'a']); }); test('model invalidates states for one line delete', () => { thisModel.forceTokenization(5); checkAndClear(['1', '2', '3', '4', '5']); thisModel.applyEdits([EditOperation.insert(new Position(1, 2), '-')]); thisModel.forceTokenization(5); checkAndClear(['1']); thisModel.applyEdits([EditOperation.delete(new Range(1, 1, 1, 2))]); thisModel.forceTokenization(5); checkAndClear(['-']); thisModel.forceTokenization(5); checkAndClear([]); }); test('model invalidates states for many lines delete', () => { thisModel.forceTokenization(5); checkAndClear(['1', '2', '3', '4', '5']); thisModel.applyEdits([EditOperation.delete(new Range(1, 1, 3, 1))]); thisModel.forceTokenization(3); checkAndClear(['3']); thisModel.forceTokenization(3); checkAndClear([]); }); }); suite('Editor Model - Model Modes 2', () => { class ModelState2 implements modes.IState { prevLineContent: string; constructor(prevLineContent: string) { this.prevLineContent = prevLineContent; } clone(): modes.IState { return new ModelState2(this.prevLineContent); } equals(other: modes.IState): boolean { return (other instanceof ModelState2) && other.prevLineContent === this.prevLineContent; } } let calledFor: string[] = []; function checkAndClear(arr: string[]): void { assert.deepEqual(calledFor, arr); calledFor = []; } const tokenizationSupport: modes.ITokenizationSupport = { getInitialState: () => new ModelState2(''), tokenize: undefined!, tokenize2: (line: string, state: modes.IState): TokenizationResult2 => { calledFor.push(line); (<ModelState2>state).prevLineContent = line; return new TokenizationResult2(new Uint32Array(0), state); } }; let thisModel: TextModel; let languageRegistration: IDisposable; setup(() => { const TEXT = 'Line1' + '\r\n' + 'Line2' + '\n' + 'Line3' + '\n' + 'Line4' + '\r\n' + 'Line5'; const LANGUAGE_ID = 'modelModeTest2'; languageRegistration = modes.TokenizationRegistry.register(LANGUAGE_ID, tokenizationSupport); thisModel = createTextModel(TEXT, undefined, new modes.LanguageIdentifier(LANGUAGE_ID, 0)); }); teardown(() => { thisModel.dispose(); languageRegistration.dispose(); }); test('getTokensForInvalidLines one text insert', () => { thisModel.forceTokenization(5); checkAndClear(['Line1', 'Line2', 'Line3', 'Line4', 'Line5']); thisModel.applyEdits([EditOperation.insert(new Position(1, 6), '-')]); thisModel.forceTokenization(5); checkAndClear(['Line1-', 'Line2']); }); test('getTokensForInvalidLines two text insert', () => { thisModel.forceTokenization(5); checkAndClear(['Line1', 'Line2', 'Line3', 'Line4', 'Line5']); thisModel.applyEdits([ EditOperation.insert(new Position(1, 6), '-'), EditOperation.insert(new Position(3, 6), '-') ]); thisModel.forceTokenization(5); checkAndClear(['Line1-', 'Line2', 'Line3-', 'Line4']); }); test('getTokensForInvalidLines one multi-line text insert, one small text insert', () => { thisModel.forceTokenization(5); checkAndClear(['Line1', 'Line2', 'Line3', 'Line4', 'Line5']); thisModel.applyEdits([EditOperation.insert(new Position(1, 6), '\nNew line\nAnother new line')]); thisModel.applyEdits([EditOperation.insert(new Position(5, 6), '-')]); thisModel.forceTokenization(7); checkAndClear(['Line1', 'New line', 'Another new line', 'Line2', 'Line3-', 'Line4']); }); test('getTokensForInvalidLines one delete text', () => { thisModel.forceTokenization(5); checkAndClear(['Line1', 'Line2', 'Line3', 'Line4', 'Line5']); thisModel.applyEdits([EditOperation.delete(new Range(1, 1, 1, 5))]); thisModel.forceTokenization(5); checkAndClear(['1', 'Line2']); }); test('getTokensForInvalidLines one line delete text', () => { thisModel.forceTokenization(5); checkAndClear(['Line1', 'Line2', 'Line3', 'Line4', 'Line5']); thisModel.applyEdits([EditOperation.delete(new Range(1, 1, 2, 1))]); thisModel.forceTokenization(4); checkAndClear(['Line2']); }); test('getTokensForInvalidLines multiple lines delete text', () => { thisModel.forceTokenization(5); checkAndClear(['Line1', 'Line2', 'Line3', 'Line4', 'Line5']); thisModel.applyEdits([EditOperation.delete(new Range(1, 1, 3, 3))]); thisModel.forceTokenization(3); checkAndClear(['ne3', 'Line4']); }); });
src/vs/editor/test/common/model/model.modes.test.ts
0
https://github.com/microsoft/vscode/commit/135b6da83746477b2983fee879122ceefa70014d
[ 0.00017816168838180602, 0.00017587382171768695, 0.00016580098599661142, 0.0001767426001606509, 0.0000024874541395547567 ]
{ "id": 5, "code_window": [ "\tprivate get toggleReplAction(): OpenDebugConsoleAction {\n", "\t\treturn this._register(this.instantiationService.createInstance(OpenDebugConsoleAction, OpenDebugConsoleAction.ID, OpenDebugConsoleAction.LABEL));\n", "\t}\n", "\n", "\t@memoize\n", "\tprivate get selectAndStartAction(): SelectAndStartAction {\n", "\t\treturn this._register(this.instantiationService.createInstance(SelectAndStartAction, SelectAndStartAction.ID, nls.localize('startAdditionalSession', \"Start Additional Session\")));\n", "\t}\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t@memoize\n", "\tprivate get stopAction(): StopAction {\n", "\t\treturn this._register(this.instantiationService.createInstance(StopAction, null));\n", "\t}\n", "\n" ], "file_path": "src/vs/workbench/contrib/debug/browser/debugViewlet.ts", "type": "add", "edit_start_line_idx": 121 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { CancellationToken } from 'vs/base/common/cancellation'; import { canceled } from 'vs/base/common/errors'; import { assign } from 'vs/base/common/objects'; import { VSBuffer, bufferToStream } from 'vs/base/common/buffer'; import { IRequestOptions, IRequestContext } from 'vs/base/parts/request/common/request'; export function request(options: IRequestOptions, token: CancellationToken): Promise<IRequestContext> { if (options.proxyAuthorization) { options.headers = assign(options.headers || {}, { 'Proxy-Authorization': options.proxyAuthorization }); } const xhr = new XMLHttpRequest(); return new Promise<IRequestContext>((resolve, reject) => { xhr.open(options.type || 'GET', options.url || '', true, options.user, options.password); setRequestHeaders(xhr, options); xhr.responseType = 'arraybuffer'; xhr.onerror = e => reject(new Error(xhr.statusText && ('XHR failed: ' + xhr.statusText) || 'XHR failed')); xhr.onload = (e) => { resolve({ res: { statusCode: xhr.status, headers: getResponseHeaders(xhr) }, stream: bufferToStream(VSBuffer.wrap(new Uint8Array(xhr.response))) }); }; xhr.ontimeout = e => reject(new Error(`XHR timeout: ${options.timeout}ms`)); if (options.timeout) { xhr.timeout = options.timeout; } xhr.send(options.data); // cancel token.onCancellationRequested(() => { xhr.abort(); reject(canceled()); }); }); } function setRequestHeaders(xhr: XMLHttpRequest, options: IRequestOptions): void { if (options.headers) { outer: for (let k in options.headers) { switch (k) { case 'User-Agent': case 'Accept-Encoding': case 'Content-Length': // unsafe headers continue outer; } xhr.setRequestHeader(k, options.headers[k]); } } } function getResponseHeaders(xhr: XMLHttpRequest): { [name: string]: string } { const headers: { [name: string]: string } = Object.create(null); for (const line of xhr.getAllResponseHeaders().split(/\r\n|\n|\r/g)) { if (line) { const idx = line.indexOf(':'); headers[line.substr(0, idx).trim().toLowerCase()] = line.substr(idx + 1).trim(); } } return headers; }
src/vs/base/parts/request/browser/request.ts
0
https://github.com/microsoft/vscode/commit/135b6da83746477b2983fee879122ceefa70014d
[ 0.00019744822930078954, 0.000176850677235052, 0.00017000803200062364, 0.00017485202988609672, 0.000007994825864443555 ]
{ "id": 6, "code_window": [ "\n", "\t\tif (this.contextService.getWorkbenchState() === WorkbenchState.EMPTY) {\n", "\t\t\treturn [this.toggleReplAction];\n", "\t\t}\n", "\n", "\t\treturn [this.startAction, this.configureAction, this.toggleReplAction];\n", "\t}\n", "\n", "\tget showInitialDebugActions(): boolean {\n", "\t\tconst state = this.debugService.state;\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tconst firstAction = this.debugService.state === State.Initializing ? this.stopAction : this.startAction;\n", "\t\treturn [firstAction, this.configureAction, this.toggleReplAction];\n" ], "file_path": "src/vs/workbench/contrib/debug/browser/debugViewlet.ts", "type": "replace", "edit_start_line_idx": 152 }
/*--------------------------------------------------------------------------------------------- * 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/debugToolBar'; import * as errors from 'vs/base/common/errors'; import * as browser from 'vs/base/browser/browser'; import * as dom from 'vs/base/browser/dom'; import * as arrays from 'vs/base/common/arrays'; import { StandardMouseEvent } from 'vs/base/browser/mouseEvent'; import { IAction, IRunEvent, WorkbenchActionExecutedEvent, WorkbenchActionExecutedClassification, Separator } from 'vs/base/common/actions'; import { ActionBar, ActionsOrientation } from 'vs/base/browser/ui/actionbar/actionbar'; import { IWorkbenchLayoutService } from 'vs/workbench/services/layout/browser/layoutService'; import { IWorkbenchContribution } from 'vs/workbench/common/contributions'; import { IDebugConfiguration, IDebugService, State } from 'vs/workbench/contrib/debug/common/debug'; import { FocusSessionActionViewItem } from 'vs/workbench/contrib/debug/browser/debugActionViewItems'; import { IConfigurationService, IConfigurationChangeEvent } from 'vs/platform/configuration/common/configuration'; import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { registerThemingParticipant, IThemeService, Themable } from 'vs/platform/theme/common/themeService'; import { registerColor, contrastBorder, widgetShadow } from 'vs/platform/theme/common/colorRegistry'; import { localize } from 'vs/nls'; import { IContextMenuService } from 'vs/platform/contextview/browser/contextView'; import { INotificationService } from 'vs/platform/notification/common/notification'; import { RunOnceScheduler } from 'vs/base/common/async'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { createAndFillInActionBarActions, MenuEntryActionViewItem, SubmenuEntryActionViewItem } from 'vs/platform/actions/browser/menuEntryActionViewItem'; import { IMenu, IMenuService, MenuId, MenuItemAction, SubmenuItemAction } from 'vs/platform/actions/common/actions'; import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { FocusSessionAction } from 'vs/workbench/contrib/debug/browser/debugActions'; import { IDisposable, dispose } from 'vs/base/common/lifecycle'; const DEBUG_TOOLBAR_POSITION_KEY = 'debug.actionswidgetposition'; const DEBUG_TOOLBAR_Y_KEY = 'debug.actionswidgety'; export class DebugToolBar extends Themable implements IWorkbenchContribution { private $el: HTMLElement; private dragArea: HTMLElement; private actionBar: ActionBar; private activeActions: IAction[]; private updateScheduler: RunOnceScheduler; private debugToolBarMenu: IMenu; private disposeOnUpdate: IDisposable | undefined; private yCoordinate = 0; private isVisible = false; private isBuilt = false; constructor( @INotificationService private readonly notificationService: INotificationService, @ITelemetryService private readonly telemetryService: ITelemetryService, @IDebugService private readonly debugService: IDebugService, @IWorkbenchLayoutService private readonly layoutService: IWorkbenchLayoutService, @IStorageService private readonly storageService: IStorageService, @IConfigurationService private readonly configurationService: IConfigurationService, @IThemeService themeService: IThemeService, @IInstantiationService private readonly instantiationService: IInstantiationService, @IMenuService menuService: IMenuService, @IContextMenuService contextMenuService: IContextMenuService, @IContextKeyService contextKeyService: IContextKeyService ) { super(themeService); this.$el = dom.$('div.debug-toolbar'); this.$el.style.top = `${layoutService.offset?.top ?? 0}px`; this.dragArea = dom.append(this.$el, dom.$('div.drag-area.codicon.codicon-gripper')); const actionBarContainer = dom.append(this.$el, dom.$('div.action-bar-container')); this.debugToolBarMenu = menuService.createMenu(MenuId.DebugToolBar, contextKeyService); this._register(this.debugToolBarMenu); this.activeActions = []; this.actionBar = this._register(new ActionBar(actionBarContainer, { orientation: ActionsOrientation.HORIZONTAL, actionViewItemProvider: (action: IAction) => { if (action.id === FocusSessionAction.ID) { return this.instantiationService.createInstance(FocusSessionActionViewItem, action); } else if (action instanceof MenuItemAction) { return this.instantiationService.createInstance(MenuEntryActionViewItem, action); } else if (action instanceof SubmenuItemAction) { return this.instantiationService.createInstance(SubmenuEntryActionViewItem, action); } return undefined; } })); this.updateScheduler = this._register(new RunOnceScheduler(() => { const state = this.debugService.state; const toolBarLocation = this.configurationService.getValue<IDebugConfiguration>('debug').toolBarLocation; if (state === State.Inactive || toolBarLocation === 'docked' || toolBarLocation === 'hidden') { return this.hide(); } const { actions, disposable } = DebugToolBar.getActions(this.debugToolBarMenu, this.debugService, this.instantiationService); if (!arrays.equals(actions, this.activeActions, (first, second) => first.id === second.id)) { this.actionBar.clear(); this.actionBar.push(actions, { icon: true, label: false }); this.activeActions = actions; } if (this.disposeOnUpdate) { dispose(this.disposeOnUpdate); } this.disposeOnUpdate = disposable; this.show(); }, 20)); this.updateStyles(); this.registerListeners(); this.hide(); } private registerListeners(): void { this._register(this.debugService.onDidChangeState(() => this.updateScheduler.schedule())); this._register(this.debugService.getViewModel().onDidFocusSession(() => this.updateScheduler.schedule())); this._register(this.debugService.onDidNewSession(() => this.updateScheduler.schedule())); this._register(this.configurationService.onDidChangeConfiguration(e => this.onDidConfigurationChange(e))); this._register(this.debugToolBarMenu.onDidChange(() => this.updateScheduler.schedule())); this._register(this.actionBar.actionRunner.onDidRun((e: IRunEvent) => { // check for error if (e.error && !errors.isPromiseCanceledError(e.error)) { this.notificationService.error(e.error); } // log in telemetry if (this.telemetryService) { this.telemetryService.publicLog2<WorkbenchActionExecutedEvent, WorkbenchActionExecutedClassification>('workbenchActionExecuted', { id: e.action.id, from: 'debugActionsWidget' }); } })); this._register(dom.addDisposableListener(window, dom.EventType.RESIZE, () => this.setCoordinates())); this._register(dom.addDisposableGenericMouseUpListner(this.dragArea, (event: MouseEvent) => { const mouseClickEvent = new StandardMouseEvent(event); if (mouseClickEvent.detail === 2) { // double click on debug bar centers it again #8250 const widgetWidth = this.$el.clientWidth; this.setCoordinates(0.5 * window.innerWidth - 0.5 * widgetWidth, 0); this.storePosition(); } })); this._register(dom.addDisposableGenericMouseDownListner(this.dragArea, (event: MouseEvent) => { dom.addClass(this.dragArea, 'dragged'); const mouseMoveListener = dom.addDisposableGenericMouseMoveListner(window, (e: MouseEvent) => { const mouseMoveEvent = new StandardMouseEvent(e); // Prevent default to stop editor selecting text #8524 mouseMoveEvent.preventDefault(); // Reduce x by width of drag handle to reduce jarring #16604 this.setCoordinates(mouseMoveEvent.posx - 14, mouseMoveEvent.posy - (this.layoutService.offset?.top ?? 0)); }); const mouseUpListener = dom.addDisposableGenericMouseUpListner(window, (e: MouseEvent) => { this.storePosition(); dom.removeClass(this.dragArea, 'dragged'); mouseMoveListener.dispose(); mouseUpListener.dispose(); }); })); this._register(this.layoutService.onPartVisibilityChange(() => this.setYCoordinate())); this._register(browser.onDidChangeZoomLevel(() => this.setYCoordinate())); } private storePosition(): void { const left = dom.getComputedStyle(this.$el).left; if (left) { const position = parseFloat(left) / window.innerWidth; this.storageService.store(DEBUG_TOOLBAR_POSITION_KEY, position, StorageScope.GLOBAL); } } protected updateStyles(): void { super.updateStyles(); if (this.$el) { this.$el.style.backgroundColor = this.getColor(debugToolBarBackground) || ''; const widgetShadowColor = this.getColor(widgetShadow); this.$el.style.boxShadow = widgetShadowColor ? `0 5px 8px ${widgetShadowColor}` : ''; const contrastBorderColor = this.getColor(contrastBorder); const borderColor = this.getColor(debugToolBarBorder); if (contrastBorderColor) { this.$el.style.border = `1px solid ${contrastBorderColor}`; } else { this.$el.style.border = borderColor ? `solid ${borderColor}` : 'none'; this.$el.style.border = '1px 0'; } } } private setYCoordinate(y = this.yCoordinate): void { const titlebarOffset = this.layoutService.offset?.top ?? 0; this.$el.style.top = `${titlebarOffset + y}px`; this.yCoordinate = y; } private setCoordinates(x?: number, y?: number): void { if (!this.isVisible) { return; } const widgetWidth = this.$el.clientWidth; if (x === undefined) { const positionPercentage = this.storageService.get(DEBUG_TOOLBAR_POSITION_KEY, StorageScope.GLOBAL); x = positionPercentage !== undefined ? parseFloat(positionPercentage) * window.innerWidth : (0.5 * window.innerWidth - 0.5 * widgetWidth); } x = Math.max(0, Math.min(x, window.innerWidth - widgetWidth)); // do not allow the widget to overflow on the right this.$el.style.left = `${x}px`; if (y === undefined) { y = this.storageService.getNumber(DEBUG_TOOLBAR_Y_KEY, StorageScope.GLOBAL, 0); } const titleAreaHeight = 35; if ((y < titleAreaHeight / 2) || (y > titleAreaHeight + titleAreaHeight / 2)) { const moveToTop = y < titleAreaHeight; this.setYCoordinate(moveToTop ? 0 : titleAreaHeight); this.storageService.store(DEBUG_TOOLBAR_Y_KEY, moveToTop ? 0 : 2 * titleAreaHeight, StorageScope.GLOBAL); } } private onDidConfigurationChange(event: IConfigurationChangeEvent): void { if (event.affectsConfiguration('debug.hideActionBar') || event.affectsConfiguration('debug.toolBarLocation')) { this.updateScheduler.schedule(); } } private show(): void { if (this.isVisible) { this.setCoordinates(); return; } if (!this.isBuilt) { this.isBuilt = true; this.layoutService.container.appendChild(this.$el); } this.isVisible = true; dom.show(this.$el); this.setCoordinates(); } private hide(): void { this.isVisible = false; dom.hide(this.$el); } static getActions(menu: IMenu, debugService: IDebugService, instantiationService: IInstantiationService): { actions: IAction[], disposable: IDisposable } { const actions: IAction[] = []; const disposable = createAndFillInActionBarActions(menu, undefined, actions, () => false); if (debugService.getViewModel().isMultiSessionView()) { actions.push(instantiationService.createInstance(FocusSessionAction, FocusSessionAction.ID, FocusSessionAction.LABEL)); } return { actions: actions.filter(a => !(a instanceof Separator)), // do not render separators for now disposable }; } dispose(): void { super.dispose(); if (this.$el) { this.$el.remove(); } if (this.disposeOnUpdate) { dispose(this.disposeOnUpdate); } } } export const debugToolBarBackground = registerColor('debugToolBar.background', { dark: '#333333', light: '#F3F3F3', hc: '#000000' }, localize('debugToolBarBackground', "Debug toolbar background color.")); export const debugToolBarBorder = registerColor('debugToolBar.border', { dark: null, light: null, hc: null }, localize('debugToolBarBorder', "Debug toolbar border color.")); export const debugIconStartForeground = registerColor('debugIcon.startForeground', { dark: '#89D185', light: '#388A34', hc: '#89D185' }, localize('debugIcon.startForeground', "Debug toolbar icon for start debugging.")); export const debugIconPauseForeground = registerColor('debugIcon.pauseForeground', { dark: '#75BEFF', light: '#007ACC', hc: '#75BEFF' }, localize('debugIcon.pauseForeground', "Debug toolbar icon for pause.")); export const debugIconStopForeground = registerColor('debugIcon.stopForeground', { dark: '#F48771', light: '#A1260D', hc: '#F48771' }, localize('debugIcon.stopForeground', "Debug toolbar icon for stop.")); export const debugIconDisconnectForeground = registerColor('debugIcon.disconnectForeground', { dark: '#F48771', light: '#A1260D', hc: '#F48771' }, localize('debugIcon.disconnectForeground', "Debug toolbar icon for disconnect.")); export const debugIconRestartForeground = registerColor('debugIcon.restartForeground', { dark: '#89D185', light: '#388A34', hc: '#89D185' }, localize('debugIcon.restartForeground', "Debug toolbar icon for restart.")); export const debugIconStepOverForeground = registerColor('debugIcon.stepOverForeground', { dark: '#75BEFF', light: '#007ACC', hc: '#75BEFF' }, localize('debugIcon.stepOverForeground', "Debug toolbar icon for step over.")); export const debugIconStepIntoForeground = registerColor('debugIcon.stepIntoForeground', { dark: '#75BEFF', light: '#007ACC', hc: '#75BEFF' }, localize('debugIcon.stepIntoForeground', "Debug toolbar icon for step into.")); export const debugIconStepOutForeground = registerColor('debugIcon.stepOutForeground', { dark: '#75BEFF', light: '#007ACC', hc: '#75BEFF' }, localize('debugIcon.stepOutForeground', "Debug toolbar icon for step over.")); export const debugIconContinueForeground = registerColor('debugIcon.continueForeground', { dark: '#75BEFF', light: '#007ACC', hc: '#75BEFF' }, localize('debugIcon.continueForeground', "Debug toolbar icon for continue.")); export const debugIconStepBackForeground = registerColor('debugIcon.stepBackForeground', { dark: '#75BEFF', light: '#007ACC', hc: '#75BEFF' }, localize('debugIcon.stepBackForeground', "Debug toolbar icon for step back.")); registerThemingParticipant((theme, collector) => { const debugIconStartColor = theme.getColor(debugIconStartForeground); if (debugIconStartColor) { collector.addRule(`.monaco-workbench .codicon-debug-start { color: ${debugIconStartColor} !important; }`); } const debugIconPauseColor = theme.getColor(debugIconPauseForeground); if (debugIconPauseColor) { collector.addRule(`.monaco-workbench .codicon-debug-pause { color: ${debugIconPauseColor} !important; }`); } const debugIconStopColor = theme.getColor(debugIconStopForeground); if (debugIconStopColor) { collector.addRule(`.monaco-workbench .codicon-debug-stop, .monaco-workbench .debug-view-content .codicon-record { color: ${debugIconStopColor} !important; }`); } const debugIconDisconnectColor = theme.getColor(debugIconDisconnectForeground); if (debugIconDisconnectColor) { collector.addRule(`.monaco-workbench .codicon-debug-disconnect { color: ${debugIconDisconnectColor} !important; }`); } const debugIconRestartColor = theme.getColor(debugIconRestartForeground); if (debugIconRestartColor) { collector.addRule(`.monaco-workbench .codicon-debug-restart, .monaco-workbench .codicon-debug-restart-frame { color: ${debugIconRestartColor} !important; }`); } const debugIconStepOverColor = theme.getColor(debugIconStepOverForeground); if (debugIconStepOverColor) { collector.addRule(`.monaco-workbench .codicon-debug-step-over { color: ${debugIconStepOverColor} !important; }`); } const debugIconStepIntoColor = theme.getColor(debugIconStepIntoForeground); if (debugIconStepIntoColor) { collector.addRule(`.monaco-workbench .codicon-debug-step-into { color: ${debugIconStepIntoColor} !important; }`); } const debugIconStepOutColor = theme.getColor(debugIconStepOutForeground); if (debugIconStepOutColor) { collector.addRule(`.monaco-workbench .codicon-debug-step-out { color: ${debugIconStepOutColor} !important; }`); } const debugIconContinueColor = theme.getColor(debugIconContinueForeground); if (debugIconContinueColor) { collector.addRule(`.monaco-workbench .codicon-debug-continue,.monaco-workbench .codicon-debug-reverse-continue { color: ${debugIconContinueColor} !important; }`); } const debugIconStepBackColor = theme.getColor(debugIconStepBackForeground); if (debugIconStepBackColor) { collector.addRule(`.monaco-workbench .codicon-debug-step-back { color: ${debugIconStepBackColor} !important; }`); } });
src/vs/workbench/contrib/debug/browser/debugToolBar.ts
1
https://github.com/microsoft/vscode/commit/135b6da83746477b2983fee879122ceefa70014d
[ 0.9506680369377136, 0.023378979414701462, 0.00016541080549359322, 0.00017171967192552984, 0.14661730825901031 ]
{ "id": 6, "code_window": [ "\n", "\t\tif (this.contextService.getWorkbenchState() === WorkbenchState.EMPTY) {\n", "\t\t\treturn [this.toggleReplAction];\n", "\t\t}\n", "\n", "\t\treturn [this.startAction, this.configureAction, this.toggleReplAction];\n", "\t}\n", "\n", "\tget showInitialDebugActions(): boolean {\n", "\t\tconst state = this.debugService.state;\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tconst firstAction = this.debugService.state === State.Initializing ? this.stopAction : this.startAction;\n", "\t\treturn [firstAction, this.configureAction, this.toggleReplAction];\n" ], "file_path": "src/vs/workbench/contrib/debug/browser/debugViewlet.ts", "type": "replace", "edit_start_line_idx": 152 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { IContextKey } from 'vs/platform/contextkey/common/contextkey'; import { Terminal, ITerminalAddon } from 'xterm'; import { addDisposableListener } from 'vs/base/browser/dom'; import { INavigationMode } from 'vs/workbench/contrib/terminal/common/terminal'; export class NavigationModeAddon implements INavigationMode, ITerminalAddon { private _terminal: Terminal | undefined; constructor( private _navigationModeContextKey: IContextKey<boolean> ) { } activate(terminal: Terminal): void { this._terminal = terminal; } dispose() { } exitNavigationMode(): void { if (!this._terminal) { return; } this._terminal.scrollToBottom(); this._terminal.focus(); } focusPreviousLine(): void { if (!this._terminal || !this._terminal.element) { return; } // Focus previous row if a row is already focused if (document.activeElement && document.activeElement.parentElement && document.activeElement.parentElement.classList.contains('xterm-accessibility-tree')) { const element = <HTMLElement | null>document.activeElement.previousElementSibling; if (element) { element.focus(); const disposable = addDisposableListener(element, 'blur', () => { this._navigationModeContextKey.set(false); disposable.dispose(); }); this._navigationModeContextKey.set(true); } return; } // Ensure a11y tree exists const treeContainer = this._terminal.element.querySelector('.xterm-accessibility-tree'); if (!treeContainer) { return; } // Target is row before the cursor const targetRow = Math.max(this._terminal.buffer.active.cursorY - 1, 0); // Check bounds if (treeContainer.childElementCount < targetRow) { return; } // Focus const element = <HTMLElement>treeContainer.childNodes.item(targetRow); element.focus(); const disposable = addDisposableListener(element, 'blur', () => { this._navigationModeContextKey.set(false); disposable.dispose(); }); this._navigationModeContextKey.set(true); } focusNextLine(): void { if (!this._terminal || !this._terminal.element) { return; } // Focus previous row if a row is already focused if (document.activeElement && document.activeElement.parentElement && document.activeElement.parentElement.classList.contains('xterm-accessibility-tree')) { const element = <HTMLElement | null>document.activeElement.nextElementSibling; if (element) { element.focus(); const disposable = addDisposableListener(element, 'blur', () => { this._navigationModeContextKey.set(false); disposable.dispose(); }); this._navigationModeContextKey.set(true); } return; } // Ensure a11y tree exists const treeContainer = this._terminal.element.querySelector('.xterm-accessibility-tree'); if (!treeContainer) { return; } // Target is cursor row const targetRow = this._terminal.buffer.active.cursorY; // Check bounds if (treeContainer.childElementCount < targetRow) { return; } // Focus row before cursor const element = <HTMLElement>treeContainer.childNodes.item(targetRow); element.focus(); const disposable = addDisposableListener(element, 'blur', () => { this._navigationModeContextKey.set(false); disposable.dispose(); }); this._navigationModeContextKey.set(true); } }
src/vs/workbench/contrib/terminal/browser/addons/navigationModeAddon.ts
0
https://github.com/microsoft/vscode/commit/135b6da83746477b2983fee879122ceefa70014d
[ 0.00018206446839030832, 0.0001733016106300056, 0.00016741167928557843, 0.00017316699086222798, 0.000003466129101070692 ]
{ "id": 6, "code_window": [ "\n", "\t\tif (this.contextService.getWorkbenchState() === WorkbenchState.EMPTY) {\n", "\t\t\treturn [this.toggleReplAction];\n", "\t\t}\n", "\n", "\t\treturn [this.startAction, this.configureAction, this.toggleReplAction];\n", "\t}\n", "\n", "\tget showInitialDebugActions(): boolean {\n", "\t\tconst state = this.debugService.state;\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tconst firstAction = this.debugService.state === State.Initializing ? this.stopAction : this.startAction;\n", "\t\treturn [firstAction, this.configureAction, this.toggleReplAction];\n" ], "file_path": "src/vs/workbench/contrib/debug/browser/debugViewlet.ts", "type": "replace", "edit_start_line_idx": 152 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { IModelService } from 'vs/editor/common/services/modelService'; import { ITextModelService } from 'vs/editor/common/services/resolverService'; import { Disposable, IDisposable, dispose } from 'vs/base/common/lifecycle'; import { IUndoRedoService, UndoRedoElementType } from 'vs/platform/undoRedo/common/undoRedo'; import { isEditStackPastFutureElements } from 'vs/editor/common/services/modelServiceImpl'; import { IUndoRedoDelegate, MultiModelEditStackElement } from 'vs/editor/common/model/editStack'; export class ModelUndoRedoParticipant extends Disposable implements IUndoRedoDelegate { constructor( @IModelService private readonly _modelService: IModelService, @ITextModelService private readonly _textModelService: ITextModelService, @IUndoRedoService private readonly _undoRedoService: IUndoRedoService, ) { super(); this._register(this._modelService.onModelRemoved((model) => { // a model will get disposed, so let's check if the undo redo stack is maintained const elements = this._undoRedoService.getElements(model.uri); if (elements.past.length === 0 && elements.future.length === 0) { return; } if (!isEditStackPastFutureElements(elements)) { return; } for (const element of elements.past) { if (element.type === UndoRedoElementType.Workspace) { element.setDelegate(this); } } for (const element of elements.future) { if (element.type === UndoRedoElementType.Workspace) { element.setDelegate(this); } } })); } public prepareUndoRedo(element: MultiModelEditStackElement): IDisposable | Promise<IDisposable> { // Load all the needed text models const missingModels = element.getMissingModels(); if (missingModels.length === 0) { // All models are available! return Disposable.None; } const disposablesPromises = missingModels.map(async (uri) => { try { const reference = await this._textModelService.createModelReference(uri); return <IDisposable>reference; } catch (err) { // This model could not be loaded, maybe it was deleted in the meantime? return Disposable.None; } }); return Promise.all(disposablesPromises).then(disposables => { return { dispose: () => dispose(disposables) }; }); } }
src/vs/editor/common/services/modelUndoRedoParticipant.ts
0
https://github.com/microsoft/vscode/commit/135b6da83746477b2983fee879122ceefa70014d
[ 0.00017752815620042384, 0.00017459159425925463, 0.00017140425916295499, 0.00017496940563432872, 0.0000022671083570457995 ]
{ "id": 6, "code_window": [ "\n", "\t\tif (this.contextService.getWorkbenchState() === WorkbenchState.EMPTY) {\n", "\t\t\treturn [this.toggleReplAction];\n", "\t\t}\n", "\n", "\t\treturn [this.startAction, this.configureAction, this.toggleReplAction];\n", "\t}\n", "\n", "\tget showInitialDebugActions(): boolean {\n", "\t\tconst state = this.debugService.state;\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tconst firstAction = this.debugService.state === State.Initializing ? this.stopAction : this.startAction;\n", "\t\treturn [firstAction, this.configureAction, this.toggleReplAction];\n" ], "file_path": "src/vs/workbench/contrib/debug/browser/debugViewlet.ts", "type": "replace", "edit_start_line_idx": 152 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Disposable } from 'vs/base/common/lifecycle'; import { addDisposableListener } from 'vs/base/browser/dom'; /** * A helper that will execute a provided function when the provided HTMLElement receives * dragover event for 800ms. If the drag is aborted before, the callback will not be triggered. */ export class DelayedDragHandler extends Disposable { private timeout: any; constructor(container: HTMLElement, callback: () => void) { super(); this._register(addDisposableListener(container, 'dragover', e => { e.preventDefault(); // needed so that the drop event fires (https://stackoverflow.com/questions/21339924/drop-event-not-firing-in-chrome) if (!this.timeout) { this.timeout = setTimeout(() => { callback(); this.timeout = null; }, 800); } })); ['dragleave', 'drop', 'dragend'].forEach(type => { this._register(addDisposableListener(container, type, () => { this.clearDragTimeout(); })); }); } private clearDragTimeout(): void { if (this.timeout) { clearTimeout(this.timeout); this.timeout = null; } } dispose(): void { super.dispose(); this.clearDragTimeout(); } } // Common data transfers export const DataTransfers = { /** * Application specific resource transfer type */ RESOURCES: 'ResourceURLs', /** * Browser specific transfer type to download */ DOWNLOAD_URL: 'DownloadURL', /** * Browser specific transfer type for files */ FILES: 'Files', /** * Typically transfer type for copy/paste transfers. */ TEXT: 'text/plain' }; export function applyDragImage(event: DragEvent, label: string | null, clazz: string): void { const dragImage = document.createElement('div'); dragImage.className = clazz; dragImage.textContent = label; if (event.dataTransfer) { document.body.appendChild(dragImage); event.dataTransfer.setDragImage(dragImage, -10, -10); // Removes the element when the DND operation is done setTimeout(() => document.body.removeChild(dragImage), 0); } } export interface IDragAndDropData { update(dataTransfer: DataTransfer): void; getData(): any; } export class DragAndDropData<T> implements IDragAndDropData { constructor(private data: T) { } update(): void { // noop } getData(): T { return this.data; } } export interface IStaticDND { CurrentDragAndDropData: IDragAndDropData | undefined; } export const StaticDND: IStaticDND = { CurrentDragAndDropData: undefined };
src/vs/base/browser/dnd.ts
0
https://github.com/microsoft/vscode/commit/135b6da83746477b2983fee879122ceefa70014d
[ 0.00017559263505972922, 0.0001716686674626544, 0.0001676602551015094, 0.0001718642597552389, 0.000002478420583429397 ]
{ "id": 7, "code_window": [ "\n", "\tget showInitialDebugActions(): boolean {\n", "\t\tconst state = this.debugService.state;\n", "\t\treturn state === State.Inactive || this.configurationService.getValue<IDebugConfiguration>('debug').toolBarLocation !== 'docked';\n", "\t}\n", "\n", "\tgetSecondaryActions(): IAction[] {\n", "\t\tif (this.showInitialDebugActions) {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\treturn state === State.Inactive || state === State.Initializing || this.configurationService.getValue<IDebugConfiguration>('debug').toolBarLocation !== 'docked';\n" ], "file_path": "src/vs/workbench/contrib/debug/browser/debugViewlet.ts", "type": "replace", "edit_start_line_idx": 157 }
/*--------------------------------------------------------------------------------------------- * 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/debugViewlet'; import * as nls from 'vs/nls'; import { IAction, IActionViewItem } from 'vs/base/common/actions'; import * as DOM from 'vs/base/browser/dom'; import { IDebugService, VIEWLET_ID, State, BREAKPOINTS_VIEW_ID, IDebugConfiguration, CONTEXT_DEBUG_UX, CONTEXT_DEBUG_UX_KEY, REPL_VIEW_ID } from 'vs/workbench/contrib/debug/common/debug'; import { StartAction, ConfigureAction, SelectAndStartAction, FocusSessionAction } from 'vs/workbench/contrib/debug/browser/debugActions'; import { StartDebugActionViewItem, FocusSessionActionViewItem } from 'vs/workbench/contrib/debug/browser/debugActionViewItems'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions'; import { IProgressService } from 'vs/platform/progress/common/progress'; import { IWorkspaceContextService, WorkbenchState } from 'vs/platform/workspace/common/workspace'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IStorageService } from 'vs/platform/storage/common/storage'; import { IThemeService } from 'vs/platform/theme/common/themeService'; import { IContextMenuService, IContextViewService } from 'vs/platform/contextview/browser/contextView'; import { IDisposable, dispose } from 'vs/base/common/lifecycle'; import { IWorkbenchLayoutService } from 'vs/workbench/services/layout/browser/layoutService'; import { memoize } from 'vs/base/common/decorators'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { DebugToolBar } from 'vs/workbench/contrib/debug/browser/debugToolBar'; import { ViewPane, ViewPaneContainer } from 'vs/workbench/browser/parts/views/viewPaneContainer'; import { IMenu, MenuId, IMenuService, MenuItemAction, SubmenuItemAction } from 'vs/platform/actions/common/actions'; import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { MenuEntryActionViewItem, SubmenuEntryActionViewItem } from 'vs/platform/actions/browser/menuEntryActionViewItem'; import { IViewDescriptorService, IViewsService } from 'vs/workbench/common/views'; import { WelcomeView } from 'vs/workbench/contrib/debug/browser/welcomeView'; import { ToggleViewAction } from 'vs/workbench/browser/actions/layoutActions'; import { RunOnceScheduler } from 'vs/base/common/async'; import { ShowViewletAction } from 'vs/workbench/browser/viewlet'; import { IViewletService } from 'vs/workbench/services/viewlet/browser/viewlet'; import { IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService'; export class DebugViewPaneContainer extends ViewPaneContainer { private startDebugActionViewItem: StartDebugActionViewItem | undefined; private progressResolve: (() => void) | undefined; private breakpointView: ViewPane | undefined; private paneListeners = new Map<string, IDisposable>(); private debugToolBarMenu: IMenu | undefined; private disposeOnTitleUpdate: IDisposable | undefined; private updateToolBarScheduler: RunOnceScheduler; constructor( @IWorkbenchLayoutService layoutService: IWorkbenchLayoutService, @ITelemetryService telemetryService: ITelemetryService, @IProgressService private readonly progressService: IProgressService, @IDebugService private readonly debugService: IDebugService, @IInstantiationService instantiationService: IInstantiationService, @IWorkspaceContextService contextService: IWorkspaceContextService, @IStorageService storageService: IStorageService, @IThemeService themeService: IThemeService, @IContextMenuService contextMenuService: IContextMenuService, @IExtensionService extensionService: IExtensionService, @IConfigurationService configurationService: IConfigurationService, @IContextViewService private readonly contextViewService: IContextViewService, @IMenuService private readonly menuService: IMenuService, @IContextKeyService private readonly contextKeyService: IContextKeyService, @IViewDescriptorService viewDescriptorService: IViewDescriptorService ) { super(VIEWLET_ID, { mergeViewWithContainerWhenSingleView: true }, instantiationService, configurationService, layoutService, contextMenuService, telemetryService, extensionService, themeService, storageService, contextService, viewDescriptorService); this.updateToolBarScheduler = this._register(new RunOnceScheduler(() => { if (this.configurationService.getValue<IDebugConfiguration>('debug').toolBarLocation === 'docked') { this.updateTitleArea(); } }, 20)); // When there are potential updates to the docked debug toolbar we need to update it this._register(this.debugService.onDidChangeState(state => this.onDebugServiceStateChange(state))); this._register(this.debugService.onDidNewSession(() => this.updateToolBarScheduler.schedule())); this._register(this.debugService.getViewModel().onDidFocusSession(() => this.updateToolBarScheduler.schedule())); this._register(this.contextKeyService.onDidChangeContext(e => { if (e.affectsSome(new Set([CONTEXT_DEBUG_UX_KEY]))) { this.updateTitleArea(); } })); this._register(this.contextService.onDidChangeWorkbenchState(() => this.updateTitleArea())); this._register(this.configurationService.onDidChangeConfiguration(e => { if (e.affectsConfiguration('debug.toolBarLocation')) { this.updateTitleArea(); } })); } create(parent: HTMLElement): void { super.create(parent); DOM.addClass(parent, 'debug-viewlet'); } focus(): void { super.focus(); if (this.startDebugActionViewItem) { this.startDebugActionViewItem.focus(); } else { this.focusView(WelcomeView.ID); } } @memoize private get startAction(): StartAction { return this._register(this.instantiationService.createInstance(StartAction, StartAction.ID, StartAction.LABEL)); } @memoize private get configureAction(): ConfigureAction { return this._register(this.instantiationService.createInstance(ConfigureAction, ConfigureAction.ID, ConfigureAction.LABEL)); } @memoize private get toggleReplAction(): OpenDebugConsoleAction { return this._register(this.instantiationService.createInstance(OpenDebugConsoleAction, OpenDebugConsoleAction.ID, OpenDebugConsoleAction.LABEL)); } @memoize private get selectAndStartAction(): SelectAndStartAction { return this._register(this.instantiationService.createInstance(SelectAndStartAction, SelectAndStartAction.ID, nls.localize('startAdditionalSession', "Start Additional Session"))); } getActions(): IAction[] { if (CONTEXT_DEBUG_UX.getValue(this.contextKeyService) === 'simple') { return []; } if (!this.showInitialDebugActions) { if (!this.debugToolBarMenu) { this.debugToolBarMenu = this.menuService.createMenu(MenuId.DebugToolBar, this.contextKeyService); this._register(this.debugToolBarMenu); this._register(this.debugToolBarMenu.onDidChange(() => this.updateToolBarScheduler.schedule())); } const { actions, disposable } = DebugToolBar.getActions(this.debugToolBarMenu, this.debugService, this.instantiationService); if (this.disposeOnTitleUpdate) { dispose(this.disposeOnTitleUpdate); } this.disposeOnTitleUpdate = disposable; return actions; } if (this.contextService.getWorkbenchState() === WorkbenchState.EMPTY) { return [this.toggleReplAction]; } return [this.startAction, this.configureAction, this.toggleReplAction]; } get showInitialDebugActions(): boolean { const state = this.debugService.state; return state === State.Inactive || this.configurationService.getValue<IDebugConfiguration>('debug').toolBarLocation !== 'docked'; } getSecondaryActions(): IAction[] { if (this.showInitialDebugActions) { return []; } return [this.selectAndStartAction, this.configureAction, this.toggleReplAction]; } getActionViewItem(action: IAction): IActionViewItem | undefined { if (action.id === StartAction.ID) { this.startDebugActionViewItem = this.instantiationService.createInstance(StartDebugActionViewItem, null, action); return this.startDebugActionViewItem; } if (action.id === FocusSessionAction.ID) { return new FocusSessionActionViewItem(action, this.debugService, this.themeService, this.contextViewService, this.configurationService); } if (action instanceof MenuItemAction) { return this.instantiationService.createInstance(MenuEntryActionViewItem, action); } else if (action instanceof SubmenuItemAction) { return this.instantiationService.createInstance(SubmenuEntryActionViewItem, action); } return undefined; } focusView(id: string): void { const view = this.getView(id); if (view) { view.focus(); } } private onDebugServiceStateChange(state: State): void { if (this.progressResolve) { this.progressResolve(); this.progressResolve = undefined; } if (state === State.Initializing) { this.progressService.withProgress({ location: VIEWLET_ID, }, _progress => { return new Promise(resolve => this.progressResolve = resolve); }); } this.updateToolBarScheduler.schedule(); } addPanes(panes: { pane: ViewPane, size: number, index?: number }[]): void { super.addPanes(panes); for (const { pane: pane } of panes) { // attach event listener to if (pane.id === BREAKPOINTS_VIEW_ID) { this.breakpointView = pane; this.updateBreakpointsMaxSize(); } else { this.paneListeners.set(pane.id, pane.onDidChange(() => this.updateBreakpointsMaxSize())); } } } removePanes(panes: ViewPane[]): void { super.removePanes(panes); for (const pane of panes) { dispose(this.paneListeners.get(pane.id)); this.paneListeners.delete(pane.id); } } private updateBreakpointsMaxSize(): void { if (this.breakpointView) { // We need to update the breakpoints view since all other views are collapsed #25384 const allOtherCollapsed = this.panes.every(view => !view.isExpanded() || view === this.breakpointView); this.breakpointView.maximumBodySize = allOtherCollapsed ? Number.POSITIVE_INFINITY : this.breakpointView.minimumBodySize; } } } export class OpenDebugConsoleAction extends ToggleViewAction { public static readonly ID = 'workbench.debug.action.toggleRepl'; public static readonly LABEL = nls.localize('toggleDebugPanel', "Debug Console"); constructor( id: string, label: string, @IViewsService viewsService: IViewsService, @IViewDescriptorService viewDescriptorService: IViewDescriptorService, @IContextKeyService contextKeyService: IContextKeyService, @IWorkbenchLayoutService layoutService: IWorkbenchLayoutService ) { super(id, label, REPL_VIEW_ID, viewsService, viewDescriptorService, contextKeyService, layoutService, 'codicon-debug-console'); } } export class OpenDebugViewletAction extends ShowViewletAction { public static readonly ID = VIEWLET_ID; public static readonly LABEL = nls.localize('toggleDebugViewlet', "Show Run and Debug"); constructor( id: string, label: string, @IViewletService viewletService: IViewletService, @IEditorGroupsService editorGroupService: IEditorGroupsService, @IWorkbenchLayoutService layoutService: IWorkbenchLayoutService ) { super(id, label, VIEWLET_ID, viewletService, editorGroupService, layoutService); } }
src/vs/workbench/contrib/debug/browser/debugViewlet.ts
1
https://github.com/microsoft/vscode/commit/135b6da83746477b2983fee879122ceefa70014d
[ 0.9983201622962952, 0.14338824152946472, 0.00016435461293440312, 0.0002691197150852531, 0.34285688400268555 ]
{ "id": 7, "code_window": [ "\n", "\tget showInitialDebugActions(): boolean {\n", "\t\tconst state = this.debugService.state;\n", "\t\treturn state === State.Inactive || this.configurationService.getValue<IDebugConfiguration>('debug').toolBarLocation !== 'docked';\n", "\t}\n", "\n", "\tgetSecondaryActions(): IAction[] {\n", "\t\tif (this.showInitialDebugActions) {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\treturn state === State.Inactive || state === State.Initializing || this.configurationService.getValue<IDebugConfiguration>('debug').toolBarLocation !== 'docked';\n" ], "file_path": "src/vs/workbench/contrib/debug/browser/debugViewlet.ts", "type": "replace", "edit_start_line_idx": 157 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as assert from 'assert'; import * as vscode from 'vscode'; import { ExtHostDocumentsAndEditors } from 'vs/workbench/api/common/extHostDocumentsAndEditors'; import { TestRPCProtocol } from 'vs/workbench/test/browser/api/testRPCProtocol'; import { DisposableStore } from 'vs/base/common/lifecycle'; import { NullLogService } from 'vs/platform/log/common/log'; import { mock } from 'vs/base/test/common/mock'; import { IModelAddedData, MainContext, MainThreadCommandsShape, MainThreadNotebookShape } from 'vs/workbench/api/common/extHost.protocol'; import { ExtHostNotebookDocument, ExtHostNotebookController } from 'vs/workbench/api/common/extHostNotebook'; import { CellKind, CellUri, NotebookCellsChangeType } from 'vs/workbench/contrib/notebook/common/notebookCommon'; import { URI } from 'vs/base/common/uri'; import { ExtHostDocuments } from 'vs/workbench/api/common/extHostDocuments'; import { ExtHostCommands } from 'vs/workbench/api/common/extHostCommands'; import { nullExtensionDescription } from 'vs/workbench/services/extensions/common/extensions'; import { isEqual } from 'vs/base/common/resources'; import { IExtensionStoragePaths } from 'vs/workbench/api/common/extHostStoragePaths'; import { generateUuid } from 'vs/base/common/uuid'; suite('NotebookCell#Document', function () { let rpcProtocol: TestRPCProtocol; let notebook: ExtHostNotebookDocument; let extHostDocumentsAndEditors: ExtHostDocumentsAndEditors; let extHostDocuments: ExtHostDocuments; let extHostNotebooks: ExtHostNotebookController; const notebookUri = URI.parse('test:///notebook.file'); const disposables = new DisposableStore(); setup(async function () { disposables.clear(); rpcProtocol = new TestRPCProtocol(); rpcProtocol.set(MainContext.MainThreadCommands, new class extends mock<MainThreadCommandsShape>() { $registerCommand() { } }); rpcProtocol.set(MainContext.MainThreadNotebook, new class extends mock<MainThreadNotebookShape>() { async $registerNotebookProvider() { } async $unregisterNotebookProvider() { } }); extHostDocumentsAndEditors = new ExtHostDocumentsAndEditors(rpcProtocol, new NullLogService()); extHostDocuments = new ExtHostDocuments(rpcProtocol, extHostDocumentsAndEditors); const extHostStoragePaths = new class extends mock<IExtensionStoragePaths>() { workspaceValue() { return URI.from({ scheme: 'test', path: generateUuid() }); } }; extHostNotebooks = new ExtHostNotebookController(rpcProtocol, new ExtHostCommands(rpcProtocol, new NullLogService()), extHostDocumentsAndEditors, { isExtensionDevelopmentDebug: false, webviewCspSource: '', webviewResourceRoot: '' }, new NullLogService(), extHostStoragePaths); let reg = extHostNotebooks.registerNotebookContentProvider(nullExtensionDescription, 'test', new class extends mock<vscode.NotebookContentProvider>() { // async openNotebook() { } }); extHostNotebooks.$acceptDocumentAndEditorsDelta({ addedDocuments: [{ handle: 0, uri: notebookUri, viewType: 'test', versionId: 0, cells: [{ handle: 0, uri: CellUri.generate(notebookUri, 0), source: ['### Heading'], eol: '\n', language: 'markdown', cellKind: CellKind.Markdown, outputs: [], }, { handle: 1, uri: CellUri.generate(notebookUri, 1), source: ['console.log("aaa")', 'console.log("bbb")'], eol: '\n', language: 'javascript', cellKind: CellKind.Code, outputs: [], }], }], addedEditors: [{ documentUri: notebookUri, id: '_notebook_editor_0', selections: [0] }] }); extHostNotebooks.$acceptDocumentAndEditorsDelta({ newActiveEditor: '_notebook_editor_0' }); notebook = extHostNotebooks.notebookDocuments[0]!; disposables.add(reg); disposables.add(notebook); disposables.add(extHostDocuments); }); test('cell document is vscode.TextDocument', async function () { assert.strictEqual(notebook.cells.length, 2); const [c1, c2] = notebook.cells; const d1 = extHostDocuments.getDocument(c1.uri); assert.ok(d1); assert.equal(d1.languageId, c1.language); assert.equal(d1.version, 1); assert.ok(d1.notebook === notebook); const d2 = extHostDocuments.getDocument(c2.uri); assert.ok(d2); assert.equal(d2.languageId, c2.language); assert.equal(d2.version, 1); assert.ok(d2.notebook === notebook); }); test('cell document goes when notebook closes', async function () { const cellUris: string[] = []; for (let cell of notebook.cells) { assert.ok(extHostDocuments.getDocument(cell.uri)); cellUris.push(cell.uri.toString()); } const removedCellUris: string[] = []; const reg = extHostDocuments.onDidRemoveDocument(doc => { removedCellUris.push(doc.uri.toString()); }); extHostNotebooks.$acceptDocumentAndEditorsDelta({ removedDocuments: [notebook.uri] }); reg.dispose(); assert.strictEqual(removedCellUris.length, 2); assert.deepStrictEqual(removedCellUris.sort(), cellUris.sort()); }); test('cell document is vscode.TextDocument after changing it', async function () { const p = new Promise((resolve, reject) => { extHostNotebooks.onDidChangeNotebookCells(e => { try { assert.strictEqual(e.changes.length, 1); assert.strictEqual(e.changes[0].items.length, 2); const [first, second] = e.changes[0].items; const doc1 = extHostDocuments.getAllDocumentData().find(data => isEqual(data.document.uri, first.uri)); assert.ok(doc1); assert.strictEqual(doc1?.document === first.document, true); const doc2 = extHostDocuments.getAllDocumentData().find(data => isEqual(data.document.uri, second.uri)); assert.ok(doc2); assert.strictEqual(doc2?.document === second.document, true); resolve(); } catch (err) { reject(err); } }); }); extHostNotebooks.$acceptModelChanged(notebookUri, { kind: NotebookCellsChangeType.ModelChange, versionId: notebook.versionId + 1, changes: [[0, 0, [{ handle: 2, uri: CellUri.generate(notebookUri, 2), source: ['Hello', 'World', 'Hello World!'], eol: '\n', language: 'test', cellKind: CellKind.Code, outputs: [], }, { handle: 3, uri: CellUri.generate(notebookUri, 3), source: ['Hallo', 'Welt', 'Hallo Welt!'], eol: '\n', language: 'test', cellKind: CellKind.Code, outputs: [], }]]] }); await p; }); test('cell document stays open when notebook is still open', async function () { const docs: vscode.TextDocument[] = []; const addData: IModelAddedData[] = []; for (let cell of notebook.cells) { const doc = extHostDocuments.getDocument(cell.uri); assert.ok(doc); assert.equal(extHostDocuments.getDocument(cell.uri).isClosed, false); docs.push(doc); addData.push({ EOL: '\n', isDirty: doc.isDirty, lines: doc.getText().split('\n'), modeId: doc.languageId, uri: doc.uri, versionId: doc.version }); } // this call happens when opening a document on the main side extHostDocumentsAndEditors.$acceptDocumentsAndEditorsDelta({ addedDocuments: addData }); // this call happens when closing a document from the main side extHostDocumentsAndEditors.$acceptDocumentsAndEditorsDelta({ removedDocuments: docs.map(d => d.uri) }); // notebook is still open -> cell documents stay open for (let cell of notebook.cells) { assert.ok(extHostDocuments.getDocument(cell.uri)); assert.equal(extHostDocuments.getDocument(cell.uri).isClosed, false); } // close notebook -> docs are closed extHostNotebooks.$acceptDocumentAndEditorsDelta({ removedDocuments: [notebook.uri] }); for (let cell of notebook.cells) { assert.throws(() => extHostDocuments.getDocument(cell.uri)); } for (let doc of docs) { assert.equal(doc.isClosed, true); } }); test('cell document knows notebook', function () { for (let cells of notebook.cells) { assert.equal(cells.document.notebook === notebook, true); } }); });
src/vs/workbench/test/browser/api/extHostNotebook.test.ts
0
https://github.com/microsoft/vscode/commit/135b6da83746477b2983fee879122ceefa70014d
[ 0.00017850908625405282, 0.00017546811432112008, 0.00016721209976822138, 0.00017610668146517128, 0.0000024696230411791475 ]
{ "id": 7, "code_window": [ "\n", "\tget showInitialDebugActions(): boolean {\n", "\t\tconst state = this.debugService.state;\n", "\t\treturn state === State.Inactive || this.configurationService.getValue<IDebugConfiguration>('debug').toolBarLocation !== 'docked';\n", "\t}\n", "\n", "\tgetSecondaryActions(): IAction[] {\n", "\t\tif (this.showInitialDebugActions) {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\treturn state === State.Inactive || state === State.Initializing || this.configurationService.getValue<IDebugConfiguration>('debug').toolBarLocation !== 'docked';\n" ], "file_path": "src/vs/workbench/contrib/debug/browser/debugViewlet.ts", "type": "replace", "edit_start_line_idx": 157 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as os from 'os'; import * as path from 'path'; import * as vscode from 'vscode'; import * as objects from '../utils/objects'; import * as arrays from './arrays'; export enum TsServerLogLevel { Off, Normal, Terse, Verbose, } export namespace TsServerLogLevel { export function fromString(value: string): TsServerLogLevel { switch (value && value.toLowerCase()) { case 'normal': return TsServerLogLevel.Normal; case 'terse': return TsServerLogLevel.Terse; case 'verbose': return TsServerLogLevel.Verbose; case 'off': default: return TsServerLogLevel.Off; } } export function toString(value: TsServerLogLevel): string { switch (value) { case TsServerLogLevel.Normal: return 'normal'; case TsServerLogLevel.Terse: return 'terse'; case TsServerLogLevel.Verbose: return 'verbose'; case TsServerLogLevel.Off: default: return 'off'; } } } export const enum SeparateSyntaxServerConfiguration { Disabled, Enabled, } export class TypeScriptServiceConfiguration { public readonly locale: string | null; public readonly globalTsdk: string | null; public readonly localTsdk: string | null; public readonly npmLocation: string | null; public readonly tsServerLogLevel: TsServerLogLevel = TsServerLogLevel.Off; public readonly tsServerPluginPaths: readonly string[]; public readonly checkJs: boolean; public readonly experimentalDecorators: boolean; public readonly disableAutomaticTypeAcquisition: boolean; public readonly separateSyntaxServer: SeparateSyntaxServerConfiguration; public readonly enableProjectDiagnostics: boolean; public readonly maxTsServerMemory: number; public readonly enablePromptUseWorkspaceTsdk: boolean; public readonly watchOptions: protocol.WatchOptions | undefined; public readonly includePackageJsonAutoImports: 'auto' | 'on' | 'off' | undefined; public static loadFromWorkspace(): TypeScriptServiceConfiguration { return new TypeScriptServiceConfiguration(); } private constructor() { const configuration = vscode.workspace.getConfiguration(); this.locale = TypeScriptServiceConfiguration.extractLocale(configuration); this.globalTsdk = TypeScriptServiceConfiguration.extractGlobalTsdk(configuration); this.localTsdk = TypeScriptServiceConfiguration.extractLocalTsdk(configuration); this.npmLocation = TypeScriptServiceConfiguration.readNpmLocation(configuration); this.tsServerLogLevel = TypeScriptServiceConfiguration.readTsServerLogLevel(configuration); this.tsServerPluginPaths = TypeScriptServiceConfiguration.readTsServerPluginPaths(configuration); this.checkJs = TypeScriptServiceConfiguration.readCheckJs(configuration); this.experimentalDecorators = TypeScriptServiceConfiguration.readExperimentalDecorators(configuration); this.disableAutomaticTypeAcquisition = TypeScriptServiceConfiguration.readDisableAutomaticTypeAcquisition(configuration); this.separateSyntaxServer = TypeScriptServiceConfiguration.readUseSeparateSyntaxServer(configuration); this.enableProjectDiagnostics = TypeScriptServiceConfiguration.readEnableProjectDiagnostics(configuration); this.maxTsServerMemory = TypeScriptServiceConfiguration.readMaxTsServerMemory(configuration); this.enablePromptUseWorkspaceTsdk = TypeScriptServiceConfiguration.readEnablePromptUseWorkspaceTsdk(configuration); this.watchOptions = TypeScriptServiceConfiguration.readWatchOptions(configuration); this.includePackageJsonAutoImports = TypeScriptServiceConfiguration.readIncludePackageJsonAutoImports(configuration); } public isEqualTo(other: TypeScriptServiceConfiguration): boolean { return this.locale === other.locale && this.globalTsdk === other.globalTsdk && this.localTsdk === other.localTsdk && this.npmLocation === other.npmLocation && this.tsServerLogLevel === other.tsServerLogLevel && this.checkJs === other.checkJs && this.experimentalDecorators === other.experimentalDecorators && this.disableAutomaticTypeAcquisition === other.disableAutomaticTypeAcquisition && arrays.equals(this.tsServerPluginPaths, other.tsServerPluginPaths) && this.separateSyntaxServer === other.separateSyntaxServer && this.enableProjectDiagnostics === other.enableProjectDiagnostics && this.maxTsServerMemory === other.maxTsServerMemory && objects.equals(this.watchOptions, other.watchOptions) && this.enablePromptUseWorkspaceTsdk === other.enablePromptUseWorkspaceTsdk && this.includePackageJsonAutoImports === other.includePackageJsonAutoImports; } private static fixPathPrefixes(inspectValue: string): string { const pathPrefixes = ['~' + path.sep]; for (const pathPrefix of pathPrefixes) { if (inspectValue.startsWith(pathPrefix)) { return path.join(os.homedir(), inspectValue.slice(pathPrefix.length)); } } return inspectValue; } private static extractGlobalTsdk(configuration: vscode.WorkspaceConfiguration): string | null { const inspect = configuration.inspect('typescript.tsdk'); if (inspect && typeof inspect.globalValue === 'string') { return this.fixPathPrefixes(inspect.globalValue); } return null; } private static extractLocalTsdk(configuration: vscode.WorkspaceConfiguration): string | null { const inspect = configuration.inspect('typescript.tsdk'); if (inspect && typeof inspect.workspaceValue === 'string') { return this.fixPathPrefixes(inspect.workspaceValue); } return null; } private static readTsServerLogLevel(configuration: vscode.WorkspaceConfiguration): TsServerLogLevel { const setting = configuration.get<string>('typescript.tsserver.log', 'off'); return TsServerLogLevel.fromString(setting); } private static readTsServerPluginPaths(configuration: vscode.WorkspaceConfiguration): string[] { return configuration.get<string[]>('typescript.tsserver.pluginPaths', []); } private static readCheckJs(configuration: vscode.WorkspaceConfiguration): boolean { return configuration.get<boolean>('javascript.implicitProjectConfig.checkJs', false); } private static readExperimentalDecorators(configuration: vscode.WorkspaceConfiguration): boolean { return configuration.get<boolean>('javascript.implicitProjectConfig.experimentalDecorators', false); } private static readNpmLocation(configuration: vscode.WorkspaceConfiguration): string | null { return configuration.get<string | null>('typescript.npm', null); } private static readDisableAutomaticTypeAcquisition(configuration: vscode.WorkspaceConfiguration): boolean { return configuration.get<boolean>('typescript.disableAutomaticTypeAcquisition', false); } private static extractLocale(configuration: vscode.WorkspaceConfiguration): string | null { return configuration.get<string | null>('typescript.locale', null); } private static readUseSeparateSyntaxServer(configuration: vscode.WorkspaceConfiguration): SeparateSyntaxServerConfiguration { const value = configuration.get('typescript.tsserver.useSeparateSyntaxServer', true); if (value === true) { return SeparateSyntaxServerConfiguration.Enabled; } return SeparateSyntaxServerConfiguration.Disabled; } private static readEnableProjectDiagnostics(configuration: vscode.WorkspaceConfiguration): boolean { return configuration.get<boolean>('typescript.tsserver.experimental.enableProjectDiagnostics', false); } private static readWatchOptions(configuration: vscode.WorkspaceConfiguration): protocol.WatchOptions | undefined { return configuration.get<protocol.WatchOptions>('typescript.tsserver.watchOptions'); } private static readIncludePackageJsonAutoImports(configuration: vscode.WorkspaceConfiguration): 'auto' | 'on' | 'off' | undefined { return configuration.get<'auto' | 'on' | 'off'>('typescript.preferences.includePackageJsonAutoImports'); } private static readMaxTsServerMemory(configuration: vscode.WorkspaceConfiguration): number { const defaultMaxMemory = 3072; const minimumMaxMemory = 128; const memoryInMB = configuration.get<number>('typescript.tsserver.maxTsServerMemory', defaultMaxMemory); if (!Number.isSafeInteger(memoryInMB)) { return defaultMaxMemory; } return Math.max(memoryInMB, minimumMaxMemory); } private static readEnablePromptUseWorkspaceTsdk(configuration: vscode.WorkspaceConfiguration): boolean { return configuration.get<boolean>('typescript.enablePromptUseWorkspaceTsdk', false); } }
extensions/typescript-language-features/src/utils/configuration.ts
0
https://github.com/microsoft/vscode/commit/135b6da83746477b2983fee879122ceefa70014d
[ 0.00022573572641704232, 0.00017416746413800865, 0.00016256736125797033, 0.00017169608327094465, 0.000012588222489284817 ]
{ "id": 7, "code_window": [ "\n", "\tget showInitialDebugActions(): boolean {\n", "\t\tconst state = this.debugService.state;\n", "\t\treturn state === State.Inactive || this.configurationService.getValue<IDebugConfiguration>('debug').toolBarLocation !== 'docked';\n", "\t}\n", "\n", "\tgetSecondaryActions(): IAction[] {\n", "\t\tif (this.showInitialDebugActions) {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\treturn state === State.Inactive || state === State.Initializing || this.configurationService.getValue<IDebugConfiguration>('debug').toolBarLocation !== 'docked';\n" ], "file_path": "src/vs/workbench/contrib/debug/browser/debugViewlet.ts", "type": "replace", "edit_start_line_idx": 157 }
/*--------------------------------------------------------------------------------------------- * 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 { createDecorator } from 'vs/platform/instantiation/common/instantiation'; import { JSONPath } from 'vs/base/common/json'; export const IJSONEditingService = createDecorator<IJSONEditingService>('jsonEditingService'); export const enum JSONEditingErrorCode { /** * Error when trying to write and save to the file while it is dirty in the editor. */ ERROR_FILE_DIRTY, /** * Error when trying to write to a file that contains JSON errors. */ ERROR_INVALID_FILE } export class JSONEditingError extends Error { constructor(message: string, public code: JSONEditingErrorCode) { super(message); } } export interface IJSONValue { path: JSONPath; value: any; } export interface IJSONEditingService { readonly _serviceBrand: undefined; write(resource: URI, values: IJSONValue[], save: boolean): Promise<void>; }
src/vs/workbench/services/configuration/common/jsonEditing.ts
0
https://github.com/microsoft/vscode/commit/135b6da83746477b2983fee879122ceefa70014d
[ 0.0001767690700944513, 0.00017215758271049708, 0.00016834844427648932, 0.0001700088323559612, 0.0000035514904084266163 ]
{ "id": 0, "code_window": [ " parseSemicolon();\n", " return finishNode(node);\n", " }\n", "\n", " function parseIndexSignatureMember(): SignatureDeclaration {\n", " var node = <SignatureDeclaration>createNode(SyntaxKind.IndexSignature);\n", " node.parameters = parseParameterList(SyntaxKind.OpenBracketToken, SyntaxKind.CloseBracketToken);\n", " node.type = parseTypeAnnotation();\n", " parseSemicolon();\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " function parseIndexSignatureMember(flags: NodeFlags, pos?: number): SignatureDeclaration {\n", " var node = <SignatureDeclaration>createNode(SyntaxKind.IndexSignature, pos);\n", " if (flags) {\n", " node.flags = flags;\n", " }\n", "\n" ], "file_path": "src/compiler/parser.ts", "type": "replace", "edit_start_line_idx": 1000 }
tests/cases/conformance/parser/ecmascript5/IndexMemberDeclarations/parserIndexMemberDeclaration10.ts(2,4): error TS1145: Modifiers not permitted on index signature members. tests/cases/conformance/parser/ecmascript5/IndexMemberDeclarations/parserIndexMemberDeclaration10.ts(2,11): error TS1030: 'static' modifier already seen. ==== tests/cases/conformance/parser/ecmascript5/IndexMemberDeclarations/parserIndexMemberDeclaration10.ts (2 errors) ==== class C { static static [x: string]: string; ~~~~~~~~~~~~~ !!! error TS1145: Modifiers not permitted on index signature members. ~~~~~~ !!! error TS1030: 'static' modifier already seen. }
tests/baselines/reference/parserIndexMemberDeclaration10.errors.txt
1
https://github.com/microsoft/TypeScript/commit/6b866e719e0c1291b87ac7dcdac4cdf1bc8cdb3f
[ 0.0006253964966163039, 0.0003990709374193102, 0.00017274539277423173, 0.0003990709374193102, 0.0002263255591969937 ]
{ "id": 0, "code_window": [ " parseSemicolon();\n", " return finishNode(node);\n", " }\n", "\n", " function parseIndexSignatureMember(): SignatureDeclaration {\n", " var node = <SignatureDeclaration>createNode(SyntaxKind.IndexSignature);\n", " node.parameters = parseParameterList(SyntaxKind.OpenBracketToken, SyntaxKind.CloseBracketToken);\n", " node.type = parseTypeAnnotation();\n", " parseSemicolon();\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " function parseIndexSignatureMember(flags: NodeFlags, pos?: number): SignatureDeclaration {\n", " var node = <SignatureDeclaration>createNode(SyntaxKind.IndexSignature, pos);\n", " if (flags) {\n", " node.flags = flags;\n", " }\n", "\n" ], "file_path": "src/compiler/parser.ts", "type": "replace", "edit_start_line_idx": 1000 }
=== tests/cases/compiler/concatError.ts === var n1: number[]; >n1 : number[] /* interface Array<T> { concat(...items: T[][]): T[]; // Note: This overload needs to be picked for arrays of arrays, even though both are applicable concat(...items: T[]): T[]; } */ var fa: number[]; >fa : number[] fa = fa.concat([0]); >fa = fa.concat([0]) : number[] >fa : number[] >fa.concat([0]) : number[] >fa.concat : { <U extends number[]>(...items: U[]): number[]; (...items: number[]): number[]; } >fa : number[] >concat : { <U extends number[]>(...items: U[]): number[]; (...items: number[]): number[]; } >[0] : number[] fa = fa.concat(0); >fa = fa.concat(0) : number[] >fa : number[] >fa.concat(0) : number[] >fa.concat : { <U extends number[]>(...items: U[]): number[]; (...items: number[]): number[]; } >fa : number[] >concat : { <U extends number[]>(...items: U[]): number[]; (...items: number[]): number[]; } /* declare class C<T> { public m(p1: C<C<T>>): C<T>; //public p: T; } var c: C<number>; var cc: C<C<number>>; c = c.m(cc); */
tests/baselines/reference/concatError.types
0
https://github.com/microsoft/TypeScript/commit/6b866e719e0c1291b87ac7dcdac4cdf1bc8cdb3f
[ 0.0001787535147741437, 0.0001728163188090548, 0.0001680033456068486, 0.0001716395781841129, 0.000004342787633504486 ]
{ "id": 0, "code_window": [ " parseSemicolon();\n", " return finishNode(node);\n", " }\n", "\n", " function parseIndexSignatureMember(): SignatureDeclaration {\n", " var node = <SignatureDeclaration>createNode(SyntaxKind.IndexSignature);\n", " node.parameters = parseParameterList(SyntaxKind.OpenBracketToken, SyntaxKind.CloseBracketToken);\n", " node.type = parseTypeAnnotation();\n", " parseSemicolon();\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " function parseIndexSignatureMember(flags: NodeFlags, pos?: number): SignatureDeclaration {\n", " var node = <SignatureDeclaration>createNode(SyntaxKind.IndexSignature, pos);\n", " if (flags) {\n", " node.flags = flags;\n", " }\n", "\n" ], "file_path": "src/compiler/parser.ts", "type": "replace", "edit_start_line_idx": 1000 }
//// [tests/cases/compiler/commentsExternalModules3.ts] //// //// [commentsExternalModules2_0.ts] /** Module comment*/ export module m1 { /** b's comment*/ export var b: number; /** foo's comment*/ function foo() { return b; } /** m2 comments*/ export module m2 { /** class comment;*/ export class c { }; /** i*/ export var i = new c(); } /** exported function*/ export function fooExport() { return foo(); } } m1.fooExport(); var myvar = new m1.m2.c(); /** Module comment */ export module m4 { /** b's comment */ export var b: number; /** foo's comment */ function foo() { return b; } /** m2 comments */ export module m2 { /** class comment; */ export class c { }; /** i */ export var i = new c(); } /** exported function */ export function fooExport() { return foo(); } } m4.fooExport(); var myvar2 = new m4.m2.c(); //// [commentsExternalModules_1.ts] /**This is on import declaration*/ import extMod = require("commentsExternalModules2_0"); // trailing comment 1 extMod.m1.fooExport(); export var newVar = new extMod.m1.m2.c(); extMod.m4.fooExport(); export var newVar2 = new extMod.m4.m2.c(); //// [commentsExternalModules2_0.js] /** Module comment*/ var m1; (function (m1) { /** b's comment*/ m1.b; /** foo's comment*/ function foo() { return m1.b; } /** m2 comments*/ var m2; (function (m2) { /** class comment;*/ var c = (function () { function c() { } return c; })(); m2.c = c; ; /** i*/ m2.i = new c(); })(m2 = m1.m2 || (m1.m2 = {})); /** exported function*/ function fooExport() { return foo(); } m1.fooExport = fooExport; })(m1 = exports.m1 || (exports.m1 = {})); m1.fooExport(); var myvar = new m1.m2.c(); /** Module comment */ var m4; (function (m4) { /** b's comment */ m4.b; /** foo's comment */ function foo() { return m4.b; } /** m2 comments */ var m2; (function (m2) { /** class comment; */ var c = (function () { function c() { } return c; })(); m2.c = c; ; /** i */ m2.i = new c(); })(m2 = m4.m2 || (m4.m2 = {})); /** exported function */ function fooExport() { return foo(); } m4.fooExport = fooExport; })(m4 = exports.m4 || (exports.m4 = {})); m4.fooExport(); var myvar2 = new m4.m2.c(); //// [commentsExternalModules_1.js] /**This is on import declaration*/ var extMod = require("commentsExternalModules2_0"); // trailing comment 1 extMod.m1.fooExport(); exports.newVar = new extMod.m1.m2.c(); extMod.m4.fooExport(); exports.newVar2 = new extMod.m4.m2.c(); //// [commentsExternalModules2_0.d.ts] /** Module comment*/ export declare module m1 { /** b's comment*/ var b: number; /** m2 comments*/ module m2 { /** class comment;*/ class c { } /** i*/ var i: c; } /** exported function*/ function fooExport(): number; } /** Module comment */ export declare module m4 { /** b's comment */ var b: number; /** m2 comments */ module m2 { /** class comment; */ class c { } /** i */ var i: c; } /** exported function */ function fooExport(): number; } //// [commentsExternalModules_1.d.ts] /**This is on import declaration*/ import extMod = require("commentsExternalModules2_0"); export declare var newVar: extMod.m1.m2.c; export declare var newVar2: extMod.m4.m2.c;
tests/baselines/reference/commentsExternalModules3.js
0
https://github.com/microsoft/TypeScript/commit/6b866e719e0c1291b87ac7dcdac4cdf1bc8cdb3f
[ 0.000177276975591667, 0.00017409847350791097, 0.00017057292279787362, 0.00017433991888538003, 0.0000019903964130207896 ]
{ "id": 0, "code_window": [ " parseSemicolon();\n", " return finishNode(node);\n", " }\n", "\n", " function parseIndexSignatureMember(): SignatureDeclaration {\n", " var node = <SignatureDeclaration>createNode(SyntaxKind.IndexSignature);\n", " node.parameters = parseParameterList(SyntaxKind.OpenBracketToken, SyntaxKind.CloseBracketToken);\n", " node.type = parseTypeAnnotation();\n", " parseSemicolon();\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " function parseIndexSignatureMember(flags: NodeFlags, pos?: number): SignatureDeclaration {\n", " var node = <SignatureDeclaration>createNode(SyntaxKind.IndexSignature, pos);\n", " if (flags) {\n", " node.flags = flags;\n", " }\n", "\n" ], "file_path": "src/compiler/parser.ts", "type": "replace", "edit_start_line_idx": 1000 }
=== tests/cases/conformance/es6/templates/templateStringWithEmbeddedAddition.ts === var x = `abc${ 10 + 10 }def`; >x : string >10 + 10 : number
tests/baselines/reference/templateStringWithEmbeddedAddition.types
0
https://github.com/microsoft/TypeScript/commit/6b866e719e0c1291b87ac7dcdac4cdf1bc8cdb3f
[ 0.00017262520850636065, 0.00017262520850636065, 0.00017262520850636065, 0.00017262520850636065, 0 ]
{ "id": 2, "code_window": [ " if (token >= SyntaxKind.Identifier || token === SyntaxKind.StringLiteral || token === SyntaxKind.NumericLiteral) {\n", " return parsePropertyMemberDeclaration(pos, flags);\n", " }\n", " if (token === SyntaxKind.OpenBracketToken) {\n", " if (flags) {\n", " var start = getTokenPos(pos);\n", " var length = getNodePos() - start;\n", " errorAtPos(start, length, Diagnostics.Modifiers_not_permitted_on_index_signature_members);\n", " }\n", " return parseIndexSignatureMember();\n", " }\n", "\n", " // 'isClassMemberStart' should have hinted not to attempt parsing.\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " return parseIndexSignatureMember(flags, pos);\n" ], "file_path": "src/compiler/parser.ts", "type": "replace", "edit_start_line_idx": 2697 }
tests/cases/conformance/parser/ecmascript5/IndexMemberDeclarations/parserIndexMemberDeclaration10.ts(2,4): error TS1145: Modifiers not permitted on index signature members. tests/cases/conformance/parser/ecmascript5/IndexMemberDeclarations/parserIndexMemberDeclaration10.ts(2,11): error TS1030: 'static' modifier already seen. ==== tests/cases/conformance/parser/ecmascript5/IndexMemberDeclarations/parserIndexMemberDeclaration10.ts (2 errors) ==== class C { static static [x: string]: string; ~~~~~~~~~~~~~ !!! error TS1145: Modifiers not permitted on index signature members. ~~~~~~ !!! error TS1030: 'static' modifier already seen. }
tests/baselines/reference/parserIndexMemberDeclaration10.errors.txt
1
https://github.com/microsoft/TypeScript/commit/6b866e719e0c1291b87ac7dcdac4cdf1bc8cdb3f
[ 0.000304849207168445, 0.0002364606480114162, 0.0001680720888543874, 0.0002364606480114162, 0.0000683885591570288 ]
{ "id": 2, "code_window": [ " if (token >= SyntaxKind.Identifier || token === SyntaxKind.StringLiteral || token === SyntaxKind.NumericLiteral) {\n", " return parsePropertyMemberDeclaration(pos, flags);\n", " }\n", " if (token === SyntaxKind.OpenBracketToken) {\n", " if (flags) {\n", " var start = getTokenPos(pos);\n", " var length = getNodePos() - start;\n", " errorAtPos(start, length, Diagnostics.Modifiers_not_permitted_on_index_signature_members);\n", " }\n", " return parseIndexSignatureMember();\n", " }\n", "\n", " // 'isClassMemberStart' should have hinted not to attempt parsing.\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " return parseIndexSignatureMember(flags, pos);\n" ], "file_path": "src/compiler/parser.ts", "type": "replace", "edit_start_line_idx": 2697 }
//// [assignmentCompatability11.ts] module __test1__ { export interface interfaceWithPublicAndOptional<T,U> { one: T; two?: U; }; var obj4: interfaceWithPublicAndOptional<number,string> = { one: 1 };; export var __val__obj4 = obj4; } module __test2__ { export var obj = {two: 1}; export var __val__obj = obj; } __test2__.__val__obj = __test1__.__val__obj4 //// [assignmentCompatability11.js] var __test1__; (function (__test1__) { ; var obj4 = { one: 1 }; ; __test1__.__val__obj4 = obj4; })(__test1__ || (__test1__ = {})); var __test2__; (function (__test2__) { __test2__.obj = { two: 1 }; __test2__.__val__obj = __test2__.obj; })(__test2__ || (__test2__ = {})); __test2__.__val__obj = __test1__.__val__obj4;
tests/baselines/reference/assignmentCompatability11.js
0
https://github.com/microsoft/TypeScript/commit/6b866e719e0c1291b87ac7dcdac4cdf1bc8cdb3f
[ 0.00017492003098595887, 0.00017205148469656706, 0.00016974609752651304, 0.0001714882964733988, 0.0000021494611246453132 ]
{ "id": 2, "code_window": [ " if (token >= SyntaxKind.Identifier || token === SyntaxKind.StringLiteral || token === SyntaxKind.NumericLiteral) {\n", " return parsePropertyMemberDeclaration(pos, flags);\n", " }\n", " if (token === SyntaxKind.OpenBracketToken) {\n", " if (flags) {\n", " var start = getTokenPos(pos);\n", " var length = getNodePos() - start;\n", " errorAtPos(start, length, Diagnostics.Modifiers_not_permitted_on_index_signature_members);\n", " }\n", " return parseIndexSignatureMember();\n", " }\n", "\n", " // 'isClassMemberStart' should have hinted not to attempt parsing.\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " return parseIndexSignatureMember(flags, pos);\n" ], "file_path": "src/compiler/parser.ts", "type": "replace", "edit_start_line_idx": 2697 }
//// [parserClassDeclarationIndexSignature1.ts] class C { [index:number]:number } //// [parserClassDeclarationIndexSignature1.js] var C = (function () { function C() { } return C; })();
tests/baselines/reference/parserClassDeclarationIndexSignature1.js
0
https://github.com/microsoft/TypeScript/commit/6b866e719e0c1291b87ac7dcdac4cdf1bc8cdb3f
[ 0.000523590249940753, 0.00034405436599627137, 0.00016451846749987453, 0.00034405436599627137, 0.00017953589849639684 ]
{ "id": 2, "code_window": [ " if (token >= SyntaxKind.Identifier || token === SyntaxKind.StringLiteral || token === SyntaxKind.NumericLiteral) {\n", " return parsePropertyMemberDeclaration(pos, flags);\n", " }\n", " if (token === SyntaxKind.OpenBracketToken) {\n", " if (flags) {\n", " var start = getTokenPos(pos);\n", " var length = getNodePos() - start;\n", " errorAtPos(start, length, Diagnostics.Modifiers_not_permitted_on_index_signature_members);\n", " }\n", " return parseIndexSignatureMember();\n", " }\n", "\n", " // 'isClassMemberStart' should have hinted not to attempt parsing.\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " return parseIndexSignatureMember(flags, pos);\n" ], "file_path": "src/compiler/parser.ts", "type": "replace", "edit_start_line_idx": 2697 }
//// [typeValueConflict2.ts] module M1 { export class A<T> { constructor(a: T) { } } } module M2 { var M1 = 0; // Should error. M1 should bind to the variable, not to the module. class B extends M1.A<string> { } } module M3 { // Shouldn't error class B extends M1.A<string> { } } //// [typeValueConflict2.js] var __extends = this.__extends || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } __.prototype = b.prototype; d.prototype = new __(); }; var M1; (function (M1) { var A = (function () { function A(a) { } return A; })(); M1.A = A; })(M1 || (M1 = {})); var M2; (function (M2) { var M1 = 0; // Should error. M1 should bind to the variable, not to the module. var B = (function (_super) { __extends(B, _super); function B() { _super.apply(this, arguments); } return B; })(M1.A); })(M2 || (M2 = {})); var M3; (function (M3) { // Shouldn't error var B = (function (_super) { __extends(B, _super); function B() { _super.apply(this, arguments); } return B; })(M1.A); })(M3 || (M3 = {}));
tests/baselines/reference/typeValueConflict2.js
0
https://github.com/microsoft/TypeScript/commit/6b866e719e0c1291b87ac7dcdac4cdf1bc8cdb3f
[ 0.00017463888798374683, 0.0001695082028163597, 0.00016578771464992315, 0.00016941616195254028, 0.000002727432729443535 ]
{ "id": 4, "code_window": [ "tests/cases/conformance/parser/ecmascript5/IndexMemberDeclarations/parserIndexMemberDeclaration10.ts(2,4): error TS1145: Modifiers not permitted on index signature members.\n", "tests/cases/conformance/parser/ecmascript5/IndexMemberDeclarations/parserIndexMemberDeclaration10.ts(2,11): error TS1030: 'static' modifier already seen.\n", "\n", "\n" ], "labels": [ "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "tests/baselines/reference/parserIndexMemberDeclaration10.errors.txt", "type": "replace", "edit_start_line_idx": 0 }
tests/cases/conformance/parser/ecmascript5/IndexMemberDeclarations/parserIndexMemberDeclaration10.ts(2,4): error TS1145: Modifiers not permitted on index signature members. tests/cases/conformance/parser/ecmascript5/IndexMemberDeclarations/parserIndexMemberDeclaration10.ts(2,11): error TS1030: 'static' modifier already seen. ==== tests/cases/conformance/parser/ecmascript5/IndexMemberDeclarations/parserIndexMemberDeclaration10.ts (2 errors) ==== class C { static static [x: string]: string; ~~~~~~~~~~~~~ !!! error TS1145: Modifiers not permitted on index signature members. ~~~~~~ !!! error TS1030: 'static' modifier already seen. }
tests/baselines/reference/parserIndexMemberDeclaration10.errors.txt
1
https://github.com/microsoft/TypeScript/commit/6b866e719e0c1291b87ac7dcdac4cdf1bc8cdb3f
[ 0.9643423557281494, 0.4959356188774109, 0.027528898790478706, 0.4959356188774109, 0.4684067368507385 ]
{ "id": 4, "code_window": [ "tests/cases/conformance/parser/ecmascript5/IndexMemberDeclarations/parserIndexMemberDeclaration10.ts(2,4): error TS1145: Modifiers not permitted on index signature members.\n", "tests/cases/conformance/parser/ecmascript5/IndexMemberDeclarations/parserIndexMemberDeclaration10.ts(2,11): error TS1030: 'static' modifier already seen.\n", "\n", "\n" ], "labels": [ "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "tests/baselines/reference/parserIndexMemberDeclaration10.errors.txt", "type": "replace", "edit_start_line_idx": 0 }
//// [commentOnImportStatement2.ts] /* not copyright */ import foo = require('./foo'); //// [commentOnImportStatement2.js]
tests/baselines/reference/commentOnImportStatement2.js
0
https://github.com/microsoft/TypeScript/commit/6b866e719e0c1291b87ac7dcdac4cdf1bc8cdb3f
[ 0.00017496157670393586, 0.00017496157670393586, 0.00017496157670393586, 0.00017496157670393586, 0 ]
{ "id": 4, "code_window": [ "tests/cases/conformance/parser/ecmascript5/IndexMemberDeclarations/parserIndexMemberDeclaration10.ts(2,4): error TS1145: Modifiers not permitted on index signature members.\n", "tests/cases/conformance/parser/ecmascript5/IndexMemberDeclarations/parserIndexMemberDeclaration10.ts(2,11): error TS1030: 'static' modifier already seen.\n", "\n", "\n" ], "labels": [ "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "tests/baselines/reference/parserIndexMemberDeclaration10.errors.txt", "type": "replace", "edit_start_line_idx": 0 }
//// [ipromise3.ts] interface IPromise3<T> { then<U>(success?: (value: T) => IPromise3<U>, error?: (error: any) => IPromise3<U>, progress?: (progress: any) => void ): IPromise3<U>; then<U>(success?: (value: T) => IPromise3<U>, error?: (error: any) => U, progress?: (progress: any) => void ): IPromise3<U>; then<U>(success?: (value: T) => U, error?: (error: any) => IPromise3<U>, progress?: (progress: any) => void ): IPromise3<U>; then<U>(success?: (value: T) => U, error?: (error: any) => U, progress?: (progress: any) => void ): IPromise3<U>; done? <U>(success?: (value: T) => any, error?: (error: any) => any, progress?: (progress: any) => void ): void; } var p1: IPromise3<string>; var p2: IPromise3<string> = p1.then(function (x) { return x; }); //// [ipromise3.js] var p1; var p2 = p1.then(function (x) { return x; });
tests/baselines/reference/ipromise3.js
0
https://github.com/microsoft/TypeScript/commit/6b866e719e0c1291b87ac7dcdac4cdf1bc8cdb3f
[ 0.0001737037382554263, 0.00017336518794763833, 0.00017302663763985038, 0.00017336518794763833, 3.385503077879548e-7 ]
{ "id": 4, "code_window": [ "tests/cases/conformance/parser/ecmascript5/IndexMemberDeclarations/parserIndexMemberDeclaration10.ts(2,4): error TS1145: Modifiers not permitted on index signature members.\n", "tests/cases/conformance/parser/ecmascript5/IndexMemberDeclarations/parserIndexMemberDeclaration10.ts(2,11): error TS1030: 'static' modifier already seen.\n", "\n", "\n" ], "labels": [ "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "tests/baselines/reference/parserIndexMemberDeclaration10.errors.txt", "type": "replace", "edit_start_line_idx": 0 }
var m1_a1 = 10; var m1_c1 = (function () { function m1_c1() { } return m1_c1; })(); var m1_instance1 = new m1_c1(); function m1_f1() { return m1_instance1; } //# sourceMappingURL=/tests/cases/projects/outputdir_mixed_subfolder/mapFiles/ref/m1.js.map
tests/baselines/reference/project/mapRootAbsolutePathMixedSubfolderNoOutdir/node/ref/m1.js
0
https://github.com/microsoft/TypeScript/commit/6b866e719e0c1291b87ac7dcdac4cdf1bc8cdb3f
[ 0.0001740349835017696, 0.00017347266839351505, 0.0001729103532852605, 0.00017347266839351505, 5.623151082545519e-7 ]
{ "id": 5, "code_window": [ "tests/cases/conformance/parser/ecmascript5/IndexMemberDeclarations/parserIndexMemberDeclaration10.ts(2,11): error TS1030: 'static' modifier already seen.\n", "\n", "\n", "==== tests/cases/conformance/parser/ecmascript5/IndexMemberDeclarations/parserIndexMemberDeclaration10.ts (2 errors) ====\n", " class C {\n", " static static [x: string]: string;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ "==== tests/cases/conformance/parser/ecmascript5/IndexMemberDeclarations/parserIndexMemberDeclaration10.ts (1 errors) ====\n" ], "file_path": "tests/baselines/reference/parserIndexMemberDeclaration10.errors.txt", "type": "replace", "edit_start_line_idx": 4 }
tests/cases/conformance/parser/ecmascript5/IndexMemberDeclarations/parserIndexMemberDeclaration10.ts(2,4): error TS1145: Modifiers not permitted on index signature members. tests/cases/conformance/parser/ecmascript5/IndexMemberDeclarations/parserIndexMemberDeclaration10.ts(2,11): error TS1030: 'static' modifier already seen. ==== tests/cases/conformance/parser/ecmascript5/IndexMemberDeclarations/parserIndexMemberDeclaration10.ts (2 errors) ==== class C { static static [x: string]: string; ~~~~~~~~~~~~~ !!! error TS1145: Modifiers not permitted on index signature members. ~~~~~~ !!! error TS1030: 'static' modifier already seen. }
tests/baselines/reference/parserIndexMemberDeclaration10.errors.txt
1
https://github.com/microsoft/TypeScript/commit/6b866e719e0c1291b87ac7dcdac4cdf1bc8cdb3f
[ 0.9975699782371521, 0.4997037649154663, 0.0018375767394900322, 0.4997037649154663, 0.4978662133216858 ]
{ "id": 5, "code_window": [ "tests/cases/conformance/parser/ecmascript5/IndexMemberDeclarations/parserIndexMemberDeclaration10.ts(2,11): error TS1030: 'static' modifier already seen.\n", "\n", "\n", "==== tests/cases/conformance/parser/ecmascript5/IndexMemberDeclarations/parserIndexMemberDeclaration10.ts (2 errors) ====\n", " class C {\n", " static static [x: string]: string;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ "==== tests/cases/conformance/parser/ecmascript5/IndexMemberDeclarations/parserIndexMemberDeclaration10.ts (1 errors) ====\n" ], "file_path": "tests/baselines/reference/parserIndexMemberDeclaration10.errors.txt", "type": "replace", "edit_start_line_idx": 4 }
//// [voidOperatorWithStringType.ts] // void operator on string type var STRING: string; var STRING1: string[] = ["", "abc"]; function foo(): string { return "abc"; } class A { public a: string; static foo() { return ""; } } module M { export var n: string; } var objA = new A(); // string type var var ResultIsAny1 = void STRING; var ResultIsAny2 = void STRING1; // string type literal var ResultIsAny3 = void ""; var ResultIsAny4 = void { x: "", y: "" }; var ResultIsAny5 = void { x: "", y: (s: string) => { return s; } }; // string type expressions var ResultIsAny6 = void objA.a; var ResultIsAny7 = void M.n; var ResultIsAny8 = void STRING1[0]; var ResultIsAny9 = void foo(); var ResultIsAny10 = void A.foo(); var ResultIsAny11 = void (STRING + STRING); var ResultIsAny12 = void STRING.charAt(0); // multiple void operators var ResultIsAny13 = void void STRING; var ResultIsAny14 = void void void (STRING + STRING); // miss assignment operators void ""; void STRING; void STRING1; void foo(); void objA.a,M.n; //// [voidOperatorWithStringType.js] // void operator on string type var STRING; var STRING1 = ["", "abc"]; function foo() { return "abc"; } var A = (function () { function A() { } A.foo = function () { return ""; }; return A; })(); var M; (function (M) { M.n; })(M || (M = {})); var objA = new A(); // string type var var ResultIsAny1 = void STRING; var ResultIsAny2 = void STRING1; // string type literal var ResultIsAny3 = void ""; var ResultIsAny4 = void { x: "", y: "" }; var ResultIsAny5 = void { x: "", y: function (s) { return s; } }; // string type expressions var ResultIsAny6 = void objA.a; var ResultIsAny7 = void M.n; var ResultIsAny8 = void STRING1[0]; var ResultIsAny9 = void foo(); var ResultIsAny10 = void A.foo(); var ResultIsAny11 = void (STRING + STRING); var ResultIsAny12 = void STRING.charAt(0); // multiple void operators var ResultIsAny13 = void void STRING; var ResultIsAny14 = void void void (STRING + STRING); // miss assignment operators void ""; void STRING; void STRING1; void foo(); void objA.a, M.n;
tests/baselines/reference/voidOperatorWithStringType.js
0
https://github.com/microsoft/TypeScript/commit/6b866e719e0c1291b87ac7dcdac4cdf1bc8cdb3f
[ 0.0023508986923843622, 0.0004140938981436193, 0.00016633734048809856, 0.00017905856657307595, 0.0006487105856649578 ]
{ "id": 5, "code_window": [ "tests/cases/conformance/parser/ecmascript5/IndexMemberDeclarations/parserIndexMemberDeclaration10.ts(2,11): error TS1030: 'static' modifier already seen.\n", "\n", "\n", "==== tests/cases/conformance/parser/ecmascript5/IndexMemberDeclarations/parserIndexMemberDeclaration10.ts (2 errors) ====\n", " class C {\n", " static static [x: string]: string;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ "==== tests/cases/conformance/parser/ecmascript5/IndexMemberDeclarations/parserIndexMemberDeclaration10.ts (1 errors) ====\n" ], "file_path": "tests/baselines/reference/parserIndexMemberDeclaration10.errors.txt", "type": "replace", "edit_start_line_idx": 4 }
=== tests/cases/compiler/declFileWithExtendsClauseThatHasItsContainerNameConflict.ts === declare module A.B.C { >A : typeof A >B : typeof B >C : typeof C class B { >B : B } } module A.B { >A : typeof A >B : typeof B export class EventManager { >EventManager : EventManager id: number; >id : number } } module A.B.C { >A : typeof A >B : typeof B >C : typeof C export class ContextMenu extends EventManager { >ContextMenu : ContextMenu >EventManager : EventManager name: string; >name : string } }
tests/baselines/reference/declFileWithExtendsClauseThatHasItsContainerNameConflict.types
0
https://github.com/microsoft/TypeScript/commit/6b866e719e0c1291b87ac7dcdac4cdf1bc8cdb3f
[ 0.9910516738891602, 0.4899706244468689, 0.00016848686209414154, 0.4843311309814453, 0.48986607789993286 ]
{ "id": 5, "code_window": [ "tests/cases/conformance/parser/ecmascript5/IndexMemberDeclarations/parserIndexMemberDeclaration10.ts(2,11): error TS1030: 'static' modifier already seen.\n", "\n", "\n", "==== tests/cases/conformance/parser/ecmascript5/IndexMemberDeclarations/parserIndexMemberDeclaration10.ts (2 errors) ====\n", " class C {\n", " static static [x: string]: string;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ "==== tests/cases/conformance/parser/ecmascript5/IndexMemberDeclarations/parserIndexMemberDeclaration10.ts (1 errors) ====\n" ], "file_path": "tests/baselines/reference/parserIndexMemberDeclaration10.errors.txt", "type": "replace", "edit_start_line_idx": 4 }
tests/cases/conformance/parser/ecmascript5/RegressionTests/parserNotHexLiteral1.ts(2,1): error TS2304: Cannot find name 'console'. tests/cases/conformance/parser/ecmascript5/RegressionTests/parserNotHexLiteral1.ts(5,1): error TS2304: Cannot find name 'console'. ==== tests/cases/conformance/parser/ecmascript5/RegressionTests/parserNotHexLiteral1.ts (2 errors) ==== var x = {e0: 'cat', x0: 'dog'}; console.info (x.x0); ~~~~~~~ !!! error TS2304: Cannot find name 'console'. // tsc dies on this next line with "bug.ts (5,16): Expected ')'" // tsc seems to be parsing the e0 as a hex constant. console.info (x.e0); ~~~~~~~ !!! error TS2304: Cannot find name 'console'.
tests/baselines/reference/parserNotHexLiteral1.errors.txt
0
https://github.com/microsoft/TypeScript/commit/6b866e719e0c1291b87ac7dcdac4cdf1bc8cdb3f
[ 0.012135536409914494, 0.006151567213237286, 0.0001675982348388061, 0.006151567213237286, 0.005983969196677208 ]
{ "id": 8, "code_window": [ "\n", "\n", "==== tests/cases/conformance/classes/indexMemberDeclarations/staticIndexers.ts (3 errors) ====\n", " // static indexers not allowed\n", " \n", " class C {\n", " static [x: string]: string;\n", " ~~~~~~\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "==== tests/cases/conformance/classes/indexMemberDeclarations/staticIndexers.ts (4 errors) ====\n" ], "file_path": "tests/baselines/reference/staticIndexers.errors.txt", "type": "replace", "edit_start_line_idx": 5 }
tests/cases/conformance/classes/indexMemberDeclarations/staticIndexers.ts(4,5): error TS1145: Modifiers not permitted on index signature members. tests/cases/conformance/classes/indexMemberDeclarations/staticIndexers.ts(8,5): error TS1145: Modifiers not permitted on index signature members. tests/cases/conformance/classes/indexMemberDeclarations/staticIndexers.ts(12,5): error TS1145: Modifiers not permitted on index signature members. ==== tests/cases/conformance/classes/indexMemberDeclarations/staticIndexers.ts (3 errors) ==== // static indexers not allowed class C { static [x: string]: string; ~~~~~~ !!! error TS1145: Modifiers not permitted on index signature members. } class D { static [x: number]: string; ~~~~~~ !!! error TS1145: Modifiers not permitted on index signature members. } class E<T> { static [x: string]: T; ~~~~~~ !!! error TS1145: Modifiers not permitted on index signature members. }
tests/baselines/reference/staticIndexers.errors.txt
1
https://github.com/microsoft/TypeScript/commit/6b866e719e0c1291b87ac7dcdac4cdf1bc8cdb3f
[ 0.9968485236167908, 0.37170252203941345, 0.04841526225209236, 0.06984374672174454, 0.44213154911994934 ]
{ "id": 8, "code_window": [ "\n", "\n", "==== tests/cases/conformance/classes/indexMemberDeclarations/staticIndexers.ts (3 errors) ====\n", " // static indexers not allowed\n", " \n", " class C {\n", " static [x: string]: string;\n", " ~~~~~~\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "==== tests/cases/conformance/classes/indexMemberDeclarations/staticIndexers.ts (4 errors) ====\n" ], "file_path": "tests/baselines/reference/staticIndexers.errors.txt", "type": "replace", "edit_start_line_idx": 5 }
class Model { public name: string; } class UI { constructor(model: Model, foo = model.name) { } }
tests/cases/compiler/parameterReferencesOtherParameter2.ts
0
https://github.com/microsoft/TypeScript/commit/6b866e719e0c1291b87ac7dcdac4cdf1bc8cdb3f
[ 0.0001832421257859096, 0.0001832421257859096, 0.0001832421257859096, 0.0001832421257859096, 0 ]
{ "id": 8, "code_window": [ "\n", "\n", "==== tests/cases/conformance/classes/indexMemberDeclarations/staticIndexers.ts (3 errors) ====\n", " // static indexers not allowed\n", " \n", " class C {\n", " static [x: string]: string;\n", " ~~~~~~\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "==== tests/cases/conformance/classes/indexMemberDeclarations/staticIndexers.ts (4 errors) ====\n" ], "file_path": "tests/baselines/reference/staticIndexers.errors.txt", "type": "replace", "edit_start_line_idx": 5 }
// Generic call with constraints infering type parameter from object member properties class C { x: string; } class D { x: string; y: string; } function foo<T, U extends T>(t: T, t2: U) { return (x: T) => t2; } var c: C; var d: D; var r = foo(c, d); var r2 = foo(d, c); // error because C does not extend D var r3 = foo(c, { x: '', foo: c }); var r4 = foo(null, null); var r5 = foo({}, null); var r6 = foo(null, {}); var r7 = foo({}, {}); var r8 = foo(() => { }, () => { }); var r9 = foo(() => { }, () => 1); function other<T, U extends T>() { var r4 = foo(c, d); var r5 = foo<T, U>(c, d); // error }
tests/cases/conformance/types/typeRelationships/typeInference/genericCallWithObjectTypeArgsAndConstraints4.ts
0
https://github.com/microsoft/TypeScript/commit/6b866e719e0c1291b87ac7dcdac4cdf1bc8cdb3f
[ 0.9981920123100281, 0.4834711253643036, 0.00017618684796616435, 0.4677581489086151, 0.4838047921657562 ]
{ "id": 8, "code_window": [ "\n", "\n", "==== tests/cases/conformance/classes/indexMemberDeclarations/staticIndexers.ts (3 errors) ====\n", " // static indexers not allowed\n", " \n", " class C {\n", " static [x: string]: string;\n", " ~~~~~~\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "==== tests/cases/conformance/classes/indexMemberDeclarations/staticIndexers.ts (4 errors) ====\n" ], "file_path": "tests/baselines/reference/staticIndexers.errors.txt", "type": "replace", "edit_start_line_idx": 5 }
=== tests/cases/conformance/types/typeRelationships/widenedTypes/initializersWidened.ts === // these are widened to any at the point of assignment var x = null; >x : any var y = undefined; >y : any >undefined : undefined
tests/baselines/reference/initializersWidened.types
0
https://github.com/microsoft/TypeScript/commit/6b866e719e0c1291b87ac7dcdac4cdf1bc8cdb3f
[ 0.003529499052092433, 0.001851583831012249, 0.000173668609932065, 0.001851583831012249, 0.001677915221080184 ]
{ "id": 9, "code_window": [ " \n", " class E<T> {\n", " static [x: string]: T;\n", " ~~~~~~\n", "!!! error TS1145: Modifiers not permitted on index signature members.\n", " }\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep" ], "after_edit": [ " ~\n", "!!! error TS2302: Static members cannot reference class type parameters.\n" ], "file_path": "tests/baselines/reference/staticIndexers.errors.txt", "type": "add", "edit_start_line_idx": 24 }
tests/cases/conformance/parser/ecmascript5/IndexMemberDeclarations/parserIndexMemberDeclaration10.ts(2,4): error TS1145: Modifiers not permitted on index signature members. tests/cases/conformance/parser/ecmascript5/IndexMemberDeclarations/parserIndexMemberDeclaration10.ts(2,11): error TS1030: 'static' modifier already seen. ==== tests/cases/conformance/parser/ecmascript5/IndexMemberDeclarations/parserIndexMemberDeclaration10.ts (2 errors) ==== class C { static static [x: string]: string; ~~~~~~~~~~~~~ !!! error TS1145: Modifiers not permitted on index signature members. ~~~~~~ !!! error TS1030: 'static' modifier already seen. }
tests/baselines/reference/parserIndexMemberDeclaration10.errors.txt
1
https://github.com/microsoft/TypeScript/commit/6b866e719e0c1291b87ac7dcdac4cdf1bc8cdb3f
[ 0.037598513066768646, 0.018882334232330322, 0.00016615408821962774, 0.018882334232330322, 0.018716180697083473 ]
{ "id": 9, "code_window": [ " \n", " class E<T> {\n", " static [x: string]: T;\n", " ~~~~~~\n", "!!! error TS1145: Modifiers not permitted on index signature members.\n", " }\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep" ], "after_edit": [ " ~\n", "!!! error TS2302: Static members cannot reference class type parameters.\n" ], "file_path": "tests/baselines/reference/staticIndexers.errors.txt", "type": "add", "edit_start_line_idx": 24 }
=== tests/cases/compiler/functionOverloads31.ts === function foo(bar:string):string; >foo : { (bar: string): string; (bar: number): number; } >bar : string function foo(bar:number):number; >foo : { (bar: string): string; (bar: number): number; } >bar : number function foo(bar:any):any{ return bar } >foo : { (bar: string): string; (bar: number): number; } >bar : any >bar : any var x = foo(5); >x : number >foo(5) : number >foo : { (bar: string): string; (bar: number): number; }
tests/baselines/reference/functionOverloads31.types
0
https://github.com/microsoft/TypeScript/commit/6b866e719e0c1291b87ac7dcdac4cdf1bc8cdb3f
[ 0.0002568129275459796, 0.00021427922183647752, 0.00017174553067889065, 0.00021427922183647752, 0.00004253369843354449 ]
{ "id": 9, "code_window": [ " \n", " class E<T> {\n", " static [x: string]: T;\n", " ~~~~~~\n", "!!! error TS1145: Modifiers not permitted on index signature members.\n", " }\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep" ], "after_edit": [ " ~\n", "!!! error TS2302: Static members cannot reference class type parameters.\n" ], "file_path": "tests/baselines/reference/staticIndexers.errors.txt", "type": "add", "edit_start_line_idx": 24 }
/// <reference path="m1.d.ts" /> declare var a1: number; declare class c1 { p1: number; } declare var instance1: c1; declare function f1(): c1;
tests/baselines/reference/project/sourcemapSimpleSpecifyOutputDirectory/node/outdir/simple/test.d.ts
0
https://github.com/microsoft/TypeScript/commit/6b866e719e0c1291b87ac7dcdac4cdf1bc8cdb3f
[ 0.00017304479843005538, 0.00017304479843005538, 0.00017304479843005538, 0.00017304479843005538, 0 ]
{ "id": 9, "code_window": [ " \n", " class E<T> {\n", " static [x: string]: T;\n", " ~~~~~~\n", "!!! error TS1145: Modifiers not permitted on index signature members.\n", " }\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep" ], "after_edit": [ " ~\n", "!!! error TS2302: Static members cannot reference class type parameters.\n" ], "file_path": "tests/baselines/reference/staticIndexers.errors.txt", "type": "add", "edit_start_line_idx": 24 }
// All errors // naked continue not allowed continue; // non-existent label ONE: for (var x in {}) continue TWO; // continue from inside function TWO: for (var x in {}) { var fn = () => { continue TWO; } } THREE: for (var x in {}) { var fn = function () { continue THREE; } } // continue forward for (var x in {}) { continue FIVE; FIVE: for (var x in {}) { } } // label on non-loop statement NINE: var y = 12; for (var x in {}) { continue NINE; }
tests/cases/conformance/statements/continueStatements/invalidForInContinueStatements.ts
0
https://github.com/microsoft/TypeScript/commit/6b866e719e0c1291b87ac7dcdac4cdf1bc8cdb3f
[ 0.003925926983356476, 0.0019089003326371312, 0.0005741482600569725, 0.0015677630435675383, 0.0012343201087787747 ]
{ "id": 0, "code_window": [ "\n", "Gaps between patch versions are faulty/broken releases.\n", "\n", "## 2.4.4\n", "\n", " * Add `module` type to browser build `<script>` handler.\n", " * Fix some `MemberExpression` modifying incorrectly setting `property` to a `MemberExpression`.\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "## 2.4.5\n", "\n", " * Avoid printing comments if they've already been output.\n", "\n" ], "file_path": "CHANGELOG.md", "type": "add", "edit_start_line_idx": 4 }
# Changelog Gaps between patch versions are faulty/broken releases. ## 2.4.4 * Add `module` type to browser build `<script>` handler. * Fix some `MemberExpression` modifying incorrectly setting `property` to a `MemberExpression`. ## 2.4.3 * Upgrade `acorn-6to5`. * Add support for `FunctionDeclaration`s in `bluebirdCoroutines` and `asyncToGenerators` transformers. ## 2.4.2 * Upgrade `acorn-6to5`. * Better uids generated for various transformers based on parent node. * Alias flat references in `coreAliasing` transformer. ## 2.4.1 * Better whitespace handling of parenthesized expressions due to trailing comments. * Fix `yield` inside of comprehensions. ## 2.4.0 * Use a closure always for classes with a super. * Always use native loops for array comprehensions. * Allow `yield` inside of comprehensions. * Add optional `bluebirdCoroutine` transformer. * Add optional `asyncToGenerator` transformer. * Move `useStrict` transformer to before `_moduleFormatter` causing `"use strict";` to always be placed the very top. ## 2.3.2 * Add parens on expressions with trailing comments. ## 2.3.1 * Add `undefinedToVoid` optional transformer. * Use `Object.defineProperty` for computed properties. ## 2.3.0 * Upgrade `acorn-6to5`. * Support circular references and hoist variable declarations in `system` module formatter. * Add optional transformers, including a new `coreAliasing` transformer that aliases native ES6 static properties to their `core-js` equivalent. ## 2.2.0 * Make `system` module formatter modules anonymous by default. * Fix duplicate comments being output, breaking code. ## 2.1.0 * Add `cache` option to register hook. * Update `core-js`. * Fix starting newline not being added on case statements. * Fix destructuring `VariableDeclaration`s not inside `BlockStatement`s and `Program`. ## 2.0.4 * Avoid being greedy when destructuring array iterables. ## 2.0.3 * Hoist function declarations in system module formatter for circular references. * Hoist default function declarations in umd and amd module formatters for circular references. ## 2.0.2 * Inherit comments in `for-of` transformer. * Remove `interopRequire` from `system` module formatter. ## 2.0.1 * Remap `UpdateExpression` module export binding. * Fix automatic closure on `PrivateDeclaration` in classes. ## 2.0.0 * Make string literal generation only escapes unicode that it has to. * Internal code generation format options have been exposed. * Change playground method binding operator from `:` to `#` removing ambiguous syntax with terns. * Fix rest parameters in async and generator functions. * Export/import declarations replace by the modules transformer now inherit comments. * Added playground flag to `6to5-node`. * `6to5-node` now behaves the same as `node`. * `6to5-node` now uses `kexec` to become the forked process to correctly propagate signals on unix. * Constants are now block scoped. * Exposed ast transformer. * Merged `commonInterop` and `common` module formatters. * Fix generator comprehensions not inheriting `arguments`, `this` etc. * Object and class mutator shorthand are now enumerable. * Remove regenerator `Generator has already finished` error which isn't spec-compliant. * Expose internal `spec` transformers that nicen up code output. * Add export variable declaration default initializers. * Propagate export declaration reassignments. * Add initializer default to block scoped variable declarations within a loop. * Flow type support. * Make async/await contextual keywords. * Allow `yield`ing of non-objects. * Class declarations now lack an IIFE. * Support falsy and `null` super classes. * Add support for experimental abstract references `private` declarations. * Leave out IIFE for class declarations. * Switched to [core-js](https://github.com/zloirock/core-js) from [es6-symbol](https://github.com/medikoo/es6-symbol) and [es6-shim](https://github.com/paulmillr/es6-shim/) for built-in polyfill. * `amd` and `umd` module formatters now behave the same as `common` with `interopRequire`. * Micro-optimizations to boost performance by 200%. * Rename module formatter methods `import` to `importDeclaration` and `export` to `exportDeclaration`. * Support multiple declarators in export variable declarations. * Freeze tagged template literal object. * Remove inlined `regenerator` fork. * Remove `ParenthesizedExpression`. * Rename `object-spread` helper to `object-without-properties`. * Rename `class-props` helper to `prototype-properties`. * Rename `extends` helper to `inherits`. * Completely rewritten `system` module formatter. ## 1.15.0 * Don't alias `GeneratorFunction` and check the name which causes minifiers to remove the name and throw an error later on when we check if it's set. ## 1.14.18 * Fix files only containg comments not being output. * Fix duplicate comments on property key shorthands. ## 1.14.17 * Add default initializer to let variables within loop bodies. * Fix excessive `break` replacement inside of switches in let scoping. ## 1.14.16 * Add object getter memos and this shorthand to playground. * Fix while loops in let scoping. * Upgrade `acorn-6to5`. ## 1.14.14 * Fix template literals escaping. ## 1.14.13 * Fix let scoping of `while` loops. * Make class methods enumerable. ## 1.14.12 * Fix duplicate dynamic expressions in call spread. ## 1.14.10 * Fix let scoping unneccesary override. ## 1.14.6 * Avoid ensuring a block on non-array node replacements. ## 1.14.5 * Upgrade `acorn-6to5`. * Fix JSON recursion error for unknown code generator node types. * Ensure that a statement is a block on block/statement types when replacing them with multiple nodes. ## 1.14.4 * Merge pretzel maps and method binding. ## 1.14.3 * Add playground pretzel maps. ## 1.14.2 * Fix `commonInterop` default export handling. * Fix keyworded property key identifiers being turned into computed property key literals. ## 1.14.1 * Inherit comments from `ClassDeclaration`. ## 1.14.0 * Add [playground](https://6to5.github.io/playground.html). ## 1.13.13 * Fix `--debug` in `bin/6to5-node`. Thanks [@timoxley](https://github.com/timoxley). ## 1.13.12 * Ignore `XJSEmptyExpression`s in `react` transformer output. ## 1.13.11 * Fix `util.regexify` on falsy values. * Fix `_aliasFunction` with rest parameters. * Export as `module.exports` instead of `exports.default` if there are no other `ExportDeclaration`s in `commonInterop` module formatter. * Add `system` module formatter. Thanks [@douglasduteil](https://github.com/douglasduteil). ## 1.13.10 * Add support for `AssignmentExpression` destructuring outside of `ExpressionStatement`. ## 1.13.9 * Fix `VirtualPropertyExpression` visitor keys. ## 1.13.8 * Only use a single reference in abstract references. ## 1.13.7 * Upgrade `acorn-6to5`. * Add experimental exponentiation operator support. ## 1.13.6 * Fix experimental object spread/rest helper. ## 1.13.5 * Upgrade `acorn-6to5`. * Add experimental support for object spread/rest. * Change `arguments` to array to an additional helper method. ## 1.13.4 * Fix single spread element returning itself. ## 1.13.3 * Upgrade `acorn-6to5`. * Add experimental support for abstract references. ## 1.13.2 * Optimise `Array.from` usage by adding a helper method. * Upgrade `acorn-6to5`. ## 1.13.1 * Fix constructor spread optimisation. Thanks [@zloirock](https://github.com/zloirock). ## 1.13.0 * Put experimental ES7 features behind a flag `--experimental` and `experimental` option. * Constructor spread performance increase. Thanks [@RReverser](https://github.com/RReverser). * Use `self` instead of `window` in the optional 6to5 runtime. Thanks [@RReverser](https://github.com/RReverser). ## 1.12.26 * Support computed property destructuring. ## 1.12.25 * Update `acorn-6to5`, `ast-types`, `es6-shim`, `chokidar`, `estraverse` and `private`. ## 1.12.24 * Collect references that haven't been declared in scope. ## 1.12.23 * Fix generator function export hoisting. ## 1.12.22 * Update `fs-readdir-recursive` and `chokidar`. * Support array destructuring on iterables. * Make amd module id optional. Thanks [@webpro](https://github.com/webpro). ## 1.12.21 * Fix unneccesary let scoping replacement. * Add `commonInterop` module formatter. Thanks [@Naddiseo](https://github.com/Naddiseo). * Fix `return` outside of function body bug. Thanks [@brentburg](https://github.com/brentburg). * Add more flexible option types. ## 1.12.20 * Append `sourceMappingURL` when using `bin/6to5` and output sourcemaps. ## 1.12.19 * Add `comments` option and `--remove-comments` flag. Thanks [@webpro](htps://github.com/webpro). * Embed `regenerator`. ## 1.12.18 * Use `global` reference instead of `window`. ## 1.12.17 * Add `moduleName`, `sourceRoot` and `filenameRelative` options. Thanks [@darvelo](https://github.com/darvelo). * Traversal optimisations. ## 1.12.16 * Fix comments not being retained from `MethodDefinition` in classes. * Add temporal dead zone in default parameters. ## 1.12.15 * Update `acorn-6to5`. ## 1.12.14 * Fix duplicate let scoping in functions. * Make JSX whitespace more React-compliant. * Add `_memberExpressionKeywords` transformer that turns keyword identifiers to computed literals. * Upgrade `regenerator-6to5`. ## 1.12.13 * Support duplicate constants within different block scopes. * Fix for-head duplication testing and replacement. * Support `raw` property on tagged template literals. ## 1.12.12 * Make scope tracker more reliable to handle all edgecases. ## 1.12.11 * Block scope classes. * Fix generation of integer `Literal`s in `MemberExpression`. ## 1.12.10 * Fix let scoping var hoisting. ## 1.12.9 * Escape unicode characters when generating string `Literal`s. * Fix semicolons being output for statements in `ExportDeclaration`. * Fix `WithStatement` missing parenthesis. ## 1.12.8 * Temporarily forbid `AssignmentExpression` destructuring outside of `ExpressionStatement`. ## 1.12.7 * Update to latest `acorn-6to5`. ## 1.12.6 * Update to latest `acorn-6to5`. ## 1.12.5 * Fix excessive whitespace trimming resulting in innaccurate sourcemap line. ## 1.12.4 * Add `doc` folder for documentation. ## 1.12.3 * Support generator comprehensions. * Use `Array.from` instead of `Array.prototype.slice` in spread transformer. * Support spread in `NewExpression`s. ## 1.12.2 * Upgrade `matcha` to `0.6.0` and `browserify` to `6.3.2`. * Add own `trimRight` helper instead of relying on the string instance method. * Support JSX spreads that aren't the first. ## 1.12.1 * Fix `this` and `arguments` mapping in the `_aliasFunctions` transformer. ## 1.12.0 * Combine `jsx` and `react` transformers to `react`. * Update `react` syntax output to React v0.12. ## 1.11.15 * Fix JSX literal whitespace generation. ## 1.11.14 * Avoid using a switch for let-scoping continue and break statements and use an if statement instead. * Remove excess whitespace and newlines from JSX literals. ## 1.11.13 * Update regenerator-6to5 * Add support for most escodegen formatting options
CHANGELOG.md
1
https://github.com/babel/babel/commit/339bf824816fd2e524859d1ea8cfb295201322ab
[ 0.0010365353664383292, 0.0002003098779823631, 0.00016463600331917405, 0.00017316098092123866, 0.00013446714729070663 ]
{ "id": 0, "code_window": [ "\n", "Gaps between patch versions are faulty/broken releases.\n", "\n", "## 2.4.4\n", "\n", " * Add `module` type to browser build `<script>` handler.\n", " * Fix some `MemberExpression` modifying incorrectly setting `property` to a `MemberExpression`.\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "## 2.4.5\n", "\n", " * Avoid printing comments if they've already been output.\n", "\n" ], "file_path": "CHANGELOG.md", "type": "add", "edit_start_line_idx": 4 }
var lyrics = ["head", "and", "toes", ...parts];
test/fixtures/transformation/optional-core-aliasing/es6-spread/actual.js
0
https://github.com/babel/babel/commit/339bf824816fd2e524859d1ea8cfb295201322ab
[ 0.0001694007369223982, 0.0001694007369223982, 0.0001694007369223982, 0.0001694007369223982, 0 ]
{ "id": 0, "code_window": [ "\n", "Gaps between patch versions are faulty/broken releases.\n", "\n", "## 2.4.4\n", "\n", " * Add `module` type to browser build `<script>` handler.\n", " * Fix some `MemberExpression` modifying incorrectly setting `property` to a `MemberExpression`.\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "## 2.4.5\n", "\n", " * Avoid printing comments if they've already been output.\n", "\n" ], "file_path": "CHANGELOG.md", "type": "add", "edit_start_line_idx": 4 }
function *gen(a, b) { yield { a: a - (yield a), b: yield b }; } genHelpers.check(gen(1, 2), [1, 2, { a: 0, b: 2 }]); genHelpers.check(gen(4, 2), [4, 2, { a: 3, b: 2 }]);
test/fixtures/transformation/es6-generators/object-literal-generator-should-yield-the-correct-object/exec.js
0
https://github.com/babel/babel/commit/339bf824816fd2e524859d1ea8cfb295201322ab
[ 0.0001675760286161676, 0.0001675760286161676, 0.0001675760286161676, 0.0001675760286161676, 0 ]
{ "id": 0, "code_window": [ "\n", "Gaps between patch versions are faulty/broken releases.\n", "\n", "## 2.4.4\n", "\n", " * Add `module` type to browser build `<script>` handler.\n", " * Fix some `MemberExpression` modifying incorrectly setting `property` to a `MemberExpression`.\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "## 2.4.5\n", "\n", " * Avoid printing comments if they've already been output.\n", "\n" ], "file_path": "CHANGELOG.md", "type": "add", "edit_start_line_idx": 4 }
"use strict"; var _toArray = function (arr) { return Array.isArray(arr) ? arr : Array.from(arr); }; var lyrics = ["head", "and", "toes"].concat(_toArray(parts));
test/fixtures/transformation/es6-spread/array-literals/expected.js
0
https://github.com/babel/babel/commit/339bf824816fd2e524859d1ea8cfb295201322ab
[ 0.00016891217092052102, 0.00016891217092052102, 0.00016891217092052102, 0.00016891217092052102, 0 ]
{ "id": 1, "code_window": [ " if (!comments || !comments.length) return;\n", "\n", " var self = this;\n", "\n", " _.each(comments, function (comment) {\n", " // find the original comment in the ast and set it as displayed\n", " _.each(self.ast.comments, function (origComment) {\n", " if (origComment.start === comment.start) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " var skip = false;\n", "\n" ], "file_path": "lib/6to5/generation/generator.js", "type": "add", "edit_start_line_idx": 276 }
module.exports = function (ast, opts, code) { var gen = new CodeGenerator(ast, opts, code); return gen.generate(); }; module.exports.CodeGenerator = CodeGenerator; var Whitespace = require("./whitespace"); var SourceMap = require("./source-map"); var Position = require("./position"); var Buffer = require("./buffer"); var util = require("../util"); var n = require("./node"); var t = require("../types"); var _ = require("lodash"); function CodeGenerator(ast, opts, code) { opts = opts || {}; this.comments = ast.comments || []; this.tokens = ast.tokens || []; this.format = CodeGenerator.normaliseOptions(opts); this.ast = ast; this.whitespace = new Whitespace(this.tokens, this.comments); this.position = new Position; this.map = new SourceMap(this.position, opts, code); this.buffer = new Buffer(this.position, this.format); } _.each(Buffer.prototype, function (fn, key) { CodeGenerator.prototype[key] = function () { return fn.apply(this.buffer, arguments); }; }); CodeGenerator.normaliseOptions = function (opts) { return _.merge({ parentheses: true, comments: opts.comments == null || opts.comments, compact: false, indent: { adjustMultilineComment: true, style: " ", base: 0 } }, opts.format || {}); }; CodeGenerator.generators = { templateLiterals: require("./generators/template-literals"), comprehensions: require("./generators/comprehensions"), expressions: require("./generators/expressions"), statements: require("./generators/statements"), playground: require("./generators/playground"), classes: require("./generators/classes"), methods: require("./generators/methods"), modules: require("./generators/modules"), types: require("./generators/types"), flow: require("./generators/flow"), base: require("./generators/base"), jsx: require("./generators/jsx") }; _.each(CodeGenerator.generators, function (generator) { _.extend(CodeGenerator.prototype, generator); }); CodeGenerator.prototype.generate = function () { var ast = this.ast; this.print(ast); var comments = []; _.each(ast.comments, function (comment) { if (!comment._displayed) comments.push(comment); }); this._printComments(comments); return { map: this.map.get(), code: this.buffer.get() }; }; CodeGenerator.prototype.buildPrint = function (parent) { var self = this; var print = function (node, opts) { return self.print(node, parent, opts); }; print.sequence = function (nodes, opts) { opts = opts || {}; opts.statement = true; return self.printJoin(print, nodes, opts); }; print.join = function (nodes, opts) { return self.printJoin(print, nodes, opts); }; print.block = function (node) { return self.printBlock(print, node); }; print.indentOnComments = function (node) { return self.printAndIndentOnComments(print, node); }; return print; }; CodeGenerator.prototype.print = function (node, parent, opts) { if (!node) return ""; var self = this; opts = opts || {}; var newline = function (leading) { if (!opts.statement && !n.isUserWhitespacable(node, parent)) { return; } var lines = 0; if (node.start != null) { // user node if (leading) { lines = self.whitespace.getNewlinesBefore(node); } else { lines = self.whitespace.getNewlinesAfter(node); } } else { // generated node if (!leading) lines++; // always include at least a single line after var needs = n.needsWhitespaceAfter; if (leading) needs = n.needsWhitespaceBefore; lines += needs(node, parent); // generated nodes can't add starting file whitespace if (!self.buffer.get()) lines = 0; } self.newline(lines); }; if (this[node.type]) { var needsCommentParens = t.isExpression(node) && node.leadingComments && node.leadingComments.length; var needsParens = needsCommentParens || n.needsParens(node, parent); if (needsParens) this.push("("); if (needsCommentParens) this.indent(); this.printLeadingComments(node, parent); newline(true); if (opts.before) opts.before(); this.map.mark(node, "start"); this[node.type](node, this.buildPrint(node), parent); if (needsCommentParens) { this.newline(); this.dedent(); } if (needsParens) this.push(")"); this.map.mark(node, "end"); if (opts.after) opts.after(); newline(false); this.printTrailingComments(node, parent); } else { throw new ReferenceError("unknown node of type " + JSON.stringify(node.type) + " with constructor " + JSON.stringify(node && node.constructor.name)); } }; CodeGenerator.prototype.printJoin = function (print, nodes, opts) { if (!nodes || !nodes.length) return; opts = opts || {}; var self = this; var len = nodes.length; if (opts.indent) self.indent(); _.each(nodes, function (node, i) { print(node, { statement: opts.statement, after: function () { if (opts.iterator) { opts.iterator(node, i); } if (opts.separator && i < len - 1) { self.push(opts.separator); } } }); }); if (opts.indent) self.dedent(); }; CodeGenerator.prototype.printAndIndentOnComments = function (print, node) { var indent = !!node.leadingComments; if (indent) this.indent(); print(node); if (indent) this.dedent(); }; CodeGenerator.prototype.printBlock = function (print, node) { if (t.isEmptyStatement(node)) { this.semicolon(); } else { this.push(" "); print(node); } }; CodeGenerator.prototype.generateComment = function (comment) { var val = comment.value; if (comment.type === "Line") { val = "//" + val; } else { val = "/*" + val + "*/"; } return val; }; CodeGenerator.prototype.printTrailingComments = function (node, parent) { this._printComments(this.getComments("trailingComments", node, parent)); }; CodeGenerator.prototype.printLeadingComments = function (node, parent) { this._printComments(this.getComments("leadingComments", node, parent)); }; CodeGenerator.prototype.getComments = function (key, node, parent) { if (t.isExpressionStatement(parent)) { return []; } var comments = []; var nodes = [node]; var self = this; if (t.isExpressionStatement(node)) { nodes.push(node.argument); } _.each(nodes, function (node) { comments = comments.concat(self._getComments(key, node)); }); return comments; }; CodeGenerator.prototype._getComments = function (key, node) { return (node && node[key]) || []; }; CodeGenerator.prototype._printComments = function (comments) { if (this.format.compact) return; if (!this.format.comments) return; if (!comments || !comments.length) return; var self = this; _.each(comments, function (comment) { // find the original comment in the ast and set it as displayed _.each(self.ast.comments, function (origComment) { if (origComment.start === comment.start) { origComment._displayed = true; return false; } }); // whitespace before self.newline(self.whitespace.getNewlinesBefore(comment)); var column = self.position.column; var val = self.generateComment(comment); if (column && !self.isLast(["\n", " ", "[", "{"])) { self._push(" "); column++; } // if (comment.type === "Block" && self.format.indent.adjustMultilineComment) { var offset = comment.loc.start.column; if (offset) { var newlineRegex = new RegExp("\\n\\s{1," + offset + "}", "g"); val = val.replace(newlineRegex, "\n"); } var indent = Math.max(self.indentSize(), column); val = val.replace(/\n/g, "\n" + util.repeat(indent)); } if (column === 0) { val = self.getIndent() + val; } // self._push(val); // whitespace after self.newline(self.whitespace.getNewlinesAfter(comment)); }); };
lib/6to5/generation/generator.js
1
https://github.com/babel/babel/commit/339bf824816fd2e524859d1ea8cfb295201322ab
[ 0.998967170715332, 0.3703131675720215, 0.00016776419943198562, 0.019035691395401955, 0.45615315437316895 ]
{ "id": 1, "code_window": [ " if (!comments || !comments.length) return;\n", "\n", " var self = this;\n", "\n", " _.each(comments, function (comment) {\n", " // find the original comment in the ast and set it as displayed\n", " _.each(self.ast.comments, function (origComment) {\n", " if (origComment.start === comment.start) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " var skip = false;\n", "\n" ], "file_path": "lib/6to5/generation/generator.js", "type": "add", "edit_start_line_idx": 276 }
function *outer() { try { yield* inner(); } catch (err) { return -1; } return 1; } function *inner() { yield void 0; } var g = outer(); g.next(); assert.equal(g.throw(new Error('foo')).value, -1);
test/fixtures/transformation/es6-generators/generator-throw-method-should-propagate-errors-unhandled-inside-a-delegate/exec.js
0
https://github.com/babel/babel/commit/339bf824816fd2e524859d1ea8cfb295201322ab
[ 0.00017383827071171254, 0.00017076299991458654, 0.00016768774366937578, 0.00017076299991458654, 0.000003075263521168381 ]
{ "id": 1, "code_window": [ " if (!comments || !comments.length) return;\n", "\n", " var self = this;\n", "\n", " _.each(comments, function (comment) {\n", " // find the original comment in the ast and set it as displayed\n", " _.each(self.ast.comments, function (origComment) {\n", " if (origComment.start === comment.start) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " var skip = false;\n", "\n" ], "file_path": "lib/6to5/generation/generator.js", "type": "add", "edit_start_line_idx": 276 }
e => { print("hello world"); }; (e1, e2, e3) => { print("hello world"); }; e => e; (e1, e2, e3) => e; (e) => { }; e => 20 + 20
test/fixtures/generation/harmony-edgecase/arrow-function/actual.js
0
https://github.com/babel/babel/commit/339bf824816fd2e524859d1ea8cfb295201322ab
[ 0.00017521133122500032, 0.00017429990111850202, 0.00017338848556391895, 0.00017429990111850202, 9.114228305406868e-7 ]
{ "id": 1, "code_window": [ " if (!comments || !comments.length) return;\n", "\n", " var self = this;\n", "\n", " _.each(comments, function (comment) {\n", " // find the original comment in the ast and set it as displayed\n", " _.each(self.ast.comments, function (origComment) {\n", " if (origComment.start === comment.start) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " var skip = false;\n", "\n" ], "file_path": "lib/6to5/generation/generator.js", "type": "add", "edit_start_line_idx": 276 }
{"version":3,"sources":["stdin"],"names":[],"mappings":";;AAAA,GAAG,CAAC,GAAG,CAAC,UAAA,CAAC;SAAI,CAAC,GAAG,CAAC;CAAA,CAAC,CAAC","file":"test.js","sourcesContent":["arr.map(x => x * x);"]}
test/fixtures/bin/6to5/stdin --out-file --source-maps/out-files/test.js.map
0
https://github.com/babel/babel/commit/339bf824816fd2e524859d1ea8cfb295201322ab
[ 0.00016736316320020705, 0.00016736316320020705, 0.00016736316320020705, 0.00016736316320020705, 0 ]
{ "id": 2, "code_window": [ " // find the original comment in the ast and set it as displayed\n", " _.each(self.ast.comments, function (origComment) {\n", " if (origComment.start === comment.start) {\n", " origComment._displayed = true;\n", " return false;\n", " }\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " // comment has already been output\n", " if (origComment._displayed) skip = true;\n", "\n" ], "file_path": "lib/6to5/generation/generator.js", "type": "add", "edit_start_line_idx": 279 }
# Changelog Gaps between patch versions are faulty/broken releases. ## 2.4.4 * Add `module` type to browser build `<script>` handler. * Fix some `MemberExpression` modifying incorrectly setting `property` to a `MemberExpression`. ## 2.4.3 * Upgrade `acorn-6to5`. * Add support for `FunctionDeclaration`s in `bluebirdCoroutines` and `asyncToGenerators` transformers. ## 2.4.2 * Upgrade `acorn-6to5`. * Better uids generated for various transformers based on parent node. * Alias flat references in `coreAliasing` transformer. ## 2.4.1 * Better whitespace handling of parenthesized expressions due to trailing comments. * Fix `yield` inside of comprehensions. ## 2.4.0 * Use a closure always for classes with a super. * Always use native loops for array comprehensions. * Allow `yield` inside of comprehensions. * Add optional `bluebirdCoroutine` transformer. * Add optional `asyncToGenerator` transformer. * Move `useStrict` transformer to before `_moduleFormatter` causing `"use strict";` to always be placed the very top. ## 2.3.2 * Add parens on expressions with trailing comments. ## 2.3.1 * Add `undefinedToVoid` optional transformer. * Use `Object.defineProperty` for computed properties. ## 2.3.0 * Upgrade `acorn-6to5`. * Support circular references and hoist variable declarations in `system` module formatter. * Add optional transformers, including a new `coreAliasing` transformer that aliases native ES6 static properties to their `core-js` equivalent. ## 2.2.0 * Make `system` module formatter modules anonymous by default. * Fix duplicate comments being output, breaking code. ## 2.1.0 * Add `cache` option to register hook. * Update `core-js`. * Fix starting newline not being added on case statements. * Fix destructuring `VariableDeclaration`s not inside `BlockStatement`s and `Program`. ## 2.0.4 * Avoid being greedy when destructuring array iterables. ## 2.0.3 * Hoist function declarations in system module formatter for circular references. * Hoist default function declarations in umd and amd module formatters for circular references. ## 2.0.2 * Inherit comments in `for-of` transformer. * Remove `interopRequire` from `system` module formatter. ## 2.0.1 * Remap `UpdateExpression` module export binding. * Fix automatic closure on `PrivateDeclaration` in classes. ## 2.0.0 * Make string literal generation only escapes unicode that it has to. * Internal code generation format options have been exposed. * Change playground method binding operator from `:` to `#` removing ambiguous syntax with terns. * Fix rest parameters in async and generator functions. * Export/import declarations replace by the modules transformer now inherit comments. * Added playground flag to `6to5-node`. * `6to5-node` now behaves the same as `node`. * `6to5-node` now uses `kexec` to become the forked process to correctly propagate signals on unix. * Constants are now block scoped. * Exposed ast transformer. * Merged `commonInterop` and `common` module formatters. * Fix generator comprehensions not inheriting `arguments`, `this` etc. * Object and class mutator shorthand are now enumerable. * Remove regenerator `Generator has already finished` error which isn't spec-compliant. * Expose internal `spec` transformers that nicen up code output. * Add export variable declaration default initializers. * Propagate export declaration reassignments. * Add initializer default to block scoped variable declarations within a loop. * Flow type support. * Make async/await contextual keywords. * Allow `yield`ing of non-objects. * Class declarations now lack an IIFE. * Support falsy and `null` super classes. * Add support for experimental abstract references `private` declarations. * Leave out IIFE for class declarations. * Switched to [core-js](https://github.com/zloirock/core-js) from [es6-symbol](https://github.com/medikoo/es6-symbol) and [es6-shim](https://github.com/paulmillr/es6-shim/) for built-in polyfill. * `amd` and `umd` module formatters now behave the same as `common` with `interopRequire`. * Micro-optimizations to boost performance by 200%. * Rename module formatter methods `import` to `importDeclaration` and `export` to `exportDeclaration`. * Support multiple declarators in export variable declarations. * Freeze tagged template literal object. * Remove inlined `regenerator` fork. * Remove `ParenthesizedExpression`. * Rename `object-spread` helper to `object-without-properties`. * Rename `class-props` helper to `prototype-properties`. * Rename `extends` helper to `inherits`. * Completely rewritten `system` module formatter. ## 1.15.0 * Don't alias `GeneratorFunction` and check the name which causes minifiers to remove the name and throw an error later on when we check if it's set. ## 1.14.18 * Fix files only containg comments not being output. * Fix duplicate comments on property key shorthands. ## 1.14.17 * Add default initializer to let variables within loop bodies. * Fix excessive `break` replacement inside of switches in let scoping. ## 1.14.16 * Add object getter memos and this shorthand to playground. * Fix while loops in let scoping. * Upgrade `acorn-6to5`. ## 1.14.14 * Fix template literals escaping. ## 1.14.13 * Fix let scoping of `while` loops. * Make class methods enumerable. ## 1.14.12 * Fix duplicate dynamic expressions in call spread. ## 1.14.10 * Fix let scoping unneccesary override. ## 1.14.6 * Avoid ensuring a block on non-array node replacements. ## 1.14.5 * Upgrade `acorn-6to5`. * Fix JSON recursion error for unknown code generator node types. * Ensure that a statement is a block on block/statement types when replacing them with multiple nodes. ## 1.14.4 * Merge pretzel maps and method binding. ## 1.14.3 * Add playground pretzel maps. ## 1.14.2 * Fix `commonInterop` default export handling. * Fix keyworded property key identifiers being turned into computed property key literals. ## 1.14.1 * Inherit comments from `ClassDeclaration`. ## 1.14.0 * Add [playground](https://6to5.github.io/playground.html). ## 1.13.13 * Fix `--debug` in `bin/6to5-node`. Thanks [@timoxley](https://github.com/timoxley). ## 1.13.12 * Ignore `XJSEmptyExpression`s in `react` transformer output. ## 1.13.11 * Fix `util.regexify` on falsy values. * Fix `_aliasFunction` with rest parameters. * Export as `module.exports` instead of `exports.default` if there are no other `ExportDeclaration`s in `commonInterop` module formatter. * Add `system` module formatter. Thanks [@douglasduteil](https://github.com/douglasduteil). ## 1.13.10 * Add support for `AssignmentExpression` destructuring outside of `ExpressionStatement`. ## 1.13.9 * Fix `VirtualPropertyExpression` visitor keys. ## 1.13.8 * Only use a single reference in abstract references. ## 1.13.7 * Upgrade `acorn-6to5`. * Add experimental exponentiation operator support. ## 1.13.6 * Fix experimental object spread/rest helper. ## 1.13.5 * Upgrade `acorn-6to5`. * Add experimental support for object spread/rest. * Change `arguments` to array to an additional helper method. ## 1.13.4 * Fix single spread element returning itself. ## 1.13.3 * Upgrade `acorn-6to5`. * Add experimental support for abstract references. ## 1.13.2 * Optimise `Array.from` usage by adding a helper method. * Upgrade `acorn-6to5`. ## 1.13.1 * Fix constructor spread optimisation. Thanks [@zloirock](https://github.com/zloirock). ## 1.13.0 * Put experimental ES7 features behind a flag `--experimental` and `experimental` option. * Constructor spread performance increase. Thanks [@RReverser](https://github.com/RReverser). * Use `self` instead of `window` in the optional 6to5 runtime. Thanks [@RReverser](https://github.com/RReverser). ## 1.12.26 * Support computed property destructuring. ## 1.12.25 * Update `acorn-6to5`, `ast-types`, `es6-shim`, `chokidar`, `estraverse` and `private`. ## 1.12.24 * Collect references that haven't been declared in scope. ## 1.12.23 * Fix generator function export hoisting. ## 1.12.22 * Update `fs-readdir-recursive` and `chokidar`. * Support array destructuring on iterables. * Make amd module id optional. Thanks [@webpro](https://github.com/webpro). ## 1.12.21 * Fix unneccesary let scoping replacement. * Add `commonInterop` module formatter. Thanks [@Naddiseo](https://github.com/Naddiseo). * Fix `return` outside of function body bug. Thanks [@brentburg](https://github.com/brentburg). * Add more flexible option types. ## 1.12.20 * Append `sourceMappingURL` when using `bin/6to5` and output sourcemaps. ## 1.12.19 * Add `comments` option and `--remove-comments` flag. Thanks [@webpro](htps://github.com/webpro). * Embed `regenerator`. ## 1.12.18 * Use `global` reference instead of `window`. ## 1.12.17 * Add `moduleName`, `sourceRoot` and `filenameRelative` options. Thanks [@darvelo](https://github.com/darvelo). * Traversal optimisations. ## 1.12.16 * Fix comments not being retained from `MethodDefinition` in classes. * Add temporal dead zone in default parameters. ## 1.12.15 * Update `acorn-6to5`. ## 1.12.14 * Fix duplicate let scoping in functions. * Make JSX whitespace more React-compliant. * Add `_memberExpressionKeywords` transformer that turns keyword identifiers to computed literals. * Upgrade `regenerator-6to5`. ## 1.12.13 * Support duplicate constants within different block scopes. * Fix for-head duplication testing and replacement. * Support `raw` property on tagged template literals. ## 1.12.12 * Make scope tracker more reliable to handle all edgecases. ## 1.12.11 * Block scope classes. * Fix generation of integer `Literal`s in `MemberExpression`. ## 1.12.10 * Fix let scoping var hoisting. ## 1.12.9 * Escape unicode characters when generating string `Literal`s. * Fix semicolons being output for statements in `ExportDeclaration`. * Fix `WithStatement` missing parenthesis. ## 1.12.8 * Temporarily forbid `AssignmentExpression` destructuring outside of `ExpressionStatement`. ## 1.12.7 * Update to latest `acorn-6to5`. ## 1.12.6 * Update to latest `acorn-6to5`. ## 1.12.5 * Fix excessive whitespace trimming resulting in innaccurate sourcemap line. ## 1.12.4 * Add `doc` folder for documentation. ## 1.12.3 * Support generator comprehensions. * Use `Array.from` instead of `Array.prototype.slice` in spread transformer. * Support spread in `NewExpression`s. ## 1.12.2 * Upgrade `matcha` to `0.6.0` and `browserify` to `6.3.2`. * Add own `trimRight` helper instead of relying on the string instance method. * Support JSX spreads that aren't the first. ## 1.12.1 * Fix `this` and `arguments` mapping in the `_aliasFunctions` transformer. ## 1.12.0 * Combine `jsx` and `react` transformers to `react`. * Update `react` syntax output to React v0.12. ## 1.11.15 * Fix JSX literal whitespace generation. ## 1.11.14 * Avoid using a switch for let-scoping continue and break statements and use an if statement instead. * Remove excess whitespace and newlines from JSX literals. ## 1.11.13 * Update regenerator-6to5 * Add support for most escodegen formatting options
CHANGELOG.md
1
https://github.com/babel/babel/commit/339bf824816fd2e524859d1ea8cfb295201322ab
[ 0.00018647877732291818, 0.00016691908240318298, 0.00016092514852061868, 0.00016590226732660085, 0.0000042585525079630315 ]
{ "id": 2, "code_window": [ " // find the original comment in the ast and set it as displayed\n", " _.each(self.ast.comments, function (origComment) {\n", " if (origComment.start === comment.start) {\n", " origComment._displayed = true;\n", " return false;\n", " }\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " // comment has already been output\n", " if (origComment._displayed) skip = true;\n", "\n" ], "file_path": "lib/6to5/generation/generator.js", "type": "add", "edit_start_line_idx": 279 }
var t = require("../../types"); var _ = require("lodash"); exports.BindMemberExpression = function (node, parent, file, scope) { var object = node.object; var prop = node.property; var temp; if (t.isDynamic(object)) { temp = object = scope.generateTemp(file); } var call = t.callExpression( t.memberExpression(t.memberExpression(object, prop), t.identifier("bind")), [object].concat(node.arguments) ); if (temp) { return t.sequenceExpression([ t.assignmentExpression("=", temp, node.object), call ]); } else { return call; } }; exports.BindFunctionExpression = function (node, parent, file, scope) { var buildCall = function (args) { var param = file.generateUidIdentifier("val", scope); return t.functionExpression(null, [param], t.blockStatement([ t.returnStatement(t.callExpression(t.memberExpression(param, node.callee), args)) ])); }; if (_.find(node.arguments, t.isDynamic)) { var temp = scope.generateTemp(file, "args"); return t.sequenceExpression([ t.assignmentExpression("=", temp, t.arrayExpression(node.arguments)), buildCall(node.arguments.map(function (node, i) { return t.memberExpression(temp, t.literal(i), true); })) ]); } else { return buildCall(node.arguments); } };
lib/6to5/transformation/transformers/playground-method-binding.js
0
https://github.com/babel/babel/commit/339bf824816fd2e524859d1ea8cfb295201322ab
[ 0.0017187781631946564, 0.00048112255171872675, 0.00016802706522867084, 0.00017394272435922176, 0.000618832535110414 ]
{ "id": 2, "code_window": [ " // find the original comment in the ast and set it as displayed\n", " _.each(self.ast.comments, function (origComment) {\n", " if (origComment.start === comment.start) {\n", " origComment._displayed = true;\n", " return false;\n", " }\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " // comment has already been output\n", " if (origComment._displayed) skip = true;\n", "\n" ], "file_path": "lib/6to5/generation/generator.js", "type": "add", "edit_start_line_idx": 279 }
"use strict"; var coords = { x: x };
test/fixtures/transformation/es6-property-name-shorthand/single/expected.js
0
https://github.com/babel/babel/commit/339bf824816fd2e524859d1ea8cfb295201322ab
[ 0.0001763803156791255, 0.0001763803156791255, 0.0001763803156791255, 0.0001763803156791255, 0 ]
{ "id": 2, "code_window": [ " // find the original comment in the ast and set it as displayed\n", " _.each(self.ast.comments, function (origComment) {\n", " if (origComment.start === comment.start) {\n", " origComment._displayed = true;\n", " return false;\n", " }\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " // comment has already been output\n", " if (origComment._displayed) skip = true;\n", "\n" ], "file_path": "lib/6to5/generation/generator.js", "type": "add", "edit_start_line_idx": 279 }
{ "modules": "amd" }
test/fixtures/transformation/es6-modules-amd/options.json
0
https://github.com/babel/babel/commit/339bf824816fd2e524859d1ea8cfb295201322ab
[ 0.00017621876031626016, 0.00017621876031626016, 0.00017621876031626016, 0.00017621876031626016, 0 ]
{ "id": 3, "code_window": [ " origComment._displayed = true;\n", " return false;\n", " }\n", " });\n", "\n", " // whitespace before\n", " self.newline(self.whitespace.getNewlinesBefore(comment));\n", "\n", " var column = self.position.column;\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " if (skip) return;\n", "\n" ], "file_path": "lib/6to5/generation/generator.js", "type": "add", "edit_start_line_idx": 284 }
module.exports = function (ast, opts, code) { var gen = new CodeGenerator(ast, opts, code); return gen.generate(); }; module.exports.CodeGenerator = CodeGenerator; var Whitespace = require("./whitespace"); var SourceMap = require("./source-map"); var Position = require("./position"); var Buffer = require("./buffer"); var util = require("../util"); var n = require("./node"); var t = require("../types"); var _ = require("lodash"); function CodeGenerator(ast, opts, code) { opts = opts || {}; this.comments = ast.comments || []; this.tokens = ast.tokens || []; this.format = CodeGenerator.normaliseOptions(opts); this.ast = ast; this.whitespace = new Whitespace(this.tokens, this.comments); this.position = new Position; this.map = new SourceMap(this.position, opts, code); this.buffer = new Buffer(this.position, this.format); } _.each(Buffer.prototype, function (fn, key) { CodeGenerator.prototype[key] = function () { return fn.apply(this.buffer, arguments); }; }); CodeGenerator.normaliseOptions = function (opts) { return _.merge({ parentheses: true, comments: opts.comments == null || opts.comments, compact: false, indent: { adjustMultilineComment: true, style: " ", base: 0 } }, opts.format || {}); }; CodeGenerator.generators = { templateLiterals: require("./generators/template-literals"), comprehensions: require("./generators/comprehensions"), expressions: require("./generators/expressions"), statements: require("./generators/statements"), playground: require("./generators/playground"), classes: require("./generators/classes"), methods: require("./generators/methods"), modules: require("./generators/modules"), types: require("./generators/types"), flow: require("./generators/flow"), base: require("./generators/base"), jsx: require("./generators/jsx") }; _.each(CodeGenerator.generators, function (generator) { _.extend(CodeGenerator.prototype, generator); }); CodeGenerator.prototype.generate = function () { var ast = this.ast; this.print(ast); var comments = []; _.each(ast.comments, function (comment) { if (!comment._displayed) comments.push(comment); }); this._printComments(comments); return { map: this.map.get(), code: this.buffer.get() }; }; CodeGenerator.prototype.buildPrint = function (parent) { var self = this; var print = function (node, opts) { return self.print(node, parent, opts); }; print.sequence = function (nodes, opts) { opts = opts || {}; opts.statement = true; return self.printJoin(print, nodes, opts); }; print.join = function (nodes, opts) { return self.printJoin(print, nodes, opts); }; print.block = function (node) { return self.printBlock(print, node); }; print.indentOnComments = function (node) { return self.printAndIndentOnComments(print, node); }; return print; }; CodeGenerator.prototype.print = function (node, parent, opts) { if (!node) return ""; var self = this; opts = opts || {}; var newline = function (leading) { if (!opts.statement && !n.isUserWhitespacable(node, parent)) { return; } var lines = 0; if (node.start != null) { // user node if (leading) { lines = self.whitespace.getNewlinesBefore(node); } else { lines = self.whitespace.getNewlinesAfter(node); } } else { // generated node if (!leading) lines++; // always include at least a single line after var needs = n.needsWhitespaceAfter; if (leading) needs = n.needsWhitespaceBefore; lines += needs(node, parent); // generated nodes can't add starting file whitespace if (!self.buffer.get()) lines = 0; } self.newline(lines); }; if (this[node.type]) { var needsCommentParens = t.isExpression(node) && node.leadingComments && node.leadingComments.length; var needsParens = needsCommentParens || n.needsParens(node, parent); if (needsParens) this.push("("); if (needsCommentParens) this.indent(); this.printLeadingComments(node, parent); newline(true); if (opts.before) opts.before(); this.map.mark(node, "start"); this[node.type](node, this.buildPrint(node), parent); if (needsCommentParens) { this.newline(); this.dedent(); } if (needsParens) this.push(")"); this.map.mark(node, "end"); if (opts.after) opts.after(); newline(false); this.printTrailingComments(node, parent); } else { throw new ReferenceError("unknown node of type " + JSON.stringify(node.type) + " with constructor " + JSON.stringify(node && node.constructor.name)); } }; CodeGenerator.prototype.printJoin = function (print, nodes, opts) { if (!nodes || !nodes.length) return; opts = opts || {}; var self = this; var len = nodes.length; if (opts.indent) self.indent(); _.each(nodes, function (node, i) { print(node, { statement: opts.statement, after: function () { if (opts.iterator) { opts.iterator(node, i); } if (opts.separator && i < len - 1) { self.push(opts.separator); } } }); }); if (opts.indent) self.dedent(); }; CodeGenerator.prototype.printAndIndentOnComments = function (print, node) { var indent = !!node.leadingComments; if (indent) this.indent(); print(node); if (indent) this.dedent(); }; CodeGenerator.prototype.printBlock = function (print, node) { if (t.isEmptyStatement(node)) { this.semicolon(); } else { this.push(" "); print(node); } }; CodeGenerator.prototype.generateComment = function (comment) { var val = comment.value; if (comment.type === "Line") { val = "//" + val; } else { val = "/*" + val + "*/"; } return val; }; CodeGenerator.prototype.printTrailingComments = function (node, parent) { this._printComments(this.getComments("trailingComments", node, parent)); }; CodeGenerator.prototype.printLeadingComments = function (node, parent) { this._printComments(this.getComments("leadingComments", node, parent)); }; CodeGenerator.prototype.getComments = function (key, node, parent) { if (t.isExpressionStatement(parent)) { return []; } var comments = []; var nodes = [node]; var self = this; if (t.isExpressionStatement(node)) { nodes.push(node.argument); } _.each(nodes, function (node) { comments = comments.concat(self._getComments(key, node)); }); return comments; }; CodeGenerator.prototype._getComments = function (key, node) { return (node && node[key]) || []; }; CodeGenerator.prototype._printComments = function (comments) { if (this.format.compact) return; if (!this.format.comments) return; if (!comments || !comments.length) return; var self = this; _.each(comments, function (comment) { // find the original comment in the ast and set it as displayed _.each(self.ast.comments, function (origComment) { if (origComment.start === comment.start) { origComment._displayed = true; return false; } }); // whitespace before self.newline(self.whitespace.getNewlinesBefore(comment)); var column = self.position.column; var val = self.generateComment(comment); if (column && !self.isLast(["\n", " ", "[", "{"])) { self._push(" "); column++; } // if (comment.type === "Block" && self.format.indent.adjustMultilineComment) { var offset = comment.loc.start.column; if (offset) { var newlineRegex = new RegExp("\\n\\s{1," + offset + "}", "g"); val = val.replace(newlineRegex, "\n"); } var indent = Math.max(self.indentSize(), column); val = val.replace(/\n/g, "\n" + util.repeat(indent)); } if (column === 0) { val = self.getIndent() + val; } // self._push(val); // whitespace after self.newline(self.whitespace.getNewlinesAfter(comment)); }); };
lib/6to5/generation/generator.js
1
https://github.com/babel/babel/commit/339bf824816fd2e524859d1ea8cfb295201322ab
[ 0.9986668825149536, 0.09188924729824066, 0.00016613870684523135, 0.0003817343385890126, 0.2864796221256256 ]
{ "id": 3, "code_window": [ " origComment._displayed = true;\n", " return false;\n", " }\n", " });\n", "\n", " // whitespace before\n", " self.newline(self.whitespace.getNewlinesBefore(comment));\n", "\n", " var column = self.position.column;\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " if (skip) return;\n", "\n" ], "file_path": "lib/6to5/generation/generator.js", "type": "add", "edit_start_line_idx": 284 }
function *gen(x) { var y = x + 1; try { throw x + 2; } catch (x) { yield x; x += 1; yield x; } yield x; try { throw x + 3; } catch (y) { yield y; y *= 2; yield y; } yield y; } genHelpers.check(gen(1), [3, 4, 1, 4, 8, 2]); genHelpers.check(gen(2), [4, 5, 2, 5, 10, 3]);
test/fixtures/transformation/es6-generators/catch-parameter-shadowing-should-leave-outer-variables-unmodified/exec.js
0
https://github.com/babel/babel/commit/339bf824816fd2e524859d1ea8cfb295201322ab
[ 0.00017691290122456849, 0.00017606983601581305, 0.000175083230715245, 0.0001762133906595409, 7.538250770267041e-7 ]
{ "id": 3, "code_window": [ " origComment._displayed = true;\n", " return false;\n", " }\n", " });\n", "\n", " // whitespace before\n", " self.newline(self.whitespace.getNewlinesBefore(comment));\n", "\n", " var column = self.position.column;\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " if (skip) return;\n", "\n" ], "file_path": "lib/6to5/generation/generator.js", "type": "add", "edit_start_line_idx": 284 }
export default 42; export default {}; export default []; export default foo; export default function () {} export default class {} export default function foo () {} export default class Foo {}
test/fixtures/transformation/es6-modules-system/exports-default/actual.js
0
https://github.com/babel/babel/commit/339bf824816fd2e524859d1ea8cfb295201322ab
[ 0.00017644524632487446, 0.00017644524632487446, 0.00017644524632487446, 0.00017644524632487446, 0 ]
{ "id": 3, "code_window": [ " origComment._displayed = true;\n", " return false;\n", " }\n", " });\n", "\n", " // whitespace before\n", " self.newline(self.whitespace.getNewlinesBefore(comment));\n", "\n", " var column = self.position.column;\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " if (skip) return;\n", "\n" ], "file_path": "lib/6to5/generation/generator.js", "type": "add", "edit_start_line_idx": 284 }
var foo = class Foo {}; var foo = class Foo extends Bar {};
test/fixtures/generation/types/ClassDeclaration/expected.js
0
https://github.com/babel/babel/commit/339bf824816fd2e524859d1ea8cfb295201322ab
[ 0.00017064434359781444, 0.00017064434359781444, 0.00017064434359781444, 0.00017064434359781444, 0 ]
{ "id": 0, "code_window": [ "\n", "You should have an `else if` statement.\n", "\n", "```js\n", "assert.match(attack.toString(), /else if/);\n", "```\n", "\n", "Your `else if` statement should check if `monsterHealth` is less than or equal to `0`.\n", "\n", "```js\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "assert.match(attack.toString(), /else\\s+if/);\n" ], "file_path": "curriculum/challenges/english/15-javascript-algorithms-and-data-structures-22/learn-basic-javascript-by-building-a-role-playing-game/62a8ee154c8946678775c4a4.md", "type": "replace", "edit_start_line_idx": 26 }
--- id: 650757918a9e97418dc3d71a title: Step 111 challengeType: 0 dashedName: step-111 --- # --description-- The last thing you will need to do is add an `else if` statement. Your condition should check if the player's `x` position is greater than or equal to the checkpoint's `x` position and less than or equal to the checkpoint's `x` position plus `40`. Inside the body of the `else if` statement, you will need to call the `showCheckpointScreen` function and pass in the string `"You reached a checkpoint!"` as an argument. Congratulations! You have completed the platformer game project! # --hints-- You should add an `else if` clause to check is the player's `x` position is greater than or equal to the checkpoint's `x` position and less than or equal to the checkpoint's `x` position plus `40`. ```js assert.match(code, /if\s*\(\s*index\s*===\s*checkpoints\.length\s*-\s*1\s*\)\s*\{\s*isCheckpointCollisionDetectionActive\s*=\s*false;?\s*showCheckpointScreen\(("|'|`)You reached the final checkpoint!\1\);?\s*movePlayer\(\s*\1ArrowRight\1,\s*0,\s*false\);?\s*\}\s*else\s*if\s*\(\s*player\.position\.x\s*>=\s*checkpoint\.position\.x\s*&&\s*player\.position\.x\s*<=\s*checkpoint\.position\.x\s\+\s*40\s*\)\s*\{\s*/) ``` You should call the `showCheckpointScreen` function and pass in "You reached a checkpoint!" as an argument. ```js assert.match(code, /if\s*\(\s*index\s*===\s*checkpoints\.length\s*-\s*1\s*\)\s*\{\s*isCheckpointCollisionDetectionActive\s*=\s*false;?\s*showCheckpointScreen\(("|'|`)You reached the final checkpoint!\1\);?\s*movePlayer\(\s*\1ArrowRight\1,\s*0,\s*false\);?\s*\}\s*else\s*if\s*\(\s*player\.position\.x\s*>=\s*checkpoint\.position\.x\s*&&\s*player\.position\.x\s*<=\s*checkpoint\.position\.x\s\+\s*40\s*\)\s*\{\s*showCheckpointScreen\(\1You\s+reached\s+a\s*checkpoint!\1\);?\s*\};?/) ``` # --seed-- ## --seed-contents-- ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Learn Intermediate OOP by Building a Platformer Game</title> <link rel="stylesheet" href="./styles.css" /> </head> <body> <div class="start-screen"> <h1 class="main-title">freeCodeCamp Code Warrior</h1> <p class="instructions"> Help the main player navigate to the yellow checkpoints. </p> <p class="instructions"> Use the keyboard arrows to move the player around. </p> <p class="instructions">You can also use the spacebar to jump.</p> <div class="btn-container"> <button class="btn" id="start-btn">Start Game</button> </div> </div> <div class="checkpoint-screen"> <h2>Congrats!</h2> <p>You reached the last checkpoint.</p> </div> <canvas id="canvas"></canvas> <script src="./script.js"></script> </body> </html> ``` ```css * { margin: 0; padding: 0; box-sizing: border-box; } :root { --main-bg-color: #0a0a23; --section-bg-color: #ffffff; --golden-yellow: #feac32; } body { background-color: var(--main-bg-color); } .start-screen { background-color: var(--section-bg-color); width: 100%; position: absolute; top: 50%; left: 50%; margin-right: -50%; transform: translate(-50%, -50%); border-radius: 30px; padding: 20px; padding-bottom: 5px; } .main-title { text-align: center; } .instructions { text-align: center; font-size: 1.2rem; margin: 15px; line-height: 2rem; } .btn { cursor: pointer; width: 100px; margin: 10px; color: #0a0a23; font-size: 18px; background-color: var(--golden-yellow); background-image: linear-gradient(#fecc4c, #ffac33); border-color: var(--golden-yellow); border-width: 3px; } .btn:hover { background-image: linear-gradient(#ffcc4c, #f89808); } .btn-container { display: flex; align-items: center; justify-content: center; } .checkpoint-screen { position: absolute; left: 0; right: 0; margin-left: auto; margin-right: auto; width: 100%; text-align: center; background-color: var(--section-bg-color); border-radius: 20px; padding: 10px; display: none; } #canvas { display: none; } @media (min-width: 768px) { .start-screen { width: 60%; max-width: 700px; } .checkpoint-screen { max-width: 300px; } } ``` ```js const startBtn = document.getElementById("start-btn"); const canvas = document.getElementById("canvas"); const startScreen = document.querySelector(".start-screen"); const checkpointScreen = document.querySelector(".checkpoint-screen"); const checkpointMessage = document.querySelector(".checkpoint-screen > p"); const ctx = canvas.getContext("2d"); canvas.width = innerWidth; canvas.height = innerHeight; const gravity = 0.5; let isCheckpointCollisionDetectionActive = true; class Player { constructor() { this.position = { x: 10, y: 400, }; this.velocity = { x: 0, y: 0, }; this.width = 40; this.height = 40; } draw() { ctx.fillStyle = "#99c9ff"; ctx.fillRect(this.position.x, this.position.y, this.width, this.height); } update() { this.draw(); this.position.x += this.velocity.x; this.position.y += this.velocity.y; if (this.position.y + this.height + this.velocity.y <= canvas.height) { if (this.position.y < 0) { this.position.y = 0; this.velocity.y = gravity; } this.velocity.y += gravity; } else { this.velocity.y = 0; } if (this.position.x < this.width) { this.position.x = this.width; } } } class Platform { constructor(x, y) { this.position = { x, y, }; this.width = 200; this.height = 40; } draw() { ctx.fillStyle = "#acd157"; ctx.fillRect(this.position.x, this.position.y, this.width, this.height); } } class CheckPoint { constructor(x, y) { this.position = { x, y, }; this.width = 40; this.height = 70; }; draw() { ctx.fillStyle = "#f1be32"; ctx.fillRect(this.position.x, this.position.y, this.width, this.height); } claim() { this.width = 0; this.height = 0; this.position.y = Infinity; } }; const player = new Player(); const platformPositions = [ { x: 500, y: 450 }, { x: 700, y: 400 }, { x: 850, y: 350 }, { x: 900, y: 350 }, { x: 1050, y: 150 }, { x: 2500, y: 450 }, { x: 2900, y: 400 }, { x: 3150, y: 350 }, { x: 3900, y: 450 }, { x: 4200, y: 400 }, { x: 4400, y: 200 }, { x: 4700, y: 150 } ]; const platforms = platformPositions.map( (platform) => new Platform(platform.x, platform.y) ); const checkpointPositions = [ { x: 1170, y: 80 }, { x: 2900, y: 330 }, { x: 4800, y: 80 }, ]; const checkpoints = checkpointPositions.map( checkpoint => new CheckPoint(checkpoint.x, checkpoint.y) ); const animate = () => { requestAnimationFrame(animate); ctx.clearRect(0, 0, canvas.width, canvas.height); platforms.forEach((platform) => { platform.draw(); }); checkpoints.forEach(checkpoint => { checkpoint.draw(); }); player.update(); if (keys.rightKey.pressed && player.position.x < 400) { player.velocity.x = 5; } else if (keys.leftKey.pressed && player.position.x > 100) { player.velocity.x = -5; } else { player.velocity.x = 0; if (keys.rightKey.pressed && isCheckpointCollisionDetectionActive) { platforms.forEach((platform) => { platform.position.x -= 5; }); checkpoints.forEach((checkpoint) => { checkpoint.position.x -= 5; }); } else if (keys.leftKey.pressed && isCheckpointCollisionDetectionActive) { platforms.forEach((platform) => { platform.position.x += 5; }); checkpoints.forEach((checkpoint) => { checkpoint.position.x += 5; }); } } platforms.forEach((platform) => { const collisionDetectionRules = [ player.position.y + player.height <= platform.position.y, player.position.y + player.height + player.velocity.y >= platform.position.y, player.position.x >= platform.position.x - player.width / 2, player.position.x <= platform.position.x + platform.width - player.width / 3, ]; if (collisionDetectionRules.every((rule) => rule)) { player.velocity.y = 0; return; } const platformDetectionRules = [ player.position.x >= platform.position.x - player.width / 2, player.position.x <= platform.position.x + platform.width - player.width / 3, player.position.y + player.height >= platform.position.y, player.position.y <= platform.position.y + platform.height, ]; if (platformDetectionRules.every(rule => rule)) { player.position.y = platform.position.y + player.height; player.velocity.y = gravity; }; }); checkpoints.forEach((checkpoint, index) => { const checkpointDetectionRules = [ player.position.x >= checkpoint.position.x, player.position.y >= checkpoint.position.y, player.position.y + player.height <= checkpoint.position.y + checkpoint.height, isCheckpointCollisionDetectionActive ]; if (checkpointDetectionRules.every((rule) => rule)) { checkpoint.claim(); --fcc-editable-region-- if (index === checkpoints.length - 1) { isCheckpointCollisionDetectionActive = false; showCheckpointScreen("You reached the final checkpoint!"); movePlayer("ArrowRight", 0, false); } --fcc-editable-region-- }; }); } const keys = { rightKey: { pressed: false }, leftKey: { pressed: false } }; const movePlayer = (key, xVelocity, isPressed) => { if (!isCheckpointCollisionDetectionActive) { player.velocity.x = 0; player.velocity.y = 0; return; } switch (key) { case "ArrowLeft": keys.leftKey.pressed = isPressed; if (xVelocity === 0) { player.velocity.x = xVelocity; } player.velocity.x -= xVelocity; break; case "ArrowUp": case " ": case "Spacebar": player.velocity.y -= 8; break; case "ArrowRight": keys.rightKey.pressed = isPressed; if (xVelocity === 0) { player.velocity.x = xVelocity; } player.velocity.x += xVelocity; } } const startGame = () => { canvas.style.display = "block"; startScreen.style.display = "none"; animate(); } const showCheckpointScreen = (msg) => { checkpointScreen.style.display = "block"; checkpointMessage.textContent = msg; if (isCheckpointCollisionDetectionActive) { setTimeout(() => (checkpointScreen.style.display = "none"), 2000); } }; startBtn.addEventListener("click", startGame); window.addEventListener("keydown", ({ key }) => { movePlayer(key, 8, true); }); window.addEventListener("keyup", ({ key }) => { movePlayer(key, 0, false); }); ``` # --solutions-- ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Learn Intermediate OOP by Building a Platformer Game</title> <link rel="stylesheet" href="./styles.css" /> </head> <body> <div class="start-screen"> <h1 class="main-title">freeCodeCamp Code Warrior</h1> <p class="instructions"> Help the main player navigate to the yellow checkpoints. </p> <p class="instructions"> Use the keyboard arrows to move the player around. </p> <p class="instructions">You can also use the spacebar to jump.</p> <div class="btn-container"> <button class="btn" id="start-btn">Start Game</button> </div> </div> <div class="checkpoint-screen"> <h2>Congrats!</h2> <p>You reached the last checkpoint.</p> </div> <canvas id="canvas"></canvas> <script src="./script.js"></script> </body> </html> ``` ```css * { margin: 0; padding: 0; box-sizing: border-box; } :root { --main-bg-color: #0a0a23; --section-bg-color: #ffffff; --golden-yellow: #feac32; } body { background-color: var(--main-bg-color); } .start-screen { background-color: var(--section-bg-color); width: 100%; position: absolute; top: 50%; left: 50%; margin-right: -50%; transform: translate(-50%, -50%); border-radius: 30px; padding: 20px; padding-bottom: 5px; } .main-title { text-align: center; } .instructions { text-align: center; font-size: 1.2rem; margin: 15px; line-height: 2rem; } .btn { cursor: pointer; width: 100px; margin: 10px; color: #0a0a23; font-size: 18px; background-color: var(--golden-yellow); background-image: linear-gradient(#fecc4c, #ffac33); border-color: var(--golden-yellow); border-width: 3px; } .btn:hover { background-image: linear-gradient(#ffcc4c, #f89808); } .btn-container { display: flex; align-items: center; justify-content: center; } .checkpoint-screen { position: absolute; left: 0; right: 0; margin-left: auto; margin-right: auto; width: 100%; text-align: center; background-color: var(--section-bg-color); border-radius: 20px; padding: 10px; display: none; } #canvas { display: none; } @media (min-width: 768px) { .start-screen { width: 60%; max-width: 700px; } .checkpoint-screen { max-width: 300px; } } ``` ```js const startBtn = document.getElementById("start-btn"); const canvas = document.getElementById("canvas"); const startScreen = document.querySelector(".start-screen"); const checkpointScreen = document.querySelector(".checkpoint-screen"); const checkpointMessage = document.querySelector(".checkpoint-screen > p"); const ctx = canvas.getContext("2d"); canvas.width = innerWidth; canvas.height = innerHeight; const gravity = 0.5; let isCheckpointCollisionDetectionActive = true; class Player { constructor() { this.position = { x: 10, y: 400, }; this.velocity = { x: 0, y: 0, }; this.width = 40; this.height = 40; } draw() { ctx.fillStyle = "#99c9ff"; ctx.fillRect(this.position.x, this.position.y, this.width, this.height); } update() { this.draw(); this.position.x += this.velocity.x; this.position.y += this.velocity.y; if (this.position.y + this.height + this.velocity.y <= canvas.height) { if (this.position.y < 0) { this.position.y = 0; this.velocity.y = gravity; } this.velocity.y += gravity; } else { this.velocity.y = 0; } if (this.position.x < this.width) { this.position.x = this.width; } } } class Platform { constructor(x, y) { this.position = { x, y, }; this.width = 200; this.height = 40; } draw() { ctx.fillStyle = "#acd157"; ctx.fillRect(this.position.x, this.position.y, this.width, this.height); } } class CheckPoint { constructor(x, y) { this.position = { x, y, }; this.width = 40; this.height = 70; }; draw() { ctx.fillStyle = "#f1be32"; ctx.fillRect(this.position.x, this.position.y, this.width, this.height); } claim() { this.width = 0; this.height = 0; this.position.y = Infinity; } }; const player = new Player(); const platformPositions = [ { x: 500, y: 450 }, { x: 700, y: 400 }, { x: 850, y: 350 }, { x: 900, y: 350 }, { x: 1050, y: 150 }, { x: 2500, y: 450 }, { x: 2900, y: 400 }, { x: 3150, y: 350 }, { x: 3900, y: 450 }, { x: 4200, y: 400 }, { x: 4400, y: 200 }, { x: 4700, y: 150 } ]; const platforms = platformPositions.map( (platform) => new Platform(platform.x, platform.y) ); const checkpointPositions = [ { x: 1170, y: 80 }, { x: 2900, y: 330 }, { x: 4800, y: 80 }, ]; const checkpoints = checkpointPositions.map( checkpoint => new CheckPoint(checkpoint.x, checkpoint.y) ); const animate = () => { requestAnimationFrame(animate); ctx.clearRect(0, 0, canvas.width, canvas.height); platforms.forEach((platform) => { platform.draw(); }); checkpoints.forEach(checkpoint => { checkpoint.draw(); }); player.update(); if (keys.rightKey.pressed && player.position.x < 400) { player.velocity.x = 5; } else if (keys.leftKey.pressed && player.position.x > 100) { player.velocity.x = -5; } else { player.velocity.x = 0; if (keys.rightKey.pressed && isCheckpointCollisionDetectionActive) { platforms.forEach((platform) => { platform.position.x -= 5; }); checkpoints.forEach((checkpoint) => { checkpoint.position.x -= 5; }); } else if (keys.leftKey.pressed && isCheckpointCollisionDetectionActive) { platforms.forEach((platform) => { platform.position.x += 5; }); checkpoints.forEach((checkpoint) => { checkpoint.position.x += 5; }); } } platforms.forEach((platform) => { const collisionDetectionRules = [ player.position.y + player.height <= platform.position.y, player.position.y + player.height + player.velocity.y >= platform.position.y, player.position.x >= platform.position.x - player.width / 2, player.position.x <= platform.position.x + platform.width - player.width / 3, ]; if (collisionDetectionRules.every((rule) => rule)) { player.velocity.y = 0; return; } const platformDetectionRules = [ player.position.x >= platform.position.x - player.width / 2, player.position.x <= platform.position.x + platform.width - player.width / 3, player.position.y + player.height >= platform.position.y, player.position.y <= platform.position.y + platform.height, ]; if (platformDetectionRules.every(rule => rule)) { player.position.y = platform.position.y + player.height; player.velocity.y = gravity; }; }); checkpoints.forEach((checkpoint, index) => { const checkpointDetectionRules = [ player.position.x >= checkpoint.position.x, player.position.y >= checkpoint.position.y, player.position.y + player.height <= checkpoint.position.y + checkpoint.height, isCheckpointCollisionDetectionActive ]; if (checkpointDetectionRules.every((rule) => rule)) { checkpoint.claim(); if (index === checkpoints.length - 1) { isCheckpointCollisionDetectionActive = false; showCheckpointScreen("You reached the final checkpoint!"); movePlayer("ArrowRight", 0, false); } else if ( player.position.x >= checkpoint.position.x && player.position.x <= checkpoint.position.x + 40 ) { showCheckpointScreen("You reached a checkpoint!"); } }; }); } const keys = { rightKey: { pressed: false }, leftKey: { pressed: false } }; const movePlayer = (key, xVelocity, isPressed) => { if (!isCheckpointCollisionDetectionActive) { player.velocity.x = 0; player.velocity.y = 0; return; } switch (key) { case "ArrowLeft": keys.leftKey.pressed = isPressed; if (xVelocity === 0) { player.velocity.x = xVelocity; } player.velocity.x -= xVelocity; break; case "ArrowUp": case " ": case "Spacebar": player.velocity.y -= 8; break; case "ArrowRight": keys.rightKey.pressed = isPressed; if (xVelocity === 0) { player.velocity.x = xVelocity; } player.velocity.x += xVelocity; } } const startGame = () => { canvas.style.display = "block"; startScreen.style.display = "none"; animate(); } const showCheckpointScreen = (msg) => { checkpointScreen.style.display = "block"; checkpointMessage.textContent = msg; if (isCheckpointCollisionDetectionActive) { setTimeout(() => (checkpointScreen.style.display = "none"), 2000); } }; startBtn.addEventListener("click", startGame); window.addEventListener("keydown", ({ key }) => { movePlayer(key, 8, true); }); window.addEventListener("keyup", ({ key }) => { movePlayer(key, 0, false); }); ```
curriculum/challenges/english/15-javascript-algorithms-and-data-structures-22/learn-intermediate-oop-by-building-a-platformer-game/650757918a9e97418dc3d71a.md
1
https://github.com/freeCodeCamp/freeCodeCamp/commit/5973899673bed0cdcd8a960453fd63639fbcf315
[ 0.0009949489030987024, 0.00018506409833207726, 0.00016505569510627538, 0.00017041995306499302, 0.00009058899740921333 ]
{ "id": 0, "code_window": [ "\n", "You should have an `else if` statement.\n", "\n", "```js\n", "assert.match(attack.toString(), /else if/);\n", "```\n", "\n", "Your `else if` statement should check if `monsterHealth` is less than or equal to `0`.\n", "\n", "```js\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "assert.match(attack.toString(), /else\\s+if/);\n" ], "file_path": "curriculum/challenges/english/15-javascript-algorithms-and-data-structures-22/learn-basic-javascript-by-building-a-role-playing-game/62a8ee154c8946678775c4a4.md", "type": "replace", "edit_start_line_idx": 26 }
--- id: 6196cee94c6da1253809dff9 title: الخطوة 20 challengeType: 0 dashedName: step-20 --- # --description-- استهدف عنصر `.back-mountain` وعيّن `width` و `height` إلى `300px`. ثم عيّن `background` إلى التدريج الخطي (linear gradient) يبدأ في `rgb(203, 241, 228)`, وينتهي في `rgb(47, 170, 255)`. # --hints-- يجب عليك استخدام منتقي `.back-mountain`. ```js assert.match(code, /\.back-mountain\s*\{/); ``` يجب عليك إعطاء `.back-mountain` خاصية `width` بقيمة `300px`. ```js assert.equal(new __helpers.CSSHelp(document).getStyle('.back-mountain')?.width, '300px'); ``` يجب عليك إعطاء `.back-mountain` خاصية `height` بقيمة `300px`. ```js assert.equal(new __helpers.CSSHelp(document).getStyle('.back-mountain')?.height, '300px'); ``` يجب عليك إعطاء `.back-mountain` خاصية `background` من `linear-gradient(rgb(203, 241, 228), rgb(47, 170, 255))`. ```js assert.include(['linear-gradient(rgb(203,241,228),rgb(47,170,255))', 'rgba(0,0,0,0)linear-gradient(rgb(203,241,228),rgb(47,170,255))repeatscroll0%0%'], new __helpers.CSSHelp(document).getStyle('.back-mountain')?.getPropVal('background', true)); ``` # --seed-- ## --seed-contents-- ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <link rel="stylesheet" href="./styles.css" /> <title>Penguin</title> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> </head> <body> <div class="left-mountain"></div> <div class="back-mountain"></div> <div class="penguin"></div> <div class="ground"></div> </body> </html> ``` ```css body { background: linear-gradient(45deg, rgb(118, 201, 255), rgb(247, 255, 222)); margin: 0; padding: 0; width: 100%; height: 100vh; overflow: hidden; } .left-mountain { width: 300px; height: 300px; background: linear-gradient(rgb(203, 241, 228), rgb(80, 183, 255)); position: absolute; transform: skew(0deg, 44deg); z-index: 2; margin-top: 100px; } --fcc-editable-region-- --fcc-editable-region-- .penguin { width: 300px; height: 300px; margin: auto; margin-top: 75px; } .ground { width: 100vw; height: 400px; background: linear-gradient(90deg, rgb(88, 175, 236), rgb(182, 255, 255)); z-index: 3; position: absolute; margin-top: -58px; } ```
curriculum/challenges/arabic/14-responsive-web-design-22/learn-css-transforms-by-building-a-penguin/6196cee94c6da1253809dff9.md
0
https://github.com/freeCodeCamp/freeCodeCamp/commit/5973899673bed0cdcd8a960453fd63639fbcf315
[ 0.00024126845528371632, 0.00017843404202722013, 0.00016582802345510572, 0.00016699684783816338, 0.000021312336684786715 ]
{ "id": 0, "code_window": [ "\n", "You should have an `else if` statement.\n", "\n", "```js\n", "assert.match(attack.toString(), /else if/);\n", "```\n", "\n", "Your `else if` statement should check if `monsterHealth` is less than or equal to `0`.\n", "\n", "```js\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "assert.match(attack.toString(), /else\\s+if/);\n" ], "file_path": "curriculum/challenges/english/15-javascript-algorithms-and-data-structures-22/learn-basic-javascript-by-building-a-role-playing-game/62a8ee154c8946678775c4a4.md", "type": "replace", "edit_start_line_idx": 26 }
--- id: 5900f3711000cf542c50fe84 title: 'Problem 5: Smallest multiple' challengeType: 1 forumTopicId: 302160 dashedName: problem-5-smallest-multiple --- # --description-- 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. What is the smallest positive number that is evenly divisible by all of the numbers from 1 to `n`? # --hints-- `smallestMult(5)` should return a number. ```js assert(typeof smallestMult(5) === 'number'); ``` `smallestMult(5)` should return 60. ```js assert.strictEqual(smallestMult(5), 60); ``` `smallestMult(7)` should return 420. ```js assert.strictEqual(smallestMult(7), 420); ``` `smallestMult(10)` should return 2520. ```js assert.strictEqual(smallestMult(10), 2520); ``` `smallestMult(13)` should return 360360. ```js assert.strictEqual(smallestMult(13), 360360); ``` `smallestMult(20)` should return 232792560. ```js assert.strictEqual(smallestMult(20), 232792560); ``` # --seed-- ## --seed-contents-- ```js function smallestMult(n) { return true; } smallestMult(20); ``` # --solutions-- ```js function smallestMult(n){ function gcd(a, b) { return b === 0 ? a : gcd(b, a%b); // Euclidean algorithm } function lcm(a, b) { return a * b / gcd(a, b); } var result = 1; for(var i = 2; i <= n; i++) { result = lcm(result, i); } return result; } ```
curriculum/challenges/chinese-traditional/18-project-euler/project-euler-problems-1-to-100/problem-5-smallest-multiple.md
0
https://github.com/freeCodeCamp/freeCodeCamp/commit/5973899673bed0cdcd8a960453fd63639fbcf315
[ 0.00020077986118849367, 0.00017352103895973414, 0.00016510132991243154, 0.00016995712940115482, 0.000010204301361227408 ]
{ "id": 0, "code_window": [ "\n", "You should have an `else if` statement.\n", "\n", "```js\n", "assert.match(attack.toString(), /else if/);\n", "```\n", "\n", "Your `else if` statement should check if `monsterHealth` is less than or equal to `0`.\n", "\n", "```js\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "assert.match(attack.toString(), /else\\s+if/);\n" ], "file_path": "curriculum/challenges/english/15-javascript-algorithms-and-data-structures-22/learn-basic-javascript-by-building-a-role-playing-game/62a8ee154c8946678775c4a4.md", "type": "replace", "edit_start_line_idx": 26 }
--- id: 655c0f39ee87517d584d81f9 title: "Dialogue: Placeholder" challengeType: 21 videoId: nLDychdBwUg dashedName: dialogue-placeholder --- # --description-- Watch the video above to understand the context of the upcoming lessons. # --assignment-- Watch the video
curriculum/challenges/german/21-a2-english-for-developers/learn-how-to-discuss-your-morning-or-evening-routine/dialogue-placeholder.md
0
https://github.com/freeCodeCamp/freeCodeCamp/commit/5973899673bed0cdcd8a960453fd63639fbcf315
[ 0.00017151085194200277, 0.00017005903646349907, 0.0001686072355369106, 0.00017005903646349907, 0.0000014518082025460899 ]
{ "id": 1, "code_window": [ "\n", "Your `else if` statement should check if `monsterHealth` is less than or equal to `0`.\n", "\n", "```js\n", "assert.match(attack.toString(), /else\\s*if\\s*\\(\\s*monsterHealth\\s*<=\\s*0\\s*\\)/);\n", "```\n", "\n", "Your `else if` statement should call the `defeatMonster` function.\n", "\n", "```js\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "assert.match(attack.toString(), /else\\s+if\\s*\\(\\s*monsterHealth\\s*<=\\s*0\\s*\\)/);\n" ], "file_path": "curriculum/challenges/english/15-javascript-algorithms-and-data-structures-22/learn-basic-javascript-by-building-a-role-playing-game/62a8ee154c8946678775c4a4.md", "type": "replace", "edit_start_line_idx": 32 }
--- id: 650757918a9e97418dc3d71a title: Step 111 challengeType: 0 dashedName: step-111 --- # --description-- The last thing you will need to do is add an `else if` statement. Your condition should check if the player's `x` position is greater than or equal to the checkpoint's `x` position and less than or equal to the checkpoint's `x` position plus `40`. Inside the body of the `else if` statement, you will need to call the `showCheckpointScreen` function and pass in the string `"You reached a checkpoint!"` as an argument. Congratulations! You have completed the platformer game project! # --hints-- You should add an `else if` clause to check is the player's `x` position is greater than or equal to the checkpoint's `x` position and less than or equal to the checkpoint's `x` position plus `40`. ```js assert.match(code, /if\s*\(\s*index\s*===\s*checkpoints\.length\s*-\s*1\s*\)\s*\{\s*isCheckpointCollisionDetectionActive\s*=\s*false;?\s*showCheckpointScreen\(("|'|`)You reached the final checkpoint!\1\);?\s*movePlayer\(\s*\1ArrowRight\1,\s*0,\s*false\);?\s*\}\s*else\s*if\s*\(\s*player\.position\.x\s*>=\s*checkpoint\.position\.x\s*&&\s*player\.position\.x\s*<=\s*checkpoint\.position\.x\s\+\s*40\s*\)\s*\{\s*/) ``` You should call the `showCheckpointScreen` function and pass in "You reached a checkpoint!" as an argument. ```js assert.match(code, /if\s*\(\s*index\s*===\s*checkpoints\.length\s*-\s*1\s*\)\s*\{\s*isCheckpointCollisionDetectionActive\s*=\s*false;?\s*showCheckpointScreen\(("|'|`)You reached the final checkpoint!\1\);?\s*movePlayer\(\s*\1ArrowRight\1,\s*0,\s*false\);?\s*\}\s*else\s*if\s*\(\s*player\.position\.x\s*>=\s*checkpoint\.position\.x\s*&&\s*player\.position\.x\s*<=\s*checkpoint\.position\.x\s\+\s*40\s*\)\s*\{\s*showCheckpointScreen\(\1You\s+reached\s+a\s*checkpoint!\1\);?\s*\};?/) ``` # --seed-- ## --seed-contents-- ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Learn Intermediate OOP by Building a Platformer Game</title> <link rel="stylesheet" href="./styles.css" /> </head> <body> <div class="start-screen"> <h1 class="main-title">freeCodeCamp Code Warrior</h1> <p class="instructions"> Help the main player navigate to the yellow checkpoints. </p> <p class="instructions"> Use the keyboard arrows to move the player around. </p> <p class="instructions">You can also use the spacebar to jump.</p> <div class="btn-container"> <button class="btn" id="start-btn">Start Game</button> </div> </div> <div class="checkpoint-screen"> <h2>Congrats!</h2> <p>You reached the last checkpoint.</p> </div> <canvas id="canvas"></canvas> <script src="./script.js"></script> </body> </html> ``` ```css * { margin: 0; padding: 0; box-sizing: border-box; } :root { --main-bg-color: #0a0a23; --section-bg-color: #ffffff; --golden-yellow: #feac32; } body { background-color: var(--main-bg-color); } .start-screen { background-color: var(--section-bg-color); width: 100%; position: absolute; top: 50%; left: 50%; margin-right: -50%; transform: translate(-50%, -50%); border-radius: 30px; padding: 20px; padding-bottom: 5px; } .main-title { text-align: center; } .instructions { text-align: center; font-size: 1.2rem; margin: 15px; line-height: 2rem; } .btn { cursor: pointer; width: 100px; margin: 10px; color: #0a0a23; font-size: 18px; background-color: var(--golden-yellow); background-image: linear-gradient(#fecc4c, #ffac33); border-color: var(--golden-yellow); border-width: 3px; } .btn:hover { background-image: linear-gradient(#ffcc4c, #f89808); } .btn-container { display: flex; align-items: center; justify-content: center; } .checkpoint-screen { position: absolute; left: 0; right: 0; margin-left: auto; margin-right: auto; width: 100%; text-align: center; background-color: var(--section-bg-color); border-radius: 20px; padding: 10px; display: none; } #canvas { display: none; } @media (min-width: 768px) { .start-screen { width: 60%; max-width: 700px; } .checkpoint-screen { max-width: 300px; } } ``` ```js const startBtn = document.getElementById("start-btn"); const canvas = document.getElementById("canvas"); const startScreen = document.querySelector(".start-screen"); const checkpointScreen = document.querySelector(".checkpoint-screen"); const checkpointMessage = document.querySelector(".checkpoint-screen > p"); const ctx = canvas.getContext("2d"); canvas.width = innerWidth; canvas.height = innerHeight; const gravity = 0.5; let isCheckpointCollisionDetectionActive = true; class Player { constructor() { this.position = { x: 10, y: 400, }; this.velocity = { x: 0, y: 0, }; this.width = 40; this.height = 40; } draw() { ctx.fillStyle = "#99c9ff"; ctx.fillRect(this.position.x, this.position.y, this.width, this.height); } update() { this.draw(); this.position.x += this.velocity.x; this.position.y += this.velocity.y; if (this.position.y + this.height + this.velocity.y <= canvas.height) { if (this.position.y < 0) { this.position.y = 0; this.velocity.y = gravity; } this.velocity.y += gravity; } else { this.velocity.y = 0; } if (this.position.x < this.width) { this.position.x = this.width; } } } class Platform { constructor(x, y) { this.position = { x, y, }; this.width = 200; this.height = 40; } draw() { ctx.fillStyle = "#acd157"; ctx.fillRect(this.position.x, this.position.y, this.width, this.height); } } class CheckPoint { constructor(x, y) { this.position = { x, y, }; this.width = 40; this.height = 70; }; draw() { ctx.fillStyle = "#f1be32"; ctx.fillRect(this.position.x, this.position.y, this.width, this.height); } claim() { this.width = 0; this.height = 0; this.position.y = Infinity; } }; const player = new Player(); const platformPositions = [ { x: 500, y: 450 }, { x: 700, y: 400 }, { x: 850, y: 350 }, { x: 900, y: 350 }, { x: 1050, y: 150 }, { x: 2500, y: 450 }, { x: 2900, y: 400 }, { x: 3150, y: 350 }, { x: 3900, y: 450 }, { x: 4200, y: 400 }, { x: 4400, y: 200 }, { x: 4700, y: 150 } ]; const platforms = platformPositions.map( (platform) => new Platform(platform.x, platform.y) ); const checkpointPositions = [ { x: 1170, y: 80 }, { x: 2900, y: 330 }, { x: 4800, y: 80 }, ]; const checkpoints = checkpointPositions.map( checkpoint => new CheckPoint(checkpoint.x, checkpoint.y) ); const animate = () => { requestAnimationFrame(animate); ctx.clearRect(0, 0, canvas.width, canvas.height); platforms.forEach((platform) => { platform.draw(); }); checkpoints.forEach(checkpoint => { checkpoint.draw(); }); player.update(); if (keys.rightKey.pressed && player.position.x < 400) { player.velocity.x = 5; } else if (keys.leftKey.pressed && player.position.x > 100) { player.velocity.x = -5; } else { player.velocity.x = 0; if (keys.rightKey.pressed && isCheckpointCollisionDetectionActive) { platforms.forEach((platform) => { platform.position.x -= 5; }); checkpoints.forEach((checkpoint) => { checkpoint.position.x -= 5; }); } else if (keys.leftKey.pressed && isCheckpointCollisionDetectionActive) { platforms.forEach((platform) => { platform.position.x += 5; }); checkpoints.forEach((checkpoint) => { checkpoint.position.x += 5; }); } } platforms.forEach((platform) => { const collisionDetectionRules = [ player.position.y + player.height <= platform.position.y, player.position.y + player.height + player.velocity.y >= platform.position.y, player.position.x >= platform.position.x - player.width / 2, player.position.x <= platform.position.x + platform.width - player.width / 3, ]; if (collisionDetectionRules.every((rule) => rule)) { player.velocity.y = 0; return; } const platformDetectionRules = [ player.position.x >= platform.position.x - player.width / 2, player.position.x <= platform.position.x + platform.width - player.width / 3, player.position.y + player.height >= platform.position.y, player.position.y <= platform.position.y + platform.height, ]; if (platformDetectionRules.every(rule => rule)) { player.position.y = platform.position.y + player.height; player.velocity.y = gravity; }; }); checkpoints.forEach((checkpoint, index) => { const checkpointDetectionRules = [ player.position.x >= checkpoint.position.x, player.position.y >= checkpoint.position.y, player.position.y + player.height <= checkpoint.position.y + checkpoint.height, isCheckpointCollisionDetectionActive ]; if (checkpointDetectionRules.every((rule) => rule)) { checkpoint.claim(); --fcc-editable-region-- if (index === checkpoints.length - 1) { isCheckpointCollisionDetectionActive = false; showCheckpointScreen("You reached the final checkpoint!"); movePlayer("ArrowRight", 0, false); } --fcc-editable-region-- }; }); } const keys = { rightKey: { pressed: false }, leftKey: { pressed: false } }; const movePlayer = (key, xVelocity, isPressed) => { if (!isCheckpointCollisionDetectionActive) { player.velocity.x = 0; player.velocity.y = 0; return; } switch (key) { case "ArrowLeft": keys.leftKey.pressed = isPressed; if (xVelocity === 0) { player.velocity.x = xVelocity; } player.velocity.x -= xVelocity; break; case "ArrowUp": case " ": case "Spacebar": player.velocity.y -= 8; break; case "ArrowRight": keys.rightKey.pressed = isPressed; if (xVelocity === 0) { player.velocity.x = xVelocity; } player.velocity.x += xVelocity; } } const startGame = () => { canvas.style.display = "block"; startScreen.style.display = "none"; animate(); } const showCheckpointScreen = (msg) => { checkpointScreen.style.display = "block"; checkpointMessage.textContent = msg; if (isCheckpointCollisionDetectionActive) { setTimeout(() => (checkpointScreen.style.display = "none"), 2000); } }; startBtn.addEventListener("click", startGame); window.addEventListener("keydown", ({ key }) => { movePlayer(key, 8, true); }); window.addEventListener("keyup", ({ key }) => { movePlayer(key, 0, false); }); ``` # --solutions-- ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Learn Intermediate OOP by Building a Platformer Game</title> <link rel="stylesheet" href="./styles.css" /> </head> <body> <div class="start-screen"> <h1 class="main-title">freeCodeCamp Code Warrior</h1> <p class="instructions"> Help the main player navigate to the yellow checkpoints. </p> <p class="instructions"> Use the keyboard arrows to move the player around. </p> <p class="instructions">You can also use the spacebar to jump.</p> <div class="btn-container"> <button class="btn" id="start-btn">Start Game</button> </div> </div> <div class="checkpoint-screen"> <h2>Congrats!</h2> <p>You reached the last checkpoint.</p> </div> <canvas id="canvas"></canvas> <script src="./script.js"></script> </body> </html> ``` ```css * { margin: 0; padding: 0; box-sizing: border-box; } :root { --main-bg-color: #0a0a23; --section-bg-color: #ffffff; --golden-yellow: #feac32; } body { background-color: var(--main-bg-color); } .start-screen { background-color: var(--section-bg-color); width: 100%; position: absolute; top: 50%; left: 50%; margin-right: -50%; transform: translate(-50%, -50%); border-radius: 30px; padding: 20px; padding-bottom: 5px; } .main-title { text-align: center; } .instructions { text-align: center; font-size: 1.2rem; margin: 15px; line-height: 2rem; } .btn { cursor: pointer; width: 100px; margin: 10px; color: #0a0a23; font-size: 18px; background-color: var(--golden-yellow); background-image: linear-gradient(#fecc4c, #ffac33); border-color: var(--golden-yellow); border-width: 3px; } .btn:hover { background-image: linear-gradient(#ffcc4c, #f89808); } .btn-container { display: flex; align-items: center; justify-content: center; } .checkpoint-screen { position: absolute; left: 0; right: 0; margin-left: auto; margin-right: auto; width: 100%; text-align: center; background-color: var(--section-bg-color); border-radius: 20px; padding: 10px; display: none; } #canvas { display: none; } @media (min-width: 768px) { .start-screen { width: 60%; max-width: 700px; } .checkpoint-screen { max-width: 300px; } } ``` ```js const startBtn = document.getElementById("start-btn"); const canvas = document.getElementById("canvas"); const startScreen = document.querySelector(".start-screen"); const checkpointScreen = document.querySelector(".checkpoint-screen"); const checkpointMessage = document.querySelector(".checkpoint-screen > p"); const ctx = canvas.getContext("2d"); canvas.width = innerWidth; canvas.height = innerHeight; const gravity = 0.5; let isCheckpointCollisionDetectionActive = true; class Player { constructor() { this.position = { x: 10, y: 400, }; this.velocity = { x: 0, y: 0, }; this.width = 40; this.height = 40; } draw() { ctx.fillStyle = "#99c9ff"; ctx.fillRect(this.position.x, this.position.y, this.width, this.height); } update() { this.draw(); this.position.x += this.velocity.x; this.position.y += this.velocity.y; if (this.position.y + this.height + this.velocity.y <= canvas.height) { if (this.position.y < 0) { this.position.y = 0; this.velocity.y = gravity; } this.velocity.y += gravity; } else { this.velocity.y = 0; } if (this.position.x < this.width) { this.position.x = this.width; } } } class Platform { constructor(x, y) { this.position = { x, y, }; this.width = 200; this.height = 40; } draw() { ctx.fillStyle = "#acd157"; ctx.fillRect(this.position.x, this.position.y, this.width, this.height); } } class CheckPoint { constructor(x, y) { this.position = { x, y, }; this.width = 40; this.height = 70; }; draw() { ctx.fillStyle = "#f1be32"; ctx.fillRect(this.position.x, this.position.y, this.width, this.height); } claim() { this.width = 0; this.height = 0; this.position.y = Infinity; } }; const player = new Player(); const platformPositions = [ { x: 500, y: 450 }, { x: 700, y: 400 }, { x: 850, y: 350 }, { x: 900, y: 350 }, { x: 1050, y: 150 }, { x: 2500, y: 450 }, { x: 2900, y: 400 }, { x: 3150, y: 350 }, { x: 3900, y: 450 }, { x: 4200, y: 400 }, { x: 4400, y: 200 }, { x: 4700, y: 150 } ]; const platforms = platformPositions.map( (platform) => new Platform(platform.x, platform.y) ); const checkpointPositions = [ { x: 1170, y: 80 }, { x: 2900, y: 330 }, { x: 4800, y: 80 }, ]; const checkpoints = checkpointPositions.map( checkpoint => new CheckPoint(checkpoint.x, checkpoint.y) ); const animate = () => { requestAnimationFrame(animate); ctx.clearRect(0, 0, canvas.width, canvas.height); platforms.forEach((platform) => { platform.draw(); }); checkpoints.forEach(checkpoint => { checkpoint.draw(); }); player.update(); if (keys.rightKey.pressed && player.position.x < 400) { player.velocity.x = 5; } else if (keys.leftKey.pressed && player.position.x > 100) { player.velocity.x = -5; } else { player.velocity.x = 0; if (keys.rightKey.pressed && isCheckpointCollisionDetectionActive) { platforms.forEach((platform) => { platform.position.x -= 5; }); checkpoints.forEach((checkpoint) => { checkpoint.position.x -= 5; }); } else if (keys.leftKey.pressed && isCheckpointCollisionDetectionActive) { platforms.forEach((platform) => { platform.position.x += 5; }); checkpoints.forEach((checkpoint) => { checkpoint.position.x += 5; }); } } platforms.forEach((platform) => { const collisionDetectionRules = [ player.position.y + player.height <= platform.position.y, player.position.y + player.height + player.velocity.y >= platform.position.y, player.position.x >= platform.position.x - player.width / 2, player.position.x <= platform.position.x + platform.width - player.width / 3, ]; if (collisionDetectionRules.every((rule) => rule)) { player.velocity.y = 0; return; } const platformDetectionRules = [ player.position.x >= platform.position.x - player.width / 2, player.position.x <= platform.position.x + platform.width - player.width / 3, player.position.y + player.height >= platform.position.y, player.position.y <= platform.position.y + platform.height, ]; if (platformDetectionRules.every(rule => rule)) { player.position.y = platform.position.y + player.height; player.velocity.y = gravity; }; }); checkpoints.forEach((checkpoint, index) => { const checkpointDetectionRules = [ player.position.x >= checkpoint.position.x, player.position.y >= checkpoint.position.y, player.position.y + player.height <= checkpoint.position.y + checkpoint.height, isCheckpointCollisionDetectionActive ]; if (checkpointDetectionRules.every((rule) => rule)) { checkpoint.claim(); if (index === checkpoints.length - 1) { isCheckpointCollisionDetectionActive = false; showCheckpointScreen("You reached the final checkpoint!"); movePlayer("ArrowRight", 0, false); } else if ( player.position.x >= checkpoint.position.x && player.position.x <= checkpoint.position.x + 40 ) { showCheckpointScreen("You reached a checkpoint!"); } }; }); } const keys = { rightKey: { pressed: false }, leftKey: { pressed: false } }; const movePlayer = (key, xVelocity, isPressed) => { if (!isCheckpointCollisionDetectionActive) { player.velocity.x = 0; player.velocity.y = 0; return; } switch (key) { case "ArrowLeft": keys.leftKey.pressed = isPressed; if (xVelocity === 0) { player.velocity.x = xVelocity; } player.velocity.x -= xVelocity; break; case "ArrowUp": case " ": case "Spacebar": player.velocity.y -= 8; break; case "ArrowRight": keys.rightKey.pressed = isPressed; if (xVelocity === 0) { player.velocity.x = xVelocity; } player.velocity.x += xVelocity; } } const startGame = () => { canvas.style.display = "block"; startScreen.style.display = "none"; animate(); } const showCheckpointScreen = (msg) => { checkpointScreen.style.display = "block"; checkpointMessage.textContent = msg; if (isCheckpointCollisionDetectionActive) { setTimeout(() => (checkpointScreen.style.display = "none"), 2000); } }; startBtn.addEventListener("click", startGame); window.addEventListener("keydown", ({ key }) => { movePlayer(key, 8, true); }); window.addEventListener("keyup", ({ key }) => { movePlayer(key, 0, false); }); ```
curriculum/challenges/english/15-javascript-algorithms-and-data-structures-22/learn-intermediate-oop-by-building-a-platformer-game/650757918a9e97418dc3d71a.md
1
https://github.com/freeCodeCamp/freeCodeCamp/commit/5973899673bed0cdcd8a960453fd63639fbcf315
[ 0.0011142975417897105, 0.00018506798369344324, 0.00016536744078621268, 0.00017474801279604435, 0.00010024444054579362 ]
{ "id": 1, "code_window": [ "\n", "Your `else if` statement should check if `monsterHealth` is less than or equal to `0`.\n", "\n", "```js\n", "assert.match(attack.toString(), /else\\s*if\\s*\\(\\s*monsterHealth\\s*<=\\s*0\\s*\\)/);\n", "```\n", "\n", "Your `else if` statement should call the `defeatMonster` function.\n", "\n", "```js\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "assert.match(attack.toString(), /else\\s+if\\s*\\(\\s*monsterHealth\\s*<=\\s*0\\s*\\)/);\n" ], "file_path": "curriculum/challenges/english/15-javascript-algorithms-and-data-structures-22/learn-basic-javascript-by-building-a-role-playing-game/62a8ee154c8946678775c4a4.md", "type": "replace", "edit_start_line_idx": 32 }
--- id: 5900f3831000cf542c50fe96 title: 'Problem 23: Non-abundant sums' challengeType: 1 forumTopicId: 301873 dashedName: problem-23-non-abundant-sums --- # --description-- A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. For example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number. A number `n` is called deficient if the sum of its proper divisors is less than `n` and it is called abundant if this sum exceeds `n`. As 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16, the smallest number that can be written as the sum of two abundant numbers is 24. By mathematical analysis, it can be shown that all integers greater than 28123 can be written as the sum of two abundant numbers. However, this upper limit cannot be reduced any further by analysis even though it is known that the greatest number that cannot be expressed as the sum of two abundant numbers is less than this limit. Find the sum of all positive integers &lt;= `n` which cannot be written as the sum of two abundant numbers. # --hints-- `sumOfNonAbundantNumbers(10000)` should return a number. ```js assert(typeof sumOfNonAbundantNumbers(10000) === 'number'); ``` `sumOfNonAbundantNumbers(10000)` should return 3731004. ```js assert(sumOfNonAbundantNumbers(10000) === 3731004); ``` `sumOfNonAbundantNumbers(15000)` should return 4039939. ```js assert(sumOfNonAbundantNumbers(15000) === 4039939); ``` `sumOfNonAbundantNumbers(20000)` should return 4159710. ```js assert(sumOfNonAbundantNumbers(20000) === 4159710); ``` `sumOfNonAbundantNumbers(28123)` should return 4179871. ```js assert(sumOfNonAbundantNumbers(28123) === 4179871); ``` # --seed-- ## --seed-contents-- ```js function sumOfNonAbundantNumbers(n) { return n; } sumOfNonAbundantNumbers(28123); ``` # --solutions-- ```js function abundantCheck(number) { let sum = 1; for (let i = 2; i <= Math.sqrt(number); i += 1) { if(number % i === 0) { sum += i + +(i !== Math.sqrt(number) && number / i); } } return sum > number; } function sumOfNonAbundantNumbers(n) { let sum = 0; const memo = {}; let abundantList = []; // Function checkSum checks if num can be represented as a sum of numbers in the stack (array) const checkSum = (num, stack, memo) => { for (let i = 0; i < stack.length; i += 1) { if ((num - stack[i]) in memo) return true; } return false; }; for (let i = 1; i <= n; i += 1) { if (abundantCheck(i)) { abundantList.push(i); memo[i] = 1; } if (checkSum(i, abundantList, memo)) continue; sum += i; } return sum; } ```
curriculum/challenges/japanese/18-project-euler/project-euler-problems-1-to-100/problem-23-non-abundant-sums.md
0
https://github.com/freeCodeCamp/freeCodeCamp/commit/5973899673bed0cdcd8a960453fd63639fbcf315
[ 0.00017719213792588562, 0.00017230583762284368, 0.0001664326700847596, 0.00017240282613784075, 0.0000039489655137003865 ]